tauri_plugin_persistence/api/
state.rs1use std::{collections::HashMap, sync::Arc};
2
3use polodb_core::{Database, Transaction};
4use serde::{Deserialize, Serialize};
5use specta::Type;
6use tokio::{fs::{File, OpenOptions}, sync::Mutex};
7
8#[derive(Clone)]
9pub struct ContextDB {
10 #[allow(dead_code)]
11 pub name: String,
12 pub path: String,
13 pub database: Arc<Mutex<Database>>,
14 pub transactions: Arc<Mutex<HashMap<bson::Uuid, Arc<Mutex<Transaction>>>>>,
15}
16
17#[derive(Clone, Serialize, Deserialize, Debug, Type)]
18#[serde(rename_all = "snake_case", tag = "mode")]
19pub enum FileHandleMode {
20 Create {
21 new: bool,
22 overwrite: bool
23 },
24 Write {
25 overwrite: bool
26 },
27 Read {}
28}
29
30impl FileHandleMode {
31 pub fn create_new(overwrite: bool) -> Self {
32 Self::Create { new: true, overwrite }
33 }
34
35 pub fn create_or_open(overwrite: bool) -> Self {
36 Self::Create { new: false, overwrite }
37 }
38
39 pub fn append() -> Self {
40 Self::Write { overwrite: false }
41 }
42
43 pub fn overwrite() -> Self {
44 Self::Write { overwrite: true }
45 }
46
47 pub fn read() -> Self {
48 Self::Read { }
49 }
50
51 pub fn create(&self) -> bool {
52 if let Self::Create { .. } = self {
53 true
54 } else {
55 false
56 }
57 }
58
59 pub fn writeable(&self) -> bool {
60 match self {
61 Self::Create {..} | Self::Write {..} => true,
62 _ => false
63 }
64 }
65
66 pub fn readable(&self) -> bool {
67 match self {
68 Self::Read {} => true,
69 _ => false
70 }
71 }
72}
73
74impl Into<OpenOptions> for FileHandleMode {
75 fn into(self) -> OpenOptions {
76 let mut base = OpenOptions::new();
77 match self {
78 Self::Create { new, overwrite: true } => base.create(true).write(true).create_new(new),
79 Self::Create {new, overwrite: false} => base.create(true).append(true).create_new(new),
80 Self::Write { overwrite: true } => base.write(true),
81 Self::Write { overwrite: false } => base.append(true),
82 Self::Read { } => base.read(true)
83 }.clone()
84 }
85}
86
87#[derive(Clone)]
88pub struct ContextFileHandle {
89 pub id: bson::Uuid,
90 pub path: String,
91 pub handle: async_dup::Arc<async_dup::Mutex<File>>,
92 pub mode: FileHandleMode
93}
94
95#[derive(Clone)]
96pub struct ContextState {
97 #[allow(dead_code)]
98 pub name: String,
99 pub root_path: String,
100 pub databases: Arc<Mutex<HashMap<String, ContextDB>>>,
101 pub files: Arc<Mutex<HashMap<bson::Uuid, ContextFileHandle>>>,
102}
103
104pub type PluginState = Mutex<HashMap<String, ContextState>>;