ch-database 0.2.1

Database and object storage primitives for SQLx, SpacetimeDB, and S3
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
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
//! Shared SpacetimeDB helper utilities.
//!
//! App-owned SpacetimeDB tables, reducers, generated bindings, and concrete
//! clients live in the owning app database crates.

use std::cell::Cell;
use std::collections::VecDeque;
use std::fmt;
use std::mem::ManuallyDrop;
use std::ops::Deref;
use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, OnceLock, RwLock, RwLockReadGuard, TryLockError, mpsc};
use std::thread;
use std::time::{Duration, Instant};

use spacetimedb_sdk::DbContext;

static RUNTIME_ENDPOINT_URL: OnceLock<String> = OnceLock::new();
static OPTIONAL_READ_DEGRADED_UNTIL: OnceLock<Mutex<Option<Instant>>> = OnceLock::new();
static SUBSCRIBE_ONCE_QUEUE: OnceLock<ReadProjectionQueue> = OnceLock::new();

thread_local! {
    static READ_PROJECTION_LOCK_TIMEOUT_OVERRIDE: Cell<Option<Duration>> = const { Cell::new(None) };
}

const CONNECT_RETRY_DELAYS_MS: [u64; 2] = [150, 500];
const OPTIONAL_READ_DEGRADE_WINDOW: Duration = Duration::from_secs(15);
const DEFAULT_READ_PROJECTION_LOCK_TIMEOUT: Duration = Duration::from_secs(5);
const MAX_PENDING_READ_PROJECTIONS: usize = 256;
const READ_PROJECTION_PENDING: u8 = 0;
const READ_PROJECTION_CANCELLED: u8 = 1;
const READ_PROJECTION_GRANTED: u8 = 2;

#[derive(Debug)]
struct ReadProjectionWaiter {
    ticket: u64,
    deadline: Instant,
    status: Arc<AtomicU8>,
    permit: mpsc::Sender<()>,
}

#[derive(Debug, Default)]
struct ReadProjectionQueueState {
    next_ticket: u64,
    serving_ticket: u64,
    active: bool,
    waiters: VecDeque<ReadProjectionWaiter>,
}

#[derive(Debug, Default)]
struct ReadProjectionQueue {
    state: Mutex<ReadProjectionQueueState>,
}

#[derive(Debug)]
struct ReadProjectionLease<'a> {
    queue: &'a ReadProjectionQueue,
    ticket: u64,
}

impl Drop for ReadProjectionLease<'_> {
    fn drop(&mut self) {
        let Ok(mut state) = self.queue.state.lock() else {
            return;
        };
        if !state.active || state.serving_ticket != self.ticket {
            return;
        }
        state.active = false;
        state.serving_ticket = self.ticket.saturating_add(1);
        advance_read_projection_queue(&mut state);
    }
}

/// Typed lifecycle failure while entering or executing a serialized read projection.
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
#[non_exhaustive]
pub enum ReadProjectionError {
    /// The caller did not acquire its FIFO lease before the bounded admission timeout.
    #[error(
        "SpacetimeDB read projection is busy; FIFO admission timed out before the read started"
    )]
    BusyBeforeStart,
    /// Shared queue state was poisoned by an unrecoverable synchronization failure.
    #[error("SpacetimeDB read projection queue was poisoned")]
    QueuePoisoned,
    /// The monotonic queue ticket space was exhausted.
    #[error("SpacetimeDB read projection queue exhausted its ticket space")]
    TicketSpaceExhausted,
    /// The caller supplied an admission timeout outside the monotonic clock range.
    #[error("SpacetimeDB read projection admission timeout exceeded the monotonic clock range")]
    AdmissionDeadlineOverflow,
    /// The app-owned projection failed after it acquired the shared lease.
    #[error("{0}")]
    Operation(String),
}

struct ReadProjectionLockTimeoutGuard<'a> {
    cell: &'a Cell<Option<Duration>>,
    previous: Option<Duration>,
}

impl Drop for ReadProjectionLockTimeoutGuard<'_> {
    fn drop(&mut self) {
        self.cell.set(self.previous);
    }
}

impl ReadProjectionQueue {
    fn acquire(&self, timeout: Duration) -> Result<ReadProjectionLease<'_>, ReadProjectionError> {
        let deadline = Instant::now()
            .checked_add(timeout)
            .ok_or(ReadProjectionError::AdmissionDeadlineOverflow)?;
        let mut state = self.lock_state_until(deadline)?;
        if state.waiters.len() >= MAX_PENDING_READ_PROJECTIONS {
            return Err(ReadProjectionError::BusyBeforeStart);
        }
        let ticket = state.next_ticket;
        state.next_ticket = state
            .next_ticket
            .checked_add(1)
            .ok_or(ReadProjectionError::TicketSpaceExhausted)?;
        if !state.active && state.waiters.is_empty() {
            state.active = true;
            state.serving_ticket = ticket;
            return Ok(ReadProjectionLease {
                queue: self,
                ticket,
            });
        }

        let status = Arc::new(AtomicU8::new(READ_PROJECTION_PENDING));
        let (permit, granted) = mpsc::channel();
        state.waiters.push_back(ReadProjectionWaiter {
            ticket,
            deadline,
            status: Arc::clone(&status),
            permit,
        });
        drop(state);

