tinystore 0.8.0

A small storage runtime for applications on SQLite: SQL, key-value state, durable jobs, files, search, logs and metrics in one directory
Documentation
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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
//! The rows of jobs.db that adding, changing, finding and keeping jobs read
//! and write: one statement a step, each a named constant. Claims and their
//! settlements are claim.rs's.

use rusqlite::{Connection, OptionalExtension, Params, params};

use super::values::Kept;
use crate::Result;
use crate::limits::Limit;
use crate::sqlite::sql_error;

/// A due job whose group has no room is parked: its next moves `PARKED_BY`
/// later, past every time a job may have, so that the next claim does not meet
/// it again, and moves back when its group frees a place.
///
/// The parked index holds the rows from `PARKED_FROM` on, and a query reaches
/// it only by naming that bound as the index does, in its digits: the primary
/// key's range looks as good to a planner without statistics, and walks the
/// parked rows of every group.
pub(crate) const PARKED_BY: i64 = 1 << 60;
pub(crate) const PARKED_FROM: i64 = 1 << 59;
macro_rules! parked_from {
    () => {
        "576460752303423488"
    };
}

/// When a job is due: its next, or a parked job's before it was parked.
pub(crate) fn due_of(next: i64) -> i64 {
    if next >= PARKED_FROM { next - PARKED_BY } else { next }
}

const REGISTER_QUEUE: &str =
    "insert into _tinystore_jobs_queues (name, kind) values (?1, ?2) on conflict (name) do nothing";
const QUEUE_NAMED: &str = "select id, kind, in_group from _tinystore_jobs_queues where name = ?1";
const COUNT_WAITING: &str = "select waiting from _tinystore_jobs_queues where id = ?1";
const KEEP_IN_GROUP: &str = "update _tinystore_jobs_queues set in_group = ?2 where id = ?1";
const UNPARK_JOBS: &str =
    concat!("update _tinystore_jobs set next = next - ?2 where queue = ?1 and next >= ", parked_from!());
const UNPARK_KEYS: &str =
    concat!("update _tinystore_jobs_keys set next = next - ?2 where queue = ?1 and next >= ", parked_from!());
const NEXT_ID: &str = "update _tinystore_jobs_meta set value = value + 1 where name = 'ids'";
/// The id `NEXT_ID` took, read back by a select rather than `returning`,
/// which costs every add a microsecond more.
const IDS: &str = "select value from _tinystore_jobs_meta where name = 'ids'";
/// A lease the file still holds at open belongs to a process that died: its
/// attempt counts, and its job is due again at once.
const COUNT_DEAD_ATTEMPTS: &str = "update _tinystore_jobs set attempt = l.attempt from _tinystore_jobs_leases l
    where _tinystore_jobs.queue = l.queue and _tinystore_jobs.next = l.next and _tinystore_jobs.id = l.id";
const DROP_DEAD_LEASES: &str = "delete from _tinystore_jobs_leases";
/// A lease that ended without a settlement, of a job a write changes: its
/// attempt counts as a dead process's does.
const COUNT_ENDED_ATTEMPT: &str = "update _tinystore_jobs set attempt = l.attempt from _tinystore_jobs_leases l
    where l.id = ?1 and _tinystore_jobs.queue = l.queue and _tinystore_jobs.next = l.next and _tinystore_jobs.id = l.id";

const JOB_BY_KEY: &str = "select j.next, j.id, j.again, j.repeat, j.spill
    from _tinystore_jobs_keys k join _tinystore_jobs j on j.queue = k.queue and j.next = k.next and j.id = k.id
    where k.queue = ?1 and k.key = ?2";
const LEASE_HELD: &str = "select 1 from _tinystore_jobs_leases where id = ?1 and until > ?2";
const FAILED_KEY: &str = "select 1 from _tinystore_jobs_failed where queue = ?1 and key = ?2";
const DONE_KEY: &str = "select 1 from _tinystore_jobs_done where queue = ?1 and key = ?2 and until > ?3";

const INSERT_JOB: &str = "insert into _tinystore_jobs (queue, next, id, key, at, attempt, repeat, value, spill, grp)
    values (?1, ?2, ?3, ?4, ?2, 0, ?5, ?6, ?7, ?8)";
