kovlet 0.1.0

Kovlet's portable sync client core: sign-in, sync, merge, outbox and files for Rust, Tauri, Swift and Kotlin apps
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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
//! An open space: write through the core, read the built-in store, files.

use std::collections::BTreeSet;
use std::path::Path;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Weak};
use std::time::Duration;

use serde::de::DeserializeOwned;
use serde_json::Value;
use tokio::sync::{broadcast, watch, Notify};

use crate::engine::session::{BatchFate, Ctl, SpaceSync};
use crate::engine::target::Target;
use crate::engine::{Ctx, Event, SpaceStatus, SubscriptionStatus};
use crate::error::{Error, Result};
use crate::mirror::Mirror;
use crate::protocol::{FileMeta, FileState, JsonMap, Mutation, MAX_MUTATIONS_PER_FRAME};
use crate::query::{evaluate_query, parse_query, query_id, QueryResult, QuerySource};
use crate::schema::Tables;
use crate::store::{PendingMutation, ReadStore, Row, Upload};

/// A handle to an open space. Cheap to clone.
#[derive(Clone)]
pub struct Space {
    pub(crate) ctx: Arc<Ctx>,
    pub(crate) sync: Arc<SpaceSync>,
    reader: Option<Arc<dyn ReadStore>>,
    #[cfg(feature = "sqlite")]
    sqlite: Option<Arc<crate::store::sqlite::SqliteStore>>,
    tables: Arc<Tables>,
    queue: Arc<QueueWorker>,
}

impl Space {
    pub(crate) fn new(
        ctx: Arc<Ctx>,
        sync: Arc<SpaceSync>,
        reader: Option<Arc<dyn ReadStore>>,
        #[cfg(feature = "sqlite")] sqlite: Option<Arc<crate::store::sqlite::SqliteStore>>,
        #[cfg(not(feature = "sqlite"))] _sqlite: Option<()>,
        tables: Tables,
    ) -> Space {
        let queue = QueueWorker::start(&ctx, &sync.target, &sync.shared.space_id);
        Space {
            ctx,
            sync,
            reader,
            #[cfg(feature = "sqlite")]
            sqlite,
            tables: Arc::new(tables),
            queue,
        }
    }

    pub fn id(&self) -> &str {
        &self.sync.shared.space_id
    }

    /// Writes to a table, through the core (write-through: the DataStore gets
    /// the change with `origin: local` before this returns).
    ///
    /// It takes the space's merge lock and calls the DataStore on this
    /// thread, so don't call it while holding a lock your DataStore needs
    /// (e.g. from inside your own storage layer): use [`Space::queue`] there.
    /// With a shared `SqliteStore`, don't call it while holding the
    /// connection's lock (inside your own transaction): use
    /// [`Space::record`] there instead.
    pub fn write(&self, table: &str) -> TableWriter {
        TableWriter { space: self.clone(), table: table.to_string() }
    }

    /// Queues local writes without blocking: safe to call from inside the
    /// app's own storage layer, while it holds its own database locks.
    ///
    /// ```no_run
    /// # fn f(space: &kovlet::Space) -> kovlet::Result<()> {
    /// use kovlet::LocalWrite;
    /// space.queue([
    ///     LocalWrite::upsert("items", "i1", serde_json::json!({"text": "Buy milk"})),
    ///     LocalWrite::delete("items", "i0"),
    /// ])?;
    /// # Ok(()) }
    /// ```
    ///
    /// **Durability.** When `queue` returns `Ok`, every write in the call is
    /// committed to Kovlet's SyncStore in **one** transaction (all or none),
    /// so it survives a crash or restart and syncs afterwards. Each write is
    /// validated (ids, field types) before anything is stored; one bad write
    /// fails the whole call.
    ///
    /// **What runs where.** `queue` only stamps the writes (HLC) and stores
    /// them. It never takes the space's merge lock and **never calls the
    /// [`DataStore`](crate::DataStore) on the caller's thread**. A
    /// Kovlet-owned worker then, in order:
    ///
    /// 1. takes the merge lock (so it serializes with remote changes),
    /// 2. merges the writes into Kovlet's clocks and outbox,
    /// 3. calls `DataStore::apply` with `origin: local`, on the worker's thread,
    /// 4. fires [`Space::changes`] and wakes the session, which sends them.
    ///
    /// **Visibility.** The app's store sees a queued row in step 3, shortly
    /// after `queue` returns, not before: read your own rows from your own
    /// store (which you just wrote), not back through Kovlet. Queued writes
    /// reach the DataStore in queue order. A queued field only lands if no
    /// newer change to it (e.g. a remote one that arrived in between) is
    /// already there. A delete or restore of a row Kovlet doesn't know yet is
    /// dropped. [`Space::queued`] counts writes not yet merged;
    /// [`Space::flush_queue`] merges them now.
    ///
    /// If the DataStore fails, the writes stay queued and the worker retries
    /// with backoff; [`Client::events`](crate::Client::events) reports the error.
    ///
    /// With a shared or lending `SqliteStore`, Kovlet's store *is* your
    /// connection, so `queue` needs it: don't call it while holding that
    /// connection's lock or inside your own transaction (use
    /// [`Space::record`] there instead, which commits with your transaction).
    pub fn queue(&self, writes: impl IntoIterator<Item = LocalWrite>) -> Result<()> {
        let mut out = Vec::new();
        for w in writes {
            out.push(match w {
                LocalWrite::Upsert { table, id, fields } => {
                    let fields = as_object(fields)?;
                    self.check_fields(&table, &fields)?;
                    self.mutation("record", "upsert", Some(&table), &id, Some(fields), None)?
                }
                LocalWrite::Delete { table, id } => self.mutation("record", "delete", Some(&table), &id, None, None)?,
                LocalWrite::Restore { table, id } => {
                    self.mutation("record", "restore", Some(&table), &id, None, None)?
                }
            });
        }
        if out.is_empty() {
            return Ok(());
        }
        self.sync.target.enqueue(&out)?;
        self.queue.kick();
        Ok(())
    }

