summary refs log tree commit diff
path: root/app/src/persistence.rs
blob: 8a0e7f204bea98bd6590b547c1d1efa6a3671071 (plain)
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
use keyring::Entry;
use serde::{Deserialize, Serialize};
/**
 *  This module keeps persistent application account and credential state,
 *  persists it to disk (and the OS keyring) and makes it available to
 *  other modules in FoxFleet.
 *
 *  All keystore and disk operations run on a secondary thread to
 *  prevent causing hangups (and as the OS keystore APIs are synchronous)
 */

use tauri::async_runtime::RuntimeHandle;
use uuid::Uuid;
use std::path::PathBuf;
use std::thread::{self, JoinHandle};
use std::{collections::HashMap, sync::Arc};
use tokio::sync::Mutex;
use tokio::sync::oneshot;
use std::sync::mpsc;
use std::fs;
use std::sync::mpsc::SendError;
use tokio::sync::oneshot::error::RecvError;

#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct Server {
    pub domain: String,
    pub client_name: String,
    pub client_id: String,
    pub client_credential_id: Uuid,
}

#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct Account {
    pub username: String, // Full @handle@domain identifier, used for persistence and key storage
    pub server_domain: String, // Web domain, used for API access
    pub api_credential_id: Uuid,
}

#[derive(Clone, Serialize, Deserialize, Debug)]
struct DiskState {
    servers: Vec<Server>,
    accounts: Vec<Account>,
}

impl Default for DiskState {
    fn default() -> Self {
        Self {
            servers: Vec::new(),
            accounts: Vec::new(),
        }
    }
}

type PutResponse = Result<(), PersistenceError>;
type LoadDiskResponse = Result<DiskState, PersistenceError>;
type GetCredentialResponse = Result<String, PersistenceError>;

enum CredentialThreadRequest {
    PutCredential {uuid: Uuid, credential: String, callback: oneshot::Sender<PutResponse>},
    GetCredential {uuid: Uuid, callback: oneshot::Sender<GetCredentialResponse>},
}

enum DiskThreadRequest {
    Write {state: DiskState, callback: oneshot::Sender<PutResponse> },
    Read {callback: oneshot::Sender<LoadDiskResponse>},
}

#[derive(Debug)]
pub enum PersistenceError {
    RecvError(RecvError),
    SendError,
    IoError(std::io::Error),
    NoDataDir,
    AccountNotFound {username: String, server_domain: String},
    ServerNotFound {server_domain: String},
    AccountAlreadyExists {username: String, server_domain: String},
    ServerAlreadyRegistered { server_domain: String },
}

impl From<RecvError> for PersistenceError {
    fn from(value: RecvError) -> Self {
        PersistenceError::RecvError(value)
    }
}

impl<T> From<SendError<T>> for PersistenceError {
    fn from(_value: SendError<T>) -> Self {
        PersistenceError::SendError
    }
}

impl From<std::io::Error> for PersistenceError {
    fn from(value: std::io::Error) -> Self {
        PersistenceError::IoError(value)
    }
}

impl From<PersistenceError> for String {
    fn from(value: PersistenceError) -> Self {
        "PersistenceError".to_string()
    }
}

struct PersistenceState {
    servers: Vec<Server>,
    accounts: Vec<Account>,
    credential_cache: HashMap<Uuid, String>,
    credential_channel: mpsc::Sender<CredentialThreadRequest>,
    disk_channel: mpsc::Sender<DiskThreadRequest>,
    credential_joinhandle: JoinHandle<()>,
    disk_joinhandle: JoinHandle<()>,
    async_runtime: RuntimeHandle,
}

#[derive(Clone)]
pub struct PersistenceController (Arc<Mutex<PersistenceState>>);

impl PersistenceController {
    pub fn new(runtime_handle: RuntimeHandle) -> Self {
        let (credential_sender, credential_receiver) = mpsc::channel::<CredentialThreadRequest>();
        let (disk_sender, disk_receiver) = mpsc::channel::<DiskThreadRequest>();

        let disk_joinhandle = thread::Builder::new()
            .name("foxfleet::persistence::disk".to_string())
            .spawn(move || DiskThread::start(disk_receiver) )
            .expect("Could not spawn disk thread");

        let credential_joinhandle = thread::Builder::new()
            .name("foxfleet::persistence::keyring".to_string())
            .spawn(move || CredentialThread::start(credential_receiver) )
            .expect("Could not spawn keyring thread");

        // Load saved or default config on startup
        let (load_send, load_recv) = oneshot::channel::<LoadDiskResponse>();

        let initial_state = disk_sender.send(DiskThreadRequest::Read { callback: load_send }).ok().map(|()| {
            runtime_handle.block_on(load_recv).ok().map(|response| response.ok())
        }).flatten().flatten().unwrap_or_default();

        return PersistenceController(Arc::new(Mutex::new(PersistenceState {
            servers: initial_state.servers,
            accounts: initial_state.accounts,
            credential_cache: HashMap::new(),
            credential_channel: credential_sender,
            disk_channel: disk_sender,
            credential_joinhandle,
            disk_joinhandle,
            async_runtime: runtime_handle,
        })))
    }

    pub async fn new_server(&self, domain: String, client_id: String, client_name: String, client_secret: String) -> Result<Server, PersistenceError> {
        let has_server_with_domain = {self.0.lock().await.servers.iter().find(|s| s.domain == domain).is_some()};

        if has_server_with_domain {
            return Err(PersistenceError::ServerAlreadyRegistered { server_domain: domain });
        }

        let client_credential_id = Uuid::new_v4();
        let server = Server {
            domain,
            client_id,
            client_name,
            client_credential_id,
        };

        self.persist_credential(client_credential_id, client_secret).await?;
        {self.0.lock().await.servers.push(server.clone())};
        self.persist_disk().await?;

        return Ok(server)
    }

