1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
//
// Wildland Project
//
// Copyright © 2022 Golem Foundation
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3 as published by
// the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

use std::mem::MaybeUninit;
use std::sync::{Arc, Mutex, Once};

use wildland_catlib::gql_catlib::GqlCatlib;
use wildland_corex::catlib_service::CatLibService;
use wildland_corex::container_manager::ContainerManager;
use wildland_corex::dfs::interface::DfsFrontend;
use wildland_corex::storage_manager::StorageManager;
use wildland_corex::template_factory::TemplateFactory;
use wildland_corex::{
    ContainerState,
    LocalSecureStorage,
    LssService,
    StorageTemplate,
    StorageTemplateError,
};
use wildland_databases::error::ClientCreationError;
use wildland_databases::redis_client::RedisClient;
use wildland_dfs::default::DefaultDfs as Dfs;

use super::config::{CatlibConfig, UserConfig};
use crate::api::config::{CargoConfig, FoundationStorageApiConfig};
use crate::api::user::UserApi;
use crate::logging;
use crate::user::UserService;
use crate::utils::{init_storage_backend_factories, init_template_validators};

pub type DfsApi = Arc<dyn DfsFrontend>;

/// Structure aggregating and exposing public API of CargoLib library.
/// All functionalities are exposed to application side through this structure (not all directly).
///
/// It can be created with [`create_cargo_lib`] function.
///
/// As mentioned above, CargoLib does not try to expose all functionalities directly by its methods,
/// but it can be treated as a starting point for using wildland core in a native app.
/// To avoid programming invalid logic on the native app side, some functionalities are
/// hidden in subsequent objects that can be obtained from CargoLib.
///
/// Usage of **Foundation Storage API** makes sense only within a user's context, so in order to avoid
/// calling its methods before a user is created/retrieved access to **Foundation Storage API** is
/// enclosed within [`crate::api::cargo_user::CargoUser`] object.
///
/// Filesystem like interface can be retrieved with the [`CargoLib::dfs_api`] method.
#[derive(Clone)]
pub struct CargoLib {
    user_api: UserApi,
    dfs_api: DfsApi,
    template_factory: TemplateFactory,
}

impl CargoLib {
    pub fn new(
        lss: Box<dyn LocalSecureStorage>,
        fsa_config: FoundationStorageApiConfig,
        catlib_config: CatlibConfig,
        multidevice_state: UserConfig,
    ) -> Result<Self, ClientCreationError> {
        let lss_service = LssService::new(lss);
        let containers_state = ContainerState::default();

        let template_factory = TemplateFactory::new(Arc::new(init_template_validators()));

        let runtime = Arc::new(
            tokio::runtime::Builder::new_multi_thread()
                .worker_threads(4)
                .enable_all()
                .build()
                .unwrap(),
        );
        let dfs_storage_factories = init_storage_backend_factories();

        let dfs_api = Arc::new(Dfs::new(
            Box::new(containers_state.clone()),
            dfs_storage_factories,
            runtime,
        ));

        let storage_manager = StorageManager::new(dfs_api.clone());
        let container_manager = ContainerManager::new(containers_state, storage_manager);

        Ok(Self {
            user_api: UserApi::new(UserService::new(
                lss_service,
                CatLibService::new(Arc::new(GqlCatlib::new(catlib_config.gql_url)))
                    .map_err(|catlib_err| ClientCreationError::IoError(catlib_err.to_string()))?,
                RedisClient::new(multidevice_state.redis_config.connection_string, None)?,
                fsa_config,
                container_manager,
                dfs_api.clone(),
            )),
            dfs_api,
            template_factory,
        })
    }

    pub fn storage_template_from_json(
        &self,
        content: Vec<u8>,
    ) -> Result<StorageTemplate, StorageTemplateError> {
        self.template_factory.storage_template_from_json(&content)
    }

    pub fn storage_template_from_yaml(
        &self,
        content: Vec<u8>,
    ) -> Result<StorageTemplate, StorageTemplateError> {
        self.template_factory.storage_template_from_yaml(&content)
    }

