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
//
// 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 thiserror::Error;
use wildland_corex::catlib_service::error::CatlibError;
use wildland_corex::{CryptoError, LssError, StorageTemplate, StorageTemplateError};
use wildland_http_client::error::WildlandHttpClientError;
use wildland_http_client::evs::{ConfirmTokenReq, EvsClient, GetStorageReq, GetStorageRes};

use super::config::FoundationStorageApiConfig;

/// Errors that may happen during using Foundation Storage API (communication with EVS server)
///
#[repr(C)]
#[derive(Error, Debug, Clone)]
pub enum FsaError {
    #[error("Evs Error: {0}: {1}")]
    EvsError(&'static str, WildlandHttpClientError),
    #[error("Crypto error: {0}")]
    CryptoError(CryptoError),
    #[error("Evs returned unexpected response: received {0}")]
    UnexpectedResponse(String),
    #[error(transparent)]
    LssError(#[from] LssError),
    #[error(transparent)]
    CatlibError(#[from] CatlibError),
    #[error("Error while creating Storage Template: {0}")]
    StorageTemplateError(StorageTemplateError),
    #[error("Connectivity Issue {0}")]
    ConnectivityIssue(String),
}

#[derive(Clone)]
pub struct FoundationStorageApi {
    evs_client: EvsClient,
}

impl FoundationStorageApi {
    pub fn new(config: &FoundationStorageApiConfig) -> Self {
        Self {
            evs_client: EvsClient::new(config.evs_url.clone()),
        }
    }

    #[tracing::instrument(level = "debug", skip_all)]
    pub fn request_free_tier_storage(
        &self,
        email: String,
    ) -> Result<FreeTierProcessHandle, FsaError> {
        self.evs_client
            .get_storage(GetStorageReq {
                email: email.clone(),
                session_id: None,
            })
            .map_err(|e| FsaError::EvsError("Requesting free storage", e))
            .and_then(|resp| match resp {
                GetStorageRes::Started { session_id } => {
                    tracing::debug!("Process of requesting Foundation Storage started with session id: {session_id}");
                    Ok(FreeTierProcessHandle {
                    email,
                    session_id,
                    evs_client: self.evs_client.clone(),
                })
            },
                other => Err(FsaError::UnexpectedResponse(other.state().into())),
            })
    }
}

/// Represents ongoing process of granting Free Foundation Storage and allows to run email verifications
/// via `verify_email` method.
#[derive(Clone)]
pub struct FreeTierProcessHandle {
    email: String,
    session_id: String,
    evs_client: EvsClient,
}

impl FreeTierProcessHandle {
    /// Verifies user's email.
    /// After successful verification it returns Foundation Storage Template (which is also saved in LSS)
    /// and saves information in CatLib that Foundation storage has been granted.
    #[tracing::instrument(level = "debug", skip_all)]
    pub fn verify_email(&self, verification_token: String) -> Result<StorageTemplate, FsaError> {
        self.evs_client
            .confirm_token(ConfirmTokenReq {
                session_id: self.session_id.clone(),
                email: self.email.clone(),
                verification_token,
            })
            .map_err(|e| match e {
                WildlandHttpClientError::ClientConnectivityError(f) => {
                    FsaError::ConnectivityIssue(format!("Code: {f}, Error:{}", e))
                }
                _ => FsaError::EvsError("Confirming token", e),
            })?;

        self.evs_client
            .get_storage(GetStorageReq {
                email: self.email.clone(),
                session_id: Some(self.session_id.clone()),
            })
            .map_err(|e| FsaError::EvsError("Getting storage after confirmation", e))
            .and_then(|resp| match resp {
                GetStorageRes::Finished { template } => {
                    serde_json::from_value(template).map_err(|err| {
                        FsaError::UnexpectedResponse(format!(
                            "Cannot deserialize storage template: {err:?}"
                        ))
                    })
                }
                other => Err(FsaError::UnexpectedResponse(other.state().into())),
            })
    }
}