menger-notes 0.9.0

menger's notes service — notes on their own API and file, every write a revision, the organization's roles held by the gate
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
//! **The notes store** — the notes, in a SQLite file of the service's
//! own, `notes.db`: never the tickets file (V2-1: the file is opened by the
//! tickets service alone).
//!
//! A note's body is a **Yjs CRDT** (V2-29's `pairing`, the owner: *"live
//! co editting … we should keep all changes over time too, so we could
//! replay how it got built. with the ability to squash, permission
//! gated"*). **Stored** in two tables:
//!
//! - `docs` — a row per note as it is now: its organization and title,
//!   the markdown derived from its CRDT (`text`, what `get`, `list`, search,
//!   agents and image references read), its revision (the last change's
//!   `seq`), who made it and who wrote it last, and a snapshot of its CRDT
//!   (`state` as of `state_seq`) so a load applies only what came after.
//!   `deleted_at` set once deleted: it reads as none.
//! - `doc_log` — **every change, forever until squashed**: a row per CRDT
//!   update (`update`, the Yjs v1 bytes as the writer sent or the service
//!   made them), per rename, per delete, with who (`by`, `principal`) and
//!   when (`at`, unix milliseconds); `seq` counts them per note. A squash
//!   ([`crate::crdt`]) replaces the rows up to a moment with one `snapshot`
//!   row holding who wrote what as its `authors`.
//!
//! NOTES-5: and `note_marks`, a row per mark on a note's text ([`crate::marks`]).
//!
//! How the body is written, replayed and squashed is [`crate::crdt`]'s; who
//! is on a note is [`crate::presence`]'s. Whether a caller may read or
//! write a note is the gate's word on its organization, asked by the
//! activation ([`crate::seam`]). Every write is said on the channel
//! ([`NotesStore::subscribe`]) for `watch`.
//!
//! One connection behind a mutex; every read and write off the runtime.

use crate::events::{Building, Note, Present, Slot, Thread, Mark};
use rusqlite::{params, Connection, OptionalExtension};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use tokio::sync::broadcast;

/// The tables — their names kept from before NOTES-3, so the release before
/// reads the same file. The table `docs`'s `seq` orders the list (newest made first) and is a
/// page's cursor through its id.
pub const TABLES: &str = "
        CREATE TABLE IF NOT EXISTS docs (
            seq         INTEGER PRIMARY KEY AUTOINCREMENT,
            id          TEXT NOT NULL UNIQUE,
            org         TEXT NOT NULL,
            title       TEXT NOT NULL,
            text        TEXT NOT NULL,
            revision    INTEGER NOT NULL,
            created_at  INTEGER NOT NULL,
            created_by  TEXT NOT NULL,
            at          INTEGER NOT NULL,
            by          TEXT NOT NULL,
            state       BLOB NOT NULL,
            state_seq   INTEGER NOT NULL,
            deleted_at  INTEGER
        );
        CREATE TABLE IF NOT EXISTS doc_log (
            id         TEXT NOT NULL,
            seq        INTEGER NOT NULL,
            kind       TEXT NOT NULL,
            update_v1  BLOB,
            title      TEXT,
            at         INTEGER NOT NULL,
            by         TEXT NOT NULL,
            principal  TEXT NOT NULL,
            bytes      INTEGER NOT NULL,
            authors    TEXT,
            PRIMARY KEY (id, seq)
        );
    ";

/// How many writes an open watch may fall behind before it hears `lagged`.
pub const CHANNEL: usize = 4096;