    /// Writes [`Space::queue`]d and not yet merged into the outbox and the DataStore.
    pub fn queued(&self) -> Result<usize> {
        self.sync.target.queued()
    }

    /// Merges every queued write now, on this thread (the worker does this
    /// on its own; use this before shutdown or in tests). It takes the merge
    /// lock and calls the DataStore: don't call it with your own locks held.
    pub fn flush_queue(&self) -> Result<()> {
        while self.sync.target.drain_queue(QUEUE_CHUNK)? > 0 {}
        Ok(())
    }

    /// Reads a table of the built-in store.
    pub fn table(&self, table: &str) -> TableReader {
        TableReader { space: self.clone(), table: table.to_string() }
    }

    /// Files in this space.
    pub fn files(&self) -> Files {
        Files { space: self.clone() }
    }

    pub fn status(&self) -> SpaceStatus {
        self.sync.status()
    }

    pub fn watch_status(&self) -> watch::Receiver<SpaceStatus> {
        self.sync.shared.status.subscribe()
    }

    /// The tables (and `"$files"`, `"$outbox"`) each change touched.
    pub fn changes(&self) -> broadcast::Receiver<BTreeSet<String>> {
        self.sync.shared.changes.subscribe()
    }

    /// Local writes not yet acknowledged.
    pub fn pending(&self) -> usize {
        self.sync.target.pending().0
    }

    // ------------------------------------------------------------ protocol 2

    /// Subscribes to a query (protocol 2, PROTOCOL.md §17.5):
    ///
    /// ```no_run
    /// # fn f(space: &kovlet::Space) -> kovlet::Result<()> {
    /// let todos = space.subscribe(serde_json::json!({
    ///     "todos": {"$": {"where": {"done": false}, "order": {"createdAt": "desc"}, "limit": 50}, "owner": {}}
    /// }))?;
    /// let result = todos.rows()?; // the nested tree, from the built-in store
    /// # Ok(()) }
    /// ```
    ///
    /// On a space opened with [`Client::open_query`](crate::Client::open_query)
    /// (and always for end users) the server sends exactly the rows the
    /// query matches (and the space's rules let the session view), then keeps
    /// them current; the store holds the union of every subscription's rows.
    /// On a full replica the query runs locally over every row.
    ///
    /// Subscribing is idempotent: the same query (and params) is the same
    /// subscription. Subscriptions persist across restarts, resuming from
    /// their last cursor, until [`LiveQuery::unsubscribe`].
    pub fn subscribe(&self, query: Value) -> Result<LiveQuery> {
        self.subscribe_with(query, None)
    }

    /// [`Space::subscribe`] with `params`: values the space's rules read as
    /// `params` (untrusted, never an identity). They are part of the
    /// subscription's identity.
    pub fn subscribe_with(&self, query: Value, params: Option<JsonMap>) -> Result<LiveQuery> {
        if !query.is_object() || query.as_object().is_some_and(|o| o.is_empty()) {
            return Err(Error::new("invalid_query", "a query is an object keyed by table name, e.g. {\"todos\": {}}"));
        }
        let pv = params.clone().map(Value::Object);
        let sub = query_id(self.id(), &query, pv.as_ref());
        if self.sync.target.add_subscription(&sub, query.clone(), params)? {
            self.sync.shared.control(Ctl::Subscribe(sub.clone()));
        }
        Ok(LiveQuery { space: self.clone(), sub, query })
    }

