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
//! The client: create it once, sign in once, open spaces, observe status.
//!
//! ```no_run
//! # async fn demo() -> kovlet::Result<()> {
//! use kovlet::{Client, SignIn, Tables, col};
//! let kovlet = Client::builder("Todos").data_dir("/tmp/todos").build()?;
//! if !kovlet.signed_in() {
//!     kovlet.sign_in(SignIn::device(|c| println!("Open {} and enter {}", c.verification_uri, c.user_code))).await?;
//! }
//! let space_id = kovlet.spaces().find_or_create("Todos").await?.id;
//! let space = kovlet.open_builtin(&space_id, Tables::new().table("todos", [("title", col::string()), ("done", col::boolean())]))?;
//! space.write("todos").upsert("t1", serde_json::json!({"title": "Buy milk", "done": false}))?;
//! # Ok(()) }
//! ```

use std::collections::{BTreeMap, HashMap};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;

use serde::{Deserialize, Serialize};
use tokio::sync::{broadcast, watch};

use crate::api::Api;
use crate::auth::key::{KeyProvider, SoftwareKeyProvider};
use crate::auth::secrets::{MemorySecretStore, SecretStore};
use crate::auth::{Auth, PkceRequest, Session, SignIn};
use crate::engine::session::{SpaceShared, SpaceSync};
use crate::engine::target::{Stores, Target};
use crate::engine::{Ctx, Event, SpaceStatus, SyncState};
use crate::error::{Error, Result};
use crate::files::Staging;
use crate::hlc::{random_node, Clock};
use crate::schema::Tables;
use crate::space::Space;
use crate::spaces::Spaces;
use crate::store::{DataStore, MemoryStore, MemorySyncStore, ReadStore, SyncStore};
use crate::transport::Transport;

/// The hosted API (BORG-96): the default base URL.
pub const DEFAULT_API_URL: &str = "https://api.kovlet.com";
/// The hosted console: consent, `/activate`.
pub const DEFAULT_CONSOLE_URL: &str = "https://kovlet.com";

/// The client's status: one shape on every platform.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct Status {
    pub state: SyncState,
    pub pending: usize,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub blocked: Option<crate::engine::Blocked>,
    pub spaces: BTreeMap<String, SpaceStatus>,
}

/// What `sync_once` did.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SyncSummary {
    /// True when every space caught up and sent its outbox before the deadline.
    pub completed: bool,
    pub status: Status,
}

/// Which store a space syncs into.
#[derive(Clone)]
pub enum SpaceStore {
    /// The client's built-in store: read rows back with `space.table(...)`.
    Builtin,
    /// The app's own store; Kovlet's bookkeeping stays in the client's SyncStore.
    Data(Arc<dyn DataStore>),
    /// A SqliteStore sharing the app's database: one transaction for both.
    #[cfg(feature = "sqlite")]
    Sqlite(Arc<crate::store::sqlite::SqliteStore>),
}

impl SpaceStore {
    pub fn data(store: impl DataStore + 'static) -> SpaceStore {
        SpaceStore::Data(Arc::new(store))
    }
}

#[cfg(feature = "sqlite")]
impl From<crate::store::sqlite::SqliteStore> for SpaceStore {
    fn from(s: crate::store::sqlite::SqliteStore) -> SpaceStore {
        SpaceStore::Sqlite(Arc::new(s))
    }
}

#[cfg(feature = "sqlite")]
impl From<Arc<crate::store::sqlite::SqliteStore>> for SpaceStore {
    fn from(s: Arc<crate::store::sqlite::SqliteStore>) -> SpaceStore {
        SpaceStore::Sqlite(s)
    }
}

impl From<Arc<dyn DataStore>> for SpaceStore {
    fn from(s: Arc<dyn DataStore>) -> SpaceStore {
        SpaceStore::Data(s)
    }
}