        let remaining = deadline.saturating_duration_since(Instant::now());
        match granted.recv_timeout(remaining) {
            Ok(()) => Ok(ReadProjectionLease {
                queue: self,
                ticket,
            }),
            Err(mpsc::RecvTimeoutError::Timeout) => {
                if status
                    .compare_exchange(
                        READ_PROJECTION_PENDING,
                        READ_PROJECTION_CANCELLED,
                        Ordering::AcqRel,
                        Ordering::Acquire,
                    )
                    .is_ok()
                {
                    return Err(ReadProjectionError::BusyBeforeStart);
                }
                if status.load(Ordering::Acquire) != READ_PROJECTION_GRANTED {
                    return Err(ReadProjectionError::BusyBeforeStart);
                }
                granted
                    .recv()
                    .map_err(|_| ReadProjectionError::QueuePoisoned)?;
                Ok(ReadProjectionLease {
                    queue: self,
                    ticket,
                })
            }
            Err(mpsc::RecvTimeoutError::Disconnected) => Err(ReadProjectionError::BusyBeforeStart),
        }
    }

    fn lock_state_until(
        &self,
        deadline: Instant,
    ) -> Result<MutexGuard<'_, ReadProjectionQueueState>, ReadProjectionError> {
        let mut first_attempt = true;
        loop {
            if !first_attempt && Instant::now() >= deadline {
                return Err(ReadProjectionError::BusyBeforeStart);
            }
            match self.state.try_lock() {
                Ok(state) => return Ok(state),
                Err(TryLockError::Poisoned(_)) => {
                    return Err(ReadProjectionError::QueuePoisoned);
                }
                Err(TryLockError::WouldBlock) => {
                    first_attempt = false;
                    let now = Instant::now();
                    if now >= deadline {
                        return Err(ReadProjectionError::BusyBeforeStart);
                    }
                    thread::park_timeout(
                        deadline
                            .saturating_duration_since(now)
                            .min(Duration::from_millis(1)),
                    );
                }
            }
        }
    }
}

fn advance_read_projection_queue(state: &mut ReadProjectionQueueState) {
    debug_assert!(state.waiters.len() <= MAX_PENDING_READ_PROJECTIONS);
    while let Some(waiter) = state.waiters.pop_front() {
        state.serving_ticket = waiter.ticket;
        if Instant::now() >= waiter.deadline {
            let _ = waiter.status.compare_exchange(
                READ_PROJECTION_PENDING,
                READ_PROJECTION_CANCELLED,
                Ordering::AcqRel,
                Ordering::Acquire,
            );
            state.serving_ticket = waiter.ticket.saturating_add(1);
            continue;
        }
        if waiter
            .status
            .compare_exchange(
                READ_PROJECTION_PENDING,
                READ_PROJECTION_GRANTED,
                Ordering::AcqRel,
                Ordering::Acquire,
            )
            .is_err()
        {
            state.serving_ticket = waiter.ticket.saturating_add(1);
            continue;
        }
        if waiter.permit.send(()).is_ok() {
            state.active = true;
            return;
        }
        waiter
            .status
            .store(READ_PROJECTION_CANCELLED, Ordering::Release);
        state.serving_ticket = waiter.ticket.saturating_add(1);
    }
}

/// Concrete SpacetimeDB database target shared by app-owned clients.
#[derive(Clone, PartialEq, Eq)]
pub struct ConnectionTarget {
    /// HTTP or WebSocket endpoint used by the generated client.
    pub endpoint_url: String,
    /// Deployed SpacetimeDB module name.
    pub module_name: String,
    /// Optional bearer token used to authenticate the connection.
    pub auth_token: Option<String>,
}

impl ConnectionTarget {
    /// Creates an unauthenticated connection target.
    #[must_use]
    pub fn new(endpoint_url: impl Into<String>, module_name: impl Into<String>) -> Self {
        Self {
            endpoint_url: endpoint_url.into(),
            module_name: module_name.into(),
            auth_token: None,
        }
    }

    /// Attaches a bearer token while keeping it redacted from debug output.
    #[must_use]
    pub fn with_auth_token(mut self, auth_token: impl Into<String>) -> Self {
        self.auth_token = Some(auth_token.into());
        self
    }
}

impl fmt::Debug for ConnectionTarget {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ConnectionTarget")
            .field("endpoint_url", &self.endpoint_url)
            .field("module_name", &self.module_name)
            .field(
                "auth_token",
                &self.auth_token.as_ref().map(|_| "[REDACTED]"),
            )
            .finish()
    }
}

/// Shared connection state reported by an app-owned generated connection builder.
///
/// The app builder wires `mark_disconnected` into the generated SDK's
/// `on_disconnect` callback and calls `mark_connected` only after its required
/// subscriptions have been applied. The shared client uses that state to rebuild
/// the complete connection without duplicating reconnect policy in each app.
#[derive(Clone, Default)]
pub struct SpacetimeDbConnectionStatus {
    connected: Arc<AtomicBool>,
}

impl SpacetimeDbConnectionStatus {
    /// Marks the generated connection and its required subscriptions ready.
    pub fn mark_connected(&self) {
        self.connected.store(true, Ordering::Release);
    }

    /// Marks the generated connection unavailable so the next access reconnects.
    pub fn mark_disconnected(&self) {
        self.connected.store(false, Ordering::Release);
    }

    /// Returns whether the complete app-owned connection is ready for use.
    #[must_use]
    pub fn is_connected(&self) -> bool {
        self.connected.load(Ordering::Acquire)
    }
}

/// One generated connection, its worker, and resources tied to that connection.
///
/// App clients may retain generated subscription handles through `keep_alive`.
/// All retained resources are released before disconnecting the generated client.
pub struct ManagedSpacetimeDbConnection<Connection>
where
    Connection: DbContext + Send + 'static,
{
    connection: Option<Connection>,
    worker: Option<thread::JoinHandle<()>>,
    keepalive: Vec<Box<dyn Send + Sync>>,
    cleanup_thread_name: String,
    status: Option<SpacetimeDbConnectionStatus>,
}

