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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
//
// 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::collections::HashMap;

use unicase::UniCase;
use wildland_corex::TemplateValidator;
use wildland_dfs::storage_backends::StorageBackendFactory;
#[cfg(feature = "lfs")]
use wildland_storage_backend::lfs::{
    template::LfsTemplateValidator,
    template::LOCAL_FILESYSTEM_KEY,
    LfsBackendFactory,
};
#[cfg(feature = "s3")]
use wildland_storage_backend::s3::{S3BackendFactory, S3TemplateValidator, S3_KEY};

// `s3sc` has priority over `s3sc_new` until `s3sc_new` is fully implemented
cfg_if::cfg_if! {
    if #[cfg(feature = "s3sc")] {
        use wildland_storage_backend::s3sc::{S3ScBackendFactory, S3ScTemplateValidator, S3SC_KEY};
    } else if #[cfg(feature = "s3sc_new")] {
        use wildland_storage_backend::s3sc_new::{S3ScBackendFactory, S3ScTemplateValidator, S3SC_KEY};
    }
}

#[tracing::instrument(level = "debug", skip_all)]
pub fn init_storage_backend_factories() -> HashMap<UniCase<String>, Box<dyn StorageBackendFactory>>
{
    let mut dfs_storage_factories: HashMap<UniCase<String>, Box<dyn StorageBackendFactory>> =
        HashMap::new();

    #[cfg(feature = "lfs")]
    dfs_storage_factories.insert(LOCAL_FILESYSTEM_KEY.into(), Box::new(LfsBackendFactory {}));
    #[cfg(feature = "s3")]
    dfs_storage_factories.insert(S3_KEY.into(), Box::new(S3BackendFactory::new()));
    #[cfg(feature = "s3sc")]
    dfs_storage_factories.insert(S3SC_KEY.into(), Box::new(S3ScBackendFactory::new()));
    #[cfg(feature = "s3sc_new")]
    dfs_storage_factories.insert(S3SC_KEY.into(), Box::new(S3ScBackendFactory::new()));

    dfs_storage_factories
}

#[tracing::instrument(level = "debug", skip_all)]
pub fn init_template_validators() -> HashMap<UniCase<String>, Box<dyn TemplateValidator>> {
    let mut template_validators: HashMap<UniCase<String>, Box<dyn TemplateValidator>> =
        HashMap::new();

    #[cfg(feature = "lfs")]
    template_validators.insert(
        LOCAL_FILESYSTEM_KEY.into(),
        Box::<LfsTemplateValidator>::default(),
    );
    #[cfg(feature = "s3")]
    template_validators.insert(S3_KEY.into(), Box::<S3TemplateValidator>::default());
    #[cfg(feature = "s3sc")]
    template_validators.insert(S3SC_KEY.into(), Box::<S3ScTemplateValidator>::default());
    #[cfg(feature = "s3sc_new")]
    template_validators.insert(S3SC_KEY.into(), Box::<S3ScTemplateValidator>::default());

    template_validators
}

#[cfg(test)]
pub(crate) mod test {
    use std::collections::HashMap;
    use std::sync::{Arc, Mutex, RwLock};

    use mockall::mock;
    use rstest::fixture;
    use uuid::{Bytes, Uuid};
    use wildland_catlib::gql_catlib::GqlCatlib;
    use wildland_corex::catlib_service::CatLibService;
    use wildland_corex::storage_manager::StorageManager;
    use wildland_corex::{
        ContainerManager,
        ContainerState,
        LocalSecureStorage,
        LssResult,
        Storage,
    };
    use wildland_databases::redis_client::RedisClient;
    use wildland_dfs::{
        AbortFlag,
        DfsFrontend,
        DfsFrontendError,
        DirEntry,
        EventReceiver,
        FsStat,
        IStream,
        NodeStat,
        OStream,
        ProgressReporter,
        SpaceUsage,
        UnixTimestamp,
        WlPermissions,
    };

    use crate::api::cargo_lib::DfsApi;
    use crate::multidevice_state::user_state::UserMultideviceState;