    /// Every subscription of this space and how far it is.
    pub fn subscriptions(&self) -> Vec<SubscriptionStatus> {
        self.sync
            .target
            .subscriptions()
            .into_iter()
            .filter(|s| s.sub != crate::engine::target::v2::WHOLE_SPACE_SUB)
            .collect()
    }

    /// Runs a query once over the built-in store (offline too), with the
    /// same matcher as the server (shared fixtures). In query mode it sees
    /// only rows some subscription holds or local writes put there.
    pub fn query(&self, query: &Value) -> Result<QueryResult> {
        let reader = self
            .reader
            .clone()
            .ok_or_else(|| Error::config("this space syncs into the app's own store: query it there"))?;
        let mut schema = self.tables.0.clone();
        schema.extend(self.sync.target.schemas());
        let q = parse_query(query, &schema)?;
        let src = BuiltinSource { reader, space: self.clone() };
        Ok(evaluate_query(&q, &src))
    }

    /// Runs a query once on the server (`POST /v1/spaces/{space}/query`),
    /// filtered by the rules for end users. Returns `{"data", "page_info",
    /// "through_seq"}`.
    pub async fn query_remote(&self, query: Value, params: Option<JsonMap>) -> Result<Value> {
        let mut body = serde_json::json!({ "query": query });
        if let Some(p) = params {
            body["params"] = Value::Object(p);
        }
        let (api, path) = (self.ctx.api.clone(), format!("/v1/spaces/{}/query", crate::api::seg(self.id())));
        let fut: crate::auth::BoxFuture<Result<Value>> =
            Box::pin(async move { api.json("POST", &path, Some(&body)).await });
        self.ctx.handle.spawn(fut).await.map_err(|e| Error::new("internal", format!("task failed: {e}")))?
    }

    /// Writes rows all or nothing (ADR 0021 §6): an atomic batch the server
    /// validates (schema, rules, unique values, quota) and applies together,
    /// or rejects together. The writes apply locally at once (write-through)
    /// and are queued as **one** outbox entry, sent alone in its own frame.
    ///
    /// If the server rejects the batch, every write in it rolls back as a
    /// unit, together with queued writes to rows it created
    /// (`dependency_rejected`), and an [`Event::Transaction`] with status
    /// `rejected` reports it. `quota_exceeded` holds the whole batch;
    /// `internal` and `rate_limited` retry it. A server or connection
    /// without atomic batches (protocol 1) rejects it with
    /// `unsupported_protocol`.
    ///
    /// ```no_run
    /// # async fn f(space: &kovlet::Space) -> kovlet::Result<()> {
    /// use kovlet::LocalWrite;
    /// use serde_json::json;
    /// let tx = space.transact([
    ///     LocalWrite::upsert("teams", "t1", json!({"name": "Core"})),
    ///     LocalWrite::upsert("members", "m1", json!({"team": "t1", "user": "u1"})),
    /// ])?;
    /// tx.settled().await?; // Ok("applied"), or the rejection
    /// # Ok(()) }
    /// ```
    pub fn transact(&self, writes: impl IntoIterator<Item = LocalWrite>) -> Result<Transaction> {
        let batch = uuid::Uuid::now_v7().to_string();
        let mut entries = Vec::new();
        for w in writes {
            let m = match w {
                LocalWrite::Upsert { table, id, fields } => {
                    let fields = as_object(fields)?;
                    self.check_fields(&table, &fields)?;
                    self.mutation("record", "upsert", Some(&table), &id, Some(fields), None)?
                }
                LocalWrite::Delete { table, id } => self.mutation("record", "delete", Some(&table), &id, None, None)?,
                LocalWrite::Restore { table, id } => {
                    self.mutation("record", "restore", Some(&table), &id, None, None)?
                }
            };
            entries.push(PendingMutation { batch: Some(batch.clone()), ..PendingMutation::new(m) });
        }
        if entries.is_empty() {
            return Err(Error::new("invalid_mutation", "a transaction needs at least one write"));
        }
        let bytes: usize = entries.iter().map(|p| serde_json::to_string(&p.mutation).map_or(0, |s| s.len() + 1)).sum();
        if bytes + 512 > crate::protocol::MAX_FRAME_BYTES {
            return Err(Error::new("too_large", "a transaction must fit in one 8 MiB frame").with_hint(
                "An atomic batch is never split across frames. Make it smaller, or store large values as files.",
            ));
        }
        if entries.len() > MAX_MUTATIONS_PER_FRAME {
            return Err(Error::new(
                "invalid_mutation",
                format!("a transaction holds at most {MAX_MUTATIONS_PER_FRAME} writes"),
            )
            .with_hint(
                "Split the writes into smaller transactions, or use space.write() for writes that needn't be atomic.",
            ));
        }
        self.sync.shared.batches.lock().unwrap().insert(batch.clone(), BatchFate::Pending);
        if let Err(e) = self.enqueue(entries, vec![]) {
            self.sync.shared.batches.lock().unwrap().remove(&batch);
            return Err(e);
        }
        Ok(Transaction { space: self.clone(), id: batch })
    }