    /// Returns structure aggregating API for user management
    #[tracing::instrument(level = "debug", skip_all)]
    pub fn user_api(&self) -> UserApi {
        self.user_api.clone()
    }

    /// Returns DFS API object that may be used to build Filesystem-like UI.
    pub fn dfs_api(&self) -> Arc<dyn DfsFrontend> {
        self.dfs_api.clone()
    }
}

/// [`CargoLib`] initializer which is the main part of Cargo public API.
/// All functionalities are exposed to application side through this structure.
///
/// Underlying structure is created only once, subsequent call will return handle to the same structure.
///
/// It requires the following arguments:
/// - lss: some type implementing [`LocalSecureStorage`] trait. It is usually provided by the native
/// to a target platform language.
/// - cfg: [`CargoConfig`] structure with config variables (logger, endpoints, etc.)
///
///
/// ```
/// # use wildland_corex::{LocalSecureStorage, LssResult};
/// # use wildland_cargo_lib::api::{config::*, cargo_lib::create_cargo_lib};
/// # use tracing::Level;
/// #
/// struct TestLss{};
///
/// impl LocalSecureStorage for TestLss {
/// // ...implementation here
/// #    fn insert(&self, key: String, value: String) -> LssResult<Option<String>>{todo!()}
/// #    fn get(&self, key: String) -> LssResult<Option<String>>{todo!()}
/// #    fn contains_key(&self, key: String) -> LssResult<bool>{todo!()}
/// #    fn keys(&self) -> LssResult<Vec<String>>{todo!()}
/// #    fn keys_starting_with(&self, prefix: String) -> LssResult<Vec<String>>{todo!()}
/// #    fn remove(&self, key: String) -> LssResult<Option<String>>{todo!()}
/// #    fn len(&self) -> LssResult<usize>{todo!()}
/// #    fn is_empty(&self) -> LssResult<bool>{todo!()}
/// }
///
/// let lss = Box::new(TestLss{});
///
///
/// # use std::path::PathBuf;
/// let cfg = CargoConfig{
///     logger_config: LoggerConfig {
///         use_logger: true,
///         log_level: Level::TRACE,
///         log_use_ansi: false,
///         log_file_path: PathBuf::from("cargo_lib_log"),
///         log_file_rotate_directory: PathBuf::from(".".to_owned()),
///         log_file_enabled: true,
///         #[cfg(any(target_os = "macos", target_os = "ios"))]
///         oslog_category: None,
///         #[cfg(any(target_os = "macos", target_os = "ios"))]
///         oslog_subsystem: None,
///     },
///     fsa_config: FoundationStorageApiConfig {
///         evs_url: "some_url".to_owned(),
///     },
///     catlib_config: CatlibConfig {
///         gql_url: url::Url::parse("http://127.0.0.1/graphql/").unwrap().try_into().unwrap(),
///     },
///     multidevice_state: UserConfig {
///         redis_config: url::Url::parse("redis://127.0.0.1/0").unwrap().try_into().unwrap()
///     }
/// };
///
/// let cargo_lib = create_cargo_lib(lss, cfg);
/// ```
pub fn create_cargo_lib(lss: Box<dyn LocalSecureStorage>, cfg: CargoConfig) -> SharedCargoLib {
    unsafe {
        INIT.call_once(|| {
            logging::init_subscriber(cfg.logger_config);
            let cargo_lib = CargoLib::new(
                lss,
                cfg.fsa_config,
                cfg.catlib_config,
                cfg.multidevice_state,
            );
            let cargo_lib = cargo_lib.map(|c| Arc::new(Mutex::new(c)));
            CARGO_LIB.write(cargo_lib);
        });
        CARGO_LIB.assume_init_ref().clone()
    }
}

static INIT: Once = Once::new();
type SharedCargoLib = Result<Arc<Mutex<CargoLib>>, ClientCreationError>;
static mut CARGO_LIB: MaybeUninit<SharedCargoLib> = MaybeUninit::uninit();