const INSERT_SPILLED: &str = "insert into _tinystore_jobs_spilled (id, value) values (?1, ?2)";
const DELETE_SPILLED: &str = "delete from _tinystore_jobs_spilled where id = ?1";
/// A key's row: where its job lies, replacing a key a job left behind.
const INSERT_KEY: &str = "insert into _tinystore_jobs_keys (queue, key, next, id) values (?1, ?2, ?3, ?4)
    on conflict (queue, key) do update set next = excluded.next, id = excluded.id";
const MOVE_KEY: &str = "update _tinystore_jobs_keys set next = ?3 where queue = ?1 and key = ?2";
const DROP_KEY: &str = "delete from _tinystore_jobs_keys where queue = ?1 and key = ?2";
/// A set's job made new: its value and time, its attempts from one, its
/// retry and error gone; the times of its last run stay, and so does a repeat
/// or a group the set does not name.
const RENEW_JOB: &str = "update _tinystore_jobs
    set next = ?4, at = ?4, attempt = 0, again = null, error = null, value = ?5, spill = ?6,
        repeat = coalesce(?7, repeat), grp = coalesce(?8, grp)
    where queue = ?1 and next = ?2 and id = ?3";
/// An update's job: its value, and what else the update named.
const UPDATE_JOB: &str = "update _tinystore_jobs
    set next = ?4, at = ?4, value = ?5, spill = ?6, repeat = coalesce(?7, repeat), grp = coalesce(?8, grp)
    where queue = ?1 and next = ?2 and id = ?3";
/// A set while the job runs: the value and repeat its next run takes, and when
/// that run is, which its settlement reads.
const ASK_AGAIN: &str = "update _tinystore_jobs
    set again = ?4, value = ?5, spill = ?6, repeat = coalesce(?7, repeat), grp = coalesce(?8, grp)
    where queue = ?1 and next = ?2 and id = ?3";
const DROP_FAILED: &str = "delete from _tinystore_jobs_failed where queue = ?1 and key = ?2 returning spill, grp";
const CANCEL_JOB: &str = "delete from _tinystore_jobs where (queue, next, id) in (
        select k.queue, k.next, k.id from _tinystore_jobs_keys k where k.queue = ?1 and k.key = ?2)
    returning id, spill, next, grp";
const DROP_LEASE: &str = "delete from _tinystore_jobs_leases where id = ?1";
const DROP_STEPS: &str = "delete from _tinystore_jobs_steps where job = ?1";
const FIRST_PARKED: &str = concat!(
    "select next, id, key from _tinystore_jobs indexed by _tinystore_jobs_parked
    where queue = ?1 and grp = ?2 and next >= ",
    parked_from!(),
    " order by next, id limit 1"
);
const MOVE_ROW: &str = "update _tinystore_jobs set next = ?4 where queue = ?1 and next = ?2 and id = ?3";
const MOVE_LEASE: &str = "update _tinystore_jobs_leases set next = ?2 where id = ?1";

/// What a write needs of a job's row.
#[derive(Clone, Debug)]
pub(crate) struct Row {
    pub(crate) next: i64,
    pub(crate) id: i64,
    pub(crate) again: Option<i64>,
    pub(crate) repeat: Option<String>,
    pub(crate) spill: Option<i64>,
}

/// A job a write adds.
#[derive(Debug)]
pub(crate) struct NewJob<'a> {
    pub(crate) queue: i64,
    pub(crate) id: i64,
    pub(crate) key: Option<&'a str>,
    pub(crate) at: i64,
    pub(crate) repeat: Option<&'a str>,
    pub(crate) group: Option<&'a str>,
    pub(crate) value: &'a Kept,
}

/// What a write gives a job that is there: its value, its time and repeat,
/// and its group.
#[derive(Debug)]
pub(crate) struct Change<'a> {
    pub(crate) next: i64,
    pub(crate) repeat: Option<&'a str>,
    pub(crate) group: Option<&'a str>,
    pub(crate) value: &'a Kept,
}

