Skip to main content

slipstream/
nats.rs

1use async_nats::jetstream::kv::Store;
2use async_trait::async_trait;
3use futures::StreamExt;
4use std::sync::{
5    Arc,
6    atomic::{AtomicBool, Ordering},
7};
8use std::time::Duration;
9use tokio::sync::{RwLock, mpsc::Sender};
10use tracing::{debug, error, info, warn};
11
12use crate::kv::{
13    KvEntry, KvError, KvPurge, KvReader, KvUpdate, KvWatcher, KvWriter, VersionToken, WatchCursor,
14};
15use crate::stores::{Connection, ConnectionCapabilities, KvStore, StoreConfig};
16
17/// Default per-operation timeout for NATS KV ops. async-nats's request/response
18/// futures don't fail in-flight requests when the underlying TCP connection
19/// goes half-dead (CLOSE_WAIT) — they just await forever. Without a timeout
20/// here, ANY hung NATS connection translates into a tokio runtime deadlock as
21/// soon as enough callers queue behind the dead connection. 30s is generous
22/// for legitimate slow ops (cold JetStream stream sync, leader election under
23/// load) and short enough that a dead connection recovers within reasonable
24/// human-debug latency.
25const KV_OP_TIMEOUT: Duration = Duration::from_secs(30);
26
27/// Server-side inactivity reaper for the ephemeral consumers `scan()`/`keys()`
28/// create. Our code deletes each consumer explicitly when the drain finishes,
29/// but that delete is best-effort: on a half-dead (CLOSE_WAIT) connection it
30/// times out, orphaning the consumer server-side where it counts against the
31/// per-stream consumer limit. Setting `inactive_threshold` makes JetStream reap
32/// any consumer that sees no activity for this long, so a failed explicit delete
33/// self-heals instead of accumulating until the limit is hit. Comfortably longer
34/// than [`KV_OP_TIMEOUT`] so it never reaps a legitimately slow in-flight drain
35/// (each delivery resets the inactivity timer).
36const CONSUMER_INACTIVE_THRESHOLD: Duration = Duration::from_secs(300);
37
38/// Run a future under [`KV_OP_TIMEOUT`], returning [`KvError::Timeout`] if it
39/// doesn't complete in time. Preserves the inner future's `Result` so callers
40/// keep their existing error-mapping logic.
41async fn timed<F, T>(fut: F) -> Result<T, KvError>
42where
43    F: std::future::Future<Output = T>,
44{
45    tokio::time::timeout(KV_OP_TIMEOUT, fut)
46        .await
47        .map_err(|_| KvError::Timeout)
48}
49
50/// Build NATS connect options (with auth applied) and resolve the URL to dial.
51///
52/// Split out from [`nats_connect`] so the connection lifecycle can attach an
53/// event callback (for health tracking) to the *same* options before dialing,
54/// without duplicating the auth-priority logic. Returns the options plus the URL
55/// to connect to (which may differ from `url` when credentials are stripped out
56/// of a `user:pass@host` URL).
57///
58/// Auth priority (first match wins):
59/// 1. Inline credentials (base64-encoded .creds content)
60/// 2. Credentials file (if provided)
61/// 3. URL-embedded credentials (user:pass@host)
62/// 4. No authentication
63async fn build_connect_options(
64    url: &str,
65    creds: Option<&str>,
66    creds_file: Option<&str>,
67) -> Result<(async_nats::ConnectOptions, String), async_nats::ConnectError> {
68    // Priority 1: Inline credentials (base64-encoded)
69    if let Some(encoded) = creds {
70        use base64::Engine;
71        let decoded = base64::engine::general_purpose::STANDARD
72            .decode(encoded)
73            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
74        let content = String::from_utf8(decoded)
75            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
76        return Ok((
77            async_nats::ConnectOptions::with_credentials(&content)?,
78            url.to_string(),
79        ));
80    }
81
82    // Priority 2: Credentials file
83    if let Some(path) = creds_file {
84        return Ok((
85            async_nats::ConnectOptions::with_credentials_file(path).await?,
86            url.to_string(),
87        ));
88    }
89
90    // Priority 3: URL-embedded credentials
91    if let Ok(parsed) = url::Url::parse(url)
92        && !parsed.username().is_empty()
93    {
94        let user = parsed.username().to_string();
95        let pass = parsed.password().unwrap_or("").to_string();
96        // Rebuild URL without credentials. If the scheme doesn't support
97        // userinfo, these calls fail and the credentials would remain embedded
98        // in the URL we later log — warn loudly rather than silently leak them.
99        let mut clean_url = parsed.clone();
100        if clean_url.set_username("").is_err() || clean_url.set_password(None).is_err() {
101            warn!("could not strip credentials from NATS URL; they may appear in logs");
102        }
103        return Ok((
104            async_nats::ConnectOptions::with_user_and_password(user, pass),
105            clean_url.as_str().to_string(),
106        ));
107    }
108
109    // Priority 4: No authentication
110    Ok((async_nats::ConnectOptions::new(), url.to_string()))
111}
112
113/// Connect to NATS with various authentication methods.
114///
115/// Supports the auth-priority order documented on [`build_connect_options`].
116/// This is the standalone helper; the [`Connection`] impl builds options the
117/// same way but also installs a health-tracking event callback.
118pub async fn nats_connect(
119    url: &str,
120    creds: Option<&str>,
121    creds_file: Option<&str>,
122) -> Result<async_nats::Client, async_nats::ConnectError> {
123    let (opts, dial_url) = build_connect_options(url, creds, creds_file).await?;
124    opts.connect(dial_url).await
125}
126
127/// Render an untrusted server payload for logging: borrowed as-is when valid
128/// UTF-8, lowercase hex otherwise. `from_utf8_lossy` would mash every invalid
129/// byte into U+FFFD — exactly the bytes an incident needs to see — so the
130/// fallback preserves them losslessly instead.
131fn payload_for_log(payload: &[u8]) -> std::borrow::Cow<'_, str> {
132    match std::str::from_utf8(payload) {
133        Ok(s) => std::borrow::Cow::Borrowed(s),
134        Err(_) => std::borrow::Cow::Owned(format!("0x{}", crate::artifact::hex_encode(payload))),
135    }
136}
137
138/// Configuration for NATS connection.
139///
140/// `Debug` is hand-written, not derived: `creds` holds decoded credential
141/// material and `creds_file` a filesystem path to secrets. A derived `Debug`
142/// would print both verbatim the moment anyone `{:?}`-formats the config (a
143/// `tracing` span, an error context, a test dump), leaking credentials into
144/// logs. The redacting impl below keeps that from being one careless format
145/// string away.
146#[derive(Clone)]
147pub struct NatsConnectionConfig {
148    pub url: String,
149    /// Base64-encoded .creds file content (for ECS / containerized environments).
150    pub creds: Option<String>,
151    /// Path to .creds file on disk (for bare-metal / local development).
152    pub creds_file: Option<String>,
153}
154
155impl std::fmt::Debug for NatsConnectionConfig {
156    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
157        f.debug_struct("NatsConnectionConfig")
158            .field("url", &self.url)
159            // Presence, never content: enough to debug "are creds set?" without
160            // ever rendering the secret itself. The same applies to `creds_file`:
161            // a path like `/run/secrets/prod.creds` leaks the secrets layout into
162            // logs/traces, so redact it to presence too.
163            .field("creds", &self.creds.as_ref().map(|_| "[redacted]"))
164            .field(
165                "creds_file",
166                &self.creds_file.as_ref().map(|_| "[redacted]"),
167            )
168            .finish()
169    }
170}
171
172/// Create a KV bucket using raw JetStream API (bypasses async-nats response parsing issues).
173///
174/// Synadia Cloud returns responses that `async_nats` can't parse. This function
175/// uses the raw JetStream API directly, bypassing the client's response deserialization.
176///
177/// `pub(crate)`: this is an internal Synadia Cloud workaround invoked by
178/// `get_or_create_bucket`, not a stable entry point. Exposing it would pin a
179/// vendor quirk into the crate's semver surface.
180pub(crate) async fn create_kv_bucket_raw(
181    client: &async_nats::Client,
182    bucket: &str,
183    max_bytes: i64,
184    history: i64,
185    max_age_nanos: i64,
186    num_replicas: usize,
187) -> Result<(), KvError> {
188    let stream_name = format!("KV_{}", bucket);
189    let subject = format!("$KV.{}.>", bucket);
190
191    // JetStream stream config for KV bucket
192    let config = serde_json::json!({
193        "name": stream_name,
194        "subjects": [subject],
195        "max_msgs_per_subject": history,
196        "max_bytes": max_bytes,
197        "max_age": max_age_nanos,
198        "storage": "file",
199        "allow_rollup_hdrs": true,
200        "deny_delete": false,
201        "deny_purge": false,
202        "allow_direct": true,
203        "discard": "new",
204        "num_replicas": num_replicas,
205        "retention": "limits"
206    });
207
208    let payload = serde_json::to_vec(&config)
209        .map_err(|e| KvError::ConnectionFailed(format!("failed to serialize config: {}", e)))?;
210
211    let response = client
212        .request(
213            format!("$JS.API.STREAM.CREATE.{}", stream_name),
214            payload.into(),
215        )
216        .await
217        .map_err(|e| KvError::ConnectionFailed(format!("failed to send create request: {}", e)))?;
218
219    debug!(bucket, response = %payload_for_log(&response.payload), "raw JetStream response");
220
221    match classify_raw_create_response(&response.payload) {
222        RawCreateOutcome::AlreadyExists => {
223            info!(bucket, "bucket already exists");
224            Ok(())
225        }
226        RawCreateOutcome::StreamLimit => {
227            info!(bucket, "stream limit reached, bucket may already exist");
228            Ok(())
229        }
230        RawCreateOutcome::Created => {
231            info!(bucket, "bucket created successfully via raw API");
232            Ok(())
233        }
234        RawCreateOutcome::Failed { code, description } => Err(KvError::ConnectionFailed(format!(
235            "JetStream error {}: {}",
236            code, description
237        ))),
238    }
239}
240
241/// Classification of a raw `$JS.API.STREAM.CREATE` response payload.
242///
243/// Separated from the I/O in [`create_kv_bucket_raw`] so the Synadia Cloud
244/// error-code logic — the reason this raw path exists — is unit-testable
245/// without a live NATS server.
246#[derive(Debug, PartialEq, Eq)]
247enum RawCreateOutcome {
248    /// No error in the response: the bucket was created.
249    Created,
250    /// `10058` — stream name already in use; the bucket exists. Non-fatal.
251    AlreadyExists,
252    /// `400` "maximum number of streams"; Synadia Cloud returns this at the
253    /// stream limit even when the bucket already exists. Non-fatal.
254    StreamLimit,
255    /// Any other JetStream error — fatal.
256    Failed { code: i64, description: String },
257}
258
259fn classify_raw_create_response(payload: &[u8]) -> RawCreateOutcome {
260    // Unparseable payloads are treated as success: the caller re-verifies the
261    // bucket with a follow-up `get_key_value`, so a garbled body here does not
262    // mask a real failure. Warn so the fallback assumption is auditable — if the
263    // re-verify step is ever refactored away, this log is the breadcrumb.
264    //
265    // INVARIANT: this `Created`-on-garbage path is only sound because every
266    // caller re-verifies the bucket exists after `create_kv_bucket_raw` returns
267    // Ok. The sole caller — `get_or_create_bucket` — does so via the
268    // `timed(js.get_key_value(...))` immediately after the raw-create fallback.
269    // Do not remove that re-verify without making this path return `Failed`.
270    let Ok(json) = serde_json::from_slice::<serde_json::Value>(payload) else {
271        warn!(
272            response = %payload_for_log(payload),
273            "unparseable STREAM.CREATE response; assuming created (caller re-verifies via get_key_value)"
274        );
275        return RawCreateOutcome::Created;
276    };
277
278    let Some(err) = json.get("error") else {
279        return RawCreateOutcome::Created;
280    };
281
282    // JetStream splits its error codes: `code` is the HTTP-style status (400,
283    // 404, 500) while `err_code` carries the granular code (e.g. 10058). The
284    // already-exists code can surface in either field depending on the server
285    // (standard NATS puts 10058 in `err_code` with `code` = 400; some managed
286    // deployments echo it in `code`), so we accept it in either.
287    let code = err.get("code").and_then(|c| c.as_i64()).unwrap_or(0);
288    let err_code = err.get("err_code").and_then(|c| c.as_i64()).unwrap_or(0);
289    let description = err
290        .get("description")
291        .and_then(|d| d.as_str())
292        .unwrap_or("unknown error");
293
294    // 10058 = stream name already in use (bucket exists) - that's OK
295    if code == 10058 || err_code == 10058 {
296        return RawCreateOutcome::AlreadyExists;
297    }
298
299    // 400 "maximum number of streams reached" may also mean bucket exists
300    // (Synadia Cloud returns this when at stream limit but bucket exists)
301    if code == 400 && description.contains("maximum number of streams") {
302        return RawCreateOutcome::StreamLimit;
303    }
304
305    RawCreateOutcome::Failed {
306        code,
307        description: description.to_string(),
308    }
309}
310
311struct NatsHandle {
312    // Held to keep the NATS connection alive for the lifetime of the handle.
313    // The `jetstream` context clones an internal reference, but this field is
314    // the authoritative owner — dropping the handle drops the connection.
315    // Also read by `store_with_config`, which clones it out from under the
316    // handle lock.
317    client: async_nats::Client,
318    jetstream: async_nats::jetstream::Context,
319}
320
321/// NATS JetStream KV connection.
322pub struct NatsConnection {
323    config: NatsConnectionConfig,
324    handle: RwLock<Option<NatsHandle>>,
325    // Shared with the installed client's event callback so `is_healthy()`
326    // tracks real connection state (Connected/Disconnected) rather than staying
327    // pinned at its connect-time value. `Arc` because the callback outlives this
328    // struct's borrow — it runs on the client's event-loop task.
329    healthy: Arc<AtomicBool>,
330    // Set only for connections built via `from_client`, where no health-tracking
331    // event callback could be installed (the client was already connected).
332    // `is_healthy()` consults this client's live `connection_state()` instead of
333    // the callback-driven `healthy` flag. `None` for the `new()` + `connect()`
334    // path, whose flag is kept current by the installed event callback.
335    //
336    // `Some(_)` is also the marker that this connection borrows a caller-owned
337    // client: it carries no URL or credentials of its own (see `from_client`),
338    // so it cannot redial. `connect()` refuses to reconnect such a connection
339    // rather than dialing the empty config URL and surfacing a cryptic error.
340    state_probe: Option<async_nats::Client>,
341}
342
343impl NatsConnection {
344    pub fn new(config: NatsConnectionConfig) -> Self {
345        Self {
346            config,
347            handle: RwLock::new(None),
348            healthy: Arc::new(AtomicBool::new(false)),
349            state_probe: None,
350        }
351    }
352
353    /// Create a NatsConnection from an existing NATS client.
354    ///
355    /// This is useful when the caller already has a NATS connection and wants
356    /// to reuse it for KV stores instead of creating a new connection.
357    pub fn from_client(client: async_nats::Client) -> Self {
358        let jetstream = async_nats::jetstream::new(client.clone());
359        let config = NatsConnectionConfig {
360            url: String::new(), // Not used when pre-connected
361            creds: None,
362            creds_file: None,
363        };
364
365        // Clone a probe handle before the client moves into `NatsHandle`.
366        // `async_nats::Client` is cheap to clone (internally an `Arc`), and
367        // `connection_state()` just reads a watch channel — no I/O.
368        let state_probe = Some(client.clone());
369        let handle = NatsHandle { client, jetstream };
370
371        Self {
372            config,
373            handle: RwLock::new(Some(handle)),
374            // A pre-connected client carries no health-tracking callback (we
375            // didn't build its options), so `is_healthy()` reads the client's
376            // live `connection_state()` via `state_probe`. The flag below only
377            // gates explicit `shutdown()`.
378            healthy: Arc::new(AtomicBool::new(true)),
379            state_probe,
380        }
381    }
382
383    async fn get_or_create_bucket(
384        client: &async_nats::Client,
385        js: &async_nats::jetstream::Context,
386        config: &StoreConfig,
387    ) -> Result<Store, KvError> {
388        // Try to get existing bucket first. Bound the call so a slow/dead
389        // NATS connection at startup can't park the daemon's init thread
390        // forever — the rest of startup (HTTP listener bind, etc.) happens
391        // after this. Without the timeout, a single bad NATS round-trip
392        // here held HTTP bind for 30s+ in observed cases.
393        //
394        // A failure here (permission denied, JetStream disabled, timeout) is not
395        // necessarily fatal — the bucket may simply not exist yet, so we fall
396        // through to create. But surface the original error first: otherwise a
397        // later create failure (e.g. "permission denied on STREAM.CREATE") masks
398        // the real cause ("permission denied on STREAM.INFO") and makes the
399        // failure undebuggable under load.
400        match timed(js.get_key_value(&config.name)).await {
401            Ok(Ok(kv)) => return Ok(kv),
402            Ok(Err(e)) => {
403                debug!(bucket = %config.name, error = ?e, "get_key_value failed; attempting create");
404            }
405            Err(_) => {
406                warn!(bucket = %config.name, timeout = ?KV_OP_TIMEOUT, "get_key_value timed out; attempting create");
407            }
408        }
409
410        // Bucket doesn't exist, create it
411        let mut kv_config = async_nats::jetstream::kv::Config {
412            bucket: config.name.clone(),
413            num_replicas: config.num_replicas.unwrap_or(1),
414            ..Default::default()
415        };
416
417        // Apply max_age (bucket-level TTL) if specified. `as_nanos()` is u128;
418        // saturate to i64::MAX rather than `as i64`, which would silently wrap a
419        // >292-year duration into a negative (and thus meaningless) TTL.
420        let max_age_nanos = if let Some(max_age) = config.max_age {
421            kv_config.max_age = max_age;
422            i64::try_from(max_age.as_nanos()).unwrap_or(i64::MAX)
423        } else {
424            0
425        };
426
427        // Apply max_history if specified. `i64::from` is lossless for a u32 and
428        // states the widening intent, where `as i64` would quietly mask a future
429        // type change that no longer fits.
430        let history = if let Some(history) = config.max_history {
431            let history = i64::from(history);
432            kv_config.history = history;
433            history
434        } else {
435            1
436        };
437
438        // Apply max_bytes if specified (required by Synadia Cloud)
439        let max_bytes = config.max_bytes.unwrap_or(10 * 1024 * 1024); // Default 10MB for Synadia Cloud
440        kv_config.max_bytes = max_bytes;
441
442        // Try normal create first, fall back to raw API if it fails (Synadia Cloud compatibility).
443        //
444        // A TIMEOUT also takes the fallback, not an early return: the raw path
445        // exists for Synadia Cloud, which is the deployment most likely to be
446        // slow or distant — `?`-propagating the timeout here would skip the
447        // exact workaround built for it. If the connection is genuinely dead,
448        // the raw path's own `timed()` bounds surface that promptly anyway.
449        match timed(js.create_key_value(kv_config)).await {
450            Ok(Ok(kv)) => return Ok(kv),
451            Ok(Err(e)) => {
452                warn!(
453                    bucket = config.name,
454                    error = ?e,
455                    "create_key_value failed, trying raw JetStream API"
456                );
457            }
458            Err(_) => {
459                warn!(
460                    bucket = config.name,
461                    timeout = ?KV_OP_TIMEOUT,
462                    "create_key_value timed out, trying raw JetStream API"
463                );
464            }
465        }
466
467        // Try raw JetStream API as fallback
468        create_kv_bucket_raw(
469            client,
470            &config.name,
471            max_bytes,
472            history,
473            max_age_nanos,
474            config.num_replicas.unwrap_or(1),
475        )
476        .await?;
477
478        // Re-verify the bucket exists. This upholds the INVARIANT in
479        // `classify_raw_create_response`: the raw path reports `Created`
480        // on an unparseable response, so this round-trip is what actually
481        // confirms the bucket — do not remove it.
482        timed(js.get_key_value(&config.name)).await?.map_err(|e| {
483            error!(bucket = config.name, error = ?e, "failed to get bucket after raw create");
484            KvError::ConnectionFailed(format!("get bucket after raw create: {:?}", e))
485        })
486    }
487}
488
489#[async_trait]
490impl Connection for NatsConnection {
491    async fn connect(&self) -> Result<(), KvError> {
492        // Fast path: skip if already connected.
493        if self.healthy.load(Ordering::Acquire) {
494            return Ok(());
495        }
496
497        // A `from_client` connection borrows a caller-owned client and kept no
498        // URL or credentials, so it cannot redial. Refuse here with an actionable
499        // message instead of dialing the empty config URL (which fails with an
500        // opaque parse/connect error). This is reachable only after `shutdown()`
501        // cleared the fast-path flag above — a live borrowed client short-circuits
502        // there. The caller must construct a `NatsConnection::new(config)` if it
503        // needs reconnect semantics.
504        if self.state_probe.is_some() {
505            return Err(KvError::ConnectionFailed(
506                "connection was built via NatsConnection::from_client and cannot \
507                 reconnect (no URL or credentials retained); construct \
508                 NatsConnection::new(config) for a reconnectable connection"
509                    .to_string(),
510            ));
511        }
512
513        let (opts, dial_url) = build_connect_options(
514            &self.config.url,
515            self.config.creds.as_deref(),
516            self.config.creds_file.as_deref(),
517        )
518        .await
519        .map_err(|e| KvError::ConnectionFailed(e.to_string()))?;
520
521        // Drive `healthy` from the client's own connection events so it reflects
522        // reality through async-nats's transparent reconnects — without this the
523        // flag stays `true` straight through a NATS outage, and a readiness probe
524        // built on `is_healthy()` keeps routing traffic to a node that can't
525        // reach NATS.
526        //
527        // `installed` gates the callback: a caller that loses the connect race
528        // (see the double-check below) tears down its freshly built client, and
529        // that teardown fires `Disconnected`. Without the gate, the loser's drop
530        // would clobber the *winner's* `healthy` flag. Only the client we
531        // actually install ever flips `installed` to `true`, so the losers'
532        // callbacks are inert.
533        let installed = Arc::new(AtomicBool::new(false));
534        let cb_healthy = Arc::clone(&self.healthy);
535        let cb_installed = Arc::clone(&installed);
536        let opts = opts.event_callback(move |event| {
537            let cb_healthy = Arc::clone(&cb_healthy);
538            let cb_installed = Arc::clone(&cb_installed);
539            async move {
540                if !cb_installed.load(Ordering::Acquire) {
541                    return;
542                }
543                match event {
544                    async_nats::Event::Connected => cb_healthy.store(true, Ordering::Release),
545                    async_nats::Event::Disconnected => cb_healthy.store(false, Ordering::Release),
546                    _ => {}
547                }
548            }
549        });
550
551        let client = opts
552            .connect(dial_url)
553            .await
554            .map_err(|e| KvError::ConnectionFailed(e.to_string()))?;
555
556        let jetstream = async_nats::jetstream::new(client.clone());
557
558        let conn = NatsHandle { client, jetstream };
559
560        // Re-check under the write lock: a concurrent caller may have connected
561        // while we were awaiting the dial. If so, drop our freshly built handle
562        // (closing its connection) instead of replacing the live one, which would
563        // orphan a connection the first caller still believes is installed.
564        // Leaving `installed = false` keeps our about-to-drop client's teardown
565        // events from touching `healthy`.
566        let mut handle = self.handle.write().await;
567        if handle.is_some() {
568            return Ok(());
569        }
570        installed.store(true, Ordering::Release);
571        *handle = Some(conn);
572        self.healthy.store(true, Ordering::Release);
573
574        Ok(())
575    }
576
577    async fn shutdown(&self) -> Result<(), KvError> {
578        self.healthy.store(false, Ordering::Release);
579        *self.handle.write().await = None;
580        Ok(())
581    }
582
583    fn is_healthy(&self) -> bool {
584        // `healthy` is the shutdown gate for both construction paths: once
585        // `shutdown()` clears it the connection is down regardless of socket
586        // state, so check it first.
587        if !self.healthy.load(Ordering::Acquire) {
588            return false;
589        }
590        match &self.state_probe {
591            // `from_client`: no event callback could be installed, so consult the
592            // client's live connection state instead of a stale connect-time
593            // value. A dead or reconnecting socket reports Pending/Disconnected,
594            // so a readiness probe correctly sees the node as unhealthy. A
595            // borrowed client is never replaced (connect() refuses to reconnect
596            // it), so this probe never goes stale.
597            Some(client) => matches!(
598                client.connection_state(),
599                async_nats::connection::State::Connected
600            ),
601            // `new()` + `connect()`: `healthy` is kept current by the installed
602            // Connected/Disconnected event callback.
603            None => true,
604        }
605    }
606
607    async fn store(&self, name: &str) -> Result<Arc<dyn KvStore>, KvError> {
608        let config = StoreConfig {
609            name: name.to_string(),
610            ..Default::default()
611        };
612        self.store_with_config(config).await
613    }
614
615    async fn store_with_config(&self, config: StoreConfig) -> Result<Arc<dyn KvStore>, KvError> {
616        // Clone the client/jetstream out from under the read lock before the
617        // (up to 60s) bucket get-or-create. Holding the read guard across that
618        // await would block `shutdown()`'s `write().await` for the full
619        // duration, stalling graceful shutdown behind an in-flight store call.
620        let (client, js) = {
621            let conn = self.handle.read().await;
622            let conn = conn.as_ref().ok_or(KvError::NotConnected)?;
623            (conn.client.clone(), conn.jetstream.clone())
624        };
625
626        let kv = Self::get_or_create_bucket(&client, &js, &config).await?;
627
628        Ok(Arc::new(NatsKvStore {
629            name: config.name,
630            client,
631            js,
632            kv,
633        }))
634    }
635
636    fn capabilities(&self) -> ConnectionCapabilities {
637        ConnectionCapabilities {
638            streaming_watch: true,
639            prefix_watch: true,
640            // `KvTtl` is not implemented for the NATS backend yet (only `KvWriter`
641            // is vended by `writer()`), so advertising `ttl: true` would lead
642            // callers that branch on this flag down a path that can never
643            // succeed. Flip to `true` together with the `KvTtl` impl.
644            ttl: false,
645            // Byte-reclaiming purge IS implemented for NATS (rollup delete) and
646            // vended via `KvStore::purge_writer`.
647            purge: true,
648            cas: true,
649            transactions: false,
650            // 0 = unlimited from this layer's perspective: we impose no cap, but
651            // the NATS server still enforces its own max payload (~1MB by
652            // default). Callers that branch on this must not read 0 as "any size
653            // is safe" — an oversized value is rejected server-side at write time.
654            max_value_size: 0,
655            global_ordering: false,
656        }
657    }
658}
659
660struct NatsKvStore {
661    name: String,
662    kv: Store,
663    client: async_nats::Client,
664    js: async_nats::jetstream::Context,
665}
666
667impl KvStore for NatsKvStore {
668    fn name(&self) -> &str {
669        &self.name
670    }
671
672    fn reader(&self) -> Arc<dyn KvReader> {
673        Arc::new(NatsKvReader {
674            kv: self.kv.clone(),
675            client: self.client.clone(),
676            js: self.js.clone(),
677            bucket: self.name.clone(),
678        })
679    }
680
681    fn watcher(&self) -> Option<Arc<dyn KvWatcher>> {
682        Some(Arc::new(NatsKvWatcher {
683            kv: self.kv.clone(),
684            client: self.client.clone(),
685            js: self.js.clone(),
686            bucket: self.name.clone(),
687        }))
688    }
689
690    fn writer(&self) -> Option<Arc<dyn KvWriter>> {
691        Some(Arc::new(NatsKvWriterImpl {
692            kv: self.kv.clone(),
693        }))
694    }
695
696    fn purge_writer(&self) -> Option<Arc<dyn KvPurge>> {
697        Some(Arc::new(NatsKvWriterImpl {
698            kv: self.kv.clone(),
699        }))
700    }
701}
702
703struct NatsKvReader {
704    kv: Store,
705    client: async_nats::Client,
706    js: async_nats::jetstream::Context,
707    // The bucket name is known at construction (it's the store's name), so
708    // `consume_last_per_subject` builds its subject filters from this field
709    // instead of issuing a `kv.status()` round-trip per `scan()`/`keys()` call
710    // just to read it back from the server.
711    bucket: String,
712}
713
714#[async_trait]
715impl KvReader for NatsKvReader {
716    async fn get(&self, key: &str) -> Result<Option<KvEntry>, KvError> {
717        // Empty value → treat as absent. This unifies a real stored `b""` and a
718        // `delete_with_version` tombstone (empty-value Put) under one "absent =
719        // None" contract, consistent with `scan()`/`keys()`. Callers needing
720        // zero-length semantics use `entry()`. See the `KvReader::get` trait doc.
721        match self.entry(key).await? {
722            Some(entry) if entry.value.is_empty() => Ok(None),
723            other => Ok(other),
724        }
725    }
726
727    async fn entry(&self, key: &str) -> Result<Option<KvEntry>, KvError> {
728        use async_nats::jetstream::kv::Operation;
729        // Use entry() instead of get() to access revision.
730        // Return Put entries even with empty values — delete_with_version
731        // writes empty bytes as a tombstone and callers need the version
732        // for CAS conflict detection. Only filter real Delete/Purge markers.
733        match timed(self.kv.entry(key)).await? {
734            Ok(Some(entry)) if entry.operation == Operation::Put => Ok(Some(KvEntry {
735                key: key.to_string(),
736                value: entry.value.to_vec(),
737                version: VersionToken::from_u64(entry.revision),
738            })),
739            Ok(Some(_)) => Ok(None), // Delete/Purge marker
740            Ok(None) => Ok(None),
741            Err(e) => Err(KvError::OperationFailed(e.to_string())),
742        }
743    }
744
745    async fn keys(&self, prefix: &str) -> Result<Vec<String>, KvError> {
746        debug!(prefix = %prefix, "listing keys with prefix");
747
748        let mut keys = Vec::new();
749        self.consume_last_per_subject(prefix, true, |msg, key| {
750            // Skip both real KV deletes and CAS tombstones (empty-value Puts
751            // written by delete_with_version). get()/scan() hide the latter, so
752            // keys() must too — otherwise a list-then-get returns phantom keys.
753            // With headers_only the payload is stripped, but NATS adds a
754            // `Nats-Msg-Size` header we use to detect the empty value.
755            if !is_kv_delete(&msg) && !is_empty_value(&msg) {
756                keys.push(key);
757            }
758        })
759        .await?;
760
761        debug!(prefix = %prefix, keys = keys.len(), "keys listing complete");
762        Ok(keys)
763    }
764
765    async fn scan(&self, prefix: &str) -> Result<Vec<KvEntry>, KvError> {
766        let mut entries = Vec::new();
767        self.consume_last_per_subject(prefix, false, |msg, key| {
768            if !is_kv_delete(&msg) && !msg.payload.is_empty() {
769                // The KV revision is the stream sequence, carried in the JetStream
770                // ACK subject (the message's reply subject). A revision of 0 means
771                // we couldn't parse it; callers treat that as "unknown version".
772                let revision = msg
773                    .reply
774                    .as_deref()
775                    .and_then(stream_sequence_from_ack)
776                    .unwrap_or(0);
777
778                entries.push(KvEntry {
779                    key,
780                    value: msg.payload.to_vec(),
781                    version: VersionToken::from_u64(revision),
782                });
783            }
784        })
785        .await?;
786
787        debug!(prefix = %prefix, entries = entries.len(), "scan complete");
788        Ok(entries)
789    }
790}
791
792/// Extract the stream sequence (== KV revision) from a JetStream ACK subject.
793///
794/// The ACK subject — delivered as a push message's reply subject — comes in two
795/// shapes, and the stream sequence sits at different offsets in each:
796///
797/// ```text
798/// legacy (9 tokens):  $JS.ACK.<stream>.<consumer>.<delivered>.<stream_seq>.<consumer_seq>.<ts>.<pending>
799/// modern (11–12):     $JS.ACK.<domain>.<account>.<stream>.<consumer>.<delivered>.<stream_seq>.<consumer_seq>.<ts>.<pending>[.<token>]
800/// ```
801///
802/// The previous implementation took the *last* token, which is `num_pending`
803/// (typically 0 on the final delivery), not the sequence — corrupting the
804/// version on every scanned entry. We instead parse from the front, accounting
805/// for the optional `<domain>.<account>` prefix that modern servers prepend.
806fn stream_sequence_from_ack(reply: &str) -> Option<u64> {
807    // The stream-seq field sits at index 5 (legacy) or 7 (modern), so we only
808    // ever read the first 8 tokens. Keep those in a stack array and count the
809    // remainder with the iterator — no heap `Vec`, which on a large `scan()`
810    // would be one allocation per delivered message.
811    let mut head = [""; 8];
812    let mut count = 0usize;
813    for (i, token) in reply.split('.').enumerate() {
814        if i < head.len() {
815            head[i] = token;
816        }
817        count += 1;
818    }
819    if count < 9 || head[0] != "$JS" || head[1] != "ACK" {
820        return None;
821    }
822    // Legacy form has exactly 9 tokens with no domain/account; anything longer
823    // carries the two-token `<domain>.<account>` prefix, shifting fields right.
824    let stream_seq_idx = if count == 9 { 5 } else { 7 };
825    head[stream_seq_idx].parse::<u64>().ok()
826}
827
828/// Check if a NATS message represents a KV delete/purge operation.
829fn is_kv_delete(msg: &async_nats::Message) -> bool {
830    msg.headers
831        .as_ref()
832        .and_then(|h| h.get("KV-Operation"))
833        .is_some()
834}
835
836/// Check if a `headers_only` delivery carries an empty value (a CAS tombstone
837/// written by `delete_with_version`).
838///
839/// When a consumer is created with `headers_only`, NATS strips the body and adds
840/// a `Nats-Msg-Size` header with the original payload length. Size 0 means the
841/// stored value is empty, which `get()`/`scan()` treat as absent. Messages
842/// without the header (e.g. non-`headers_only` deliveries) are not classified as
843/// empty here — callers on that path inspect the payload directly instead.
844fn is_empty_value(msg: &async_nats::Message) -> bool {
845    msg.headers
846        .as_ref()
847        .and_then(|h| h.get("Nats-Msg-Size"))
848        .map(|v| v.as_str() == "0")
849        .unwrap_or(false)
850}
851
852impl NatsKvReader {
853    /// Subscribe to last-per-subject messages for a KV prefix, calling `on_msg`
854    /// for each delivered message. Handles the subscribe-first race workaround,
855    /// consumer lifecycle, and cleanup.
856    async fn consume_last_per_subject(
857        &self,
858        prefix: &str,
859        headers_only: bool,
860        mut on_msg: impl FnMut(async_nats::Message, String),
861    ) -> Result<(), KvError> {
862        use async_nats::jetstream::consumer::push;
863        use async_nats::jetstream::consumer::{AckPolicy, DeliverPolicy};
864
865        // The bucket name is known at construction, so the subject filters are
866        // built directly from `self.bucket` — no `kv.status()` round-trip just
867        // to read it back. Every *remaining* setup await below is still bounded
868        // by `timed()`: a half-dead NATS connection (CLOSE_WAIT) would otherwise
869        // park here before the per-message drain timer downstream ever starts,
870        // hanging scan()/keys() indefinitely — the same failure `timed()` guards
871        // on the write path.
872        let bucket = self.bucket.as_str();
873
874        let nats_filter = if prefix.is_empty() {
875            format!("$KV.{bucket}.>")
876        } else {
877            format!("$KV.{bucket}.{prefix}>")
878        };
879
880        // Work around async-nats <=0.46 subscribe-after-create race:
881        // subscribe to the inbox FIRST, then create the consumer.
882        let inbox = self.client.new_inbox();
883        let mut sub = timed(self.client.subscribe(inbox.clone()))
884            .await?
885            .map_err(|e| KvError::OperationFailed(format!("subscribe inbox: {e}")))?;
886
887        let stream = timed(self.js.get_stream(format!("KV_{bucket}")))
888            .await?
889            .map_err(|e| KvError::OperationFailed(format!("get KV stream: {e}")))?;
890
891        let consumer = timed(stream.create_consumer(push::Config {
892            deliver_subject: inbox,
893            deliver_policy: DeliverPolicy::LastPerSubject,
894            filter_subject: nats_filter,
895            headers_only,
896            // This is a one-shot point-in-time drain — we never ack. Under
897            // the default `AckPolicy::Explicit`, JetStream stops delivering
898            // once `max_ack_pending` (default 1000) messages sit unacked,
899            // which would silently truncate scan()/keys() to the first ~1000
900            // keys (or stall waiting for deliveries that never come) on any
901            // larger bucket. `None` removes the ack-pending gate entirely.
902            ack_policy: AckPolicy::None,
903            // Safety net for the best-effort `delete_consumer` below: if that
904            // cleanup times out on a half-dead connection, JetStream still reaps
905            // this consumer after `CONSUMER_INACTIVE_THRESHOLD` of inactivity, so
906            // repeated timed-out scans can't pile orphaned consumers up against
907            // the per-stream limit.
908            inactive_threshold: CONSUMER_INACTIVE_THRESHOLD,
909            ..Default::default()
910        }))
911        .await?
912        .map_err(|e| KvError::OperationFailed(format!("create consumer: {e}")))?;
913
914        let num_pending = consumer.cached_info().num_pending;
915
916        // Drain exactly `num_pending` messages, but bound each await: a half-dead
917        // connection (CLOSE_WAIT) would otherwise park this loop forever, the same
918        // failure `timed()` guards on the write path. On timeout we still fall
919        // through to consumer cleanup, then surface `Timeout`.
920        let mut timed_out = false;
921        if num_pending > 0 {
922            let mut delivered = 0u64;
923            let kv_prefix = format!("$KV.{bucket}.");
924
925            while delivered < num_pending {
926                match tokio::time::timeout(KV_OP_TIMEOUT, sub.next()).await {
927                    Ok(Some(msg)) => {
928                        let key = msg
929                            .subject
930                            .strip_prefix(&kv_prefix)
931                            .unwrap_or(msg.subject.as_str())
932                            .to_string();
933
934                        on_msg(msg, key);
935                        delivered += 1;
936                    }
937                    Ok(None) => break, // subscription closed early
938                    Err(_) => {
939                        timed_out = true;
940                        break;
941                    }
942                }
943            }
944        }
945
946        // Clean up ephemeral consumer (best-effort), even on timeout — a stalled
947        // scan shouldn't also leak a server-side consumer. A leaked consumer
948        // lingers on the server and counts against per-stream limits, so surface
949        // failures in observability without failing the operation. Bound the
950        // delete with `timed()`: on the same half-dead (CLOSE_WAIT) connection
951        // that tripped the drain timeout above, an unbounded delete would re-park
952        // here forever, defeating the timeout recovery we just performed.
953        match timed(stream.delete_consumer(&consumer.cached_info().name)).await {
954            Ok(Ok(_)) => {}
955            Ok(Err(e)) => {
956                // `warn!`, not `debug!`: a leaked ephemeral consumer lingers on
957                // the server and counts against per-stream limits. Under a flaky
958                // NATS connection every scan()/keys() leaks one, so this must be
959                // visible in default spans before the pile-up hits the limit.
960                warn!(error = %e, "failed to delete ephemeral consumer (best-effort)");
961            }
962            Err(_) => {
963                warn!("timed out deleting ephemeral consumer (best-effort)");
964            }
965        }
966
967        if timed_out {
968            return Err(KvError::Timeout);
969        }
970        Ok(())
971    }
972}
973
974/// Convert a NATS KV entry to a KvUpdate.
975///
976/// Takes the entry by value so the key `String` moves into the `KvUpdate`
977/// instead of allocating a fresh copy per watch event.
978fn nats_entry_to_kv_update(entry: async_nats::jetstream::kv::Entry) -> KvUpdate {
979    use async_nats::jetstream::kv::Operation;
980    let version = VersionToken::from_u64(entry.revision);
981    match entry.operation {
982        Operation::Put => KvUpdate::Put(KvEntry {
983            key: entry.key,
984            value: entry.value.to_vec(),
985            version,
986        }),
987        Operation::Delete => KvUpdate::Delete {
988            key: entry.key,
989            version,
990        },
991        Operation::Purge => KvUpdate::Purge {
992            key: entry.key,
993            version,
994        },
995    }
996}
997
998/// Stream updates from a NATS Watch into a channel until it ends or the receiver drops.
999async fn stream_watch(
1000    mut watcher: async_nats::jetstream::kv::Watch,
1001    tx: &Sender<KvUpdate>,
1002) -> Result<(), KvError> {
1003    while let Some(entry) = watcher.next().await {
1004        match entry {
1005            Ok(entry) => {
1006                let update = nats_entry_to_kv_update(entry);
1007                if tx.send(update).await.is_err() {
1008                    debug!("watch receiver closed");
1009                    break;
1010                }
1011            }
1012            Err(e) => {
1013                error!(error = %e, "NATS KV watch error");
1014                return Err(KvError::WatchError(e.to_string()));
1015            }
1016        }
1017    }
1018    Ok(())
1019}
1020
1021/// Cadence of the floor guard's no-traffic backstop probe (one stream-info
1022/// RPC per interval per guarded watch). The PRIMARY detection is in-band —
1023/// the gapped-delivery check fires the moment evidence surfaces — so this
1024/// interval only bounds detection latency when NOTHING is being delivered;
1025/// it is not load-bearing for eventual detection.
1026const FLOOR_GUARD_INTERVAL: Duration = Duration::from_secs(30);
1027
1028/// [`stream_watch`] for the dense ALL-scope resume path, with the LIVE
1029/// retention floor guard (`tests/model_live_watch.rs` — the live twin of
1030/// [`NatsKvWatcher::check_resume_window`]).
1031///
1032/// The hazard: retention overrunning a live consumer makes JetStream
1033/// silently skip evicted messages — delete markers included — with no error
1034/// anywhere (the same clamp behavior as resumes, mid-stream). Unguarded,
1035/// that is PERMANENT silent fold divergence; the model proves it reachable.
1036///
1037/// Detection is primarily **in-band**: an unfiltered `ByStartSequence`
1038/// consumer sees every retained message, so a delivered revision that jumps
1039/// the frontier by more than one is evidence of eviction inside the gap.
1040/// The model checker REJECTED a periodic-only design with exactly the trace
1041/// this closes — deliveries can catch the frontier up past the gap between
1042/// probes, erasing the evidence — so the check runs AT the gapped delivery,
1043/// before the entry is processed: fetch `first_sequence` and apply the
1044/// shared kernel (`protocol::resume_window_ok`) to the frontier. A benign
1045/// gap (interior per-subject eviction with the floor still at or below the
1046/// frontier) passes; head eviction past the frontier fails the watch, and
1047/// the caller's restart routes into the verified resume → `CursorExpired` →
1048/// resync repair path. The periodic probe backstops the no-traffic case.
1049///
1050/// Scope: sound only where density holds — the unfiltered resume watch.
1051/// Prefix-scoped watches deliver sparse revisions by design and cannot
1052/// distinguish benign from hazardous eviction client-side; they retain the
1053/// (narrowed) retention-outlives-lag operating axiom plus the resume-time
1054/// check on every restart (model axiom 5).
1055///
1056/// The guarantee split, precisely: the SAFETY half — never folding past
1057/// unexamined evidence of loss — is unconditional in this loop (the gap
1058/// check precedes processing, and a stalled downstream stalls folding too).
1059/// The REPAIR half is conditional on the caller restarting the failed watch
1060/// (standard supervision; same posture as the resync fail-stop): a trip
1061/// with no restart is a loudly dead watch, never a silently wrong one.
1062async fn stream_watch_floor_guarded(
1063    mut watcher: async_nats::jetstream::kv::Watch,
1064    tx: &Sender<KvUpdate>,
1065    resume_revision: u64,
1066    js: &async_nats::jetstream::Context,
1067    bucket: &str,
1068) -> Result<(), KvError> {
1069    let stream_name = format!("KV_{bucket}");
1070    let first_sequence = || async {
1071        let stream = timed(js.get_stream(&stream_name))
1072            .await?
1073            .map_err(|e| KvError::OperationFailed(format!("floor guard stream lookup: {e}")))?;
1074        Ok::<u64, KvError>(stream.cached_info().state.first_sequence)
1075    };
1076    fn trip(frontier: u64, first: u64, bucket: &str) -> KvError {
1077        warn!(
1078            frontier,
1079            first_sequence = first,
1080            bucket,
1081            "stream retention overran this live watch; failing so the restart can resync \
1082             (messages in the gap were evicted unseen)"
1083        );
1084        KvError::WatchError(format!(
1085            "stream retention overran live watch (first_sequence {first} > delivered \
1086             frontier {frontier} + 1); restart will resync"
1087        ))
1088    }
1089
1090    let mut frontier = resume_revision;
1091    let mut backstop = tokio::time::interval(FLOOR_GUARD_INTERVAL);
1092    backstop.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
1093    backstop.tick().await; // consume the immediate first tick
1094
1095    loop {
1096        tokio::select! {
1097            entry = watcher.next() => {
1098                let Some(entry) = entry else { break };
1099                match entry {
1100                    Ok(entry) => {
1101                        let revision = entry.revision;
1102                        // In-band gap check BEFORE processing: never fold
1103                        // past unexamined evidence of eviction.
1104                        if revision > frontier.saturating_add(1) {
1105                            let first = first_sequence().await?;
1106                            if !crate::protocol::resume_window_ok(frontier, first) {
1107                                return Err(trip(frontier, first, bucket));
1108                            }
1109                            // Benign interior gap: every evicted revision
1110                            // below a still-low floor was a per-subject
1111                            // overwrite, whose later revision the fold will
1112                            // see — safe for last-write-wins.
1113                        }
1114                        frontier = frontier.max(revision);
1115                        let update = nats_entry_to_kv_update(entry);
1116                        if tx.send(update).await.is_err() {
1117                            debug!("watch receiver closed");
1118                            break;
1119                        }
1120                    }
1121                    Err(e) => {
1122                        error!(error = %e, "NATS KV watch error");
1123                        return Err(KvError::WatchError(e.to_string()));
1124                    }
1125                }
1126            }
1127            _ = backstop.tick() => {
1128                // No-traffic backstop: nothing is being delivered, so the
1129                // in-band check has no evidence to act on; probe the floor
1130                // directly.
1131                let first = first_sequence().await?;
1132                if !crate::protocol::resume_window_ok(frontier, first) {
1133                    return Err(trip(frontier, first, bucket));
1134                }
1135            }
1136        }
1137    }
1138    Ok(())
1139}
1140
1141/// Check if a NATS watch error indicates the requested start sequence is
1142/// too old (compacted), meaning callers should fall back to a full watch.
1143///
1144/// SECOND line of defense only: live nats-server (2.14) does not error on a
1145/// below-head start sequence at all — it silently clamps to the first
1146/// retained message (pinned by `tests/resync.rs`), so the PRIMARY expiry
1147/// detection is [`NatsKvWatcher::check_resume_window`]'s proactive
1148/// `first_sequence` comparison. This matcher remains for server versions or
1149/// paths that do error, where mapping to [`KvError::CursorExpired`] keeps
1150/// the fallback reachable instead of stranding the caller.
1151///
1152/// async-nats has no granular error kind for this: `WatchErrorKind` is only
1153/// `InvalidKey`/`TimedOut`/`ConsumerCreate`/`Other`, and "start sequence too old"
1154/// arrives as `ConsumerCreate`/`Other` with the real reason buried in the source
1155/// error's *message*. So we substring-match the full error string — which already
1156/// includes the source, since `Error`'s `Display` renders `"{kind}: {source}"`.
1157///
1158/// Two deliberate choices make this robust to wording drift:
1159/// - We lowercase first, so a capitalization change in NATS/async-nats can't slip
1160///   past.
1161/// - Detection is biased toward `true`. A false positive only costs an
1162///   unnecessary (but always-safe) full `watch_all()` replay; a false negative
1163///   propagates `WatchError` and strands a caller that would otherwise recover.
1164///
1165/// If these messages ever change, `cursor_expired_matches_known_nats_error_strings`
1166/// is the canary that fails loudly on the next dependency bump.
1167fn is_cursor_expired_error(err: &str) -> bool {
1168    use std::sync::OnceLock;
1169    // One Aho-Corasick automaton over all needles: a single pass over the error
1170    // string regardless of how many needles accumulate as NATS versions reword
1171    // their messages, vs. one `windows()` scan per needle. Case-insensitivity is
1172    // baked into the automaton, so no lowercased copy is allocated either.
1173    static MATCHER: OnceLock<aho_corasick::AhoCorasick> = OnceLock::new();
1174    MATCHER
1175        .get_or_init(|| {
1176            aho_corasick::AhoCorasick::builder()
1177                .ascii_case_insensitive(true)
1178                .build([
1179                    "start sequence",
1180                    "first sequence",
1181                    "sequence not found",
1182                    "too old",
1183                ])
1184                .expect("static needle set always compiles")
1185        })
1186        .is_match(err)
1187}
1188
1189struct NatsKvWatcher {
1190    kv: Store,
1191    // `watch_prefixes_from` has no async-nats equivalent (there is no
1192    // `watch_many_from_revision`), so it hand-builds the multi-filter ordered
1193    // consumer itself — which needs the raw client (inbox allocation), the
1194    // JetStream context (stream lookup), and the bucket name (subject filters),
1195    // same as the reader's scan path.
1196    client: async_nats::Client,
1197    js: async_nats::jetstream::Context,
1198    bucket: String,
1199}
1200
1201/// Decode a raw KV stream message (as delivered by a hand-built ordered push
1202/// consumer) into a [`KvUpdate`] — the same mapping `async-nats`'s `kv::Watch`
1203/// performs internally for the `watch_*` paths: key from the subject (stripping
1204/// the `$KV.{bucket}.` prefix), operation from the `KV-Operation` header
1205/// (absent = Put), revision from the stream sequence in the ACK reply subject.
1206///
1207/// Returns `None` for a subject outside the bucket's keyspace, which a
1208/// subject-filtered consumer should never deliver — skipped rather than
1209/// surfaced, matching `kv::Watch`'s behavior.
1210fn kv_message_to_update(msg: &async_nats::Message, kv_prefix: &str) -> Option<KvUpdate> {
1211    let key = msg.subject.strip_prefix(kv_prefix)?.to_string();
1212    // An unparseable (or absent) ACK subject yields the UNKNOWN version, not a
1213    // fabricated revision 0: `from_u64(0)` is a *parseable* position that
1214    // `watch_applied` would adopt as its batch high-water — regressing the
1215    // persisted cursor to 0 and forcing a full replay on the next restart.
1216    // `unknown()` is the honest value; the cursor-authority loop skips it.
1217    let version = msg
1218        .reply
1219        .as_deref()
1220        .and_then(stream_sequence_from_ack)
1221        .map(VersionToken::from_u64)
1222        .unwrap_or_else(VersionToken::unknown);
1223    let operation = msg
1224        .headers
1225        .as_ref()
1226        .and_then(|h| h.get("KV-Operation"))
1227        .map(|v| v.as_str());
1228    Some(match operation {
1229        Some("DEL") => KvUpdate::Delete { key, version },
1230        Some("PURGE") => KvUpdate::Purge { key, version },
1231        // No header (or an explicit "PUT") is a put — the common case carries
1232        // no KV-Operation header at all.
1233        _ => KvUpdate::Put(KvEntry {
1234            key,
1235            value: msg.payload.to_vec(),
1236            version,
1237        }),
1238    })
1239}
1240
1241impl NatsKvWatcher {
1242    /// Proactive cursor-expiry detection, REQUIRED before any `*_from` resume.
1243    ///
1244    /// NATS does **not** error when an ordered consumer's `ByStartSequence`
1245    /// falls below the stream's first retained sequence — it silently delivers
1246    /// from the first available message (pinned against a live nats-server by
1247    /// `tests/resync.rs::nats_silently_clamps_resume_below_first_seq`). A
1248    /// silent clamp skips the gap's evicted messages — delete markers
1249    /// included — without ever taking the `CursorExpired` → resync path, so
1250    /// expiry MUST be detected by comparing the stream's `first_sequence`
1251    /// against the resume point before trusting the consumer. The
1252    /// error-string matching at the consumer-create sites stays as a second
1253    /// line of defense for server versions that do error.
1254    ///
1255    /// Why `first_sequence` is the right boundary: interior (per-subject
1256    /// history) eviction inside the gap is safe for a last-write-wins fold —
1257    /// an overwrite-evicted revision implies a LATER revision of the same
1258    /// subject exists and will be delivered. Lost *deletes* come from head
1259    /// eviction (stream limits/age), which is exactly what advances
1260    /// `first_sequence`. (An admin interior purge of a subject can also
1261    /// destroy a delete marker without moving the head — that is a manual
1262    /// destructive operation, same trust class as deleting the stream.)
1263    ///
1264    /// Head eviction racing the window between this check and consumer
1265    /// creation is the same exposure any live consumer has against
1266    /// aggressive retention; the check bounds the silent gap to that
1267    /// milliseconds-scale window, where the prior behavior left it unbounded.
1268    async fn check_resume_window(&self, revision: u64) -> Result<(), KvError> {
1269        let stream = timed(self.js.get_stream(format!("KV_{}", self.bucket)))
1270            .await?
1271            .map_err(|e| {
1272                KvError::OperationFailed(format!("get KV stream for resume check: {e}"))
1273            })?;
1274        let first = stream.cached_info().state.first_sequence;
1275        // The shared protocol kernel — the same guard the model checker's
1276        // Resume transition executes (`crate::protocol::resume_window_ok`).
1277        if !crate::protocol::resume_window_ok(revision, first) {
1278            warn!(
1279                revision,
1280                first_sequence = first,
1281                "resume cursor is below the stream's first retained sequence; cursor expired"
1282            );
1283            return Err(KvError::CursorExpired);
1284        }
1285        Ok(())
1286    }
1287}
1288
1289#[async_trait]
1290impl KvWatcher for NatsKvWatcher {
1291    async fn watch_all(&self, tx: Sender<KvUpdate>) -> Result<(), KvError> {
1292        // `watch_with_history` (DeliverPolicy::LastPerSubject), NOT `watch_all`
1293        // (DeliverPolicy::New): the trait contract is state-sync — current value
1294        // of every key first, then live updates. async-nats's `watch_all` only
1295        // delivers messages published AFTER the consumer exists, which would
1296        // leave a no-cursor consumer empty until keys happen to change.
1297        //
1298        // Bound the watch *setup* with `timed()` for the same reason every KV op
1299        // is bounded: a half-dead (CLOSE_WAIT) NATS connection parks this await
1300        // forever instead of failing. The streaming drain in `stream_watch` is
1301        // intentionally unbounded (a watch is long-lived), but establishing it
1302        // must not be able to hang a reconnecting caller.
1303        let watcher = timed(self.kv.watch_with_history(">"))
1304            .await?
1305            .map_err(|e| KvError::WatchError(e.to_string()))?;
1306        stream_watch(watcher, &tx).await
1307    }
1308
1309    async fn watch_prefix(&self, prefix: &str, tx: Sender<KvUpdate>) -> Result<(), KvError> {
1310        // Use native NATS subject-based filtering. KV key "node.abc" maps to
1311        // subject "$KV.BUCKET.node.abc", and ">" is the multi-level wildcard.
1312        // `_with_history` for the same state-sync contract as `watch_all`.
1313        let nats_key = format!("{prefix}>");
1314        let watcher = timed(self.kv.watch_with_history(&nats_key))
1315            .await?
1316            .map_err(|e| KvError::WatchError(e.to_string()))?;
1317        stream_watch(watcher, &tx).await
1318    }
1319
1320    async fn watch_prefixes(&self, prefixes: &[&str], tx: Sender<KvUpdate>) -> Result<(), KvError> {
1321        if prefixes.is_empty() {
1322            // Nothing to watch. Critically, do NOT fall through to `watch_many`
1323            // with an empty filter set — an unfiltered ordered consumer would
1324            // watch the WHOLE bucket, the opposite of a scoped watch.
1325            return Ok(());
1326        }
1327        // ONE multi-filter consumer for every prefix (NATS 2.10 `filter_subjects`)
1328        // rather than one consumer per prefix. `watch_many_with_history` builds a
1329        // single ordered push consumer with `filter_subjects = [{p}> ...]` and
1330        // yields the same `Entry` stream as `watch`, so `stream_watch` is reused
1331        // verbatim. This is the per-stream-consumer-count fix: a node scoped to N
1332        // prefixes costs 1 consumer, not N. `_with_history` for the same
1333        // state-sync contract as `watch_all`.
1334        let keys: Vec<String> = prefixes.iter().map(|p| format!("{p}>")).collect();
1335        let watcher = timed(self.kv.watch_many_with_history(keys))
1336            .await?
1337            .map_err(|e| KvError::WatchError(e.to_string()))?;
1338        stream_watch(watcher, &tx).await
1339    }
1340
1341    async fn watch_all_from(
1342        &self,
1343        cursor: &WatchCursor,
1344        tx: Sender<KvUpdate>,
1345    ) -> Result<(), KvError> {
1346        let revision = match cursor.as_u64() {
1347            Some(rev) if rev > 0 => rev,
1348            _ => return self.watch_all(tx).await,
1349        };
1350        self.check_resume_window(revision).await?;
1351
1352        let watcher = match timed(self.kv.watch_all_from_revision(revision + 1)).await? {
1353            Ok(w) => w,
1354            Err(e) => {
1355                let err_str = e.to_string();
1356                if is_cursor_expired_error(&err_str) {
1357                    warn!(revision, error = %err_str, "cursor expired, caller should fall back to full watch");
1358                    return Err(KvError::CursorExpired);
1359                }
1360                return Err(KvError::WatchError(err_str));
1361            }
1362        };
1363        // Re-check AFTER the consumer exists: head eviction in the window
1364        // between the pre-flight check and consumer creation would otherwise
1365        // clamp silently.
1366        self.check_resume_window(revision).await?;
1367
1368        info!(revision, "resumed watch from cursor");
1369        // The LIVE floor guard takes over from here: in-band gapped-delivery
1370        // checks plus a no-traffic backstop, so retention overrunning this
1371        // watch mid-stream fail-stops into the restart→resync repair path
1372        // instead of silently skipping evicted deletes (model:
1373        // tests/model_live_watch.rs).
1374        stream_watch_floor_guarded(watcher, &tx, revision, &self.js, &self.bucket).await
1375    }
1376
1377    async fn watch_prefix_from(
1378        &self,
1379        prefix: &str,
1380        cursor: &WatchCursor,
1381        tx: Sender<KvUpdate>,
1382    ) -> Result<(), KvError> {
1383        let revision = match cursor.as_u64() {
1384            Some(rev) if rev > 0 => rev,
1385            _ => return self.watch_prefix(prefix, tx).await,
1386        };
1387        self.check_resume_window(revision).await?;
1388
1389        let nats_key = format!("{prefix}>");
1390        let watcher = match timed(self.kv.watch_from_revision(&nats_key, revision + 1)).await? {
1391            Ok(w) => w,
1392            Err(e) => {
1393                let err_str = e.to_string();
1394                if is_cursor_expired_error(&err_str) {
1395                    warn!(revision, prefix, error = %err_str, "cursor expired for prefix watch, caller should fall back");
1396                    return Err(KvError::CursorExpired);
1397                }
1398                return Err(KvError::WatchError(err_str));
1399            }
1400        };
1401        // Same post-create re-check as watch_all_from: close the
1402        // check→create eviction window.
1403        self.check_resume_window(revision).await?;
1404
1405        info!(revision, prefix, "resumed prefix watch from cursor");
1406        stream_watch(watcher, &tx).await
1407    }
1408
1409    async fn watch_prefixes_from(
1410        &self,
1411        prefixes: &[&str],
1412        cursor: &WatchCursor,
1413        tx: Sender<KvUpdate>,
1414    ) -> Result<(), KvError> {
1415        use async_nats::jetstream::consumer::{DeliverPolicy, ReplayPolicy, push};
1416
1417        if prefixes.is_empty() {
1418            // Same guard as watch_prefixes: an empty filter set must not become
1419            // an unfiltered whole-bucket consumer.
1420            return Ok(());
1421        }
1422        let revision = match cursor.as_u64() {
1423            Some(rev) if rev > 0 => rev,
1424            _ => return self.watch_prefixes(prefixes, tx).await,
1425        };
1426
1427        // async-nats has `watch_many` (multi-filter) and `watch_from_revision`
1428        // (seek) but no combination of the two, so build the multi-filter
1429        // ordered push consumer ourselves — the exact consumer
1430        // `watch_many_with_deliver_policy` would build, with
1431        // `ByStartSequence(cursor+1)` for the delta seek. The ordered-consumer
1432        // machinery (gap detection, auto-recreate from the last delivered
1433        // sequence) comes with `OrderedConfig` for free.
1434        let bucket = self.bucket.as_str();
1435        let kv_prefix = format!("$KV.{bucket}.");
1436        let filter_subjects: Vec<String> = prefixes
1437            .iter()
1438            .map(|p| format!("{kv_prefix}{p}>"))
1439            .collect();
1440
1441        let stream = timed(self.js.get_stream(format!("KV_{bucket}")))
1442            .await?
1443            .map_err(|e| KvError::WatchError(format!("get KV stream: {e}")))?;
1444
1445        // Same proactive expiry detection as `check_resume_window` (NATS
1446        // silently clamps a below-head ByStartSequence; see that method's
1447        // docs) — checked on the stream handle this path already fetched,
1448        // via the shared protocol kernel.
1449        let first = stream.cached_info().state.first_sequence;
1450        if !crate::protocol::resume_window_ok(revision, first) {
1451            warn!(
1452                revision,
1453                first_sequence = first,
1454                ?prefixes,
1455                "resume cursor is below the stream's first retained sequence; cursor expired"
1456            );
1457            return Err(KvError::CursorExpired);
1458        }
1459
1460        let consumer = match timed(stream.create_consumer(push::OrderedConfig {
1461            deliver_subject: self.client.new_inbox(),
1462            description: Some("kv multi-prefix resume consumer".to_string()),
1463            filter_subjects,
1464            replay_policy: ReplayPolicy::Instant,
1465            deliver_policy: DeliverPolicy::ByStartSequence {
1466                start_sequence: revision + 1,
1467            },
1468            ..Default::default()
1469        }))
1470        .await?
1471        {
1472            Ok(c) => c,
1473            Err(e) => {
1474                // Same expiry classification as watch_all_from: a start sequence
1475                // the stream has compacted past surfaces as a consumer-create
1476                // error whose message names the sequence problem.
1477                let err_str = e.to_string();
1478                if is_cursor_expired_error(&err_str) {
1479                    warn!(revision, ?prefixes, error = %err_str, "cursor expired for multi-prefix watch, caller should fall back");
1480                    return Err(KvError::CursorExpired);
1481                }
1482                return Err(KvError::WatchError(err_str));
1483            }
1484        };
1485
1486        // Re-check AFTER the consumer exists (fresh stream info, not the
1487        // handle's cached copy): closes the check→create eviction window,
1488        // same as the single-filter resume paths.
1489        self.check_resume_window(revision).await?;
1490
1491        let mut messages = timed(consumer.messages())
1492            .await?
1493            .map_err(|e| KvError::WatchError(e.to_string()))?;
1494
1495        info!(
1496            revision,
1497            ?prefixes,
1498            "resumed multi-prefix watch from cursor"
1499        );
1500        while let Some(msg) = messages.next().await {
1501            match msg {
1502                Ok(msg) => {
1503                    // A subject-filtered consumer only delivers in-keyspace
1504                    // subjects; `None` here would be a server bug, skipped to
1505                    // match kv::Watch's tolerance.
1506                    let Some(update) = kv_message_to_update(&msg, &kv_prefix) else {
1507                        continue;
1508                    };
1509                    if tx.send(update).await.is_err() {
1510                        debug!("watch receiver closed");
1511                        break;
1512                    }
1513                }
1514                Err(e) => {
1515                    error!(error = %e, "NATS KV multi-prefix watch error");
1516                    return Err(KvError::WatchError(e.to_string()));
1517                }
1518            }
1519        }
1520        Ok(())
1521    }
1522}
1523
1524struct NatsKvWriterImpl {
1525    kv: Store,
1526}
1527
1528#[async_trait]
1529impl KvWriter for NatsKvWriterImpl {
1530    async fn put(&self, key: &str, value: &[u8]) -> Result<VersionToken, KvError> {
1531        let rev = timed(self.kv.put(key, value.to_vec().into()))
1532            .await?
1533            .map_err(|e| KvError::OperationFailed(e.to_string()))?;
1534        Ok(VersionToken::from_u64(rev))
1535    }
1536
1537    async fn delete(&self, key: &str) -> Result<bool, KvError> {
1538        // NATS delete doesn't tell us if key existed, so we always return true
1539        timed(self.kv.delete(key))
1540            .await?
1541            .map_err(|e| KvError::OperationFailed(e.to_string()))?;
1542        Ok(true)
1543    }
1544
1545    async fn create(&self, key: &str, value: &[u8]) -> Result<VersionToken, KvError> {
1546        use async_nats::jetstream::kv::CreateErrorKind;
1547        timed(self.kv.create(key, value.to_vec().into()))
1548            .await?
1549            .map(VersionToken::from_u64)
1550            .map_err(|e| {
1551                if e.kind() == CreateErrorKind::AlreadyExists {
1552                    KvError::AlreadyExists
1553                } else {
1554                    KvError::OperationFailed(e.to_string())
1555                }
1556            })
1557    }
1558
1559    async fn update(
1560        &self,
1561        key: &str,
1562        value: &[u8],
1563        expected: &VersionToken,
1564    ) -> Result<VersionToken, KvError> {
1565        use async_nats::jetstream::kv::UpdateErrorKind;
1566        let rev = expected.as_u64().ok_or_else(|| {
1567            KvError::OperationFailed("invalid version token for NATS update".into())
1568        })?;
1569        timed(self.kv.update(key, value.to_vec().into(), rev))
1570            .await?
1571            .map(VersionToken::from_u64)
1572            .map_err(|e| {
1573                if e.kind() == UpdateErrorKind::WrongLastRevision {
1574                    KvError::RevisionMismatch
1575                } else {
1576                    KvError::OperationFailed(e.to_string())
1577                }
1578            })
1579    }
1580
1581    async fn delete_with_version(
1582        &self,
1583        key: &str,
1584        expected: &VersionToken,
1585    ) -> Result<bool, KvError> {
1586        use async_nats::jetstream::kv::UpdateErrorKind;
1587        let rev = expected.as_u64().ok_or_else(|| {
1588            KvError::OperationFailed("invalid version token for NATS delete".into())
1589        })?;
1590        // Write empty value with CAS — logically deletes while preserving conflict detection
1591        timed(self.kv.update(key, Vec::new().into(), rev))
1592            .await?
1593            .map(|_| true)
1594            .map_err(|e| {
1595                if e.kind() == UpdateErrorKind::WrongLastRevision {
1596                    KvError::RevisionMismatch
1597                } else {
1598                    KvError::OperationFailed(e.to_string())
1599                }
1600            })
1601    }
1602}
1603
1604#[async_trait]
1605impl KvPurge for NatsKvWriterImpl {
1606    async fn purge(&self, key: &str) -> Result<(), KvError> {
1607        // Rollup purge (`Nats-Rollup: sub`): drops all prior revisions of the
1608        // subject, reclaiming bytes against `max_bytes` — unlike `delete`, which
1609        // only appends a marker. Idempotent: purging an absent key is a no-op.
1610        timed(self.kv.purge(key))
1611            .await?
1612            .map_err(|e| KvError::OperationFailed(e.to_string()))?;
1613        Ok(())
1614    }
1615}
1616
1617impl std::fmt::Debug for NatsConnection {
1618    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1619        f.debug_struct("NatsConnection")
1620            .field("url", &self.config.url)
1621            // `Acquire` to match every other read of `healthy` — a `Relaxed`
1622            // outlier here reads like a deliberate exception during an atomics
1623            // audit, and the fmt path is far too cold for the ordering to cost
1624            // anything.
1625            .field("healthy", &self.healthy.load(Ordering::Acquire))
1626            .finish()
1627    }
1628}
1629
1630#[cfg(test)]
1631mod tests {
1632    use super::*;
1633
1634    #[test]
1635    fn raw_create_success_has_no_error() {
1636        // A successful STREAM.CREATE echoes back the stream config, no "error".
1637        let payload = br#"{"type":"io.nats.jetstream.api.v1.stream_create_response","config":{"name":"KV_certs"}}"#;
1638        assert_eq!(
1639            classify_raw_create_response(payload),
1640            RawCreateOutcome::Created
1641        );
1642    }
1643
1644    #[test]
1645    fn raw_create_swallows_stream_already_exists() {
1646        // 10058 = stream name already in use → the bucket already exists, OK.
1647        let payload =
1648            br#"{"error":{"code":400,"err_code":10058,"description":"stream name already in use"}}"#;
1649        assert_eq!(
1650            classify_raw_create_response(payload),
1651            RawCreateOutcome::AlreadyExists
1652        );
1653    }
1654
1655    #[test]
1656    fn raw_create_swallows_stream_limit() {
1657        // Synadia Cloud returns 400 + "maximum number of streams" at the limit,
1658        // but the bucket may already exist — treat as non-fatal.
1659        let payload =
1660            br#"{"error":{"code":400,"description":"maximum number of streams reached"}}"#;
1661        assert_eq!(
1662            classify_raw_create_response(payload),
1663            RawCreateOutcome::StreamLimit
1664        );
1665    }
1666
1667    #[test]
1668    fn raw_create_propagates_unknown_error() {
1669        // Any other JetStream error is fatal and must surface code + description.
1670        let payload = br#"{"error":{"code":403,"description":"insufficient permissions"}}"#;
1671        match classify_raw_create_response(payload) {
1672            RawCreateOutcome::Failed { code, description } => {
1673                assert_eq!(code, 403);
1674                assert_eq!(description, "insufficient permissions");
1675            }
1676            other => panic!("expected Failed, got {other:?}"),
1677        }
1678    }
1679
1680    #[test]
1681    fn raw_create_400_without_stream_limit_is_fatal() {
1682        // A bare 400 that isn't the stream-limit message must NOT be swallowed,
1683        // otherwise a genuine bad-config rejection would masquerade as success.
1684        let payload = br#"{"error":{"code":400,"description":"invalid stream config"}}"#;
1685        match classify_raw_create_response(payload) {
1686            RawCreateOutcome::Failed { code, description } => {
1687                assert_eq!(code, 400);
1688                assert!(description.contains("invalid stream config"));
1689            }
1690            other => panic!("expected Failed, got {other:?}"),
1691        }
1692    }
1693
1694    #[test]
1695    fn raw_create_unparseable_payload_is_treated_as_success() {
1696        // The caller re-verifies with get_key_value, so a garbled body must not
1697        // be reported as a hard failure here.
1698        assert_eq!(
1699            classify_raw_create_response(b"not json at all"),
1700            RawCreateOutcome::Created
1701        );
1702    }
1703
1704    #[test]
1705    fn ack_subject_legacy_format() {
1706        // $JS.ACK.<stream>.<consumer>.<delivered>.<stream_seq>.<consumer_seq>.<ts>.<pending>
1707        let reply = "$JS.ACK.KV_certs.cons.1.42.7.1700000000000000000.0";
1708        assert_eq!(stream_sequence_from_ack(reply), Some(42));
1709    }
1710
1711    #[test]
1712    fn ack_subject_modern_format_with_domain_and_account() {
1713        // $JS.ACK.<domain>.<account>.<stream>.<consumer>.<delivered>.<stream_seq>.<consumer_seq>.<ts>.<pending>
1714        let reply = "$JS.ACK.hub.AABBCC.KV_certs.cons.1.42.7.1700000000000000000.0";
1715        assert_eq!(stream_sequence_from_ack(reply), Some(42));
1716    }
1717
1718    #[test]
1719    fn ack_subject_modern_format_with_trailing_token() {
1720        // Some servers append a random trailing token (12 tokens total).
1721        let reply = "$JS.ACK.hub.AABBCC.KV_certs.cons.1.99.7.1700000000000000000.0.rng";
1722        assert_eq!(stream_sequence_from_ack(reply), Some(99));
1723    }
1724
1725    #[test]
1726    fn ack_subject_last_token_is_not_the_sequence() {
1727        // Regression guard: the final token is num_pending, never the sequence.
1728        // The old code returned this (0), corrupting every scanned entry's version.
1729        let reply = "$JS.ACK.KV_certs.cons.1.42.7.1700000000000000000.0";
1730        assert_ne!(stream_sequence_from_ack(reply), Some(0));
1731    }
1732
1733    #[test]
1734    fn ack_subject_rejects_garbage() {
1735        assert_eq!(stream_sequence_from_ack(""), None);
1736        assert_eq!(stream_sequence_from_ack("not.an.ack.subject"), None);
1737        assert_eq!(stream_sequence_from_ack("$JS.ACK.too.few.tokens"), None);
1738        // Right shape, non-numeric sequence field.
1739        assert_eq!(stream_sequence_from_ack("$JS.ACK.s.c.1.notnum.7.0.0"), None);
1740    }
1741
1742    #[test]
1743    fn cursor_expired_matches_known_nats_error_strings() {
1744        // These substrings come from async-nats error messages. If the library
1745        // rewrites them, watch_all_from would return WatchError instead of
1746        // CursorExpired, breaking callers that fall back to watch_all() on expiry.
1747        assert!(is_cursor_expired_error(
1748            "consumer start sequence is too old"
1749        ));
1750        assert!(is_cursor_expired_error("first sequence is 42, requested 1"));
1751        assert!(is_cursor_expired_error("sequence not found in stream"));
1752        // "too old" on its own (no "sequence" wording) must still be caught.
1753        assert!(is_cursor_expired_error("requested revision is too old"));
1754        // Case-insensitive: a capitalization change upstream must not slip past.
1755        assert!(is_cursor_expired_error("Consumer Start Sequence Too Old"));
1756        assert!(!is_cursor_expired_error("connection refused"));
1757        assert!(!is_cursor_expired_error("permission denied"));
1758        assert!(!is_cursor_expired_error("stream not found"));
1759    }
1760
1761    fn raw_kv_msg(
1762        subject: &str,
1763        reply: Option<&str>,
1764        payload: &[u8],
1765        op: Option<&str>,
1766    ) -> async_nats::Message {
1767        let headers = op.map(|op| {
1768            let mut h = async_nats::HeaderMap::new();
1769            h.insert("KV-Operation", op);
1770            h
1771        });
1772        async_nats::Message {
1773            subject: subject.to_string().into(),
1774            reply: reply.map(|r| r.to_string().into()),
1775            payload: payload.to_vec().into(),
1776            headers,
1777            status: None,
1778            description: None,
1779            length: 0,
1780        }
1781    }
1782
1783    const ACK_42: &str = "$JS.ACK.KV_certs.cons.1.42.7.1700000000000000000.0";
1784
1785    #[test]
1786    fn kv_message_decodes_put_without_operation_header() {
1787        // The common case: a put carries no KV-Operation header at all.
1788        let msg = raw_kv_msg("$KV.certs.node.a", Some(ACK_42), b"v1", None);
1789        match kv_message_to_update(&msg, "$KV.certs.").expect("in keyspace") {
1790            KvUpdate::Put(e) => {
1791                assert_eq!(e.key, "node.a");
1792                assert_eq!(e.value, b"v1");
1793                assert_eq!(e.version.as_u64(), Some(42));
1794            }
1795            other => panic!("expected Put, got {other:?}"),
1796        }
1797    }
1798
1799    #[test]
1800    fn kv_message_decodes_delete_and_purge_markers() {
1801        let msg = raw_kv_msg("$KV.certs.node.a", Some(ACK_42), b"", Some("DEL"));
1802        assert!(matches!(
1803            kv_message_to_update(&msg, "$KV.certs.").expect("in keyspace"),
1804            KvUpdate::Delete { ref key, ref version } if key == "node.a" && version.as_u64() == Some(42)
1805        ));
1806
1807        let msg = raw_kv_msg("$KV.certs.node.a", Some(ACK_42), b"", Some("PURGE"));
1808        assert!(matches!(
1809            kv_message_to_update(&msg, "$KV.certs.").expect("in keyspace"),
1810            KvUpdate::Purge { ref key, .. } if key == "node.a"
1811        ));
1812    }
1813
1814    #[test]
1815    fn kv_message_outside_keyspace_is_skipped() {
1816        // A subject-filtered consumer should never deliver this; the decode
1817        // skips rather than mis-keys it.
1818        let msg = raw_kv_msg("$KV.other.node.a", Some(ACK_42), b"v", None);
1819        assert!(kv_message_to_update(&msg, "$KV.certs.").is_none());
1820    }
1821
1822    #[test]
1823    fn kv_message_without_reply_gets_unknown_version() {
1824        // No ACK reply subject → revision unparseable → the UNKNOWN token,
1825        // never a fabricated revision 0. A parseable `Some(0)` would be
1826        // adopted by watch_applied as a real batch high-water and regress
1827        // the persisted cursor to 0 (full replay on next restart); unknown
1828        // is skipped by the cursor-authority loop instead.
1829        let msg = raw_kv_msg("$KV.certs.node.a", None, b"v", None);
1830        match kv_message_to_update(&msg, "$KV.certs.").expect("in keyspace") {
1831            KvUpdate::Put(e) => {
1832                assert!(e.version.is_unknown());
1833                assert_eq!(e.version.as_u64(), None);
1834            }
1835            other => panic!("expected Put, got {other:?}"),
1836        }
1837    }
1838
1839    #[test]
1840    fn raw_create_already_exists_when_10058_in_code_field() {
1841        // Some Synadia Cloud deployments echo 10058 in `code` rather than
1842        // `err_code`. Both paths must return AlreadyExists, not Failed.
1843        let payload = br#"{"error":{"code":10058,"description":"stream name already in use"}}"#;
1844        assert_eq!(
1845            classify_raw_create_response(payload),
1846            RawCreateOutcome::AlreadyExists
1847        );
1848    }
1849
1850    #[test]
1851    fn raw_create_error_without_code_defaults_to_zero() {
1852        // Defensive: a malformed error object still classifies as Failed rather
1853        // than silently passing, with code defaulting to 0.
1854        let payload = br#"{"error":{"description":"mystery"}}"#;
1855        match classify_raw_create_response(payload) {
1856            RawCreateOutcome::Failed { code, description } => {
1857                assert_eq!(code, 0);
1858                assert_eq!(description, "mystery");
1859            }
1860            other => panic!("expected Failed, got {other:?}"),
1861        }
1862    }
1863}
1864
1865/// Live-server conformance tests for the floor guard
1866/// ([`stream_watch_floor_guarded`]) — these drive the guarded loop DIRECTLY
1867/// with a deliberately clamped `Watch`, which reproduces exactly the state
1868/// retention leaves behind when it overruns a live consumer (the watcher
1869/// methods' resume-time checks can't be raced deterministically from
1870/// outside, but the guarded loop neither knows nor cares how its watch got
1871/// clamped). Spawns a throwaway `nats-server` (mise-installed, same pattern
1872/// as tests/common).
1873#[cfg(test)]
1874mod floor_guard_tests {
1875    use super::*;
1876    use std::process::{Child, Command, Stdio};
1877
1878    struct TestServer {
1879        child: Child,
1880        url: String,
1881        _dir: tempfile::TempDir,
1882    }
1883
1884    impl Drop for TestServer {
1885        fn drop(&mut self) {
1886            let _ = self.child.kill();
1887            let _ = self.child.wait();
1888        }
1889    }
1890
1891    async fn start_server() -> TestServer {
1892        let bin = std::env::var("NATS_SERVER_BIN").unwrap_or_else(|_| "nats-server".into());
1893        let port = std::net::TcpListener::bind("127.0.0.1:0")
1894            .unwrap()
1895            .local_addr()
1896            .unwrap()
1897            .port();
1898        let dir = tempfile::tempdir().unwrap();
1899        let child = Command::new(&bin)
1900            .args([
1901                "--jetstream",
1902                "--addr",
1903                "127.0.0.1",
1904                "--port",
1905                &port.to_string(),
1906                "--store_dir",
1907                dir.path().to_str().unwrap(),
1908            ])
1909            .stdout(Stdio::null())
1910            .stderr(Stdio::null())
1911            .spawn()
1912            .unwrap_or_else(|e| panic!("spawn {bin}: {e}; run `mise install`"));
1913        let server = TestServer {
1914            child,
1915            url: format!("nats://127.0.0.1:{port}"),
1916            _dir: dir,
1917        };
1918        for _ in 0..100 {
1919            if async_nats::connect(&server.url).await.is_ok() {
1920                return server;
1921            }
1922            tokio::time::sleep(Duration::from_millis(100)).await;
1923        }
1924        panic!("nats-server never became ready");
1925    }
1926
1927    /// `(js, kv store)` with five revisions across five subjects (history 1).
1928    async fn seeded_bucket(
1929        url: &str,
1930    ) -> (
1931        async_nats::jetstream::Context,
1932        async_nats::jetstream::kv::Store,
1933    ) {
1934        let client = async_nats::connect(url).await.unwrap();
1935        let js = async_nats::jetstream::new(client);
1936        let kv = js
1937            .create_key_value(async_nats::jetstream::kv::Config {
1938                bucket: "guard".into(),
1939                history: 1,
1940                ..Default::default()
1941            })
1942            .await
1943            .unwrap();
1944        for i in 1..=5u8 {
1945            kv.put(format!("k{i}"), vec![i].into()).await.unwrap();
1946        }
1947        (js, kv)
1948    }
1949
1950    /// `KvPurge::purge` must reclaim bytes against `max_bytes` — unlike
1951    /// `delete`/`delete_with_version`, which only append markers. This is the
1952    /// in-repo twin of the "does purge actually free bytes?" gate: fill a
1953    /// bucket, purge half the keys, assert the stream's byte count drops.
1954    #[tokio::test(flavor = "multi_thread")]
1955    async fn purge_reclaims_bytes() {
1956        use crate::kv::KvPurge;
1957
1958        let server = start_server().await;
1959        let client = async_nats::connect(&server.url).await.unwrap();
1960        let js = async_nats::jetstream::new(client);
1961        let kv = js
1962            .create_key_value(async_nats::jetstream::kv::Config {
1963                bucket: "purge".into(),
1964                history: 1,
1965                ..Default::default()
1966            })
1967            .await
1968            .unwrap();
1969
1970        // Fill with sizable values across many distinct keys.
1971        let val = vec![b'x'; 4096];
1972        for i in 0..50u32 {
1973            kv.put(format!("k{i}"), val.clone().into()).await.unwrap();
1974        }
1975        let before = js
1976            .get_stream("KV_purge")
1977            .await
1978            .unwrap()
1979            .info()
1980            .await
1981            .unwrap()
1982            .state
1983            .bytes;
1984
1985        // Purge half the keys through the KvPurge impl.
1986        let writer = NatsKvWriterImpl { kv: kv.clone() };
1987        for i in 0..25u32 {
1988            writer.purge(&format!("k{i}")).await.unwrap();
1989        }
1990
1991        // Purge is a rollup: prior revisions of each subject are removed, so the
1992        // stream's byte count must fall. (A residual purge marker may remain per
1993        // subject — far smaller than the 4KiB value — so we assert a strict drop,
1994        // not zero.) Poll briefly in case the server reflects reclamation async.
1995        let mut after = before;
1996        for _ in 0..20 {
1997            after = js
1998                .get_stream("KV_purge")
1999                .await
2000                .unwrap()
2001                .info()
2002                .await
2003                .unwrap()
2004                .state
2005                .bytes;
2006            if after < before {
2007                break;
2008            }
2009            tokio::time::sleep(Duration::from_millis(100)).await;
2010        }
2011        assert!(
2012            after < before,
2013            "purge must reclaim bytes: before={before} after={after}"
2014        );
2015
2016        // Purge is idempotent: re-purging an absent key is not an error.
2017        writer.purge("k0").await.unwrap();
2018    }
2019
2020    /// TRUE POSITIVE: the watch was clamped past evicted revisions (purge
2021    /// advanced first_seq beyond the frontier) — the first gapped delivery
2022    /// must trip the guard BEFORE the entry is processed, never silently
2023    /// folding past the lost range. This is the live twin of the model's
2024    /// `GuardRepair`-only-progress gate.
2025    #[tokio::test(flavor = "multi_thread")]
2026    async fn gapped_delivery_with_advanced_floor_trips() {
2027        let server = start_server().await;
2028        let (js, kv) = seeded_bucket(&server.url).await;
2029
2030        // Evict revisions 1-3 outright: first_sequence becomes 4.
2031        let mut stream = js.get_stream("KV_guard").await.unwrap();
2032        stream.purge().sequence(4).await.unwrap();
2033        assert_eq!(stream.info().await.unwrap().state.first_sequence, 4);
2034
2035        // A consumer resuming from revision 1 gets CLAMPED to revision 4
2036        // (NATS's silent skip, pinned by tests/resync.rs). Hand that watch
2037        // to the guarded loop as a live consumer whose retention just
2038        // overran it.
2039        let watch = kv.watch_all_from_revision(2).await.unwrap();
2040        let (tx, mut rx) = tokio::sync::mpsc::channel(64);
2041        let drain = tokio::spawn(async move { while rx.recv().await.is_some() {} });
2042
2043        // The 5s bound pins IN-BAND detection: the trip must come from the
2044        // gapped-delivery check itself, not the 30s no-traffic backstop. A
2045        // regression to periodic-only detection (the design the model
2046        // checker rejected — catch-up between probes erases the evidence)
2047        // fails this bound.
2048        let err = tokio::time::timeout(
2049            Duration::from_secs(5),
2050            stream_watch_floor_guarded(watch, &tx, 1, &js, "guard"),
2051        )
2052        .await
2053        .expect("the trip must be IN-BAND (immediate), not backstop-paced")
2054        .expect_err("a gapped delivery over an advanced floor must trip");
2055        assert!(
2056            err.to_string().contains("retention overran live watch"),
2057            "{err}"
2058        );
2059        drop(tx);
2060        let _ = drain.await;
2061    }
2062
2063    /// NO FALSE POSITIVE: interior (per-subject) eviction also gaps the
2064    /// delivered revisions, but the floor stays at or below the frontier —
2065    /// benign for a last-write-wins fold, and the guard must let it
2066    /// through. (Every existing bootstrap e2e also rides this path on its
2067    /// resume; this pins the discrimination explicitly.)
2068    #[tokio::test(flavor = "multi_thread")]
2069    async fn benign_interior_gap_passes() {
2070        let server = start_server().await;
2071        let (js, kv) = seeded_bucket(&server.url).await;
2072
2073        // Overwrite k2 and k3: revisions 2 and 3 are interior-evicted
2074        // (history 1), revisions 6 and 7 replace them. first_sequence stays
2075        // 1 (k1's revision is retained).
2076        kv.put("k2", vec![22].into()).await.unwrap();
2077        kv.put("k3", vec![33].into()).await.unwrap();
2078        let mut stream = js.get_stream("KV_guard").await.unwrap();
2079        assert_eq!(stream.info().await.unwrap().state.first_sequence, 1);
2080
2081        // Resume from revision 1: deliveries jump 2 and 3 — gapped, benign.
2082        let watch = kv.watch_all_from_revision(2).await.unwrap();
2083        let (tx, mut rx) = tokio::sync::mpsc::channel(64);
2084        let guard =
2085            tokio::spawn(
2086                async move { stream_watch_floor_guarded(watch, &tx, 1, &js, "guard").await },
2087            );
2088
2089        let mut got = Vec::new();
2090        while got.len() < 4 {
2091            let update = tokio::time::timeout(Duration::from_secs(5), rx.recv())
2092                .await
2093                .expect("deliveries continue past benign gaps")
2094                .expect("watch alive");
2095            got.push(update.version().as_u64().unwrap());
2096        }
2097        assert_eq!(got, vec![4, 5, 6, 7], "interior gaps jumped, tail dense");
2098        guard.abort(); // endless live watch; the assertion above is the test
2099    }
2100}