    fn mutation(
        &self,
        kind: &str,
        op: &str,
        table: Option<&str>,
        id: &str,
        fields: Option<JsonMap>,
        file: Option<FileMeta>,
    ) -> Result<Mutation> {
        let m = Mutation {
            mutation_id: uuid::Uuid::now_v7().to_string(),
            hlc: self.ctx.clock.tick(),
            kind: kind.into(),
            op: op.into(),
            table: table.map(String::from),
            id: id.to_string(),
            fields,
            file,
        };
        m.validate()?;
        Ok(m)
    }

    fn check_fields(&self, table: &str, fields: &JsonMap) -> Result<()> {
        let known = self.sync.target.schemas();
        let schema = known.get(table).or_else(|| self.tables.0.get(table));
        let Some(schema) = schema else { return Ok(()) };
        for (k, v) in fields {
            let Some(col) = schema.columns.get(k) else { continue };
            let ok = match (col.ty.as_str(), v) {
                (_, Value::Null) => col.optional,
                ("string" | "datetime" | "ref" | "file_ref", Value::String(_)) => true,
                ("number", Value::Number(_)) => true,
                ("boolean", Value::Bool(_)) => true,
                ("json", _) => true,
                _ => false,
            };
            if !ok {
                let reason = if v.is_null() { "null_not_allowed" } else { "type_mismatch" };
                return Err(Error::new("schema_violation", format!("{table}.{k}: expected {}", col.ty))
                    .with_details(serde_json::json!({"table": table, "field": k, "reason": reason, "expected": col.ty}))
                    .with_hint(format!("Column {table}.{k} is {}; send a {} value.", col.ty, col.ty)));
            }
        }
        Ok(())
    }

    fn enqueue(&self, entries: Vec<PendingMutation>, files: Vec<FileState>) -> Result<()> {
        // Storage work on the caller's thread: a write returns once it's durable.
        self.sync.target.write(entries, files)?;
        Ok(())
    }

    /// Links rows the app already had (before it linked this space, or after
    /// [`Client::forget_space`](crate::Client::forget_space)) without
    /// overwriting newer edits from other devices: queues an upsert only for
    /// the rows **the space doesn't have**, and skips the others so the space's
    /// values reach the app.
    ///
    /// Until the space's first snapshot completes, the rows wait, and the core
    /// decides which ones the space has in the same transaction as the
    /// snapshot's last change (an empty space gets every row). After that, it
    /// decides at once. The rows go to the app's store too (they are the app's
    /// own values). Seeding is not saved: if the app quits before the snapshot
    /// completes, call it again; rows already queued or synced are skipped.
    ///
    /// ```no_run
    /// # fn f(space: &kovlet::Space) -> kovlet::Result<()> {
    /// space.seed("todos", [("t1", serde_json::json!({"title": "Buy milk"}))])?;
    /// # Ok(()) }
    /// ```
    ///
    /// Like [`Space::write`], don't call it while holding a shared
    /// `SqliteStore`'s connection lock.
    pub fn seed<I, K>(&self, table: &str, rows: I) -> Result<()>
    where
        I: IntoIterator<Item = (K, Value)>,
        K: AsRef<str>,
    {
        let mut muts = Vec::new();
        for (id, fields) in rows {
            let fields = as_object(fields)?;
            self.check_fields(table, &fields)?;
            muts.push(self.mutation("record", "upsert", Some(table), id.as_ref(), Some(fields), None)?);
        }
        if muts.is_empty() {
            return Ok(());
        }
        self.sync.target.seed(muts, self.ctx.clock.clone())
    }

    /// Record mode (SqliteStore shared with the app): queues a write the app
    /// has already made to its own row, inside the app's open transaction.
    ///
    /// ```no_run
    /// # fn f(space: &kovlet::Space, db: &mut rusqlite::Connection) -> kovlet::Result<()> {
    /// let tx = db.transaction()?;
    /// tx.execute("UPDATE items SET text = ?1 WHERE id = ?2", ("Buy milk", "i1"))?;
    /// space.record(&tx, "items", "i1", serde_json::json!({"text": "Buy milk"}))?;
    /// tx.commit()?;
    /// # Ok(()) }
    /// ```
    #[cfg(feature = "sqlite")]
    pub fn record(&self, conn: &rusqlite::Connection, table: &str, id: &str, fields: Value) -> Result<()> {
        let Some(store) = &self.sqlite else {
            return Err(Error::config("record() needs a space opened with a shared SqliteStore"));
        };
        let fields = as_object(fields)?;
        self.check_fields(table, &fields)?;
        let m = self.mutation("record", "upsert", Some(table), id, Some(fields), None)?;
        let target = self.sync.target.clone();
        store.transaction_on(conn, &mut |v| target.record_in(v, m.clone()))?;
        self.after_record();
        Ok(())
    }

