kevy_embedded/replica_glue.rs
1//! Glue between the public `Store` surface and the replica runner —
2//! the constructor that decides whether to spawn the background
3//! thread, plus the read-only enforcement helper that every mutating
4//! API in `ops.rs` calls. Extracted from `store.rs` to keep that file
5//! under the 500-LOC ceiling.
6
7use std::sync::atomic::{AtomicU64, Ordering};
8
9use crate::config::Config;
10use crate::store::Shards;
11
12/// Construct + spawn the replica runner when configured. Returns
13/// `None` when the upstream is unset (normal primary store). The
14/// returned handle is owned by `DropGuard`, which joins the runner
15/// thread on the last `Store` clone drop.
16#[cfg(not(target_arch = "wasm32"))]
17pub(crate) fn spawn_replica_runner(
18 config: &Config,
19 shards: &Shards,
20) -> Option<crate::replica_runner::ReplicaRunner> {
21 let upstream = config.replica_upstream.as_ref()?.clone();
22 Some(crate::replica_runner::ReplicaRunner::spawn(
23 shards.clone(),
24 upstream,
25 config.replica_id.clone(),
26 config.replica_reconnect_min,
27 config.replica_reconnect_max,
28 ))
29}
30
31/// Generate a process-unique replica id for `Store::open_replica`.
32/// Format: `"kevy-embedded-{pid}-{seq}"` — the pid stays stable across
33/// a process, the seq counter advances per open so two embeds in the
34/// same process don't collide on a single slot in the primary's
35/// SlotTable (the bug that would otherwise cause backlog frames a
36/// fresh replica still needs to be evicted as soon as the prior
37/// embed disconnects).
38#[cfg(not(target_arch = "wasm32"))]
39pub(crate) fn fresh_replica_id() -> String {
40 static SEQ: AtomicU64 = AtomicU64::new(0);
41 let n = SEQ.fetch_add(1, Ordering::Relaxed);
42 format!("kevy-embedded-{}-{}", std::process::id(), n)
43}
44
45impl crate::Store {
46 /// The embed-writer replication listener's actually-bound address,
47 /// when this store was opened with
48 /// [`Config::with_embed_writer`](crate::Config::with_embed_writer).
49 /// Open with port `0` to let the OS pick a free port and read the
50 /// real one back here — the race-free way to run an ephemeral
51 /// writer (tests, sidecars, one process per scope).
52 #[cfg(not(target_arch = "wasm32"))]
53 pub fn writer_addr(&self) -> Option<std::net::SocketAddr> {
54 self.guard.replica_source.as_ref().map(|s| s.local_addr())
55 }
56}