/// A write, as the channel says it to every open watch.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Change {
    /// A note made (body included).
    Created(Note),
    /// A CRDT update applied: the note after it (body included), the
    /// update's bytes (base64), its `seq`, and the presence session it came
    /// from, when it said.
    Updated { doc: Note, update: String, seq: u32, session: Option<String> },
    Renamed(Note),
    Deleted { id: String, org: String, at: i64, by: String },
    /// The changes up to `until` collapsed into one snapshot.
    Squashed { id: String, org: String, until: u32, removed: u32, at: i64, by: String },
    /// Someone is on a note, or moved their caret.
    Present { org: String, present: Present },
    /// Someone left a note.
    Left { id: String, org: String, session: String, client: Option<u64> },
    /// V2-30: a question asked on a range, a reply under it, a thread resolved (or opened again).
    Asked { org: String, thread: Thread },
    Replied { org: String, thread: Thread },
    Resolved { org: String, thread: Thread },
    /// NOTES-4: a slot filled or emptied, a build said, props merged (by `by`) — the slot whole.
    SlotChanged { org: String, slot: Slot },
    BuildingChanged { org: String, slot: Slot },
    PropsChanged { org: String, slot: Slot, by: String },
    /// NOTES-5: a mark made or changed (whole), or taken off.
    Marked { org: String, mark: Mark },
    Unmarked { id: String, org: String, mark: String },
}

impl Change {
    /// The note it is of.
    pub fn id(&self) -> &str {
        match self {
            Change::Created(d) | Change::Renamed(d) | Change::Updated { doc: d, .. } => &d.id,
            Change::Deleted { id, .. } | Change::Squashed { id, .. } | Change::Left { id, .. } => id,
            Change::Present { present, .. } => &present.id,
            Change::Asked { thread, .. } | Change::Replied { thread, .. } | Change::Resolved { thread, .. } => &thread.id,
            Change::SlotChanged { slot, .. } | Change::BuildingChanged { slot, .. } | Change::PropsChanged { slot, .. } => &slot.id,
            Change::Marked { mark, .. } => &mark.id,
            Change::Unmarked { id, .. } => id,
        }
    }

    /// The organization that note is in.
    pub fn org(&self) -> &str {
        match self {
            Change::Created(d) | Change::Renamed(d) | Change::Updated { doc: d, .. } => &d.org,
            Change::Deleted { org, .. } | Change::Squashed { org, .. } | Change::Present { org, .. } | Change::Left { org, .. } => org,
            Change::Asked { org, .. } | Change::Replied { org, .. } | Change::Resolved { org, .. } => org,
            Change::SlotChanged { org, .. } | Change::BuildingChanged { org, .. } | Change::PropsChanged { org, .. } => org,
            Change::Marked { org, .. } | Change::Unmarked { org, .. } => org,
        }
    }
}

/// Why the store did not.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum StoreError {
    /// No note of that id (or a deleted one).
    NotFound(String),
    /// The note has no change at that `seq` (or it was squashed).
    NoRevision(String, u32),
    /// V2-30: no thread of that id on the note.
    NoThread(String),
    /// NOTES-5: no mark of that id on the note.
    NoMark(String),
    /// NOTES-5: the mark places no component, so it has no props.
    NoComponent(String),
    /// V2-30: a range that is not one of the text.
    BadRange(String),
    /// The update or state is not one the CRDT reads.
    BadUpdate(String),
    /// The quota refused the write (its words).
    Quota(String),
    /// V2-39: the quota refused it, with its reason (`over_allowance`, …).
    Allowance(crate::quota::Refused),
    /// NOTES-4: what a write would make is past its cap (its words).
    TooLarge(String),
    /// The file.
    Db(String),
}

impl std::fmt::Display for StoreError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            StoreError::NotFound(id) => write!(f, "no note {id}"),
            StoreError::NoRevision(id, r) => write!(f, "note {id} has no change {r}"),
            StoreError::NoThread(t) => write!(f, "no thread {t}"),
            StoreError::NoMark(m) => write!(f, "no mark {m}"),
            StoreError::NoComponent(m) => write!(f, "mark {m} places no component"),
            StoreError::BadRange(e) => write!(f, "not a range of the text: {e}"),
            StoreError::BadUpdate(e) => write!(f, "not a Yjs v1 update: {e}"),
            StoreError::Quota(e) => write!(f, "{e}"),
            StoreError::Allowance(r) => write!(f, "{}", r.message),
            StoreError::TooLarge(e) => write!(f, "{e}"),
            StoreError::Db(e) => write!(f, "the notes file: {e}"),
        }
    }
}

