1use std::fmt;
2use std::mem;
3use std::sync::atomic::{AtomicBool, Ordering};
4use std::sync::{Arc, Mutex, MutexGuard, PoisonError, TryLockError};
5use std::time::Duration;
6
7use rusqlite::{Connection, ErrorCode, Transaction, TransactionBehavior};
8use tokio::time::Instant;
9
10use crate::gate::Priority;
11use crate::{Error, Options, connect};
12
13const NO_BUSY_WAIT_SQL: &str = include_str!("../queries/no_busy_wait.sql");
14const WAL_CHECKPOINT_SQL: &str = include_str!("../queries/wal_checkpoint.sql");
15const WAL_CHECKPOINT_PASSIVE_SQL: &str = include_str!("../queries/wal_checkpoint_passive.sql");
16const PROGRESS_STEPS: i32 = 1000;
17
18#[cfg(test)]
19mod tests;
20
21#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
22pub struct WriteOptions {
23 pub priority: Priority,
24 pub deadline: Option<Instant>,
25}
26
27#[derive(Debug)]
28pub enum WriteError<E> {
29 NotStarted(Error),
30 Aborted(E),
31 Expired,
32 RolledBack(Error),
33 CommitUnknown(rusqlite::Error),
34}
35
36impl<E> fmt::Display for WriteError<E> {
37 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
38 formatter.write_str(match self {
39 Self::NotStarted(_) => "sqlitedb: write not started",
40 Self::Aborted(_) | Self::RolledBack(_) => "sqlitedb: write rolled back",
41 Self::Expired => "sqlitedb: write rolled back: deadline passed before commit",
42 Self::CommitUnknown(_) => "sqlitedb: commit failed, outcome unknown",
43 })
44 }
45}
46
47impl<E: std::error::Error + 'static> std::error::Error for WriteError<E> {
48 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
49 match self {
50 Self::NotStarted(error) | Self::RolledBack(error) => Some(error),
51 Self::Aborted(error) => Some(error),
52 Self::Expired => None,
53 Self::CommitUnknown(error) => Some(error),
54 }
55 }
56}
57
58enum Slot {
59 Empty,
60 Idle {
61 connection: Connection,
62 since: Instant,
63 },
64 Closed,
65}
66
67pub struct Writer {
68 options: Options,
69 bound: Arc<Bound>,
70 slot: Mutex<Slot>,
71}
72
73impl Writer {
74 pub fn new(options: Options, mut connection: Connection) -> Result<Self, Error> {
75 let bound = Arc::default();
76 Bound::install(&bound, &mut connection)?;
77 Ok(Self {
78 options,
79 bound,
80 slot: Mutex::new(Slot::idle(connection)),
81 })
82 }
83
84 pub fn transact<T, E, F>(&self, deadline: Option<Instant>, apply: F) -> Result<T, WriteError<E>>
85 where
86 F: FnOnce(&Transaction<'_>) -> Result<T, E>,
87 {
88 let budget = Budget::new(&self.bound, deadline, self.options.busy_timeout);
89 if budget.expired() {
90 return Err(WriteError::NotStarted(Error::Deadline));
91 }
92 let mut connection = self.take().map_err(WriteError::NotStarted)?;
93 let settled = match budget.arm(&connection) {
94 Ok(()) => run(&mut connection, &budget, apply),
95 Err(error) => Settled::discard(WriteError::NotStarted(error)),
96 };
97 if settled.reusable {
98 match budget.settle(&connection) {
99 Ok(()) => self.give_back(connection),
100 Err(error) => tracing::warn!(%error, "sqlitedb: discarding the writer connection"),
101 }
102 }
103 settled.outcome
104 }
105
106 pub fn with_connection<T>(
107 &self,
108 task: impl FnOnce(&mut Connection) -> Result<T, Error>,
109 ) -> Result<T, Error> {
110 let mut connection = self.take()?;
111 let result = task(&mut connection);
112 if result.is_ok() {
113 self.give_back(connection);
114 }
115 result
116 }
117
118 pub fn optimize(&self, sql: &str) -> Result<(), Error> {
119 self.with_connection(|connection| {
120 connection
121 .execute_batch(sql)
122 .map_err(Error::sqlite("optimize"))
123 })
124 }
125
126 pub fn checkpoint_passive(&self) -> Result<(), Error> {
127 self.with_connection(|connection| {
128 checkpoint(connection, WAL_CHECKPOINT_PASSIVE_SQL)
129 .map(|_| ())
130 .map_err(Error::sqlite("passive wal checkpoint"))
131 })
132 }
133
134 pub fn sweep(&self, max_idle: Duration) {
135 let mut slot = match self.slot.try_lock() {
136 Ok(slot) => slot,
137 Err(TryLockError::Poisoned(poisoned)) => poisoned.into_inner(),
138 Err(TryLockError::WouldBlock) => return,
139 };
140 if matches!(&*slot, Slot::Idle { since, .. } if since.elapsed() >= max_idle) {
141 let expired = mem::replace(&mut *slot, Slot::Empty);
142 drop(slot);
143 drop(expired);
144 }
145 }
146
147 pub fn close(&self, owner: bool, readers_in_use: usize) -> Result<(), Error> {
148 let previous = mem::replace(&mut *self.lock(), Slot::Closed);
149 let connection = match previous {
150 Slot::Idle { connection, .. } => connection,
151 Slot::Empty if owner => connect::writer(&self.options, false)?,
152 Slot::Empty | Slot::Closed => return Ok(()),
153 };
154 let checkpointed = if owner {
155 truncate(&connection, readers_in_use)
156 } else {
157 Ok(())
158 };
159 let closed = connection
160 .close()
161 .map_err(|(_, error)| Error::sqlite("close writer")(error));
162 Error::join([checkpointed, closed])
163 }
164
165 fn take(&self) -> Result<Connection, Error> {
166 let previous = {
167 let mut slot = self.lock();
168 if matches!(*slot, Slot::Closed) {
169 return Err(Error::Closed);
170 }
171 mem::replace(&mut *slot, Slot::Empty)
172 };
173 if let Slot::Idle { connection, .. } = previous {
174 return Ok(connection);
175 }
176 let mut connection = connect::writer(&self.options, false)?;
177 Bound::install(&self.bound, &mut connection)?;
178 Ok(connection)
179 }
180
181 fn give_back(&self, connection: Connection) {
182 let mut slot = self.lock();
183 if matches!(*slot, Slot::Empty) {
184 *slot = Slot::idle(connection);
185 }
186 }
187
188 fn lock(&self) -> MutexGuard<'_, Slot> {
189 self.slot.lock().unwrap_or_else(PoisonError::into_inner)
190 }
191
192 #[cfg(test)]
193 pub fn is_open(&self) -> bool {
194 matches!(*self.lock(), Slot::Idle { .. })
195 }
196}
197
198impl Slot {
199 fn idle(connection: Connection) -> Self {
200 Self::Idle {
201 connection,
202 since: Instant::now(),
203 }
204 }
205}
206
207#[derive(Debug, Default)]
208struct Bound {
209 applying: AtomicBool,
210 interrupted: AtomicBool,
211 deadline: Mutex<Option<Instant>>,
212}
213
214impl Bound {
215 fn install(this: &Arc<Self>, connection: &mut Connection) -> Result<(), Error> {
216 let bound = Arc::clone(this);
217 connection
218 .commit_hook(Some(move || bound.applying.load(Ordering::Acquire)))
219 .map_err(Error::sqlite("refuse commits inside the write"))?;
220 let bound = Arc::clone(this);
221 connection
222 .progress_handler(PROGRESS_STEPS, Some(move || bound.interrupt()))
223 .map_err(Error::sqlite("bound statements"))
224 }
225
226 fn interrupt(&self) -> bool {
227 let passed = self.applying.load(Ordering::Acquire)
228 && self
229 .deadline
230 .lock()
231 .unwrap_or_else(PoisonError::into_inner)
232 .is_some_and(|deadline| Instant::now() >= deadline);
233 if passed {
234 self.interrupted.store(true, Ordering::Release);
235 }
236 passed
237 }
238}
239
240struct Budget<'a> {
241 bound: &'a Bound,
242 deadline: Option<Instant>,
243 busy_timeout: Duration,
244}
245
246impl<'a> Budget<'a> {
247 const fn new(bound: &'a Bound, deadline: Option<Instant>, busy_timeout: Duration) -> Self {
248 Self {
249 bound,
250 deadline,
251 busy_timeout,
252 }
253 }
254
255 fn arm(&self, connection: &Connection) -> Result<(), Error> {
256 if let Some(deadline) = self.deadline {
257 let remaining =
258 deadline.saturating_duration_since(Instant::now()) + Duration::from_millis(1);
259 connection
260 .busy_timeout(remaining.min(self.busy_timeout))
261 .map_err(Error::sqlite("bound the busy wait"))?;
262 }
263 *self
264 .bound
265 .deadline
266 .lock()
267 .unwrap_or_else(PoisonError::into_inner) = self.deadline;
268 self.bound.interrupted.store(false, Ordering::Release);
269 self.bound.applying.store(true, Ordering::Release);
270 Ok(())
271 }
272
273 fn settle(&self, connection: &Connection) -> Result<(), Error> {
274 self.bound.applying.store(false, Ordering::Release);
275 if self.deadline.is_none() {
276 return Ok(());
277 }
278 connection
279 .busy_timeout(self.busy_timeout)
280 .map_err(Error::sqlite("restore the busy wait"))
281 }
282
283 fn expired(&self) -> bool {
284 self.deadline
285 .is_some_and(|deadline| Instant::now() >= deadline)
286 }
287
288 fn interrupted(&self) -> bool {
289 self.bound.interrupted.load(Ordering::Acquire)
290 }
291
292 fn begin_error(&self, source: rusqlite::Error) -> Error {
293 let waited = matches!(
294 source.sqlite_error_code(),
295 Some(ErrorCode::DatabaseBusy | ErrorCode::OperationInterrupted)
296 );
297 if waited && self.expired() {
298 Error::Deadline
299 } else {
300 Error::Sqlite {
301 action: "begin",
302 source,
303 }
304 }
305 }
306}
307
308impl Drop for Budget<'_> {
309 fn drop(&mut self) {
310 self.bound.applying.store(false, Ordering::Release);
311 }
312}
313
314struct Settled<T, E> {
315 outcome: Result<T, WriteError<E>>,
316 reusable: bool,
317}
318
319impl<T, E> Settled<T, E> {
320 const fn keep(outcome: Result<T, WriteError<E>>) -> Self {
321 Self {
322 outcome,
323 reusable: true,
324 }
325 }
326
327 const fn discard(error: WriteError<E>) -> Self {
328 Self {
329 outcome: Err(error),
330 reusable: false,
331 }
332 }
333
334 fn rolled_back(error: WriteError<E>, transaction: Transaction<'_>) -> Self {
335 Self {
336 outcome: Err(error),
337 reusable: roll_back(transaction),
338 }
339 }
340}
341
342fn run<T, E, F>(connection: &mut Connection, budget: &Budget<'_>, apply: F) -> Settled<T, E>
343where
344 F: FnOnce(&Transaction<'_>) -> Result<T, E>,
345{
346 let transaction = match connection.transaction_with_behavior(TransactionBehavior::Immediate) {
347 Ok(transaction) => transaction,
348 Err(error) => return Settled::keep(Err(WriteError::NotStarted(budget.begin_error(error)))),
349 };
350 let applied = apply(&transaction);
351 let settled = budget.settle(&transaction);
352 match (applied, settled) {
353 (Err(_), _) if budget.interrupted() => {
354 Settled::rolled_back(WriteError::Expired, transaction)
355 }
356 (Err(error), _) => Settled::rolled_back(WriteError::Aborted(error), transaction),
357 (Ok(_), _) if budget.expired() => Settled::rolled_back(WriteError::Expired, transaction),
358 (Ok(_), Err(error)) => {
359 roll_back(transaction);
360 Settled::discard(WriteError::RolledBack(error))
361 }
362 (Ok(value), Ok(())) => match transaction.commit() {
363 Ok(()) => Settled::keep(Ok(value)),
364 Err(error) => Settled::discard(WriteError::CommitUnknown(error)),
365 },
366 }
367}
368
369fn roll_back(transaction: Transaction<'_>) -> bool {
370 if transaction.is_autocommit() {
371 return true;
372 }
373 transaction
374 .rollback()
375 .inspect_err(|error| tracing::warn!(%error, "sqlitedb: rollback failed"))
376 .is_ok()
377}
378
379fn checkpoint(connection: &Connection, sql: &str) -> rusqlite::Result<(i64, i64, i64)> {
380 connection.query_row(sql, [], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)))
381}
382
383fn truncate(connection: &Connection, readers_in_use: usize) -> Result<(), Error> {
384 connection
385 .execute_batch(NO_BUSY_WAIT_SQL)
386 .map_err(Error::sqlite("closing wal checkpoint"))?;
387 let (busy, frames, checkpointed) = checkpoint(connection, WAL_CHECKPOINT_SQL)
388 .map_err(Error::sqlite("closing wal checkpoint"))?;
389 if busy == 0 {
390 return Ok(());
391 }
392 if readers_in_use > 0 {
393 return Err(Error::CheckpointIncomplete {
394 readers: readers_in_use,
395 });
396 }
397 tracing::warn!(
398 frames,
399 checkpointed,
400 "sqlitedb: wal kept at close because another connection holds it"
401 );
402 Ok(())
403}