/// Builds a [`Client`].
pub struct ClientBuilder {
    app_name: String,
    base_url: String,
    console_url: String,
    data_dir: Option<PathBuf>,
    memory: bool,
    secrets: Option<Arc<dyn SecretStore>>,
    keys: Option<Arc<dyn KeyProvider>>,
    transport: Option<Arc<dyn Transport>>,
    sync_store: Option<Arc<dyn SyncStore>>,
    keychain_service: Option<String>,
    protocol: Option<u32>,
    as_end_user: Option<String>,
}

impl ClientBuilder {
    /// Pins the sync protocol: `1` (one space per socket, a full replica;
    /// no atomic batches or query subscriptions) or `2`. By default the
    /// client speaks 2 and falls back to 1 for a day when a server refuses it.
    pub fn protocol(mut self, version: u32) -> Self {
        self.protocol = Some(version);
        self
    }
    /// A machine session (Machine Auth Key) acts as this end user over
    /// protocol 2 (`hello.as_end_user`, ADR 0021 §2.6): the space's rules
    /// apply as they would to that end user. Needs the `impersonate` flag on
    /// the machine's grant.
    pub fn as_end_user(mut self, end_user_id: impl Into<String>) -> Self {
        self.as_end_user = Some(end_user_id.into());
        self
    }
    /// The API base URL (default `https://api.kovlet.com`).
    pub fn base_url(mut self, url: impl Into<String>) -> Self {
        self.base_url = url.into().trim_end_matches('/').to_string();
        self
    }
    /// The console URL for consent and `/activate` (default `https://kovlet.com`).
    pub fn console_url(mut self, url: impl Into<String>) -> Self {
        self.console_url = url.into().trim_end_matches('/').to_string();
        self
    }
    /// Where Kovlet keeps its SQLite bookkeeping, the built-in store and staged files.
    pub fn data_dir(mut self, dir: impl AsRef<Path>) -> Self {
        self.data_dir = Some(dir.as_ref().to_path_buf());
        self
    }
    /// Keep everything in memory (tests, scripts). Nothing survives a restart.
    pub fn memory(mut self) -> Self {
        self.memory = true;
        self
    }
    /// Where tokens and the software device key live (default: the OS keychain,
    /// else 0600 files in `data_dir`).
    pub fn secret_store(mut self, s: Arc<dyn SecretStore>) -> Self {
        self.secrets = Some(s);
        self
    }
    /// The device key (default: a software P-256 key in the SecretStore).
    /// Swift passes a Secure Enclave key, Kotlin an Android Keystore key.
    pub fn key_provider(mut self, k: Arc<dyn KeyProvider>) -> Self {
        self.keys = Some(k);
        self
    }
    /// HTTP and WebSocket (default: [`crate::transport::NativeTransport`]).
    pub fn transport(mut self, t: Arc<dyn Transport>) -> Self {
        self.transport = Some(t);
        self
    }
    /// Kovlet's bookkeeping store (default: SQLite in `data_dir`, or memory).
    pub fn sync_store(mut self, s: Arc<dyn SyncStore>) -> Self {
        self.sync_store = Some(s);
        self
    }
    /// The keychain service name (default: `kovlet.<app name>`).
    pub fn keychain_service(mut self, s: impl Into<String>) -> Self {
        self.keychain_service = Some(s.into());
        self
    }