impl<Connection> ManagedSpacetimeDbConnection<Connection>
where
    Connection: DbContext + Send + 'static,
{
    /// Wraps a generated connection and its background worker in the shared owner.
    pub fn new(connection: Connection, worker: thread::JoinHandle<()>) -> Self {
        Self {
            connection: Some(connection),
            worker: Some(worker),
            keepalive: Vec::new(),
            cleanup_thread_name: "spacetimedb-cleanup".to_owned(),
            status: None,
        }
    }

    /// Returns the generated connection while an app builder finishes setup.
    pub fn connection(&self) -> &Connection {
        self.connection
            .as_ref()
            .expect("SpacetimeDB connection is only taken during Drop")
    }

    /// Keeps a connection-scoped callback or subscription handle alive.
    pub fn keep_alive(&mut self, resource: impl Send + Sync + 'static) {
        self.keepalive.push(Box::new(resource));
    }

    fn set_cleanup_thread_name(&mut self, cleanup_thread_name: String) {
        self.cleanup_thread_name = cleanup_thread_name;
    }

    fn set_status(&mut self, status: SpacetimeDbConnectionStatus) {
        self.status = Some(status);
    }
}

impl<Connection> Drop for ManagedSpacetimeDbConnection<Connection>
where
    Connection: DbContext + Send + 'static,
{
    fn drop(&mut self) {
        let connection = self.connection.take();
        let worker = self.worker.take();
        let keepalive = std::mem::take(&mut self.keepalive);
        if connection.is_none() && worker.is_none() && keepalive.is_empty() {
            return;
        }

        let cleanup_thread_name = self.cleanup_thread_name.clone();
        let _ = thread::Builder::new()
            .name(cleanup_thread_name)
            .spawn(move || {
                for resource in keepalive {
                    let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                        drop(resource);
                    }));
                }
                if let Some(connection) = connection {
                    let connection = ManuallyDrop::new(connection);
                    let disconnected =
                        std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                            let _ = connection.disconnect();
                        }))
                        .is_ok();
                    if disconnected {
                        let connection = ManuallyDrop::into_inner(connection);
                        let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                            drop(connection);
                        }));
                    }
                }
                if let Some(worker) = worker {
                    let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                        let _ = worker.join();
                    }));
                }
            });
    }
}

type ReconnectBuilder<Connection> = dyn Fn(
        &ConnectionTarget,
        SpacetimeDbConnectionStatus,
    ) -> Result<ManagedSpacetimeDbConnection<Connection>, String>
    + Send
    + Sync;

enum SpacetimeDbClientConnection<Connection>
where
    Connection: DbContext + Send + 'static,
{
    Fixed(ManagedSpacetimeDbConnection<Connection>),
    Reconnecting(RwLock<ManagedSpacetimeDbConnection<Connection>>),
}

/// Shared lifecycle owner for generated app-specific SpacetimeDB connections.
///
/// Apps still own their generated `DbConnection` type, table accessors, reducers,
/// subscriptions, and row projection logic. This shared owner centralizes retry,
/// reconnect, worker ownership, optional-read degradation, serial read-projection
/// throttling, and panic-tolerant cleanup.
pub struct SpacetimeDbClient<Connection>
where
    Connection: DbContext + Send + 'static,
{
    target: ConnectionTarget,
    connection_label: String,
    connection: SpacetimeDbClientConnection<Connection>,
    reconnect_builder: Option<Arc<ReconnectBuilder<Connection>>>,
}

/// Process-local registry for sharing one reconnecting client per database target.
pub struct SpacetimeDbClientRegistry<Connection>
where
    Connection: DbContext + Send + 'static,
{
    clients: Mutex<Vec<(ConnectionTarget, Arc<SpacetimeDbClient<Connection>>)>>,
}

/// Failure while resolving a shared SpacetimeDB client.
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
#[non_exhaustive]
pub enum SpacetimeDbClientRegistryError {
    /// The process-local registry can no longer be accessed safely.
    #[error("SpacetimeDB client registry lock was poisoned")]
    LockPoisoned,
    /// A generated app client could not connect to its configured target.
    #[error("SpacetimeDB client {label} could not connect: {message}")]
    Connection {
        /// Human-readable owner label supplied by the app client.
        label: String,
        /// Concrete connection failure returned by the generated client builder.
        message: String,
    },
}

impl<Connection> SpacetimeDbClientRegistry<Connection>
where
    Connection: DbContext + Send + 'static,
{
    /// Creates an empty shared-client registry.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            clients: Mutex::new(Vec::new()),
        }
    }

    /// Returns the existing client for `target` or builds and retains one.
    pub fn get_or_connect_reconnecting<Build>(
        &self,
        target: ConnectionTarget,
        connection_label: impl Into<String>,
        build: Build,
    ) -> Result<Arc<SpacetimeDbClient<Connection>>, SpacetimeDbClientRegistryError>
    where
        Build: Fn(
                &ConnectionTarget,
                SpacetimeDbConnectionStatus,
            ) -> Result<ManagedSpacetimeDbConnection<Connection>, String>
            + Send
            + Sync
            + 'static,
    {
        let connection_label = connection_label.into();
        let mut clients = self
            .clients
            .lock()
            .map_err(|_| SpacetimeDbClientRegistryError::LockPoisoned)?;
        if let Some((_, client)) = clients.iter().find(|(candidate, _)| candidate == &target) {
            return Ok(Arc::clone(client));
        }

        let client = Arc::new(
            SpacetimeDbClient::connect_reconnecting(
                target.clone(),
                connection_label.clone(),
                build,
            )
            .map_err(|message| SpacetimeDbClientRegistryError::Connection {
                label: connection_label,
                message,
            })?,
        );
        clients.push((target, Arc::clone(&client)));
        Ok(client)
    }
}

impl<Connection> Default for SpacetimeDbClientRegistry<Connection>
where
    Connection: DbContext + Send + 'static,
{
    fn default() -> Self {
        Self::new()
    }
}