    mock! {
        pub DfsApi {}
        impl DfsFrontend for DfsApi {
            fn get_path(&self, identifier: String) -> Result<String, DfsFrontendError>;
            fn read_dir(&self, path: String) -> Result<Vec<DirEntry>, DfsFrontendError>;
            fn metadata(&self, path: String) -> Result<NodeStat, DfsFrontendError>;
            fn remove_file(&self, path: String) -> Result<(), DfsFrontendError>;
            fn rename(&self, old_path: String, new_path: String) -> Result<(), DfsFrontendError>;
            fn set_permissions(
                &self,
                path: String,
                permissions: WlPermissions,
            ) -> Result<(), DfsFrontendError>;
            fn set_owner(&self, path: String) -> Result<(), DfsFrontendError>;
            fn create_dir(&self, path: String) -> Result<(), DfsFrontendError>;
            fn remove_dir(&self, path: String, is_recursive: bool) -> Result<(), DfsFrontendError>;
            fn stat_fs(&self, path: String) -> Result<FsStat, DfsFrontendError>;
            fn get_receiver(&self) -> Arc<Mutex<dyn EventReceiver>>;
            fn mount(&self, storage: &Storage) -> Result<(), DfsFrontendError>;
            fn get_space_usage(&self, storage: &Storage) -> Result<SpaceUsage, DfsFrontendError>;
            fn is_accessible(&self, storage: &Storage) -> Result<bool, DfsFrontendError>;
            fn download(
                &self,
                path: String,
                output: Box<dyn OStream>,
                progress_reporter: Box<dyn ProgressReporter>,
                abort_flag: &AbortFlag,
            ) -> Result<(), DfsFrontendError>;
            fn upload(
                &self,
                path: String,
                input: Box<dyn IStream>,
                progress_reporter: Box<dyn ProgressReporter>,
                abort_flag: &AbortFlag,
                creation_time: Option<UnixTimestamp>,
            ) -> Result<(), DfsFrontendError>;
        }
    }

    #[fixture]
    pub(crate) fn dfs_api_mock() -> DfsApi {
        Arc::new(MockDfsApi::new())
    }

    #[fixture]
    pub(crate) fn container_manager() -> ContainerManager {
        let mut dfs_mock = MockDfsApi::new();
        dfs_mock.expect_mount().returning(|_| Ok(()));
        let storage_manager = StorageManager::new(Arc::new(dfs_mock));

        ContainerManager::new(ContainerState::default(), storage_manager)
    }

    #[fixture]
    pub(crate) fn catlib_service() -> CatLibService {
        let catlib_gql_url = std::env::var("CATALOG_BACKEND_GQL_URL")
            .unwrap_or_else(|_| "http://localhost:8000/graphql/".into());
        let catlib = Arc::new(GqlCatlib::new(catlib_gql_url));
        CatLibService::new(catlib).unwrap()
    }

    #[fixture]
    #[once]
    pub(crate) fn multidevice_client() -> RedisClient {
        let uuid = uuid::Builder::from_random_bytes(rand::random::<Bytes>()).into_uuid();
        let redis_url =
            std::env::var("CARGO_REDIS_URL").unwrap_or_else(|_| "redis://127.0.0.1:6379/0".into());
        RedisClient::new(redis_url, Some(uuid.to_string())).unwrap()
    }

    #[fixture]
    pub(crate) fn multidevice_state(
        #[default(Uuid::new_v4().to_string())] user_prefix: String,
        multidevice_client: &RedisClient,
    ) -> UserMultideviceState {
        let device_uuid = Uuid::new_v4();
        UserMultideviceState::new(&user_prefix, &device_uuid.to_string(), multidevice_client)
    }

    #[fixture]
    pub(crate) fn lss_stub() -> Box<dyn LocalSecureStorage> {
        #[derive(Default)]
        struct LssStub {
            storage: RwLock<HashMap<String, String>>,
        }

        impl LocalSecureStorage for LssStub {
            fn insert(&self, key: String, value: String) -> LssResult<Option<String>> {
                Ok(self.storage.write().unwrap().insert(key, value))
            }

            fn get(&self, key: String) -> LssResult<Option<String>> {
                Ok(self.storage.read().unwrap().get(&key).cloned())
            }

            fn contains_key(&self, key: String) -> LssResult<bool> {
                Ok(self.storage.read().unwrap().contains_key(&key))
            }

            fn keys(&self) -> LssResult<Vec<String>> {
                Ok(self.storage.read().unwrap().keys().cloned().collect())
            }

            fn keys_starting_with(&self, prefix: String) -> LssResult<Vec<String>> {
                Ok(self
                    .storage
                    .read()
                    .unwrap()
                    .keys()
                    .filter(|key| key.starts_with(&prefix))
                    .cloned()
                    .collect())
            }

            fn remove(&self, key: String) -> LssResult<Option<String>> {
                Ok(self.storage.write().unwrap().remove(&key))
            }

            fn len(&self) -> LssResult<usize> {
                Ok(self.storage.read().unwrap().len())
            }

            fn is_empty(&self) -> LssResult<bool> {
                Ok(self.storage.read().unwrap().is_empty())
            }
        }

        Box::<LssStub>::default()
    }
}