    /// Record mode for deletes and restores (`op` = `delete` or `restore`).
    #[cfg(feature = "sqlite")]
    pub fn record_trash(&self, conn: &rusqlite::Connection, table: &str, id: &str, deleted: bool) -> Result<()> {
        let Some(store) = &self.sqlite else {
            return Err(Error::config("record_trash() needs a space opened with a shared SqliteStore"));
        };
        let m = self.mutation("record", if deleted { "delete" } else { "restore" }, Some(table), id, None, None)?;
        let target = self.sync.target.clone();
        store.transaction_on(conn, &mut |v| target.record_in(v, m.clone()))?;
        self.after_record();
        Ok(())
    }

    #[cfg(feature = "sqlite")]
    fn after_record(&self) {
        // The app's transaction may still roll back: re-read the outbox once
        // it has settled (the refresh waits for the connection's lock).
        let t = self.sync.target.clone();
        crate::engine::spawn_blocking(&self.ctx.handle, move || {
            std::thread::sleep(std::time::Duration::from_millis(5));
            let _ = t.refresh_outbox();
        });
    }
}

fn as_object(v: Value) -> Result<JsonMap> {
    match v {
        Value::Object(m) => Ok(m),
        _ => Err(Error::new("invalid_mutation", "fields must be a JSON object")),
    }
}

/// A query subscription ([`Space::subscribe`]). Cheap to clone; dropping it
/// keeps the subscription (it persists until [`LiveQuery::unsubscribe`]).
#[derive(Clone)]
pub struct LiveQuery {
    space: Space,
    sub: String,
    query: Value,
}

impl LiveQuery {
    /// The subscription id (stable per space, query and params).
    pub fn id(&self) -> &str {
        &self.sub
    }

    pub fn query(&self) -> &Value {
        &self.query
    }

    /// How far the subscription is (`complete`, `error`, `more`).
    pub fn status(&self) -> Option<SubscriptionStatus> {
        self.space.sync.target.subscriptions().into_iter().find(|s| s.sub == self.sub)
    }

    /// The query's current result from the built-in store (the nested tree).
    pub fn rows(&self) -> Result<QueryResult> {
        self.space.query(&self.query)
    }

    /// Calls `f` with the result now and after every change to the space's
    /// rows, on a core thread. Stops when the returned handle is dropped.
    pub fn observe(&self, f: impl Fn(QueryResult) + Send + Sync + 'static) -> Result<Subscription> {
        f(self.rows()?);
        let mut rx = self.space.changes();
        let me = self.clone();
        let h = crate::engine::spawn(&self.space.ctx.handle, async move {
            loop {
                match rx.recv().await {
                    Ok(t) if t.iter().all(|x| x.starts_with('$')) => continue,
                    Ok(_) | Err(broadcast::error::RecvError::Lagged(_)) => {}
                    Err(_) => break,
                }
                let q = me.clone();
                if let Ok(Ok(r)) =
                    crate::engine::spawn_blocking(&tokio::runtime::Handle::current(), move || q.rows()).await
                {
                    f(r);
                }
            }
        });
        Ok(Subscription(Some(h)))
    }

    /// Ends the subscription: rows only it held leave the store.
    pub fn unsubscribe(&self) -> Result<()> {
        if self.space.sync.target.remove_subscription(&self.sub)? {
            self.space.sync.shared.control(Ctl::Unsubscribe(self.sub.clone()));
        }
        Ok(())
    }
}

/// The built-in store as a query source.
struct BuiltinSource {
    reader: Arc<dyn ReadStore>,
    space: Space,
}

impl QuerySource for BuiltinSource {
    fn rows(&self, table: &str) -> Vec<JsonMap> {
        let rows = self.reader.rows(self.space.id(), table).unwrap_or_default();
        rows.into_iter()
            .filter_map(|r| match r.to_object() {
                Value::Object(o) => Some(o),
                _ => None,
            })
            .collect()
    }
    fn confirmed(&self, table: &str, id: &str) -> bool {
        self.space.sync.target.held(table, id)
    }
    fn complete(&self, _table: &str) -> bool {
        !self.space.sync.target.partial()
    }
}

/// An atomic batch ([`Space::transact`]).
#[derive(Clone)]
pub struct Transaction {
    space: Space,
    /// The batch id (`mutate.batch_id`).
    pub id: String,
}