    pub fn build(self) -> Result<Client> {
        if self.app_name.trim().is_empty() {
            return Err(Error::config("app_name is required"));
        }
        if self.data_dir.is_none() && !self.memory && self.sync_store.is_none() {
            return Err(Error::config("set data_dir(...) (or memory() for tests)"));
        }
        if self.protocol.is_some_and(|p| p != 1 && p != 2) {
            return Err(Error::config("protocol is 1 or 2"));
        }
        if self.protocol == Some(1) && self.as_end_user.is_some() {
            return Err(Error::config("as_end_user needs protocol 2"));
        }
        let runtime = tokio::runtime::Builder::new_multi_thread()
            .worker_threads(1)
            .max_blocking_threads(8)
            .thread_name("kovlet")
            .enable_all()
            .build()
            .map_err(|e| Error::config(format!("runtime: {e}")))?;
        let handle = runtime.handle().clone();

        let (sync_store, builtin): (Arc<dyn SyncStore>, Arc<dyn BuiltinStore>) =
            match (&self.sync_store, &self.data_dir) {
                (Some(s), _) => (s.clone(), Arc::new(MemoryStore::new())),
                (None, Some(dir)) if !self.memory => open_dir_store(dir)?,
                _ => {
                    let mem = Arc::new(MemoryStore::new());
                    (Arc::new(MemorySyncStore::new()), mem)
                }
            };
        let secrets: Arc<dyn SecretStore> = match (self.secrets, &self.data_dir, self.memory) {
            (Some(s), _, _) => s,
            (None, _, true) => Arc::new(MemorySecretStore::new()),
            (None, Some(dir), false) => {
                default_secrets(dir, self.keychain_service.unwrap_or_else(|| format!("kovlet.{}", self.app_name)))?
            }
            (None, None, false) => Arc::new(MemorySecretStore::new()),
        };
        let keys = self.keys.unwrap_or_else(|| Arc::new(SoftwareKeyProvider::new(secrets.clone(), "device_key")));
        let transport = match self.transport {
            Some(t) => t,
            None => crate::transport::default_transport()?,
        };
        let auth = Arc::new(Auth::new(self.base_url, self.console_url, self.app_name, transport, secrets, keys));

        // A stable HLC node id per installation, and the high-water mark.
        let node = match sync_store.meta_get("node")? {
            Some(n) if crate::hlc::valid_node(&n) => n,
            _ => {
                let n = random_node();
                sync_store.meta_set("node", &n)?;
                n
            }
        };
        let clock = Arc::new(Clock::new(node));
        if let Some(h) = sync_store.meta_get("hlc")? {
            clock.restore(&h);
        }
        let (events, _) = broadcast::channel(256);
        let staging = Staging::new(if self.memory { None } else { self.data_dir.as_ref().map(|d| d.join("staging")) });
        let ctx = Arc::new(Ctx {
            handle,
            auth: auth.clone(),
            api: Api { auth, wait: true },
            clock,
            events,
            staging,
            meta: sync_store.clone(),
            protocol: self.protocol,
            as_end_user: self.as_end_user,
        });
        let (status, _) = watch::channel(Status::default());
        let inner = Arc::new(Inner {
            ctx,
            runtime: Mutex::new(Some(runtime)),
            spaces: Mutex::new(HashMap::new()),
            sync_store,
            builtin,
            paused: AtomicBool::new(false),
            authorizing: AtomicBool::new(false),
            status,
        });
        inner.recompute();
        // Keep the aggregate status in step with sign-in.
        let weak = Arc::downgrade(&inner);
        let weak2 = Arc::downgrade(&inner);
        let mut reachable = inner.ctx.auth.watch_reachable();
        crate::engine::spawn(&inner.ctx.handle, async move {
            while reachable.changed().await.is_ok() {
                match weak2.upgrade() {
                    Some(i) => i.recompute(),
                    None => break,
                }
            }
        });
        let mut signed = inner.ctx.auth.watch_signed_in();
        crate::engine::spawn(&inner.ctx.handle, async move {
            while signed.changed().await.is_ok() {
                match weak.upgrade() {
                    Some(i) => i.recompute(),
                    None => break,
                }
            }
        });
        Ok(Client { inner })
    }
}

/// A built-in store: a DataStore the app can read.
pub(crate) trait BuiltinStore: DataStore + ReadStore {}
impl<T: DataStore + ReadStore> BuiltinStore for T {}

#[cfg(feature = "sqlite")]
fn open_dir_store(dir: &Path) -> Result<(Arc<dyn SyncStore>, Arc<dyn BuiltinStore>)> {
    std::fs::create_dir_all(dir).map_err(Error::storage)?;
    let s = Arc::new(crate::store::sqlite::SqliteStore::open(dir.join("kovlet.db"))?);
    Ok((s.clone(), s))
}