/// Read guard for the generated connection currently owned by the shared client.
pub struct SpacetimeDbConnectionGuard<'a, Connection>
where
    Connection: DbContext + Send + 'static,
{
    connection: RwLockReadGuard<'a, ManagedSpacetimeDbConnection<Connection>>,
}

impl<Connection> Deref for SpacetimeDbConnectionGuard<'_, Connection>
where
    Connection: DbContext + Send + 'static,
{
    type Target = Connection;

    fn deref(&self) -> &Self::Target {
        self.connection.connection()
    }
}

impl<Connection> SpacetimeDbClient<Connection>
where
    Connection: DbContext + Send + 'static,
{
    /// Connects a required app-owned client using the shared retry and cleanup policy.
    pub fn connect<Build>(
        target: ConnectionTarget,
        connection_label: impl Into<String>,
        build: Build,
    ) -> Result<Self, String>
    where
        Build: FnMut(&ConnectionTarget) -> Result<(Connection, thread::JoinHandle<()>), String>
            + Send
            + 'static,
    {
        let connection_label = connection_label.into();
        let connection =
            connect_with_retries(target.clone(), connection_label.clone(), build, false)?;
        Ok(Self {
            target,
            connection_label,
            connection: SpacetimeDbClientConnection::Fixed(connection),
            reconnect_builder: None,
        })
    }

    /// Connects an optional read projection unless its shared circuit breaker is degraded.
    pub fn connect_optional_read<Build>(
        target: ConnectionTarget,
        connection_label: impl Into<String>,
        build: Build,
    ) -> Result<Self, String>
    where
        Build: FnMut(&ConnectionTarget) -> Result<(Connection, thread::JoinHandle<()>), String>
            + Send
            + 'static,
    {
        ensure_optional_read_not_degraded()?;
        let connection_label = connection_label.into();
        let connection =
            connect_with_retries(target.clone(), connection_label.clone(), build, true)?;
        Ok(Self {
            target,
            connection_label,
            connection: SpacetimeDbClientConnection::Fixed(connection),
            reconnect_builder: None,
        })
    }

    /// Connects a required app-owned client and restores it after disconnection.
    pub fn connect_reconnecting<Build>(
        target: ConnectionTarget,
        connection_label: impl Into<String>,
        build: Build,
    ) -> Result<Self, String>
    where
        Build: Fn(
                &ConnectionTarget,
                SpacetimeDbConnectionStatus,
            ) -> Result<ManagedSpacetimeDbConnection<Connection>, String>
            + Send
            + Sync
            + 'static,
    {
        let connection_label = connection_label.into();
        let reconnect_builder: Arc<ReconnectBuilder<Connection>> = Arc::new(build);
        let connection = connect_reconnecting_with_retries(
            target.clone(),
            connection_label.clone(),
            reconnect_builder.clone(),
        )?;
        Ok(Self {
            target,
            connection_label,
            connection: SpacetimeDbClientConnection::Reconnecting(RwLock::new(connection)),
            reconnect_builder: Some(reconnect_builder),
        })
    }

    /// Returns a fixed generated connection owned by this lifecycle guard.
    ///
    /// Reconnecting clients use `reconnecting_connection` so access remains locked
    /// while a disconnected connection is replaced.
    pub fn connection(&self) -> &Connection {
        let SpacetimeDbClientConnection::Fixed(connection) = &self.connection else {
            panic!("reconnecting SpacetimeDB clients use reconnecting_connection")
        };
        connection.connection()
    }

    /// Returns the current reconnecting connection, rebuilding it when required.
    pub fn reconnecting_connection(
        &self,
    ) -> Result<SpacetimeDbConnectionGuard<'_, Connection>, String> {
        self.ensure_connected()?;
        let SpacetimeDbClientConnection::Reconnecting(connection) = &self.connection else {
            return Err("fixed SpacetimeDB clients use connection".to_owned());
        };
        connection
            .read()
            .map(|connection| SpacetimeDbConnectionGuard { connection })
            .map_err(|_| "SpacetimeDB connection lock was poisoned".to_owned())
    }

    /// Returns the last connection status reported by a reconnecting client.
    #[must_use]
    pub fn is_connected(&self) -> bool {
        match &self.connection {
            SpacetimeDbClientConnection::Fixed(_) => true,
            SpacetimeDbClientConnection::Reconnecting(connection) => {
                connection.read().is_ok_and(|connection| {
                    connection
                        .status
                        .as_ref()
                        .is_some_and(SpacetimeDbConnectionStatus::is_connected)
                })
            }
        }
    }

    /// Invalidates the current reconnecting connection after an incomplete
    /// connection-scoped operation.
    ///
    /// The next `reconnecting_connection` access rebuilds the app-owned
    /// connection through its registered builder.
    pub fn invalidate_reconnecting_connection(&self) -> Result<(), String> {
        let SpacetimeDbClientConnection::Reconnecting(connection) = &self.connection else {
            return Err("fixed SpacetimeDB clients cannot be invalidated".to_owned());
        };
        let connection = connection
            .read()
            .map_err(|_| "SpacetimeDB connection lock was poisoned".to_owned())?;
        let status = connection
            .status
            .as_ref()
            .ok_or_else(|| "SpacetimeDB reconnecting connection has no status owner".to_owned())?;
        status.mark_disconnected();
        Ok(())
    }

    fn ensure_connected(&self) -> Result<(), String> {
        let Some(reconnect_builder) = self.reconnect_builder.as_ref() else {
            return Ok(());
        };
        let SpacetimeDbClientConnection::Reconnecting(connection) = &self.connection else {
            return Err("SpacetimeDB reconnect builder has no reconnecting connection".to_owned());
        };
        {
            let connection = connection
                .read()
                .map_err(|_| "SpacetimeDB connection lock was poisoned".to_owned())?;
            if connection
                .status
                .as_ref()
                .is_some_and(SpacetimeDbConnectionStatus::is_connected)
            {
                return Ok(());
            }
        }

        let mut connection = connection
            .write()
            .map_err(|_| "SpacetimeDB connection lock was poisoned".to_owned())?;
        if connection
            .status
            .as_ref()
            .is_some_and(SpacetimeDbConnectionStatus::is_connected)
        {
            return Ok(());
        }
        *connection = connect_reconnecting_with_retries(
            self.target.clone(),
            self.connection_label.clone(),
            reconnect_builder.clone(),
        )?;
        Ok(())
    }
}