/// The id and kind of the queue `name`, if it was registered.
#[cfg(feature = "replication")]
pub(crate) fn find_queue(c: &Connection, name: &str) -> Result<Option<(i64, String)>> {
    c.prepare_cached(QUEUE_NAMED)
        .and_then(|mut select| select.query_row([name], |row| Ok((row.get(0)?, row.get(1)?))).optional())
        .map_err(|error| sql_error("a queue's registration", error))
}

/// Registers a queue on its first open, and answers its id, its kind and the
/// group bound it was last opened with.
pub(crate) fn queue(c: &Connection, name: &str, kind: &str) -> Result<(i64, String, i64)> {
    let named = || {
        c.prepare_cached(QUEUE_NAMED)
            .and_then(|mut select| {
                select.query_row([name], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?))).optional()
            })
            .map_err(|error| sql_error("a queue's registration", error))
    };
    // Found before it is made, so that a copy, which writes nothing, opens a
    // queue its home made.
    if let Some(found) = named()? {
        return Ok(found);
    }
    execute(c, REGISTER_QUEUE, params![name, kind], "a queue's registration")?;
    named()?.ok_or_else(|| crate::Error::internal("a queue registered and not found"))
}

/// Keeps the group bound a queue opens with, and gives back the jobs another
/// one parked, since only a settlement in their group would give them back
/// otherwise.
pub(crate) fn keep_group_bound(c: &Connection, queue: i64, was: i64, is: i64) -> Result<()> {
    if was == is {
        return Ok(());
    }
    execute(c, UNPARK_JOBS, params![queue, PARKED_BY], "the jobs another group bound parked")?;
    execute(c, UNPARK_KEYS, params![queue, PARKED_BY], "the jobs another group bound parked")?;
    execute(c, KEEP_IN_GROUP, params![queue, is], "a queue's group bound").map(drop)
}

/// The next job id, taken by the write that inserts its row: it commits or
/// rolls back with the row, so that an id is never given twice, not after a
/// crash either, and no write waits for another to reserve it one.
pub(crate) fn next_id(c: &Connection) -> Result<i64> {
    execute(c, NEXT_ID, [], "the next job id")?;
    c.prepare_cached(IDS)
        .and_then(|mut select| select.query_row([], |row| row.get(0)))
        .map_err(|error| sql_error("the next job id", error))
}

pub(crate) fn end_dead_leases(c: &Connection) -> Result<()> {
    execute(c, COUNT_DEAD_ATTEMPTS, [], "the leases of a process that died")?;
    execute(c, DROP_DEAD_LEASES, [], "the leases of a process that died").map(drop)
}

pub(crate) fn job_by_key(c: &Connection, queue: i64, key: &str) -> Result<Option<Row>> {
    c.prepare_cached(JOB_BY_KEY)
        .and_then(|mut select| {
            select
                .query_row(params![queue, key], |row| {
                    Ok(Row {
                        next: row.get(0)?,
                        id: row.get(1)?,
                        again: row.get(2)?,
                        repeat: row.get(3)?,
                        spill: row.get(4)?,
                    })
                })
                .optional()
        })
        .map_err(|error| sql_error("the job under an id", error))
}

/// Whether a claim holds the job at `now`; a lease that has ended holds
/// nothing, and the next claim takes the job.
pub(crate) fn lease_held(c: &Connection, id: i64, now: i64) -> Result<bool> {
    exists(c, LEASE_HELD, params![id, now])
}

pub(crate) fn failed_key(c: &Connection, queue: i64, key: &str) -> Result<bool> {
    exists(c, FAILED_KEY, params![queue, key])
}

pub(crate) fn done_key(c: &Connection, queue: i64, key: &str, now: i64) -> Result<bool> {
    exists(c, DONE_KEY, params![queue, key, now])
}