#[cfg(not(feature = "sqlite"))]
fn open_dir_store(_dir: &Path) -> Result<(Arc<dyn SyncStore>, Arc<dyn BuiltinStore>)> {
    Err(Error::config("data_dir needs the sqlite feature; pass sync_store(...) or use memory()"))
}

fn default_secrets(dir: &Path, service: String) -> Result<Arc<dyn SecretStore>> {
    #[cfg(feature = "os-keychain")]
    {
        if cfg!(any(target_os = "macos", target_os = "windows", target_os = "linux")) {
            let k = crate::auth::secrets::KeychainSecretStore::new(service);
            if k.available() {
                return Ok(Arc::new(k));
            }
        }
    }
    let _ = service;
    Ok(Arc::new(crate::auth::secrets::FileSecretStore::new(dir.join("secrets"))?))
}

pub(crate) struct Inner {
    pub ctx: Arc<Ctx>,
    runtime: Mutex<Option<tokio::runtime::Runtime>>,
    spaces: Mutex<HashMap<String, (Arc<SpaceSync>, Space)>>,
    sync_store: Arc<dyn SyncStore>,
    builtin: Arc<dyn BuiltinStore>,
    paused: AtomicBool,
    authorizing: AtomicBool,
    status: watch::Sender<Status>,
}

impl Drop for Inner {
    fn drop(&mut self) {
        for (s, _) in self.spaces.lock().unwrap().values() {
            s.stop();
        }
        if let Some(rt) = self.runtime.lock().unwrap().take() {
            rt.shutdown_background();
        }
    }
}

fn rank(s: SyncState) -> u8 {
    match s {
        SyncState::Error => 0,
        SyncState::SignedOut => 1,
        SyncState::Authorizing => 2,
        SyncState::Offline => 3,
        SyncState::Connecting => 4,
        SyncState::Syncing => 5,
        SyncState::Live => 6,
    }
}

impl Inner {
    fn syncs(&self) -> Vec<Arc<SpaceSync>> {
        self.spaces.lock().unwrap().values().map(|(s, _)| s.clone()).collect()
    }

    fn recompute(&self) {
        let spaces: BTreeMap<String, SpaceStatus> =
            self.spaces.lock().unwrap().iter().map(|(id, (s, _))| (id.clone(), s.status())).collect();
        let signed_in = self.ctx.auth.signed_in();
        let mut state = if self.authorizing.load(Ordering::SeqCst) {
            SyncState::Authorizing
        } else if !signed_in {
            SyncState::SignedOut
        } else if self.paused.load(Ordering::SeqCst) {
            SyncState::Offline
        } else if !spaces.is_empty() {
            SyncState::Live // lowered to the worst space below
        } else {
            // With no space open, the last request says whether the server is there.
            match *self.ctx.auth.watch_reachable().borrow() {
                Some(true) => SyncState::Live,
                Some(false) => SyncState::Offline,
                None => SyncState::Connecting,
            }
        };
        if signed_in && !self.authorizing.load(Ordering::SeqCst) {
            for s in spaces.values() {
                if rank(s.state) < rank(state) {
                    state = s.state;
                }
            }
        }
        let pending = spaces.values().map(|s| s.pending).sum();
        let blocked = spaces.values().find_map(|s| s.blocked.clone());
        let st = Status { state, pending, blocked, spaces };
        self.status.send_if_modified(|cur| {
            if *cur == st {
                false
            } else {
                *cur = st;
                true
            }
        });
    }
}

/// A Kovlet client. Cheap to clone; every method is thread-safe.
#[derive(Clone)]
pub struct Client {
    pub(crate) inner: Arc<Inner>,
}

impl Client {
    pub fn builder(app_name: impl Into<String>) -> ClientBuilder {
        ClientBuilder {
            app_name: app_name.into(),
            base_url: DEFAULT_API_URL.into(),
            console_url: DEFAULT_CONSOLE_URL.into(),
            data_dir: None,
            memory: false,
            secrets: None,
            keys: None,
            transport: None,
            sync_store: None,
            keychain_service: None,
            protocol: None,
            as_end_user: None,
        }
    }