impl std::error::Error for StoreError {}

impl From<rusqlite::Error> for StoreError {
    fn from(e: rusqlite::Error) -> Self {
        StoreError::Db(e.to_string())
    }
}

/// What a page of `list` asks.
#[derive(Debug, Clone, Default)]
pub struct Listing {
    /// The organizations whose notes may be listed (`None`: every one).
    pub orgs: Option<Vec<String>>,
    /// Words the title holds, case-blind.
    pub query: Option<String>,
    /// The page's size.
    pub limit: usize,
    /// The id of the last row of the page before.
    pub after: Option<String>,
}

/// A page of `list`: its rows, the cursor past it, how many more match.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Page {
    pub rows: Vec<Note>,
    pub next: Option<String>,
    pub remaining: u64,
}

/// The file, open, with the CRDTs it has loaded and who is on them.
pub struct NotesStore {
    conn: Mutex<Connection>,
    path: PathBuf,
    changes: broadcast::Sender<Change>,
    /// Each loaded note's CRDT — loaded on its first write or sync, kept.
    pub(crate) loaded: Mutex<HashMap<String, Arc<Mutex<yrs::Doc>>>>,
    /// Who is on which note ([`crate::presence`]).
    pub(crate) presence: crate::presence::Presence,
    /// The meter every byte written is reserved against (V2-31's).
    pub(crate) quota: std::sync::RwLock<Arc<dyn crate::quota::Quota>>,
    /// NOTES-4: the build under way in each slot ([`crate::slot`]) — memory only.
    pub(crate) builds: Mutex<HashMap<String, Building>>,
}

impl std::fmt::Debug for NotesStore {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("NotesStore").field("path", &self.path).finish()
    }
}

/// Now, in unix seconds.
pub(crate) fn now() -> i64 {
    now_ms() / 1000
}

/// Now, in unix milliseconds — a log row's `at`.
pub(crate) fn now_ms() -> i64 {
    std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_millis() as i64)
}

/// The columns a [`Note`] is read from, in [`doc_of`]'s order.
pub(crate) const DOC_COLUMNS: &str = "id, org, title, text, revision, created_at, created_by, at, by";

pub(crate) fn doc_of(r: &rusqlite::Row<'_>) -> rusqlite::Result<Note> {
    let body: String = r.get(3)?;
    Ok(Note {
        id: r.get(0)?,
        org: r.get(1)?,
        title: r.get(2)?,
        bytes: body.len() as u64,
        body: Some(body),
        revision: r.get(4)?,
        created_at: r.get(5)?,
        created_by: r.get(6)?,
        at: r.get(7)?,
        by: r.get(8)?,
    })
}

/// The live note `id`, body and all, in `conn`.
pub(crate) fn live_doc(conn: &Connection, id: &str) -> Result<Note, StoreError> {
    conn.query_row(&format!("SELECT {DOC_COLUMNS} FROM docs WHERE id = ?1 AND deleted_at IS NULL"), [id], doc_of)
        .optional()?
        .ok_or_else(|| StoreError::NotFound(id.to_string()))
}

/// One row of the log, as it is written.
pub(crate) struct LogRow<'a> {
    pub id: &'a str,
    pub seq: u32,
    pub kind: &'a str,
    pub update: Option<&'a [u8]>,
    pub title: Option<&'a str>,
    pub at: i64,
    pub by: &'a str,
    pub principal: &'a str,
    pub authors: Option<&'a str>,
}