/// Refuses a job past the queue's `max_waiting`. The count is the queue's row,
/// which triggers keep, so that a transaction sees its own adds.
pub(crate) fn check_room(c: &Connection, queue: i64, max_waiting: u64) -> Result<()> {
    let waiting: i64 = c
        .prepare_cached(COUNT_WAITING)
        .and_then(|mut select| select.query_row([queue], |row| row.get(0)))
        .map_err(|error| sql_error("the jobs a queue holds", error))?;
    let waiting = u64::try_from(waiting).unwrap_or(0);
    if waiting >= max_waiting {
        let held = Limit { name: "waiting jobs", bound: max_waiting };
        return Err(held.refuse(waiting + 1, format!("the queue holds {waiting} jobs, its max_waiting")));
    }
    Ok(())
}

/// Adds a job's row, its value spilled to a row of its own past the inline
/// bound, and its key where it has one.
pub(crate) fn insert(c: &Connection, job: &NewJob<'_>) -> Result<()> {
    let spill = spill(c, job.id, job.value)?;
    let params = params![job.queue, job.at, job.id, job.key, job.repeat, job.value.inline(), spill, job.group];
    execute(c, INSERT_JOB, params, "a job's row")?;
    if let Some(key) = job.key {
        execute(c, INSERT_KEY, params![job.queue, key, job.at, job.id], "a job's id")?;
    }
    Ok(())
}

/// Makes the job a set names new: its value, time, repeat and group, its
/// attempts from one, its steps gone with the run they belonged to. No live
/// lease holds it.
pub(crate) fn renew(c: &Connection, queue: i64, key: &str, there: &Row, change: &Change<'_>) -> Result<()> {
    end_lease(c, there.id)?;
    rewrite(c, queue, there, change, (RENEW_JOB, "a set's job"))?;
    execute(c, DROP_STEPS, [there.id], "a set's job: the steps of its last run")?;
    follow(c, queue, key, there.next, change.next)
}

/// Gives a job that is not running what an update names; a repeat or a group
/// left out stays as it was. No live lease holds it. The steps an earlier
/// attempt kept go with the value they were kept for, as a set's do.
pub(crate) fn update(c: &Connection, queue: i64, key: &str, there: &Row, change: &Change<'_>) -> Result<()> {
    end_lease(c, there.id)?;
    rewrite(c, queue, there, change, (UPDATE_JOB, "an update's job"))?;
    execute(c, DROP_STEPS, [there.id], "an update's job: the steps kept for its old value")?;
    follow(c, queue, key, there.next, change.next)
}

/// Ends the lease of a job whose lease ended before a write changed it, its
/// attempt counted: its holder may still settle, and would settle the job as
/// the write left it, deleting a change it was never given.
fn end_lease(c: &Connection, id: i64) -> Result<()> {
    execute(c, COUNT_ENDED_ATTEMPT, [id], "the lease a changed job outlived")?;
    execute(c, DROP_LEASE, [id], "the lease a changed job outlived").map(drop)
}

/// Writes what a change names over the job that is there with `statement`,
/// its value spilled anew; `what` names the write in an error.
fn rewrite(
    c: &Connection,
    queue: i64,
    there: &Row,
    change: &Change<'_>,
    (statement, what): (&str, &str),
) -> Result<()> {
    drop_spill(c, there.spill)?;
    let spill = spill(c, there.id, change.value)?;
    let params =
        params![queue, there.next, there.id, change.next, change.value.inline(), spill, change.repeat, change.group];
    execute(c, statement, params, what).map(drop)
}

/// Asks one run more of a job that runs: its next run takes the new value and
/// repeat, at `again`, or at the repeat's next time when that is none.
pub(crate) fn ask_again(
    c: &Connection,
    queue: i64,
    there: &Row,
    again: Option<i64>,
    change: &Change<'_>,
) -> Result<()> {
    drop_spill(c, there.spill)?;
    let spill = spill(c, there.id, change.value)?;
    let params = params![queue, there.next, there.id, again, change.value.inline(), spill, change.repeat, change.group];
    execute(c, ASK_AGAIN, params, "a set of a running job").map(drop)
}