impl Transaction {
    /// Resolves when the server answers: `Ok("applied")` (or `"duplicate"`,
    /// a retry of a batch that had applied), or the rejection (the batch is
    /// rolled back by then). Waits across reconnects; a held batch
    /// (`quota_exceeded`) keeps waiting.
    pub async fn settled(&self) -> Result<String> {
        let shared = self.space.sync.shared.clone();
        loop {
            let notified = shared.batch_settled.notified();
            tokio::pin!(notified);
            notified.as_mut().enable();
            let fate = {
                let mut b = shared.batches.lock().unwrap();
                match b.get(&self.id) {
                    Some(BatchFate::Done(_)) => b.remove(&self.id),
                    _ => None,
                }
            };
            if let Some(BatchFate::Done(r)) = fate {
                return r;
            }
            notified.await;
        }
    }
}

/// One write for [`Space::queue`].
#[derive(Debug, Clone, PartialEq)]
pub enum LocalWrite {
    /// Inserts the row, or updates these fields of it (`fields` is a JSON object).
    Upsert { table: String, id: String, fields: Value },
    /// Moves the row to the Trash.
    Delete { table: String, id: String },
    /// Takes the row out of the Trash.
    Restore { table: String, id: String },
}

impl LocalWrite {
    pub fn upsert(table: impl Into<String>, id: impl Into<String>, fields: Value) -> LocalWrite {
        LocalWrite::Upsert { table: table.into(), id: id.into(), fields }
    }
    pub fn delete(table: impl Into<String>, id: impl Into<String>) -> LocalWrite {
        LocalWrite::Delete { table: table.into(), id: id.into() }
    }
    pub fn restore(table: impl Into<String>, id: impl Into<String>) -> LocalWrite {
        LocalWrite::Restore { table: table.into(), id: id.into() }
    }
}

/// How many queued writes the worker merges per transaction.
const QUEUE_CHUNK: usize = 10_000;

/// The Kovlet-owned worker behind [`Space::queue`]. It starts with the space
/// (merging anything a previous run left queued) and stops when the last
/// handle to the space is dropped.
struct QueueWorker {
    kick: Arc<Notify>,
    closed: Arc<AtomicBool>,
}

impl QueueWorker {
    fn start(ctx: &Arc<Ctx>, target: &Arc<Target>, space_id: &str) -> Arc<QueueWorker> {
        let kick = Arc::new(Notify::new());
        let closed = Arc::new(AtomicBool::new(false));
        let (k, c, ctx2, t, space) =
            (kick.clone(), closed.clone(), ctx.clone(), Arc::downgrade(target), space_id.to_string());
        crate::engine::spawn(&ctx.handle, async move { run_queue(ctx2, t, k, c, space).await });
        kick.notify_one(); // leftovers from a previous run
        Arc::new(QueueWorker { kick, closed })
    }

    fn kick(&self) {
        self.kick.notify_one();
    }
}

impl Drop for QueueWorker {
    fn drop(&mut self) {
        self.closed.store(true, Ordering::SeqCst);
        self.kick.notify_one();
    }
}

async fn run_queue(ctx: Arc<Ctx>, target: Weak<Target>, kick: Arc<Notify>, closed: Arc<AtomicBool>, space: String) {
    let mut attempt: u32 = 0;
    loop {
        kick.notified().await;
        loop {
            if closed.load(Ordering::SeqCst) {
                return;
            }
            let Some(t) = target.upgrade() else { return };
            let r = crate::engine::spawn_blocking(&ctx.handle, move || {
                while t.drain_queue(QUEUE_CHUNK)? > 0 {}
                Ok(())
            })
            .await
            .map_err(|e| Error::new("apply_failed", format!("queue task failed: {e}")))
            .and_then(|r: Result<()>| r);
            match r {
                Ok(()) => {
                    attempt = 0;
                    break;
                }
                Err(e) => {
                    tracing::warn!("kovlet: queued writes for {space} not applied yet: {e}");
                    let error = e.with_hint("Writes queued with space.queue() stay queued and are retried with backoff until the DataStore accepts them.");
                    let _ = ctx.events.send(Event::Error { space_id: Some(space.clone()), error });
                    attempt += 1;
                    let wait = Duration::from_millis((100u64 << attempt.min(8)).min(30_000));
                    tokio::select! {
                        _ = tokio::time::sleep(wait) => {}
                        _ = kick.notified() => {}
                    }
                }
            }
        }
    }
}

/// `space.write("todos")`.
pub struct TableWriter {
    space: Space,
    table: String,
}

