creddy/src-tauri/src/state.rs

75 lines
1.7 KiB
Rust
Raw Normal View History

use std::sync::RwLock;
use serde::{Serialize, Deserialize};
use tokio::sync::oneshot::Sender;
use crate::ipc;
#[derive(Serialize, Deserialize)]
pub enum Credentials {
LongLived {
key_id: String,
secret_key: String,
},
ShortLived {
key_id: String,
secret_key: String,
session_token: String,
},
}
#[derive(Serialize, Deserialize)]
pub enum CurrentSession {
Unlocked(String),
Locked,
Empty,
}
pub struct AppState {
current_session: RwLock<CurrentSession>,
request_count: RwLock<u64>,
open_requests: RwLock<HashMap<u64, Sender>>,
}
impl AppState {
pub fn new(current_session: CurrentSession) -> Self {
AppState {
current_session,
request_count: 0,
open_requests: HashMap::new(),
}
}
pub fn register_request(&mut self, chan: Sender) -> u64 {
let count = {
let c = self.request_count.write().unwrap();
*c += 1;
c
};
let open_requests = self.open_requests.write().unwrap();
self.open_requests.insert(count, chan);
count
}
pub fn send_response(&mut self, req_id: u64, response: ipc::RequestResponse) -> Result<(), SendResponseError> {
let mut open_requests = self.open_requests.write().unwrap();
let chan = self.open_requests
.remove(&req_id)
.ok_or(SendResponseError::NotFound)
?;
chan.send(response)
.map_err(|_e| SendResponseError::Abandoned)
}
}
pub enum SendResponseError {
NotFound, // no request with the given id
Abandoned, // request has already been closed by client
}