ch-database 0.1.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
//! Shared SpacetimeDB helper utilities.
//!
//! App-owned SpacetimeDB tables, reducers, generated bindings, and concrete
//! clients live in the owning app database crates.

use std::fmt;
use std::mem::ManuallyDrop;
use std::ops::Deref;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, OnceLock, RwLock, RwLockReadGuard};
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_LOCK: OnceLock<Mutex<()>> = OnceLock::new();

const CONNECT_RETRY_DELAYS_MS: [u64; 2] = [150, 500];
const OPTIONAL_READ_DEGRADE_WINDOW: Duration = Duration::from_secs(15);

/// 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 || {
                drop(keepalive);
                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>>>,
}

/// 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)
                })
            }
        }
    }

    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 subscription projection lock.
pub fn with_serialized_read_projection<T>(
    read_projection: impl FnOnce() -> Result<T, String>,
) -> Result<T, String> {
    let _guard = subscribe_once_lock()
        .lock()
        .map_err(|_| "SpacetimeDB subscribe-once read lock was poisoned".to_string())?;
    let result = read_projection();
    if let Err(error) = &result {
        record_optional_read_failure(error.as_str());
    }
    result
}

/// 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_lock() -> &'static Mutex<()> {
    SUBSCRIBE_ONCE_LOCK.get_or_init(|| Mutex::new(()))
}

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",
        "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, SpacetimeDbConnectionStatus, is_optional_read_circuit_breaking_error,
        is_optional_read_degrading_error, runtime_endpoint_url, scoped_key, scoped_key3,
        set_runtime_endpoint_url,
    };

    #[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"
        ));
    }
}