uqa_storage_sqlite/mvcc/serializable/
liveness.rs1use std::sync::Arc;
10
11#[cfg(any(windows, all(unix, not(target_os = "emscripten"))))]
12use uqa_core::memory::BudgetedVec;
13use uqa_storage::{
14 mvcc::{
15 admit_serializable, LocalSerializableLeases, SerializableCoordinator, SerializableGraph,
16 SerializableLeases, SerializableOperation, SerializableParticipant,
17 SerializableTransactionId, VersionResult,
18 },
19 read_control::{CancellationToken, StorageReadControl},
20};
21
22use super::SQLiteRecordStore;
23use crate::connection::ownership::DatabaseOwner;
24
25#[cfg(any(windows, all(unix, not(target_os = "emscripten"))))]
26use super::super::leases::{LeaseNamespace, NativeLeaseAdmission, NativeLeaseFile};
27
28enum Liveness {
29 #[cfg(any(windows, all(unix, not(target_os = "emscripten"))))]
30 Native {
31 file: NativeLeaseFile,
32 _admission: NativeLeaseAdmission,
33 live: BudgetedVec<u64>,
34 owner: Option<Arc<DatabaseOwner>>,
35 },
36 Local {
37 leases: Arc<LocalSerializableLeases>,
38 owner: Option<Arc<DatabaseOwner>>,
39 },
40}
41
42impl Liveness {
43 fn open(
44 store: &SQLiteRecordStore,
45 graph: &SerializableGraph,
46 control: &StorageReadControl,
47 ) -> VersionResult<Self> {
48 #[cfg(any(windows, all(unix, not(target_os = "emscripten"))))]
49 if let Some(path) = store.connection.database_path() {
50 let file = lease_file(path, graph)?;
51 let admission = file.admit(control)?;
52 let mut live = BudgetedVec::new(control.memory());
53 file.visit(control, &mut |allocation| {
54 live.push(allocation)?;
55 Ok(())
56 })?;
57 live.sort_unstable();
58 return Ok(Self::Native {
59 file,
60 _admission: admission,
61 live,
62 owner: store.connection.database_owner(),
63 });
64 }
65 #[cfg(not(any(windows, all(unix, not(target_os = "emscripten")))))]
66 if let Some(path) = store.connection.database_path() {
67 return Ok(Self::Local {
68 leases: local_file_registry(path, control)?,
69 owner: store.connection.database_owner(),
70 });
71 }
72 let _ = graph;
73 Ok(Self::Local {
74 leases: store.connection.serializable_local_leases(control),
75 owner: store.connection.database_owner(),
76 })
77 }
78}
79
80#[cfg(any(windows, all(unix, not(target_os = "emscripten"))))]
81pub(in crate::mvcc) fn lease_file(
82 path: &std::path::Path,
83 graph: &SerializableGraph,
84) -> VersionResult<NativeLeaseFile> {
85 let uqa_storage::PersistentStorageIdentity::File(path) =
86 uqa_storage::PersistentStorageIdentity::for_database_path(path)?
87 else {
88 unreachable!("database file identity")
89 };
90 let mut sidecar = path.into_os_string();
91 sidecar.push(".uqa-serializable-leases");
92 NativeLeaseFile::open(
93 std::path::Path::new(&sidecar),
94 LeaseNamespace {
95 magic: *b"UQASSL01",
96 database: graph.database(),
97 incarnation: Some(graph.coordinator()),
98 },
99 )
100}
101
102impl SerializableLeases for Liveness {
103 fn is_alive(
104 &self,
105 id: SerializableTransactionId,
106 control: &StorageReadControl,
107 ) -> VersionResult<bool> {
108 control.cancellation().check()?;
109 Ok(match self {
110 #[cfg(any(windows, all(unix, not(target_os = "emscripten"))))]
111 Self::Native { live, .. } => live.binary_search(&id.allocation()).is_ok(),
112 Self::Local { leases, .. } => leases.is_alive(id),
113 })
114 }
115
116 fn retain(
117 &self,
118 id: SerializableTransactionId,
119 control: &StorageReadControl,
120 ) -> VersionResult<SerializableParticipant> {
121 match self {
122 #[cfg(any(windows, all(unix, not(target_os = "emscripten"))))]
123 Self::Native { file, owner, .. } => SerializableParticipant::retain(
124 id,
125 file.retain_with(id.allocation(), owner.clone(), control)?,
126 control,
127 ),
128 Self::Local { leases, owner } => leases.retain_with(id, owner.clone(), control),
129 }
130 }
131
132 fn reclaim(&self) {
133 match self {
134 #[cfg(any(windows, all(unix, not(target_os = "emscripten"))))]
135 Self::Native { .. } => {}
136 Self::Local { leases, .. } => leases.reclaim(),
137 }
138 }
139}
140
141impl SQLiteRecordStore {
142 pub fn admit_serializable<T>(
144 &self,
145 read_only: bool,
146 control: &StorageReadControl,
147 capture: impl FnOnce() -> VersionResult<T>,
148 ) -> VersionResult<(SerializableParticipant, T)> {
149 admit_serializable(self, read_only, control, capture)
150 }
151
152 pub fn recover_serializable(&self, control: &StorageReadControl) -> VersionResult<()> {
154 self.recover_serializable_participants(control)
155 }
156}
157
158impl SerializableCoordinator for SQLiteRecordStore {
159 fn with_serializable_admission(
160 &self,
161 control: &StorageReadControl,
162 operation: &mut SerializableOperation<'_>,
163 ) -> VersionResult<()> {
164 let mut held = self.serializable_admission(control)?;
165 let liveness = Liveness::open(self, held.graph(), control)?;
166 let result = operation(held.graph_mut(), &liveness);
167 let finish = StorageReadControl::new(control.memory(), &CancellationToken::new());
169 held.persist(&finish)?;
170 result
171 }
172}
173
174#[cfg(not(any(windows, all(unix, not(target_os = "emscripten")))))]
175fn local_file_registry(
176 path: &std::path::Path,
177 control: &StorageReadControl,
178) -> VersionResult<Arc<LocalSerializableLeases>> {
179 use parking_lot::Mutex;
180 use std::{
181 collections::HashMap,
182 path::PathBuf,
183 sync::{OnceLock, Weak},
184 };
185 type Registries = HashMap<PathBuf, Weak<LocalSerializableLeases>>;
186 static REGISTRIES: OnceLock<Mutex<Registries>> = OnceLock::new();
187 let uqa_storage::PersistentStorageIdentity::File(path) =
188 uqa_storage::PersistentStorageIdentity::for_database_path(path)?
189 else {
190 unreachable!("database file identity")
191 };
192 let mut registries = REGISTRIES.get_or_init(Mutex::default).lock();
193 registries.retain(|_, leases| leases.strong_count() != 0);
194 if let Some(leases) = registries.get(&path).and_then(Weak::upgrade) {
195 return Ok(leases);
196 }
197 let leases = Arc::new(LocalSerializableLeases::new(control.memory()));
198 registries.insert(path, Arc::downgrade(&leases));
199 Ok(leases)
200}