/// Runs one read projection while holding the shared FIFO subscription lease.
///
/// Subscription projections share one generated-client cache, so overlapping
/// projections are not safe. FIFO admission prevents a burst of newer readers
/// from starving an earlier request, while the caller-scoped admission timeout
/// keeps the queue bounded.
pub fn with_serialized_read_projection<T>(
    read_projection: impl FnOnce() -> Result<T, String>,
) -> Result<T, String> {
    with_serialized_read_projection_typed(read_projection).map_err(|error| match error {
        ReadProjectionError::Operation(error) => error,
        error => error.to_string(),
    })
}

/// Typed variant of [`with_serialized_read_projection`].
///
/// Apps that need to distinguish admission pressure from a projection failure
/// should use this owner instead of classifying error strings.
pub fn with_serialized_read_projection_typed<T>(
    read_projection: impl FnOnce() -> Result<T, String>,
) -> Result<T, ReadProjectionError> {
    let lock_timeout = READ_PROJECTION_LOCK_TIMEOUT_OVERRIDE
        .with(|timeout| timeout.get())
        .unwrap_or(DEFAULT_READ_PROJECTION_LOCK_TIMEOUT);
    let _lease = subscribe_once_queue().acquire(lock_timeout)?;
    let result = read_projection();
    if let Err(error) = &result {
        record_optional_read_failure(error.as_str());
    }
    result.map_err(ReadProjectionError::Operation)
}

/// Applies a shorter projection-lock budget to reads that are optional for the
/// caller, without weakening required product reads on the same client.
pub fn with_read_projection_lock_timeout<T>(timeout: Duration, operation: impl FnOnce() -> T) -> T {
    READ_PROJECTION_LOCK_TIMEOUT_OVERRIDE.with(|cell| {
        let _guard = ReadProjectionLockTimeoutGuard {
            cell,
            previous: cell.replace(Some(timeout)),
        };
        operation()
    })
}

/// Returns the caller-scoped optional projection budget, when one is active.
/// App-owned clients use the same budget for subscription cleanup so a fast
/// optional read cannot outlive its outer bootstrap timeout.
#[must_use]
pub fn read_projection_timeout_override() -> Option<Duration> {
    READ_PROJECTION_LOCK_TIMEOUT_OVERRIDE.with(|timeout| timeout.get())
}

/// Sets the process-wide SpacetimeDB endpoint discovered by the runtime adapter.
///
/// The first non-empty endpoint wins for the lifetime of the process.
pub fn set_runtime_endpoint_url(endpoint_url: impl Into<String>) {
    let endpoint_url = endpoint_url.into().trim().to_string();
    if endpoint_url.is_empty() {
        return;
    }

    let _ = RUNTIME_ENDPOINT_URL.set(endpoint_url);
}

/// Returns the process-wide SpacetimeDB endpoint, when one has been configured.
pub fn runtime_endpoint_url() -> Option<String> {
    RUNTIME_ENDPOINT_URL.get().cloned()
}

/// Invalid component in a scoped storage key.
#[derive(Clone, Copy, Debug, thiserror::Error, PartialEq, Eq)]
#[non_exhaustive]
pub enum ScopedKeyError {
    /// A component was empty after trimming.
    #[error("scoped key parts must not be empty")]
    EmptyPart,
    /// A component contains the separator and would make the key ambiguous.
    #[error("scoped key parts must not contain ':'")]
    ContainsSeparator,
    /// Leading or trailing whitespace would change the key silently.
    #[error("scoped key parts must not contain surrounding whitespace")]
    SurroundingWhitespace,
}

/// Builds a validated two-part colon-delimited key.
pub fn scoped_key(left: &str, right: &str) -> Result<String, ScopedKeyError> {
    validate_scoped_key_part(left)?;
    validate_scoped_key_part(right)?;
    Ok(format!("{left}:{right}"))
}

/// Builds a validated three-part colon-delimited key.
pub fn scoped_key3(left: &str, middle: &str, right: &str) -> Result<String, ScopedKeyError> {
    validate_scoped_key_part(left)?;
    validate_scoped_key_part(middle)?;
    validate_scoped_key_part(right)?;
    Ok(format!("{left}:{middle}:{right}"))
}

fn validate_scoped_key_part(part: &str) -> Result<(), ScopedKeyError> {
    if part.trim().is_empty() {
        return Err(ScopedKeyError::EmptyPart);
    }
    if part.trim() != part {
        return Err(ScopedKeyError::SurroundingWhitespace);
    }
    if part.contains(':') {
        return Err(ScopedKeyError::ContainsSeparator);
    }
    Ok(())
}

fn connect_with_retries<Connection, Build>(
    target: ConnectionTarget,
    connection_label: String,
    mut build: Build,
    optional_read: bool,
) -> Result<ManagedSpacetimeDbConnection<Connection>, String>
where
    Connection: DbContext + Send + 'static,
    Build: FnMut(&ConnectionTarget) -> Result<(Connection, thread::JoinHandle<()>), String>
        + Send
        + 'static,
{
    connect_managed_with_retries(
        target,
        connection_label,
        move |target| {
            let (connection, worker) = build(target)?;
            Ok(ManagedSpacetimeDbConnection::new(connection, worker))
        },
        optional_read,
    )
}