    pub(crate) fn ctx(&self) -> &Arc<Ctx> {
        &self.inner.ctx
    }

    /// Runs a JSON call on the runtime (status `authorizing` meanwhile when
    /// `signing_in`). One boxed future type for every caller keeps the
    /// mobile binary small (ADR 0017 §1).
    pub(crate) async fn run_json(
        &self,
        f: crate::auth::BoxFuture<Result<serde_json::Value>>,
        signing_in: bool,
    ) -> Result<serde_json::Value> {
        if signing_in {
            self.inner.authorizing.store(true, Ordering::SeqCst);
            self.inner.recompute();
        }
        let r = self.on_runtime(f).await;
        if signing_in {
            self.inner.authorizing.store(false, Ordering::SeqCst);
            self.inner.recompute();
        }
        r
    }

    /// Runs a sign-in on the runtime, with status `authorizing` meanwhile.
    pub(crate) async fn authorizing<T: Send + 'static>(
        &self,
        f: impl std::future::Future<Output = Result<T>> + Send + 'static,
    ) -> Result<T> {
        self.inner.authorizing.store(true, Ordering::SeqCst);
        self.inner.recompute();
        let r = self.on_runtime(f).await;
        self.inner.authorizing.store(false, Ordering::SeqCst);
        self.inner.recompute();
        r
    }

    /// The signed-in identity changed (an end user signed in, out, or
    /// switched): another end user must not see the previous one's rows or
    /// send their queued writes, so every open space forgets them; then the
    /// spaces reconnect with the new session.
    /// Who the stored session is: `eu:<id>` for an end user, `m:<user or machine>` otherwise.
    pub(crate) fn identity(&self) -> Option<String> {
        let s = self.session()?;
        Some(match s.end_user {
            Some(eu) => format!("eu:{}", eu.user.id),
            None => {
                format!("m:{}", s.user_id.unwrap_or(if s.machine_id.is_empty() { s.client_id } else { s.machine_id }))
            }
        })
    }

    pub(crate) async fn identity_changed(&self, before: Option<&str>, after: Option<&str>) {
        if before == after {
            return;
        }
        let syncs = self.inner.syncs();
        for s in &syncs {
            s.stop();
        }
        if before.is_some() {
            for s in &syncs {
                // A frame of the old session still being applied must land
                // before the wipe, not after it.
                s.stopped(Duration::from_secs(10)).await;
                let t = s.target.clone();
                let r = crate::engine::spawn_blocking(&self.ctx().handle, move || t.wipe())
                    .await
                    .map_err(|e| Error::new("internal", e.to_string()))
                    .and_then(|r| r);
                if let Err(e) = r {
                    tracing::warn!("kovlet: forgetting the previous identity's rows failed: {e}");
                }
            }
        }
        if !self.inner.paused.load(Ordering::SeqCst) {
            for s in &syncs {
                s.start();
            }
        }
        self.inner.recompute();
    }

    /// End-user sign-in for one Data Space and app (ADR 0021 §2). `app_id`
    /// is the app's public id from the Kovlet console; the space's owner
    /// turns end-user sign-in on for it.
    pub fn end_users(&self, space_id: &str, app_id: &str) -> crate::end_users::EndUsers {
        crate::end_users::EndUsers { client: self.clone(), space_id: space_id.to_string(), app_id: app_id.to_string() }
    }

    /// Runs a future on the client's runtime, from any executor.
    async fn on_runtime<T: Send + 'static>(
        &self,
        f: impl std::future::Future<Output = Result<T>> + Send + 'static,
    ) -> Result<T> {
        // Boxed: one task type per result type, not per caller (binary size).
        let f: crate::auth::BoxFuture<Result<T>> = Box::pin(f);
        self.ctx().handle.spawn(f).await.map_err(|e| Error::new("internal", format!("task failed: {e}")))?
    }

    pub fn signed_in(&self) -> bool {
        self.ctx().auth.signed_in()
    }

    /// The stored session, if signed in.
    pub fn session(&self) -> Option<Session> {
        self.ctx().auth.session()
    }

    /// Signs in once; the session persists and refreshes by itself.
    pub async fn sign_in(&self, how: SignIn) -> Result<Session> {
        let before = self.identity().filter(|i| i.starts_with("eu:"));
        let auth = self.ctx().auth.clone();
        let r = self.authorizing(async move { auth.sign_in(&how).await }).await;
        if r.is_ok() && before.is_some() {
            // A member or machine session replaces an end user's.
            self.identity_changed(before.as_deref(), None).await;
        }
        r
    }

    /// Starts a PKCE sign-in for apps that drive the browser themselves:
    /// open `url`, then pass the redirect to [`Client::pkce_finish`].
    pub fn pkce_begin(&self, redirect_uri: &str) -> Result<PkceRequest> {
        self.ctx().auth.pkce_begin(redirect_uri, None)
    }

    pub async fn pkce_finish(&self, callback_url: &str, request: &PkceRequest) -> Result<Session> {
        let auth = self.ctx().auth.clone();
        let (cb, req) = (callback_url.to_string(), request.clone());
        self.on_runtime(async move { auth.pkce_finish(&cb, &req).await }).await
    }

    /// Signs out (ends the session family). The device key stays, so the next
    /// sign-in reuses this machine and its grants.
    pub async fn sign_out(&self) -> Result<()> {
        let auth = self.ctx().auth.clone();
        // The next user must not see this one's spaces.
        crate::spaces::forget(self.ctx())?;
        let end_user = self.identity().filter(|i| i.starts_with("eu:"));
        let r = self.on_runtime(async move { auth.sign_out().await }).await;
        if end_user.is_some() {
            self.identity_changed(end_user.as_deref(), None).await;
        }
        r
    }

    /// The app-scoped spaces API.
    pub fn spaces(&self) -> Spaces {
        Spaces { ctx: self.ctx().clone(), wait: true }
    }

    /// Opens a space that syncs into the built-in store.
    pub fn open_builtin(&self, space_id: &str, tables: Tables) -> Result<Space> {
        self.open(space_id, tables, SpaceStore::Builtin)
    }

    /// Opens a space as a full replica: every row, file and schema change.
    /// Any number of spaces can be open; each syncs on its own socket
    /// (protocol 2 with a `"*"` subscription, or protocol 1). While an end
    /// user is signed in, the space syncs their query subscriptions instead
    /// (see [`Client::open_query`]).
    pub fn open(&self, space_id: &str, tables: Tables, store: impl Into<SpaceStore>) -> Result<Space> {
        self.open_mode(space_id, tables, store.into(), false)
    }

    /// Opens a space as a partial replica (protocol 2): the store holds only
    /// the rows of the queries the app subscribes to with
    /// [`Space::subscribe`], plus rows with writes the server hasn't judged.
    /// A row no subscription holds any more leaves the store as a
    /// [`crate::Change::Purge`]. Against a server without protocol 2, the
    /// space falls back to a full replica.
    pub fn open_query(&self, space_id: &str, tables: Tables, store: impl Into<SpaceStore>) -> Result<Space> {
        self.open_mode(space_id, tables, store.into(), true)
    }

    fn open_mode(&self, space_id: &str, tables: Tables, store: SpaceStore, query_mode: bool) -> Result<Space> {
        if !crate::protocol::valid_entity_id(space_id) {
            return Err(Error::config(format!("bad space id {space_id:?}")));
        }
        tables.validate()?;
        let mut spaces = self.inner.spaces.lock().unwrap();
        if let Some((_, s)) = spaces.get(space_id) {
            return Ok(s.clone());
        }
        let shared = SpaceShared::new(space_id);
        let (stores, reader, sqlite): (Stores, Option<Arc<dyn ReadStore>>, _) = match store {
            SpaceStore::Builtin => {
                let b = self.inner.builtin.clone();
                #[cfg(feature = "sqlite")]
                let combined = self.sqlite_builtin();
                #[cfg(not(feature = "sqlite"))]
                let combined: Option<()> = None;
                let stores = match combined {
                    #[cfg(feature = "sqlite")]
                    Some(s) => Stores::Combined(s),
                    _ => Stores::Split { data: as_data(b.clone()), sync: self.inner.sync_store.clone() },
                };
                (stores, Some(as_reader(b)), None)
            }
            SpaceStore::Data(d) => (Stores::Split { data: d, sync: self.inner.sync_store.clone() }, None, None),
            #[cfg(feature = "sqlite")]
            SpaceStore::Sqlite(s) => (Stores::Combined(s.clone()), None, Some(s)),
        };
        let (sh, shf) = (shared.clone(), shared.clone());
        let target = Arc::new(Target::new(space_id, stores, move |t| sh.changed(t)).on_files(move |origin, files| {
            let _ = shf.files.send((origin, Arc::new(files.to_vec())));
        }));
        target.load()?;
        let sync = SpaceSync::new(target, shared.clone(), self.ctx().clone(), tables.0.clone(), query_mode);
        let space = Space::new(self.ctx().clone(), sync.clone(), reader, sqlite, tables);
        spaces.insert(space_id.to_string(), (sync.clone(), space.clone()));
        drop(spaces);
        // Forward the space's status into the aggregate.
        let weak = Arc::downgrade(&self.inner);
        let mut rx = shared.status.subscribe();
        crate::engine::spawn(&self.ctx().handle, async move {
            while rx.changed().await.is_ok() {
                match weak.upgrade() {
                    Some(i) => i.recompute(),
                    None => break,
                }
            }
        });
        if !self.inner.paused.load(Ordering::SeqCst) {
            sync.start();
        }
        self.inner.recompute();
        Ok(space)
    }

    #[cfg(feature = "sqlite")]
    fn sqlite_builtin(&self) -> Option<Arc<dyn SyncStore>> {
        // The built-in SQLite store is both seams: one transaction per batch.
        let s = self.inner.sync_store.clone();
        s.transactional().is_some().then_some(s)
    }

    /// An open space.
    pub fn space(&self, space_id: &str) -> Option<Space> {
        self.inner.spaces.lock().unwrap().get(space_id).map(|(_, s)| s.clone())
    }

    /// Stops syncing a space and forgets the handle. Local state stays.
    /// Blocks while a storage write the socket started finishes.
    pub fn close_space(&self, space_id: &str) {
        let closed = self.inner.spaces.lock().unwrap().remove(space_id);
        if let Some((s, _)) = closed {
            s.stop();
            // A snapshot or ack already in flight finishes or is refused here.
            s.target.close();
        }
        self.inner.recompute();
    }

    /// Forgets a space's local sync state: its cursor, cached schemas, clocks
    /// and outbox (writes not yet uploaded are dropped). The app's rows stay.
    /// The next [`Client::open`] starts from a snapshot, so unlinking and
    /// linking again, or linking another local database to the same space,
    /// misses nothing. Pair it with [`Space::seed`] to upload only the local
    /// rows the space lacks.
    ///
    /// Pass the store the space is opened with. Refused (`space_open`) while
    /// the space is open: [`Client::close_space`] it first.
    pub fn forget_space(&self, space_id: &str, store: impl Into<SpaceStore>) -> Result<()> {
        let spaces = self.inner.spaces.lock().unwrap();
        if spaces.contains_key(space_id) {
            return Err(Error::new("space_open", format!("space {space_id} is open"))
                .with_hint("Call close_space(id) before forget_space(id)."));
        }
        let sync: Arc<dyn SyncStore> = match store.into() {
            SpaceStore::Builtin | SpaceStore::Data(_) => self.inner.sync_store.clone(),
            #[cfg(feature = "sqlite")]
            SpaceStore::Sqlite(s) => s,
        };
        sync.forget_space(space_id)?;
        crate::engine::target::v2::forget(sync.as_ref(), space_id)
    }

    /// The current status.
    pub fn status(&self) -> Status {
        self.inner.status.borrow().clone()
    }

    /// Status updates, starting with the current one.
    pub fn watch_status(&self) -> watch::Receiver<Status> {
        self.inner.status.subscribe()
    }

    /// Rejections and session errors.
    pub fn events(&self) -> broadcast::Receiver<Event> {
        self.ctx().events.subscribe()
    }

    /// Call when the app moves to the background: flushes the outbox for up
    /// to `grace`, then closes sockets cleanly.
    pub async fn pause(&self, grace: Duration) {
        let inner = self.inner.clone();
        let _ = self
            .on_runtime(async move {
                inner.paused.store(true, Ordering::SeqCst);
                let syncs = inner.syncs();
                let _ = tokio::time::timeout(grace, wait_flushed(&syncs)).await;
                // A resume() during the grace period wins.
                if inner.paused.load(Ordering::SeqCst) {
                    for s in &syncs {
                        s.stop();
                    }
                }
                inner.recompute();
                Ok(())
            })
            .await;
    }

    /// Call when the app returns to the foreground: reconnects at once.
    pub fn resume(&self) {
        self.inner.paused.store(false, Ordering::SeqCst);
        for s in self.inner.syncs() {
            s.start();
        }
        self.inner.recompute();
    }

    /// For background slots (BGAppRefreshTask, WorkManager): connects, catches
    /// up, flushes the outbox and staged uploads while time remains, then
    /// returns to the previous paused/running state.
    pub async fn sync_once(&self, deadline: Duration) -> SyncSummary {
        let inner = self.inner.clone();
        let r = self
            .on_runtime(async move {
                let was_paused = inner.paused.load(Ordering::SeqCst);
                let syncs = inner.syncs();
                for s in &syncs {
                    s.start();
                }
                let completed = tokio::time::timeout(deadline, async {
                    for s in &syncs {
                        let mut rx = s.shared.status.subscribe();
                        let _ = rx.wait_for(|st| st.state == SyncState::Live || st.state == SyncState::Error).await;
                    }
                    wait_flushed(&syncs).await;
                })
                .await
                .is_ok();
                if was_paused {
                    for s in &syncs {
                        s.stop();
                    }
                }
                inner.recompute();
                Ok(completed)
            })
            .await;
        SyncSummary { completed: r.unwrap_or(false), status: self.status() }
    }

    /// Sends writes the server held back (`quota_exceeded`) again.
    pub fn retry_held(&self) {
        for (s, _) in self.inner.spaces.lock().unwrap().values() {
            s.retry_held();
        }
    }

    /// The runtime handle the client runs on.
    pub fn runtime(&self) -> tokio::runtime::Handle {
        self.ctx().handle.clone()
    }
}