/// Appends `row` to the log.
pub(crate) fn log(tx: &Connection, row: LogRow<'_>) -> Result<(), StoreError> {
    tx.execute(
        "INSERT INTO doc_log (id, seq, kind, update_v1, title, at, by, principal, bytes, authors) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
        params![row.id, row.seq, row.kind, row.update, row.title, row.at, row.by, row.principal, row.update.map_or(0, |u| u.len() as i64), row.authors],
    )?;
    Ok(())
}

impl NotesStore {
    /// The store on `path`, made if missing; a file without the tables
    /// gains them, empty — once; on every later open a no-op. Every write
    /// allowed ([`crate::quota::AllowAll`]) until a meter is set.
    pub fn open(path: &Path) -> Result<Self, StoreError> {
        if let Some(dir) = path.parent().filter(|d| !d.as_os_str().is_empty()) {
            std::fs::create_dir_all(dir).map_err(|e| StoreError::Db(format!("{}: {e}", dir.display())))?;
        }
        let conn = Connection::open(path)?;
        conn.execute_batch("PRAGMA journal_mode = WAL; PRAGMA synchronous = NORMAL;")?;
        conn.execute_batch(TABLES)?;
        conn.execute_batch(crate::threads::TABLES)?;
        conn.execute_batch(crate::slot::TABLES)?;
        conn.execute_batch(crate::marks::TABLES)?;
        Ok(Self {
            conn: Mutex::new(conn),
            path: path.to_path_buf(),
            changes: broadcast::channel(CHANNEL).0,
            loaded: Mutex::new(HashMap::new()),
            presence: crate::presence::Presence::default(),
            quota: std::sync::RwLock::new(Arc::new(crate::quota::AllowAll)),
            builds: Mutex::new(HashMap::new()),
        })
    }

    /// The same store, its writes reserved against `quota` (V2-31's meter).
    pub fn metered(self, quota: Arc<dyn crate::quota::Quota>) -> Self {
        self.set_quota(quota);
        self
    }

    /// V2-31: its writes reserved against `quota` from now on — the builder
    /// sets the quota service's meter on a store already shared.
    pub fn set_quota(&self, quota: Arc<dyn crate::quota::Quota>) {
        *self.quota.write().unwrap_or_else(|p| p.into_inner()) = quota;
    }

    /// The meter now.
    pub(crate) fn quota(&self) -> Arc<dyn crate::quota::Quota> {
        self.quota.read().unwrap_or_else(|p| p.into_inner()).clone()
    }

    /// V2-31: what each principal keeps, as the quota service counts it —
    /// **the update log as stored**: every change's bytes its writer's, and
    /// a squash's snapshot shared among its authors by what each wrote
    /// ([`crate::events::shares`]) — so a squash shrinks it; `count` the
    /// notes they made (a `create` change, or, folded into a snapshot,
    /// its earliest author's). (principal, count, bytes), by principal.
    pub async fn usage_by_principal(self: &Arc<Self>) -> Result<Vec<(String, u64, u64)>, StoreError> {
        let rows = self.usage_rows(false).await?;
        Ok(rows.into_iter().map(|((p, _), (n, b))| (p, n, b)).collect())
    }

    /// V2-70: [`Self::usage_by_principal`] by the UTC day each change was
    /// kept (days since 1970-01-01; a snapshot's shares on its own day):
    /// (principal, day, count, bytes) — what the quota service's history is
    /// backfilled from; summed per principal, the same.
    pub async fn usage_daily(self: &Arc<Self>) -> Result<Vec<(String, i64, u64, u64)>, StoreError> {
        let rows = self.usage_rows(true).await?;
        Ok(rows.into_iter().map(|((p, d), (n, b))| (p, d, n, b)).collect())
    }