fn connect_reconnecting_with_retries<Connection>(
    target: ConnectionTarget,
    connection_label: String,
    build: Arc<ReconnectBuilder<Connection>>,
) -> Result<ManagedSpacetimeDbConnection<Connection>, String>
where
    Connection: DbContext + Send + 'static,
{
    let readiness_label = connection_label.clone();
    connect_managed_with_retries(
        target,
        connection_label,
        move |target| {
            let status = SpacetimeDbConnectionStatus::default();
            let mut connection = build(target, status.clone())?;
            if !status.is_connected() {
                return Err(format!(
                    "SpacetimeDB {readiness_label} connection setup did not mark the connection ready"
                ));
            }
            connection.set_status(status);
            Ok(connection)
        },
        false,
    )
}

fn connect_managed_with_retries<Connection, Build>(
    target: ConnectionTarget,
    connection_label: String,
    mut build: Build,
    optional_read: bool,
) -> Result<ManagedSpacetimeDbConnection<Connection>, String>
where
    Connection: DbContext + Send + 'static,
    Build: FnMut(&ConnectionTarget) -> Result<ManagedSpacetimeDbConnection<Connection>, String>
        + Send
        + 'static,
{
    let cleanup_thread_name = cleanup_thread_name(connection_label.as_str());
    let endpoint_url = target.endpoint_url.clone();
    let module_name = target.module_name.clone();
    let thread_endpoint_url = endpoint_url.clone();
    let thread_module_name = module_name.clone();
    let thread_label = connection_label.clone();
    let connection_thread = thread::spawn(move || {
        let mut last_error = None;
        for attempt in 0..=CONNECT_RETRY_DELAYS_MS.len() {
            match build(&target) {
                Ok(connection) => return Ok(connection),
                Err(error) => {
                    last_error = Some(error);
                    if let Some(delay_ms) = CONNECT_RETRY_DELAYS_MS.get(attempt) {
                        thread::sleep(Duration::from_millis(*delay_ms));
                    }
                }
            }
        }
        Err(last_error.unwrap_or_else(|| {
            format!(
                "SpacetimeDB {thread_label} connection to {thread_module_name} at {thread_endpoint_url} failed"
            )
        }))
    });

    let mut connection = match connection_thread.join() {
        Ok(Ok(connection)) => connection,
        Ok(Err(error)) => {
            if optional_read {
                record_optional_read_failure(error.as_str());
            }
            return Err(error);
        }
        Err(payload) => {
            let message = panic_message(
                &payload,
                format!(
                    "SpacetimeDB {connection_label} connection to {module_name} at {endpoint_url} panicked"
                ),
            );
            if optional_read {
                record_optional_read_failure(message.as_str());
            }
            return Err(message);
        }
    };
    connection.set_cleanup_thread_name(cleanup_thread_name);
    Ok(connection)
}

fn cleanup_thread_name(connection_label: &str) -> String {
    let label = connection_label
        .chars()
        .map(|value| {
            if value.is_ascii_alphanumeric() {
                value.to_ascii_lowercase()
            } else {
                '-'
            }
        })
        .collect::<String>()
        .trim_matches('-')
        .to_string();
    match label.as_str() {
        "" => "spacetimedb-cleanup".to_owned(),
        _ => format!("{label}-cleanup"),
    }
}

fn panic_message(payload: &Box<dyn std::any::Any + Send>, fallback: String) -> String {
    if let Some(message) = payload.downcast_ref::<&str>() {
        format!("{fallback}: {message}")
    } else if let Some(message) = payload.downcast_ref::<String>() {
        format!("{fallback}: {message}")
    } else {
        fallback
    }
}

fn optional_read_degraded_until() -> &'static Mutex<Option<Instant>> {
    OPTIONAL_READ_DEGRADED_UNTIL.get_or_init(|| Mutex::new(None))
}

fn subscribe_once_queue() -> &'static ReadProjectionQueue {
    SUBSCRIBE_ONCE_QUEUE.get_or_init(ReadProjectionQueue::default)
}

fn ensure_optional_read_not_degraded() -> Result<(), String> {
    let mut degraded_until = optional_read_degraded_until()
        .lock()
        .map_err(|_| "SpacetimeDB optional read circuit breaker was poisoned".to_string())?;
    let Some(until) = *degraded_until else {
        return Ok(());
    };
    if Instant::now() < until {
        return Err(
            "SpacetimeDB optional read projections are temporarily degraded after a recent live-state failure"
                .to_string(),
        );
    }
    *degraded_until = None;
    Ok(())
}

/// Records a transport-level optional-read failure in the shared circuit breaker.
pub fn record_optional_read_failure(error: &str) {
    if !is_optional_read_circuit_breaking_error(error) {
        return;
    }
    if let Ok(mut degraded_until) = optional_read_degraded_until().lock() {
        *degraded_until = Some(Instant::now() + OPTIONAL_READ_DEGRADE_WINDOW);
    }
}

/// Reports whether an optional-read error should degrade its caller-facing feature.
pub fn is_optional_read_degrading_error(error: &str) -> bool {
    let error = error.to_ascii_lowercase();
    [
        "connection refused",
        "subscription did not apply",
        "subscription failed before read projection",
        "read projection is busy",
        "live-state connection",
        "panicked",
        "buffer should be unique",
    ]
    .into_iter()
    .any(|needle| error.contains(needle))
}

fn is_optional_read_circuit_breaking_error(error: &str) -> bool {
    let error = error.to_ascii_lowercase();
    [
        "connection refused",
        "live-state connection",
        "panicked",
        "buffer should be unique",
    ]
    .into_iter()
    .any(|needle| error.contains(needle))
}