impl TableWriter {
    /// Inserts the row, or updates these fields of it. `null` empties an optional field.
    pub fn upsert(&self, id: &str, fields: Value) -> Result<()> {
        let fields = as_object(fields)?;
        self.space.check_fields(&self.table, &fields)?;
        let m = self.space.mutation("record", "upsert", Some(&self.table), id, Some(fields), None)?;
        self.space.enqueue(vec![PendingMutation::new(m)], vec![])
    }

    /// Upserts many rows as **one** write: one transaction, one
    /// `DataStore::apply` batch (write-through, like [`TableWriter::upsert`];
    /// all rows or none). From inside the app's storage layer, use
    /// [`Space::queue`] instead.
    pub fn upsert_many<I, S>(&self, rows: I) -> Result<()>
    where
        I: IntoIterator<Item = (S, Value)>,
        S: AsRef<str>,
    {
        let mut entries = Vec::new();
        for (id, fields) in rows {
            let fields = as_object(fields)?;
            self.space.check_fields(&self.table, &fields)?;
            let m = self.space.mutation("record", "upsert", Some(&self.table), id.as_ref(), Some(fields), None)?;
            entries.push(PendingMutation::new(m));
        }
        if entries.is_empty() {
            return Ok(());
        }
        self.space.enqueue(entries, vec![])
    }

    /// Upserts a serializable value whose `id` field is the row id.
    pub fn put<T: serde::Serialize>(&self, row: &T) -> Result<()> {
        let mut v = as_object(serde_json::to_value(row)?)?;
        let id = match v.remove("id") {
            Some(Value::String(s)) => s,
            Some(Value::Number(n)) => n.to_string(),
            _ => return Err(Error::new("invalid_id", "the row has no string id field")),
        };
        self.upsert(&id, Value::Object(v))
    }

    /// Moves the row to the Trash.
    pub fn delete(&self, id: &str) -> Result<()> {
        let m = self.space.mutation("record", "delete", Some(&self.table), id, None, None)?;
        self.space.enqueue(vec![PendingMutation::new(m)], vec![])
    }

    /// Takes the row out of the Trash (an upsert never does).
    pub fn restore(&self, id: &str) -> Result<()> {
        let m = self.space.mutation("record", "restore", Some(&self.table), id, None, None)?;
        self.space.enqueue(vec![PendingMutation::new(m)], vec![])
    }
}

/// `space.table("todos")`: reads from the built-in store.
pub struct TableReader {
    space: Space,
    table: String,
}

/// Unsubscribes when dropped.
pub struct Subscription(Option<tokio::task::JoinHandle<()>>);

impl Drop for Subscription {
    fn drop(&mut self) {
        if let Some(h) = self.0.take() {
            h.abort();
        }
    }
}

impl TableReader {
    fn reader(&self) -> Result<&Arc<dyn ReadStore>> {
        self.space
            .reader
            .as_ref()
            .ok_or_else(|| Error::config("this space syncs into the app's own store: read it there"))
    }

    /// Live (not trashed) rows, ordered by id.
    pub fn all(&self) -> Result<Vec<Row>> {
        self.reader()?.rows(self.space.id(), &self.table)
    }

    /// Live rows decoded as `T` (the row id goes into the `id` field).
    pub fn all_as<T: DeserializeOwned>(&self) -> Result<Vec<T>> {
        self.all()?.iter().map(|r| serde_json::from_value(r.to_object()).map_err(Error::from)).collect()
    }

    /// One row (trashed rows included; check `trashed`).
    pub fn get(&self, id: &str) -> Result<Option<Row>> {
        self.reader()?.get(self.space.id(), &self.table, id)
    }

    /// Calls `f` with the live rows now and after every change to the table,
    /// on a core thread.
    pub fn observe(&self, f: impl Fn(Vec<Row>) + Send + Sync + 'static) -> Result<Subscription> {
        let reader = self.reader()?.clone();
        let mut rx = self.space.changes();
        let (space, table) = (self.space.id().to_string(), self.table.clone());
        f(reader.rows(&space, &table)?);
        let h = crate::engine::spawn(&self.space.ctx.handle, async move {
            loop {
                match rx.recv().await {
                    Ok(t) if !t.contains(&table) => continue,
                    Ok(_) | Err(broadcast::error::RecvError::Lagged(_)) => {}
                    Err(_) => break,
                }
                let (r, s, t) = (reader.clone(), space.clone(), table.clone());
                if let Ok(Ok(rows)) =
                    crate::engine::spawn_blocking(&tokio::runtime::Handle::current(), move || r.rows(&s, &t)).await
                {
                    f(rows);
                }
            }
        });
        Ok(Subscription(Some(h)))
    }
}

/// `space.files()`.
pub struct Files {
    space: Space,
}