    /// What each principal keeps, by (principal, day — 0 unless `by_day`).
    async fn usage_rows(self: &Arc<Self>, by_day: bool) -> Result<std::collections::BTreeMap<(String, i64), (u64, u64)>, StoreError> {
        self.blocking(move |s| {
            let conn = s.lock();
            let mut stmt = conn.prepare("SELECT kind, principal, bytes, authors, at FROM doc_log")?;
            let rows = stmt.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?, r.get::<_, i64>(2)?, r.get::<_, Option<String>>(3)?, r.get::<_, i64>(4)?)))?;
            let mut out: std::collections::BTreeMap<(String, i64), (u64, u64)> = std::collections::BTreeMap::new();
            for row in rows {
                let (kind, principal, bytes, authors, at) = row?;
                let day = if by_day { at.div_euclid(86_400_000) } else { 0 };
                match (kind.as_str(), authors) {
                    ("snapshot", Some(a)) => {
                        let authors: Vec<crate::events::Author> = serde_json::from_str(&a).unwrap_or_default();
                        if let Some(first) = authors.iter().min_by_key(|a| a.first) {
                            out.entry((first.principal.clone(), day)).or_default().0 += 1;
                        }
                        for (who, n) in crate::events::shares(bytes.max(0) as u64, &authors) {
                            out.entry((who, day)).or_default().1 += n;
                        }
                    }
                    (k, _) => {
                        let e = out.entry((principal, day)).or_default();
                        e.0 += u64::from(k == "create");
                        e.1 += bytes.max(0) as u64;
                    }
                }
            }
            Ok(out)
        })
        .await
    }

    /// The file it keeps.
    pub fn path(&self) -> &Path {
        &self.path
    }

    pub(crate) fn lock(&self) -> std::sync::MutexGuard<'_, Connection> {
        self.conn.lock().unwrap_or_else(|p| p.into_inner())
    }

    /// Off the runtime, with the store.
    pub(crate) async fn blocking<T: Send + 'static>(self: &Arc<Self>, work: impl FnOnce(&Arc<NotesStore>) -> Result<T, StoreError> + Send + 'static) -> Result<T, StoreError> {
        let store = Arc::clone(self);
        tokio::task::spawn_blocking(move || work(&store)).await.map_err(|e| StoreError::Db(format!("notes task failed: {e}")))?
    }

    /// Every write from now on, as it is committed.
    pub fn subscribe(&self) -> broadcast::Receiver<Change> {
        self.changes.subscribe()
    }

    /// Say `change` to every open watch.
    pub(crate) fn said(&self, change: Change) {
        let _ = self.changes.send(change);
    }

    /// The note `id` as it is now, body and all; [`StoreError::NotFound`]
    /// for none (or a deleted one).
    pub async fn get(self: &Arc<Self>, id: &str) -> Result<Note, StoreError> {
        let id = id.to_string();
        self.blocking(move |s| live_doc(&s.lock(), &id)).await
    }

    /// A page of the notes `ask` admits, newest made first, without
    /// their bodies.
    pub async fn list(self: &Arc<Self>, ask: Listing) -> Result<Page, StoreError> {
        self.blocking(move |s| {
            let conn = s.lock();
            let mut sql = format!("SELECT {DOC_COLUMNS}, seq FROM docs WHERE deleted_at IS NULL");
            let mut args: Vec<rusqlite::types::Value> = Vec::new();
            if let Some(orgs) = &ask.orgs {
                if orgs.is_empty() {
                    return Ok(Page { rows: Vec::new(), next: None, remaining: 0 });
                }
                sql.push_str(&format!(" AND org IN ({})", vec!["?"; orgs.len()].join(", ")));
                args.extend(orgs.iter().cloned().map(rusqlite::types::Value::Text));
            }
            for word in ask.query.as_deref().unwrap_or_default().split_whitespace() {
                sql.push_str(" AND instr(lower(title), ?) > 0");
                args.push(rusqlite::types::Value::Text(word.to_lowercase()));
            }
            if let Some(after) = &ask.after {
                let seq: Option<i64> = conn.query_row("SELECT seq FROM docs WHERE id = ?1", [after], |r| r.get(0)).optional()?;
                sql.push_str(" AND seq < ?");
                args.push(rusqlite::types::Value::Integer(seq.unwrap_or(i64::MAX)));
            }
            sql.push_str(" ORDER BY seq DESC");
            let mut stmt = conn.prepare(&sql)?;
            let all = stmt.query_map(rusqlite::params_from_iter(args.iter()), doc_of)?.collect::<Result<Vec<_>, _>>()?;
            let limit = ask.limit.max(1);
            let remaining = all.len().saturating_sub(limit) as u64;
            let rows: Vec<Note> = all.into_iter().take(limit).map(|d| d.summary()).collect();
            let next = (remaining > 0).then(|| rows.last().map(|d| d.id.clone())).flatten();
            Ok(Page { rows, next, remaining })
        })
        .await
    }

    /// Retitles `id` to `title`, by `by` (`principal`): a change more in the log.
    pub async fn rename(self: &Arc<Self>, id: &str, title: &str, by: &str, principal: &str) -> Result<Note, StoreError> {
        let (id, title, by, principal) = (id.to_string(), title.to_string(), by.to_string(), principal.to_string());
        let doc = self
            .blocking(move |s| {
                let conn = s.lock();
                let tx = conn.unchecked_transaction()?;
                let was = live_doc(&tx, &id)?;
                let doc = Note { title, revision: was.revision + 1, at: now(), by, ..was };
                tx.execute("UPDATE docs SET title = ?2, revision = ?3, at = ?4, by = ?5 WHERE id = ?1", params![doc.id, doc.title, doc.revision, doc.at, doc.by])?;
                log(&tx, LogRow { id: &doc.id, seq: doc.revision, kind: "rename", update: None, title: Some(&doc.title), at: now_ms(), by: &doc.by, principal: &principal, authors: None })?;
                tx.commit()?;
                Ok(doc)
            })
            .await?;
        self.said(Change::Renamed(doc.clone()));
        Ok(doc)
    }

    /// Deletes `id`, by `by`: it reads as none from now on; its log, and one
    /// row more saying the delete, stay in the file.
    pub async fn delete(self: &Arc<Self>, id: &str, by: &str, principal: &str) -> Result<(String, i64), StoreError> {
        let (id, by, principal) = (id.to_string(), by.to_string(), principal.to_string());
        let gone = id.clone();
        let (org, at, by) = self
            .blocking(move |s| {
                let conn = s.lock();
                let tx = conn.unchecked_transaction()?;
                let was = live_doc(&tx, &id)?;
                let doc = Note { revision: was.revision + 1, at: now(), by, ..was };
                tx.execute("UPDATE docs SET deleted_at = ?2, revision = ?3, at = ?2, by = ?4 WHERE id = ?1", params![doc.id, doc.at, doc.revision, doc.by])?;
                log(&tx, LogRow { id: &doc.id, seq: doc.revision, kind: "delete", update: None, title: None, at: now_ms(), by: &doc.by, principal: &principal, authors: None })?;
                tx.commit()?;
                s.loaded.lock().unwrap_or_else(|p| p.into_inner()).remove(&id);
                Ok((doc.org, doc.at, doc.by))
            })
            .await?;
        self.said(Change::Deleted { id: gone, org: org.clone(), at, by });
        Ok((org, at))
    }

    /// The organization the live note `id` is in.
    pub async fn org_of(self: &Arc<Self>, id: &str) -> Result<String, StoreError> {
        Ok(self.get(id).await?.org)
    }

    /// How many notes the store keeps — for a log line.
    pub fn count(&self) -> usize {
        self.lock().query_row("SELECT count(*) FROM docs WHERE deleted_at IS NULL", [], |r| r.get::<_, i64>(0)).unwrap_or(0) as usize
    }
}

#[cfg(test)]
mod tests;
#[cfg(test)]
mod tests_slot;