#[cfg(test)]
mod tests {
    use super::{
        ConnectionTarget, MAX_PENDING_READ_PROJECTIONS, READ_PROJECTION_CANCELLED,
        ReadProjectionError, ReadProjectionQueue, ReadProjectionWaiter,
        SpacetimeDbConnectionStatus, is_optional_read_circuit_breaking_error,
        is_optional_read_degrading_error, runtime_endpoint_url, scoped_key, scoped_key3,
        set_runtime_endpoint_url, with_serialized_read_projection,
        with_serialized_read_projection_typed,
    };
    use std::sync::atomic::AtomicU8;
    use std::sync::{Arc, Mutex, mpsc};
    use std::thread;
    use std::time::{Duration, Instant};

    #[test]
    fn connection_target_debug_output_redacts_auth_token() {
        let target = ConnectionTarget::new("https://database.example.invalid", "module")
            .with_auth_token("visible-auth-token");

        let debug = format!("{target:?}");

        assert!(!debug.contains("visible-auth-token"));
        assert!(debug.contains("[REDACTED]"));
    }

    #[test]
    fn reconnect_status_is_shared_without_relaxed_visibility() {
        let status = SpacetimeDbConnectionStatus::default();
        let callback_status = status.clone();

        assert!(!status.is_connected());
        status.mark_connected();
        assert!(callback_status.is_connected());
        callback_status.mark_disconnected();
        assert!(!status.is_connected());
    }

    #[test]
    fn scoped_key_rejects_blank_parts() {
        assert!(scoped_key("", "session").is_err());
        assert!(scoped_key("owner", " ").is_err());
        assert_eq!(
            scoped_key("owner", "session").expect("valid key"),
            "owner:session"
        );
        assert!(scoped_key("owner:project", "timeline").is_err());
        assert!(scoped_key(" owner", "timeline").is_err());
        assert_eq!(
            scoped_key3("owner", "project", "timeline").expect("valid key"),
            "owner:project:timeline"
        );
    }

    #[test]
    fn runtime_endpoint_url_ignores_blank_values() {
        set_runtime_endpoint_url(" ");

        assert_eq!(runtime_endpoint_url(), None);
    }

    #[test]
    fn optional_read_degrade_detection_matches_live_state_failures() {
        assert!(is_optional_read_degrading_error(
            "SpacetimeDB live-state connection to module at http://127.0.0.1:4531 failed: connection refused"
        ));
        assert!(is_optional_read_degrading_error(
            "SpacetimeDB subscription did not apply before read projection timeout: timed out waiting on channel"
        ));
        assert!(is_optional_read_degrading_error(
            "thread panicked at crates/client-api/src/routes/subscribe.rs:1366:48: buffer should be unique"
        ));
    }

    #[test]
    fn optional_read_degrade_detection_ignores_domain_errors() {
        assert!(!is_optional_read_degrading_error(
            "requested record does not exist"
        ));
        assert!(!is_optional_read_degrading_error(
            "stored payload could not be deserialized"
        ));
    }

    #[test]
    fn optional_read_circuit_breaker_ignores_subscription_apply_timeouts() {
        assert!(!is_optional_read_circuit_breaking_error(
            "SpacetimeDB subscription did not apply before read projection timeout: timed out waiting on channel"
        ));
        assert!(is_optional_read_degrading_error(
            "SpacetimeDB subscription did not apply before read projection timeout: timed out waiting on channel"
        ));
        assert!(is_optional_read_circuit_breaking_error(
            "SpacetimeDB live-state connection to module at http://127.0.0.1:4531 failed: connection refused"
        ));
        assert!(is_optional_read_circuit_breaking_error(
            "thread panicked at crates/client-api/src/routes/subscribe.rs:1366:48: buffer should be unique"
        ));
    }

    #[test]
    fn typed_projection_errors_preserve_operation_failures_without_string_classification() {
        let typed_error = with_serialized_read_projection_typed::<()>(|| {
            Err("domain projection failed".to_string())
        })
        .expect_err("typed projection failure");
        assert_eq!(
            typed_error,
            ReadProjectionError::Operation("domain projection failed".to_string())
        );

        let legacy_error =
            with_serialized_read_projection::<()>(|| Err("domain projection failed".to_string()))
                .expect_err("legacy projection failure");
        assert_eq!(legacy_error, "domain projection failed");
    }

    #[test]
    fn serialized_read_projection_reports_typed_bounded_admission_failure() {
        let queue = ReadProjectionQueue::default();
        let _lease = queue
            .acquire(Duration::from_secs(1))
            .expect("first projection lease");
        let started_at = Instant::now();

        let error = queue
            .acquire(Duration::from_millis(25))
            .expect_err("contended projection must remain bounded");

        assert_eq!(error, ReadProjectionError::BusyBeforeStart);
        assert!(error.to_string().contains("read projection is busy"));
        assert!(started_at.elapsed() < Duration::from_secs(1));
        assert!(is_optional_read_degrading_error(error.to_string().as_str()));
    }

    #[test]
    fn projection_admission_deadline_includes_queue_state_lock_contention() {
        let queue = Arc::new(ReadProjectionQueue::default());
        let state = queue.state.lock().expect("projection queue state");
        let contender_queue = Arc::clone(&queue);
        let (result_tx, result_rx) = mpsc::channel();
        let contender = thread::spawn(move || {
            result_tx
                .send(
                    contender_queue
                        .acquire(Duration::from_millis(25))
                        .map(|_| ()),
                )
                .expect("contender result receiver");
        });

        let started_at = Instant::now();
        assert_eq!(
            result_rx
                .recv_timeout(Duration::from_millis(100))
                .expect("queue-state contention must honor the admission deadline"),
            Err(ReadProjectionError::BusyBeforeStart)
        );
        assert!(started_at.elapsed() < Duration::from_millis(100));
        assert_eq!(state.next_ticket, 0);
        drop(state);
        contender.join().expect("projection contender");
    }