impl Files {
    fn queue_put(&self, id: Option<&str>, path: &str, mime: &str, sha: String, size: u64) -> Result<FileState> {
        let id = id.map(String::from).unwrap_or_else(|| uuid::Uuid::now_v7().to_string());
        let meta = FileMeta { path: path.into(), sha256: sha.clone(), size_bytes: Some(size), mime_type: mime.into() };
        let m = self.space.mutation("file", "put", None, &id, None, Some(meta))?;
        let state = FileState {
            id: id.clone(),
            path: path.into(),
            sha256: sha.clone(),
            size_bytes: size,
            mime_type: mime.into(),
            hlc: Some(m.hlc.clone()),
            ..Default::default()
        };
        let upload = Upload { sha256: sha, size_bytes: size, mime_type: mime.into(), done: false };
        self.space.enqueue(
            vec![PendingMutation { mutation: m, upload: Some(upload), held: None, batch: None }],
            vec![state.clone()],
        )?;
        Ok(state)
    }

    /// Stores bytes at `path`: staged now, uploaded in the background, then committed.
    /// Pass `id` to overwrite an existing file; otherwise a new UUIDv7 is used.
    pub fn put(&self, path: &str, bytes: &[u8], mime_type: &str, id: Option<&str>) -> Result<FileState> {
        let (sha, size) = self.space.ctx.staging.stage_bytes(bytes)?;
        self.queue_put(id, path, mime_type, sha, size)
    }

    /// Like [`Files::put`], streaming from a local file.
    pub fn put_file(&self, path: &str, local: &Path, mime_type: &str, id: Option<&str>) -> Result<FileState> {
        let (sha, size) = self.space.ctx.staging.stage_file(local)?;
        self.queue_put(id, path, mime_type, sha, size)
    }

    /// Moves a file to a new path.
    pub fn move_to(&self, id: &str, new_path: &str) -> Result<()> {
        let meta = FileMeta { path: new_path.into(), ..Default::default() };
        let m = self.space.mutation("file", "move", None, id, None, Some(meta))?;
        self.space.enqueue(vec![PendingMutation::new(m)], vec![])
    }

    /// Moves a file to the Trash.
    pub fn delete(&self, id: &str) -> Result<()> {
        let m = self.space.mutation("file", "delete", None, id, None, None)?;
        let local = self.local(id).map(|f| FileState { deleted: true, ..f });
        self.space.enqueue(vec![PendingMutation::new(m)], local.into_iter().collect())
    }

    /// Takes a file out of the Trash.
    pub fn restore(&self, id: &str) -> Result<()> {
        let m = self.space.mutation("file", "restore", None, id, None, None)?;
        self.space.enqueue(vec![PendingMutation::new(m)], vec![])
    }

    fn local(&self, id: &str) -> Option<FileState> {
        self.space.reader.as_ref()?.files(self.space.id()).ok()?.into_iter().find(|f| f.id == id)
    }

    /// Live files in the built-in store (metadata).
    pub fn all(&self) -> Result<Vec<FileState>> {
        match &self.space.reader {
            Some(r) => r.files(self.space.id()),
            None => {
                Err(Error::config("this space syncs into the app's own store: file metadata arrives as file changes"))
            }
        }
    }

    /// Lists files on the server under `prefix`.
    pub async fn list(&self, prefix: Option<&str>) -> Result<Vec<FileState>> {
        let (ctx, space, prefix) = (self.space.ctx.clone(), self.space.id().to_string(), prefix.map(String::from));
        let c = ctx.clone();
        ctx.handle
            .spawn(async move { crate::files::list(&c, &space, prefix.as_deref()).await })
            .await
            .map_err(Error::network)?
    }

    /// Mirrors the files under `prefix` (e.g. `"attachments/"`) into the local
    /// folder `dir`, both ways, until the returned [`Mirror`] is dropped:
    /// files the folder lacks are downloaded (now and as they change), and
    /// files the space lacks are uploaded. Files match by path and SHA-256,
    /// so mirroring the same folder again (after a restart or a re-link)
    /// uploads nothing twice. Tell it about files the app writes later with
    /// [`Mirror::notify_added`]. Deletes and moves are not mirrored.
    ///
    /// The work runs on the core's runtime; this returns at once.
    pub fn mirror(&self, dir: impl Into<std::path::PathBuf>, prefix: &str) -> Result<Mirror> {
        Mirror::start(self.space.clone(), dir.into(), prefix)
    }

    /// Downloads a file to `to`, verifying its SHA-256.
    pub async fn download(&self, id: &str, to: &Path) -> Result<FileState> {
        let (ctx, space, id, to) =
            (self.space.ctx.clone(), self.space.id().to_string(), id.to_string(), to.to_path_buf());
        let c = ctx.clone();
        ctx.handle
            .spawn(async move { crate::files::download(&c, &space, &id, &to).await })
            .await
            .map_err(Error::network)?
    }
}