// Copyright (C) 2022 Aravinth Manivannan // SPDX-FileCopyrightText: 2023 Aravinth Manivannan // // SPDX-License-Identifier: AGPL-3.0-or-later use std::collections::HashMap; use std::sync::{Arc, RwLock}; use tokio::sync::mpsc::Sender; use crate::db::*; use crate::docker::Docker; //use crate::docker::DockerLike; use crate::settings::Settings; use super::complaince::result::Result as CResult; pub type ArcFullCtx = Arc; pub type ArcMinCtx = Arc; pub trait FullAppContext: std::marker::Send + std::marker::Sync + CloneFullAppCtx { fn settings(&self) -> &Settings; fn db(&self) -> &Database; fn docker(&self) -> Arc; fn results(&self) -> &ResultStore; fn port(&self) -> u32; } pub trait CloneFullAppCtx { fn clone_f(&self) -> Box; } impl CloneFullAppCtx for T where T: FullAppContext + Clone + 'static, { fn clone_f(&self) -> Box { Box::new(self.clone()) } } impl Clone for Box { fn clone(&self) -> Self { (**self).clone_f() } } pub trait MinAppContext: std::marker::Send + std::marker::Sync { fn docker_(&self) -> Arc; fn results_(&self) -> &ResultStore; fn port_(&self) -> u32; } impl MinAppContext for Arc { fn docker_(&self) -> Arc { self.docker() } fn results_(&self) -> &ResultStore { self.results() } fn port_(&self) -> u32 { self.port() } } #[derive(Clone)] pub struct DaemonCtx { settings: Settings, db: Database, results: ResultStore, docker: Arc, } impl FullAppContext for DaemonCtx { fn settings(&self) -> &Settings { &self.settings } fn db(&self) -> &Database { &self.db } fn docker(&self) -> Arc { self.docker.clone() } fn results(&self) -> &ResultStore { &self.results } fn port(&self) -> u32 { self.settings.server.port } } impl MinAppContext for DaemonCtx { fn docker_(&self) -> Arc { self.docker() } fn results_(&self) -> &ResultStore { self.results() } fn port_(&self) -> u32 { self.port() } } pub type ResultStore = Arc>>>; impl DaemonCtx { pub async fn new(settings: Settings) -> Self { let results = HashMap::default(); let results = Arc::new(RwLock::new(results)); let db = get_db(&settings).await; Self { settings, db, results, docker: Arc::new(Docker::new()), } } } #[derive(Clone)] pub struct CliCtx { results: ResultStore, docker: Arc, } impl MinAppContext for CliCtx { fn docker_(&self) -> Arc { self.docker.clone() } fn results_(&self) -> &ResultStore { &self.results } fn port_(&self) -> u32 { 80 } } impl CliCtx { pub fn new() -> Self { let results = HashMap::default(); let results = Arc::new(RwLock::new(results)); Self { results, docker: Arc::new(Docker::new()), } } }