    pub async fn get_server(&self, domain: &String) -> Option<Server> {
        let server = {self.0.lock().await.servers.iter().find(|s| s.domain == *domain).cloned()};
        return server
    }

    pub async fn new_account(&self, username: String, server_domain: String, api_token: String) -> Result<Account, PersistenceError> {
        let has_account_already = {self.0.lock().await.accounts.iter().find(|a| a.username == username && a.server_domain == server_domain).is_some()};

        if has_account_already {
            return Err(PersistenceError::AccountAlreadyExists {username, server_domain});
        }

        let api_credential_id = Uuid::new_v4();
        let account = Account {
            username,
            server_domain,
            api_credential_id
        };

        self.persist_credential(api_credential_id, api_token).await?;
        {self.0.lock().await.accounts.push(account.clone())};
        self.persist_disk().await?;

        return Ok(account)
    }

    pub async fn get_account(&self, username: &String, server_domain: &String) -> Option<Account> {
        let account = {self.0.lock().await.accounts.iter().find(|a| a.username == *username && a.server_domain == *server_domain).cloned()};
        return account
    }

    pub async fn get_all_accounts(&self) -> Vec<Account> {
        let accounts = {self.0.lock().await.accounts.clone()};
        return accounts
    }

    async fn persist_credential(&self, credential_id: Uuid, value: String) -> Result<(), PersistenceError> {
        let credential_channel = {self.0.lock().await.credential_channel.clone()};

        let (sender, receiver) = oneshot::channel::<PutResponse>();
        credential_channel.send(CredentialThreadRequest::PutCredential { uuid: credential_id, credential: value.clone(), callback: sender })?;
        receiver.await??;

        {self.0.lock().await.credential_cache.insert(credential_id, value)};

        Ok(())
    }

    pub async fn get_credential(&self, credential_id: Uuid) -> Result<String, PersistenceError> {
        if let Some(cached) = {self.0.lock().await.credential_cache.get(&credential_id).cloned()} {
            return Ok(cached)
        }

        let credential_channel = {self.0.lock().await.credential_channel.clone()};

        let (sender, receiver) = oneshot::channel::<GetCredentialResponse>();
        credential_channel.send(CredentialThreadRequest::GetCredential { uuid: credential_id, callback: sender })?;
        let retrieved = receiver.await??;

        {self.0.lock().await.credential_cache.insert(credential_id, retrieved.clone())};

        return Ok(retrieved)
    }

    async fn persist_disk(&self) -> Result<(), PersistenceError> {
        let (disk_channel, accounts, servers) = {
            let state = self.0.lock().await;
            (state.disk_channel.clone(), state.accounts.clone(), state.servers.clone())
        };

        let (sender, receiver) = oneshot::channel::<PutResponse>();

        disk_channel.send(DiskThreadRequest::Write { state: DiskState {
            accounts,
            servers,
        }, callback: sender})?;

        receiver.await??;

        Ok(())
    }
}

struct DiskThread;
impl DiskThread {
    fn start(receiver: mpsc::Receiver<DiskThreadRequest>) {
        loop {
            match receiver.recv() {
                Ok(DiskThreadRequest::Write { state, callback }) => callback.send(Self::write(state)).expect("Disk thread hung up on"),
                Ok(DiskThreadRequest::Read { callback }) => callback.send(Self::read()).expect("Disk thread hung up on"),
                Err(_) => panic!("Disk thread hung up on, exiting"),
            }
        }
    }

    fn write(state: DiskState) -> PutResponse {
        Self::ensure_dir_exists()?;
        let file_path = Self::file_path();
        let data = toml::to_string(&state).unwrap();

        fs::write(file_path, data)?;

        Ok(())
    }

    fn read() -> LoadDiskResponse {
        Self::ensure_dir_exists()?;
        let file_path = Self::file_path();
        let data = fs::read_to_string(file_path)?;

        let result : DiskState = toml::from_str(&data).unwrap();

        Ok(result)
    }

    fn file_path() -> PathBuf {
        dirs::data_dir().unwrap().join("foxfleet/data.toml")
    }

    fn ensure_dir_exists() -> Result<(), PersistenceError> {
        let dir = dirs::data_dir().ok_or(PersistenceError::NoDataDir)?.join("foxfleet");
        if !fs::exists(&dir)? {
            fs::create_dir(&dir)?;
        }

        Ok(())
    }
}

struct CredentialThread;
impl CredentialThread {
    fn start(receiver: mpsc::Receiver<CredentialThreadRequest>) {
        loop {
            match receiver.recv() {
                Ok(CredentialThreadRequest::PutCredential { uuid, credential, callback }) => callback.send(Self::put(uuid, credential)).expect("Credential thread hung up on"),
                Ok(CredentialThreadRequest::GetCredential { uuid, callback }) => callback.send(Self::get(uuid)).expect("Credential thread hung up on"),
                Err(_) => panic!("Credential thread hung up on, exiting"),
            }
        }
    }

    fn get(uuid: Uuid) -> GetCredentialResponse {
        let entry = Entry::new("dev.tempest.foxfleet", &uuid.to_string()).unwrap();
        let credential = entry.get_password().unwrap();
        Ok(credential)
    }

    fn put(uuid: Uuid, credential: String) -> PutResponse {
        let entry = Entry::new("dev.tempest.foxfleet", &uuid.to_string()).unwrap();
        entry.set_password(credential.as_str()).unwrap();
        Ok(())
    }
}