fn as_data(b: Arc<dyn BuiltinStore>) -> Arc<dyn DataStore> {
    struct D(Arc<dyn BuiltinStore>);
    impl DataStore for D {
        fn apply(&self, batch: &crate::store::ChangeBatch) -> Result<()> {
            self.0.apply(batch)
        }
    }
    Arc::new(D(b))
}

fn as_reader(b: Arc<dyn BuiltinStore>) -> Arc<dyn ReadStore> {
    struct R(Arc<dyn BuiltinStore>);
    impl ReadStore for R {
        fn rows(&self, s: &str, t: &str) -> Result<Vec<crate::store::Row>> {
            self.0.rows(s, t)
        }
        fn get(&self, s: &str, t: &str, id: &str) -> Result<Option<crate::store::Row>> {
            self.0.get(s, t, id)
        }
        fn files(&self, s: &str) -> Result<Vec<crate::protocol::FileState>> {
            self.0.files(s)
        }
    }
    Arc::new(R(b))
}

/// Waits until no space has unsent (non-held) writes or uploads.
async fn wait_flushed(syncs: &[Arc<SpaceSync>]) {
    loop {
        let busy = syncs.iter().any(|s| {
            let (pending, held, _) = s.target.pending();
            (pending > held || s.uploads() > 0) && s.running()
        });
        if !busy {
            return;
        }
        tokio::time::sleep(Duration::from_millis(50)).await;
    }
}