    #[test]
    fn projection_waiter_is_not_admitted_after_its_deadline() {
        let queue = Arc::new(ReadProjectionQueue::default());
        let first_lease = queue
            .acquire(Duration::from_secs(1))
            .expect("first projection lease");

        let waiter_queue = Arc::clone(&queue);
        let (waiter_result_tx, waiter_result_rx) = mpsc::channel();
        let waiter = thread::spawn(move || {
            waiter_result_tx
                .send(waiter_queue.acquire(Duration::from_millis(25)).map(|_| ()))
                .expect("waiter result receiver");
        });
        wait_for_projection_ticket_count(queue.as_ref(), 2);

        let state = queue.state.lock().expect("projection queue state");
        let started_at = Instant::now();
        assert_eq!(
            waiter_result_rx
                .recv_timeout(Duration::from_millis(100))
                .expect("waiter must honor its deadline without reacquiring queue state"),
            Err(ReadProjectionError::BusyBeforeStart)
        );
        assert!(started_at.elapsed() < Duration::from_millis(100));
        drop(state);
        waiter.join().expect("projection waiter");
        drop(first_lease);
    }

    #[test]
    fn cancelled_projection_backlog_is_bounded_and_released_in_one_pass() {
        let queue = ReadProjectionQueue::default();
        let first_lease = queue
            .acquire(Duration::from_secs(1))
            .expect("first projection lease");
        let mut cancelled_receivers = Vec::with_capacity(MAX_PENDING_READ_PROJECTIONS);

        {
            let mut state = queue.state.lock().expect("projection queue state");
            for _ in 0..MAX_PENDING_READ_PROJECTIONS {
                let ticket = state.next_ticket;
                state.next_ticket = state.next_ticket.checked_add(1).expect("test ticket space");
                let (permit, receiver) = mpsc::channel();
                cancelled_receivers.push(receiver);
                state.waiters.push_back(ReadProjectionWaiter {
                    ticket,
                    deadline: Instant::now() + Duration::from_secs(1),
                    status: Arc::new(AtomicU8::new(READ_PROJECTION_CANCELLED)),
                    permit,
                });
            }
        }

        assert_eq!(
            queue
                .acquire(Duration::from_millis(25))
                .expect_err("bounded backlog must reject another waiter"),
            ReadProjectionError::BusyBeforeStart
        );

        let started_at = Instant::now();
        drop(first_lease);
        assert!(started_at.elapsed() < Duration::from_secs(1));

        let state = queue.state.lock().expect("projection queue state");
        assert!(state.waiters.is_empty());
        assert!(!state.active);
        drop(cancelled_receivers);
    }

    #[test]
    fn serialized_read_projection_serves_waiters_in_fifo_order() {
        let queue = Arc::new(ReadProjectionQueue::default());
        let first_lease = queue
            .acquire(Duration::from_secs(1))
            .expect("first projection lease");
        let order = Arc::new(Mutex::new(Vec::new()));

        let second_queue = Arc::clone(&queue);
        let second_order = Arc::clone(&order);
        let second = thread::spawn(move || {
            let _lease = second_queue
                .acquire(Duration::from_secs(1))
                .expect("second projection lease");
            second_order.lock().expect("second order").push(2);
        });
        wait_for_projection_ticket_count(queue.as_ref(), 2);

        let third_queue = Arc::clone(&queue);
        let third_order = Arc::clone(&order);
        let third = thread::spawn(move || {
            let _lease = third_queue
                .acquire(Duration::from_secs(1))
                .expect("third projection lease");
            third_order.lock().expect("third order").push(3);
        });
        wait_for_projection_ticket_count(queue.as_ref(), 3);

        drop(first_lease);
        second.join().expect("second projection worker");
        third.join().expect("third projection worker");

        assert_eq!(order.lock().expect("projection order").as_slice(), [2, 3]);
    }

    #[test]
    fn cancelled_projection_ticket_does_not_block_the_next_waiter() {
        let queue = Arc::new(ReadProjectionQueue::default());
        let first_lease = queue
            .acquire(Duration::from_secs(1))
            .expect("first projection lease");

        let cancelled_queue = Arc::clone(&queue);
        let cancelled = thread::spawn(move || {
            cancelled_queue
                .acquire(Duration::from_millis(25))
                .map(|_| ())
        });
        assert_eq!(
            cancelled.join().expect("cancelled projection worker"),
            Err(ReadProjectionError::BusyBeforeStart)
        );

        let next_queue = Arc::clone(&queue);
        let next = thread::spawn(move || next_queue.acquire(Duration::from_secs(1)).is_ok());
        wait_for_projection_ticket_count(queue.as_ref(), 3);
        drop(first_lease);

        assert!(next.join().expect("next projection worker"));
    }

    #[test]
    fn panicking_projection_releases_its_fifo_lease() {
        let queue = ReadProjectionQueue::default();

        let panic = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let _lease = queue
                .acquire(Duration::from_secs(1))
                .expect("panicking projection lease");
            panic!("projection panic fixture");
        }));

        assert!(panic.is_err());
        assert!(queue.acquire(Duration::from_millis(25)).is_ok());
    }

    fn wait_for_projection_ticket_count(queue: &ReadProjectionQueue, expected: u64) {
        let deadline = Instant::now() + Duration::from_secs(1);
        loop {
            if queue
                .state
                .lock()
                .expect("projection queue state")
                .next_ticket
                >= expected
            {
                return;
            }
            assert!(
                Instant::now() < deadline,
                "projection waiter did not enter the FIFO queue"
            );
            thread::yield_now();
        }
    }
}