/// Deletes the failed job under a key and its spilled value, and answers its
/// group when there was one.
pub(crate) fn drop_failed(c: &Connection, queue: i64, key: &str) -> Result<Option<Option<String>>> {
    let dropped: Option<(Option<i64>, Option<String>)> = c
        .prepare_cached(DROP_FAILED)
        .and_then(|mut delete| delete.query_row(params![queue, key], |row| Ok((row.get(0)?, row.get(1)?))).optional())
        .map_err(|error| sql_error("a failed job", error))?;
    let Some((spilled, group)) = dropped else {
        return Ok(None);
    };
    drop_spill(c, spilled)?;
    Ok(Some(group))
}

/// A job a cancel took from the queue's rows.
#[derive(Debug)]
pub(crate) struct Taken {
    pub(crate) id: i64,
    pub(crate) group: Option<String>,
    /// Whether it held, or was due to take, its group's place.
    pub(crate) placed: bool,
}

/// Deletes the job under a key, waiting or running, with its lease, its
/// spilled value and its key.
pub(crate) fn cancel(c: &Connection, queue: i64, key: &str) -> Result<Option<Taken>> {
    let taken: Option<(i64, Option<i64>, i64, Option<String>)> = c
        .prepare_cached(CANCEL_JOB)
        .and_then(|mut delete| {
            delete
                .query_row(params![queue, key], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)))
                .optional()
        })
        .map_err(|error| sql_error("a cancel", error))?;
    let Some((id, spilled, next, group)) = taken else {
        return Ok(None);
    };
    execute(c, DROP_LEASE, [id], "a cancel: the job's lease")?;
    drop_spill(c, spilled)?;
    execute(c, DROP_KEY, params![queue, key], "a cancel: the job's id")?;
    Ok(Some(Taken { id, group, placed: next < PARKED_FROM }))
}

/// Gives the first parked job of a group back its time, once the group has
/// freed a place.
pub(crate) fn unpark_one(c: &Connection, queue: i64, group: &str) -> Result<()> {
    let first: Option<(i64, i64, Option<String>)> = c
        .prepare_cached(FIRST_PARKED)
        .and_then(|mut select| {
            select.query_row(params![queue, group], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?))).optional()
        })
        .map_err(|error| sql_error("a group's first parked job", error))?;
    let Some((next, id, key)) = first else {
        return Ok(());
    };
    move_to(c, queue, (next, id, key.as_deref()), next - PARKED_BY)
}

/// Moves a job's row to `to`, with its key and a lease it outlived.
pub(crate) fn move_to(c: &Connection, queue: i64, (next, id, key): (i64, i64, Option<&str>), to: i64) -> Result<()> {
    execute(c, MOVE_ROW, params![queue, next, id, to], "a job's move")?;
    execute(c, MOVE_LEASE, params![id, to], "a job's move: its lease")?;
    match key {
        Some(key) => follow(c, queue, key, next, to),
        None => Ok(()),
    }
}

/// Moves a job's key along when the job's row moves.
pub(crate) fn follow(c: &Connection, queue: i64, key: &str, from: i64, to: i64) -> Result<()> {
    if from == to {
        return Ok(());
    }
    execute(c, MOVE_KEY, params![queue, key, to], "a job's id").map(drop)
}

pub(crate) fn drop_spill(c: &Connection, spilled: Option<i64>) -> Result<()> {
    match spilled {
        Some(id) => execute(c, DELETE_SPILLED, [id], "a large value").map(drop),
        None => Ok(()),
    }
}

pub(crate) fn drop_steps(c: &Connection, job: i64) -> Result<()> {
    execute(c, DROP_STEPS, [job], "the steps of a run that ended").map(drop)
}

/// Writes a value past the inline bound to a row of its own under the job's
/// id, and answers that id.
fn spill(c: &Connection, id: i64, value: &Kept) -> Result<Option<i64>> {
    match value {
        Kept::Inline(_) => Ok(None),
        Kept::Spilled(bytes) => {
            execute(c, INSERT_SPILLED, params![id, bytes], "a large value")?;
            Ok(Some(id))
        }
    }
}

pub(crate) use crate::sqlite::execute_cached as execute;

pub(crate) fn exists(c: &Connection, sql: &str, params: impl Params) -> Result<bool> {
    c.prepare_cached(sql).and_then(|mut select| select.exists(params)).map_err(|error| sql_error("a read", error))
}