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, 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    // `dead_code` because we never read it directly after construction.
316    #[allow(dead_code)]
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            cas: true,
646            transactions: false,
647            // 0 = unlimited from this layer's perspective: we impose no cap, but
648            // the NATS server still enforces its own max payload (~1MB by
649            // default). Callers that branch on this must not read 0 as "any size
650            // is safe" — an oversized value is rejected server-side at write time.
651            max_value_size: 0,
652            global_ordering: false,
653        }
654    }
655}
656
657struct NatsKvStore {
658    name: String,
659    kv: Store,
660    client: async_nats::Client,
661    js: async_nats::jetstream::Context,
662}
663
664impl KvStore for NatsKvStore {
665    fn name(&self) -> &str {
666        &self.name
667    }
668
669    fn reader(&self) -> Arc<dyn KvReader> {
670        Arc::new(NatsKvReader {
671            kv: self.kv.clone(),
672            client: self.client.clone(),
673            js: self.js.clone(),
674            bucket: self.name.clone(),
675        })
676    }
677
678    fn watcher(&self) -> Option<Arc<dyn KvWatcher>> {
679        Some(Arc::new(NatsKvWatcher {
680            kv: self.kv.clone(),
681            client: self.client.clone(),
682            js: self.js.clone(),
683            bucket: self.name.clone(),
684        }))
685    }
686
687    fn writer(&self) -> Option<Arc<dyn KvWriter>> {
688        Some(Arc::new(NatsKvWriterImpl {
689            kv: self.kv.clone(),
690        }))
691    }
692}
693
694struct NatsKvReader {
695    kv: Store,
696    client: async_nats::Client,
697    js: async_nats::jetstream::Context,
698    // The bucket name is known at construction (it's the store's name), so
699    // `consume_last_per_subject` builds its subject filters from this field
700    // instead of issuing a `kv.status()` round-trip per `scan()`/`keys()` call
701    // just to read it back from the server.
702    bucket: String,
703}
704
705#[async_trait]
706impl KvReader for NatsKvReader {
707    async fn get(&self, key: &str) -> Result<Option<KvEntry>, KvError> {
708        // Empty value → treat as absent. This unifies a real stored `b""` and a
709        // `delete_with_version` tombstone (empty-value Put) under one "absent =
710        // None" contract, consistent with `scan()`/`keys()`. Callers needing
711        // zero-length semantics use `entry()`. See the `KvReader::get` trait doc.
712        match self.entry(key).await? {
713            Some(entry) if entry.value.is_empty() => Ok(None),
714            other => Ok(other),
715        }
716    }
717
718    async fn entry(&self, key: &str) -> Result<Option<KvEntry>, KvError> {
719        use async_nats::jetstream::kv::Operation;
720        // Use entry() instead of get() to access revision.
721        // Return Put entries even with empty values — delete_with_version
722        // writes empty bytes as a tombstone and callers need the version
723        // for CAS conflict detection. Only filter real Delete/Purge markers.
724        match timed(self.kv.entry(key)).await? {
725            Ok(Some(entry)) if entry.operation == Operation::Put => Ok(Some(KvEntry {
726                key: key.to_string(),
727                value: entry.value.to_vec(),
728                version: VersionToken::from_u64(entry.revision),
729            })),
730            Ok(Some(_)) => Ok(None), // Delete/Purge marker
731            Ok(None) => Ok(None),
732            Err(e) => Err(KvError::OperationFailed(e.to_string())),
733        }
734    }
735
736    async fn keys(&self, prefix: &str) -> Result<Vec<String>, KvError> {
737        debug!(prefix = %prefix, "listing keys with prefix");
738
739        let mut keys = Vec::new();
740        self.consume_last_per_subject(prefix, true, |msg, key| {
741            // Skip both real KV deletes and CAS tombstones (empty-value Puts
742            // written by delete_with_version). get()/scan() hide the latter, so
743            // keys() must too — otherwise a list-then-get returns phantom keys.
744            // With headers_only the payload is stripped, but NATS adds a
745            // `Nats-Msg-Size` header we use to detect the empty value.
746            if !is_kv_delete(&msg) && !is_empty_value(&msg) {
747                keys.push(key);
748            }
749        })
750        .await?;
751
752        debug!(prefix = %prefix, keys = keys.len(), "keys listing complete");
753        Ok(keys)
754    }
755
756    async fn scan(&self, prefix: &str) -> Result<Vec<KvEntry>, KvError> {
757        let mut entries = Vec::new();
758        self.consume_last_per_subject(prefix, false, |msg, key| {
759            if !is_kv_delete(&msg) && !msg.payload.is_empty() {
760                // The KV revision is the stream sequence, carried in the JetStream
761                // ACK subject (the message's reply subject). A revision of 0 means
762                // we couldn't parse it; callers treat that as "unknown version".
763                let revision = msg
764                    .reply
765                    .as_deref()
766                    .and_then(stream_sequence_from_ack)
767                    .unwrap_or(0);
768
769                entries.push(KvEntry {
770                    key,
771                    value: msg.payload.to_vec(),
772                    version: VersionToken::from_u64(revision),
773                });
774            }
775        })
776        .await?;
777
778        debug!(prefix = %prefix, entries = entries.len(), "scan complete");
779        Ok(entries)
780    }
781}
782
783/// Extract the stream sequence (== KV revision) from a JetStream ACK subject.
784///
785/// The ACK subject — delivered as a push message's reply subject — comes in two
786/// shapes, and the stream sequence sits at different offsets in each:
787///
788/// ```text
789/// legacy (9 tokens):  $JS.ACK.<stream>.<consumer>.<delivered>.<stream_seq>.<consumer_seq>.<ts>.<pending>
790/// modern (11–12):     $JS.ACK.<domain>.<account>.<stream>.<consumer>.<delivered>.<stream_seq>.<consumer_seq>.<ts>.<pending>[.<token>]
791/// ```
792///
793/// The previous implementation took the *last* token, which is `num_pending`
794/// (typically 0 on the final delivery), not the sequence — corrupting the
795/// version on every scanned entry. We instead parse from the front, accounting
796/// for the optional `<domain>.<account>` prefix that modern servers prepend.
797fn stream_sequence_from_ack(reply: &str) -> Option<u64> {
798    // The stream-seq field sits at index 5 (legacy) or 7 (modern), so we only
799    // ever read the first 8 tokens. Keep those in a stack array and count the
800    // remainder with the iterator — no heap `Vec`, which on a large `scan()`
801    // would be one allocation per delivered message.
802    let mut head = [""; 8];
803    let mut count = 0usize;
804    for (i, token) in reply.split('.').enumerate() {
805        if i < head.len() {
806            head[i] = token;
807        }
808        count += 1;
809    }
810    if count < 9 || head[0] != "$JS" || head[1] != "ACK" {
811        return None;
812    }
813    // Legacy form has exactly 9 tokens with no domain/account; anything longer
814    // carries the two-token `<domain>.<account>` prefix, shifting fields right.
815    let stream_seq_idx = if count == 9 { 5 } else { 7 };
816    head[stream_seq_idx].parse::<u64>().ok()
817}
818
819/// Check if a NATS message represents a KV delete/purge operation.
820fn is_kv_delete(msg: &async_nats::Message) -> bool {
821    msg.headers
822        .as_ref()
823        .and_then(|h| h.get("KV-Operation"))
824        .is_some()
825}
826
827/// Check if a `headers_only` delivery carries an empty value (a CAS tombstone
828/// written by `delete_with_version`).
829///
830/// When a consumer is created with `headers_only`, NATS strips the body and adds
831/// a `Nats-Msg-Size` header with the original payload length. Size 0 means the
832/// stored value is empty, which `get()`/`scan()` treat as absent. Messages
833/// without the header (e.g. non-`headers_only` deliveries) are not classified as
834/// empty here — callers on that path inspect the payload directly instead.
835fn is_empty_value(msg: &async_nats::Message) -> bool {
836    msg.headers
837        .as_ref()
838        .and_then(|h| h.get("Nats-Msg-Size"))
839        .map(|v| v.as_str() == "0")
840        .unwrap_or(false)
841}
842
843impl NatsKvReader {
844    /// Subscribe to last-per-subject messages for a KV prefix, calling `on_msg`
845    /// for each delivered message. Handles the subscribe-first race workaround,
846    /// consumer lifecycle, and cleanup.
847    async fn consume_last_per_subject(
848        &self,
849        prefix: &str,
850        headers_only: bool,
851        mut on_msg: impl FnMut(async_nats::Message, String),
852    ) -> Result<(), KvError> {
853        use async_nats::jetstream::consumer::push;
854        use async_nats::jetstream::consumer::{AckPolicy, DeliverPolicy};
855
856        // The bucket name is known at construction, so the subject filters are
857        // built directly from `self.bucket` — no `kv.status()` round-trip just
858        // to read it back. Every *remaining* setup await below is still bounded
859        // by `timed()`: a half-dead NATS connection (CLOSE_WAIT) would otherwise
860        // park here before the per-message drain timer downstream ever starts,
861        // hanging scan()/keys() indefinitely — the same failure `timed()` guards
862        // on the write path.
863        let bucket = self.bucket.as_str();
864
865        let nats_filter = if prefix.is_empty() {
866            format!("$KV.{bucket}.>")
867        } else {
868            format!("$KV.{bucket}.{prefix}>")
869        };
870
871        // Work around async-nats <=0.46 subscribe-after-create race:
872        // subscribe to the inbox FIRST, then create the consumer.
873        let inbox = self.client.new_inbox();
874        let mut sub = timed(self.client.subscribe(inbox.clone()))
875            .await?
876            .map_err(|e| KvError::OperationFailed(format!("subscribe inbox: {e}")))?;
877
878        let stream = timed(self.js.get_stream(format!("KV_{bucket}")))
879            .await?
880            .map_err(|e| KvError::OperationFailed(format!("get KV stream: {e}")))?;
881
882        let consumer = timed(stream.create_consumer(push::Config {
883            deliver_subject: inbox,
884            deliver_policy: DeliverPolicy::LastPerSubject,
885            filter_subject: nats_filter,
886            headers_only,
887            // This is a one-shot point-in-time drain — we never ack. Under
888            // the default `AckPolicy::Explicit`, JetStream stops delivering
889            // once `max_ack_pending` (default 1000) messages sit unacked,
890            // which would silently truncate scan()/keys() to the first ~1000
891            // keys (or stall waiting for deliveries that never come) on any
892            // larger bucket. `None` removes the ack-pending gate entirely.
893            ack_policy: AckPolicy::None,
894            // Safety net for the best-effort `delete_consumer` below: if that
895            // cleanup times out on a half-dead connection, JetStream still reaps
896            // this consumer after `CONSUMER_INACTIVE_THRESHOLD` of inactivity, so
897            // repeated timed-out scans can't pile orphaned consumers up against
898            // the per-stream limit.
899            inactive_threshold: CONSUMER_INACTIVE_THRESHOLD,
900            ..Default::default()
901        }))
902        .await?
903        .map_err(|e| KvError::OperationFailed(format!("create consumer: {e}")))?;
904
905        let num_pending = consumer.cached_info().num_pending;
906
907        // Drain exactly `num_pending` messages, but bound each await: a half-dead
908        // connection (CLOSE_WAIT) would otherwise park this loop forever, the same
909        // failure `timed()` guards on the write path. On timeout we still fall
910        // through to consumer cleanup, then surface `Timeout`.
911        let mut timed_out = false;
912        if num_pending > 0 {
913            let mut delivered = 0u64;
914            let kv_prefix = format!("$KV.{bucket}.");
915
916            while delivered < num_pending {
917                match tokio::time::timeout(KV_OP_TIMEOUT, sub.next()).await {
918                    Ok(Some(msg)) => {
919                        let key = msg
920                            .subject
921                            .strip_prefix(&kv_prefix)
922                            .unwrap_or(msg.subject.as_str())
923                            .to_string();
924
925                        on_msg(msg, key);
926                        delivered += 1;
927                    }
928                    Ok(None) => break, // subscription closed early
929                    Err(_) => {
930                        timed_out = true;
931                        break;
932                    }
933                }
934            }
935        }
936
937        // Clean up ephemeral consumer (best-effort), even on timeout — a stalled
938        // scan shouldn't also leak a server-side consumer. A leaked consumer
939        // lingers on the server and counts against per-stream limits, so surface
940        // failures in observability without failing the operation. Bound the
941        // delete with `timed()`: on the same half-dead (CLOSE_WAIT) connection
942        // that tripped the drain timeout above, an unbounded delete would re-park
943        // here forever, defeating the timeout recovery we just performed.
944        match timed(stream.delete_consumer(&consumer.cached_info().name)).await {
945            Ok(Ok(_)) => {}
946            Ok(Err(e)) => {
947                // `warn!`, not `debug!`: a leaked ephemeral consumer lingers on
948                // the server and counts against per-stream limits. Under a flaky
949                // NATS connection every scan()/keys() leaks one, so this must be
950                // visible in default spans before the pile-up hits the limit.
951                warn!(error = %e, "failed to delete ephemeral consumer (best-effort)");
952            }
953            Err(_) => {
954                warn!("timed out deleting ephemeral consumer (best-effort)");
955            }
956        }
957
958        if timed_out {
959            return Err(KvError::Timeout);
960        }
961        Ok(())
962    }
963}
964
965/// Convert a NATS KV entry to a KvUpdate.
966///
967/// Takes the entry by value so the key `String` moves into the `KvUpdate`
968/// instead of allocating a fresh copy per watch event.
969fn nats_entry_to_kv_update(entry: async_nats::jetstream::kv::Entry) -> KvUpdate {
970    use async_nats::jetstream::kv::Operation;
971    let version = VersionToken::from_u64(entry.revision);
972    match entry.operation {
973        Operation::Put => KvUpdate::Put(KvEntry {
974            key: entry.key,
975            value: entry.value.to_vec(),
976            version,
977        }),
978        Operation::Delete => KvUpdate::Delete {
979            key: entry.key,
980            version,
981        },
982        Operation::Purge => KvUpdate::Purge {
983            key: entry.key,
984            version,
985        },
986    }
987}
988
989/// Stream updates from a NATS Watch into a channel until it ends or the receiver drops.
990async fn stream_watch(
991    mut watcher: async_nats::jetstream::kv::Watch,
992    tx: &Sender<KvUpdate>,
993) -> Result<(), KvError> {
994    while let Some(entry) = watcher.next().await {
995        match entry {
996            Ok(entry) => {
997                let update = nats_entry_to_kv_update(entry);
998                if tx.send(update).await.is_err() {
999                    debug!("watch receiver closed");
1000                    break;
1001                }
1002            }
1003            Err(e) => {
1004                error!(error = %e, "NATS KV watch error");
1005                return Err(KvError::WatchError(e.to_string()));
1006            }
1007        }
1008    }
1009    Ok(())
1010}
1011
1012/// Cadence of the floor guard's no-traffic backstop probe (one stream-info
1013/// RPC per interval per guarded watch). The PRIMARY detection is in-band —
1014/// the gapped-delivery check fires the moment evidence surfaces — so this
1015/// interval only bounds detection latency when NOTHING is being delivered;
1016/// it is not load-bearing for eventual detection.
1017const FLOOR_GUARD_INTERVAL: Duration = Duration::from_secs(30);
1018
1019/// [`stream_watch`] for the dense ALL-scope resume path, with the LIVE
1020/// retention floor guard (`tests/model_live_watch.rs` — the live twin of
1021/// [`NatsKvWatcher::check_resume_window`]).
1022///
1023/// The hazard: retention overrunning a live consumer makes JetStream
1024/// silently skip evicted messages — delete markers included — with no error
1025/// anywhere (the same clamp behavior as resumes, mid-stream). Unguarded,
1026/// that is PERMANENT silent fold divergence; the model proves it reachable.
1027///
1028/// Detection is primarily **in-band**: an unfiltered `ByStartSequence`
1029/// consumer sees every retained message, so a delivered revision that jumps
1030/// the frontier by more than one is evidence of eviction inside the gap.
1031/// The model checker REJECTED a periodic-only design with exactly the trace
1032/// this closes — deliveries can catch the frontier up past the gap between
1033/// probes, erasing the evidence — so the check runs AT the gapped delivery,
1034/// before the entry is processed: fetch `first_sequence` and apply the
1035/// shared kernel (`protocol::resume_window_ok`) to the frontier. A benign
1036/// gap (interior per-subject eviction with the floor still at or below the
1037/// frontier) passes; head eviction past the frontier fails the watch, and
1038/// the caller's restart routes into the verified resume → `CursorExpired` →
1039/// resync repair path. The periodic probe backstops the no-traffic case.
1040///
1041/// Scope: sound only where density holds — the unfiltered resume watch.
1042/// Prefix-scoped watches deliver sparse revisions by design and cannot
1043/// distinguish benign from hazardous eviction client-side; they retain the
1044/// (narrowed) retention-outlives-lag operating axiom plus the resume-time
1045/// check on every restart (model axiom 5).
1046///
1047/// The guarantee split, precisely: the SAFETY half — never folding past
1048/// unexamined evidence of loss — is unconditional in this loop (the gap
1049/// check precedes processing, and a stalled downstream stalls folding too).
1050/// The REPAIR half is conditional on the caller restarting the failed watch
1051/// (standard supervision; same posture as the resync fail-stop): a trip
1052/// with no restart is a loudly dead watch, never a silently wrong one.
1053async fn stream_watch_floor_guarded(
1054    mut watcher: async_nats::jetstream::kv::Watch,
1055    tx: &Sender<KvUpdate>,
1056    resume_revision: u64,
1057    js: &async_nats::jetstream::Context,
1058    bucket: &str,
1059) -> Result<(), KvError> {
1060    let stream_name = format!("KV_{bucket}");
1061    let first_sequence = || async {
1062        let stream = timed(js.get_stream(&stream_name))
1063            .await?
1064            .map_err(|e| KvError::OperationFailed(format!("floor guard stream lookup: {e}")))?;
1065        Ok::<u64, KvError>(stream.cached_info().state.first_sequence)
1066    };
1067    fn trip(frontier: u64, first: u64, bucket: &str) -> KvError {
1068        warn!(
1069            frontier,
1070            first_sequence = first,
1071            bucket,
1072            "stream retention overran this live watch; failing so the restart can resync \
1073             (messages in the gap were evicted unseen)"
1074        );
1075        KvError::WatchError(format!(
1076            "stream retention overran live watch (first_sequence {first} > delivered \
1077             frontier {frontier} + 1); restart will resync"
1078        ))
1079    }
1080
1081    let mut frontier = resume_revision;
1082    let mut backstop = tokio::time::interval(FLOOR_GUARD_INTERVAL);
1083    backstop.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
1084    backstop.tick().await; // consume the immediate first tick
1085
1086    loop {
1087        tokio::select! {
1088            entry = watcher.next() => {
1089                let Some(entry) = entry else { break };
1090                match entry {
1091                    Ok(entry) => {
1092                        let revision = entry.revision;
1093                        // In-band gap check BEFORE processing: never fold
1094                        // past unexamined evidence of eviction.
1095                        if revision > frontier.saturating_add(1) {
1096                            let first = first_sequence().await?;
1097                            if !crate::protocol::resume_window_ok(frontier, first) {
1098                                return Err(trip(frontier, first, bucket));
1099                            }
1100                            // Benign interior gap: every evicted revision
1101                            // below a still-low floor was a per-subject
1102                            // overwrite, whose later revision the fold will
1103                            // see — safe for last-write-wins.
1104                        }
1105                        frontier = frontier.max(revision);
1106                        let update = nats_entry_to_kv_update(entry);
1107                        if tx.send(update).await.is_err() {
1108                            debug!("watch receiver closed");
1109                            break;
1110                        }
1111                    }
1112                    Err(e) => {
1113                        error!(error = %e, "NATS KV watch error");
1114                        return Err(KvError::WatchError(e.to_string()));
1115                    }
1116                }
1117            }
1118            _ = backstop.tick() => {
1119                // No-traffic backstop: nothing is being delivered, so the
1120                // in-band check has no evidence to act on; probe the floor
1121                // directly.
1122                let first = first_sequence().await?;
1123                if !crate::protocol::resume_window_ok(frontier, first) {
1124                    return Err(trip(frontier, first, bucket));
1125                }
1126            }
1127        }
1128    }
1129    Ok(())
1130}
1131
1132/// Check if a NATS watch error indicates the requested start sequence is
1133/// too old (compacted), meaning callers should fall back to a full watch.
1134///
1135/// SECOND line of defense only: live nats-server (2.14) does not error on a
1136/// below-head start sequence at all — it silently clamps to the first
1137/// retained message (pinned by `tests/resync.rs`), so the PRIMARY expiry
1138/// detection is [`NatsKvWatcher::check_resume_window`]'s proactive
1139/// `first_sequence` comparison. This matcher remains for server versions or
1140/// paths that do error, where mapping to [`KvError::CursorExpired`] keeps
1141/// the fallback reachable instead of stranding the caller.
1142///
1143/// async-nats has no granular error kind for this: `WatchErrorKind` is only
1144/// `InvalidKey`/`TimedOut`/`ConsumerCreate`/`Other`, and "start sequence too old"
1145/// arrives as `ConsumerCreate`/`Other` with the real reason buried in the source
1146/// error's *message*. So we substring-match the full error string — which already
1147/// includes the source, since `Error`'s `Display` renders `"{kind}: {source}"`.
1148///
1149/// Two deliberate choices make this robust to wording drift:
1150/// - We lowercase first, so a capitalization change in NATS/async-nats can't slip
1151///   past.
1152/// - Detection is biased toward `true`. A false positive only costs an
1153///   unnecessary (but always-safe) full `watch_all()` replay; a false negative
1154///   propagates `WatchError` and strands a caller that would otherwise recover.
1155///
1156/// If these messages ever change, `cursor_expired_matches_known_nats_error_strings`
1157/// is the canary that fails loudly on the next dependency bump.
1158fn is_cursor_expired_error(err: &str) -> bool {
1159    use std::sync::OnceLock;
1160    // One Aho-Corasick automaton over all needles: a single pass over the error
1161    // string regardless of how many needles accumulate as NATS versions reword
1162    // their messages, vs. one `windows()` scan per needle. Case-insensitivity is
1163    // baked into the automaton, so no lowercased copy is allocated either.
1164    static MATCHER: OnceLock<aho_corasick::AhoCorasick> = OnceLock::new();
1165    MATCHER
1166        .get_or_init(|| {
1167            aho_corasick::AhoCorasick::builder()
1168                .ascii_case_insensitive(true)
1169                .build([
1170                    "start sequence",
1171                    "first sequence",
1172                    "sequence not found",
1173                    "too old",
1174                ])
1175                .expect("static needle set always compiles")
1176        })
1177        .is_match(err)
1178}
1179
1180struct NatsKvWatcher {
1181    kv: Store,
1182    // `watch_prefixes_from` has no async-nats equivalent (there is no
1183    // `watch_many_from_revision`), so it hand-builds the multi-filter ordered
1184    // consumer itself — which needs the raw client (inbox allocation), the
1185    // JetStream context (stream lookup), and the bucket name (subject filters),
1186    // same as the reader's scan path.
1187    client: async_nats::Client,
1188    js: async_nats::jetstream::Context,
1189    bucket: String,
1190}
1191
1192/// Decode a raw KV stream message (as delivered by a hand-built ordered push
1193/// consumer) into a [`KvUpdate`] — the same mapping `async-nats`'s `kv::Watch`
1194/// performs internally for the `watch_*` paths: key from the subject (stripping
1195/// the `$KV.{bucket}.` prefix), operation from the `KV-Operation` header
1196/// (absent = Put), revision from the stream sequence in the ACK reply subject.
1197///
1198/// Returns `None` for a subject outside the bucket's keyspace, which a
1199/// subject-filtered consumer should never deliver — skipped rather than
1200/// surfaced, matching `kv::Watch`'s behavior.
1201fn kv_message_to_update(msg: &async_nats::Message, kv_prefix: &str) -> Option<KvUpdate> {
1202    let key = msg.subject.strip_prefix(kv_prefix)?.to_string();
1203    // An unparseable (or absent) ACK subject yields the UNKNOWN version, not a
1204    // fabricated revision 0: `from_u64(0)` is a *parseable* position that
1205    // `watch_applied` would adopt as its batch high-water — regressing the
1206    // persisted cursor to 0 and forcing a full replay on the next restart.
1207    // `unknown()` is the honest value; the cursor-authority loop skips it.
1208    let version = msg
1209        .reply
1210        .as_deref()
1211        .and_then(stream_sequence_from_ack)
1212        .map(VersionToken::from_u64)
1213        .unwrap_or_else(VersionToken::unknown);
1214    let operation = msg
1215        .headers
1216        .as_ref()
1217        .and_then(|h| h.get("KV-Operation"))
1218        .map(|v| v.as_str());
1219    Some(match operation {
1220        Some("DEL") => KvUpdate::Delete { key, version },
1221        Some("PURGE") => KvUpdate::Purge { key, version },
1222        // No header (or an explicit "PUT") is a put — the common case carries
1223        // no KV-Operation header at all.
1224        _ => KvUpdate::Put(KvEntry {
1225            key,
1226            value: msg.payload.to_vec(),
1227            version,
1228        }),
1229    })
1230}
1231
1232impl NatsKvWatcher {
1233    /// Proactive cursor-expiry detection, REQUIRED before any `*_from` resume.
1234    ///
1235    /// NATS does **not** error when an ordered consumer's `ByStartSequence`
1236    /// falls below the stream's first retained sequence — it silently delivers
1237    /// from the first available message (pinned against a live nats-server by
1238    /// `tests/resync.rs::nats_silently_clamps_resume_below_first_seq`). A
1239    /// silent clamp skips the gap's evicted messages — delete markers
1240    /// included — without ever taking the `CursorExpired` → resync path, so
1241    /// expiry MUST be detected by comparing the stream's `first_sequence`
1242    /// against the resume point before trusting the consumer. The
1243    /// error-string matching at the consumer-create sites stays as a second
1244    /// line of defense for server versions that do error.
1245    ///
1246    /// Why `first_sequence` is the right boundary: interior (per-subject
1247    /// history) eviction inside the gap is safe for a last-write-wins fold —
1248    /// an overwrite-evicted revision implies a LATER revision of the same
1249    /// subject exists and will be delivered. Lost *deletes* come from head
1250    /// eviction (stream limits/age), which is exactly what advances
1251    /// `first_sequence`. (An admin interior purge of a subject can also
1252    /// destroy a delete marker without moving the head — that is a manual
1253    /// destructive operation, same trust class as deleting the stream.)
1254    ///
1255    /// Head eviction racing the window between this check and consumer
1256    /// creation is the same exposure any live consumer has against
1257    /// aggressive retention; the check bounds the silent gap to that
1258    /// milliseconds-scale window, where the prior behavior left it unbounded.
1259    async fn check_resume_window(&self, revision: u64) -> Result<(), KvError> {
1260        let stream = timed(self.js.get_stream(format!("KV_{}", self.bucket)))
1261            .await?
1262            .map_err(|e| {
1263                KvError::OperationFailed(format!("get KV stream for resume check: {e}"))
1264            })?;
1265        let first = stream.cached_info().state.first_sequence;
1266        // The shared protocol kernel — the same guard the model checker's
1267        // Resume transition executes (`crate::protocol::resume_window_ok`).
1268        if !crate::protocol::resume_window_ok(revision, first) {
1269            warn!(
1270                revision,
1271                first_sequence = first,
1272                "resume cursor is below the stream's first retained sequence; cursor expired"
1273            );
1274            return Err(KvError::CursorExpired);
1275        }
1276        Ok(())
1277    }
1278}
1279
1280#[async_trait]
1281impl KvWatcher for NatsKvWatcher {
1282    async fn watch_all(&self, tx: Sender<KvUpdate>) -> Result<(), KvError> {
1283        // `watch_with_history` (DeliverPolicy::LastPerSubject), NOT `watch_all`
1284        // (DeliverPolicy::New): the trait contract is state-sync — current value
1285        // of every key first, then live updates. async-nats's `watch_all` only
1286        // delivers messages published AFTER the consumer exists, which would
1287        // leave a no-cursor consumer empty until keys happen to change.
1288        //
1289        // Bound the watch *setup* with `timed()` for the same reason every KV op
1290        // is bounded: a half-dead (CLOSE_WAIT) NATS connection parks this await
1291        // forever instead of failing. The streaming drain in `stream_watch` is
1292        // intentionally unbounded (a watch is long-lived), but establishing it
1293        // must not be able to hang a reconnecting caller.
1294        let watcher = timed(self.kv.watch_with_history(">"))
1295            .await?
1296            .map_err(|e| KvError::WatchError(e.to_string()))?;
1297        stream_watch(watcher, &tx).await
1298    }
1299
1300    async fn watch_prefix(&self, prefix: &str, tx: Sender<KvUpdate>) -> Result<(), KvError> {
1301        // Use native NATS subject-based filtering. KV key "node.abc" maps to
1302        // subject "$KV.BUCKET.node.abc", and ">" is the multi-level wildcard.
1303        // `_with_history` for the same state-sync contract as `watch_all`.
1304        let nats_key = format!("{prefix}>");
1305        let watcher = timed(self.kv.watch_with_history(&nats_key))
1306            .await?
1307            .map_err(|e| KvError::WatchError(e.to_string()))?;
1308        stream_watch(watcher, &tx).await
1309    }
1310
1311    async fn watch_prefixes(&self, prefixes: &[&str], tx: Sender<KvUpdate>) -> Result<(), KvError> {
1312        if prefixes.is_empty() {
1313            // Nothing to watch. Critically, do NOT fall through to `watch_many`
1314            // with an empty filter set — an unfiltered ordered consumer would
1315            // watch the WHOLE bucket, the opposite of a scoped watch.
1316            return Ok(());
1317        }
1318        // ONE multi-filter consumer for every prefix (NATS 2.10 `filter_subjects`)
1319        // rather than one consumer per prefix. `watch_many_with_history` builds a
1320        // single ordered push consumer with `filter_subjects = [{p}> ...]` and
1321        // yields the same `Entry` stream as `watch`, so `stream_watch` is reused
1322        // verbatim. This is the per-stream-consumer-count fix: a node scoped to N
1323        // prefixes costs 1 consumer, not N. `_with_history` for the same
1324        // state-sync contract as `watch_all`.
1325        let keys: Vec<String> = prefixes.iter().map(|p| format!("{p}>")).collect();
1326        let watcher = timed(self.kv.watch_many_with_history(keys))
1327            .await?
1328            .map_err(|e| KvError::WatchError(e.to_string()))?;
1329        stream_watch(watcher, &tx).await
1330    }
1331
1332    async fn watch_all_from(
1333        &self,
1334        cursor: &WatchCursor,
1335        tx: Sender<KvUpdate>,
1336    ) -> Result<(), KvError> {
1337        let revision = match cursor.as_u64() {
1338            Some(rev) if rev > 0 => rev,
1339            _ => return self.watch_all(tx).await,
1340        };
1341        self.check_resume_window(revision).await?;
1342
1343        let watcher = match timed(self.kv.watch_all_from_revision(revision + 1)).await? {
1344            Ok(w) => w,
1345            Err(e) => {
1346                let err_str = e.to_string();
1347                if is_cursor_expired_error(&err_str) {
1348                    warn!(revision, error = %err_str, "cursor expired, caller should fall back to full watch");
1349                    return Err(KvError::CursorExpired);
1350                }
1351                return Err(KvError::WatchError(err_str));
1352            }
1353        };
1354        // Re-check AFTER the consumer exists: head eviction in the window
1355        // between the pre-flight check and consumer creation would otherwise
1356        // clamp silently.
1357        self.check_resume_window(revision).await?;
1358
1359        info!(revision, "resumed watch from cursor");
1360        // The LIVE floor guard takes over from here: in-band gapped-delivery
1361        // checks plus a no-traffic backstop, so retention overrunning this
1362        // watch mid-stream fail-stops into the restart→resync repair path
1363        // instead of silently skipping evicted deletes (model:
1364        // tests/model_live_watch.rs).
1365        stream_watch_floor_guarded(watcher, &tx, revision, &self.js, &self.bucket).await
1366    }
1367
1368    async fn watch_prefix_from(
1369        &self,
1370        prefix: &str,
1371        cursor: &WatchCursor,
1372        tx: Sender<KvUpdate>,
1373    ) -> Result<(), KvError> {
1374        let revision = match cursor.as_u64() {
1375            Some(rev) if rev > 0 => rev,
1376            _ => return self.watch_prefix(prefix, tx).await,
1377        };
1378        self.check_resume_window(revision).await?;
1379
1380        let nats_key = format!("{prefix}>");
1381        let watcher = match timed(self.kv.watch_from_revision(&nats_key, revision + 1)).await? {
1382            Ok(w) => w,
1383            Err(e) => {
1384                let err_str = e.to_string();
1385                if is_cursor_expired_error(&err_str) {
1386                    warn!(revision, prefix, error = %err_str, "cursor expired for prefix watch, caller should fall back");
1387                    return Err(KvError::CursorExpired);
1388                }
1389                return Err(KvError::WatchError(err_str));
1390            }
1391        };
1392        // Same post-create re-check as watch_all_from: close the
1393        // check→create eviction window.
1394        self.check_resume_window(revision).await?;
1395
1396        info!(revision, prefix, "resumed prefix watch from cursor");
1397        stream_watch(watcher, &tx).await
1398    }
1399
1400    async fn watch_prefixes_from(
1401        &self,
1402        prefixes: &[&str],
1403        cursor: &WatchCursor,
1404        tx: Sender<KvUpdate>,
1405    ) -> Result<(), KvError> {
1406        use async_nats::jetstream::consumer::{DeliverPolicy, ReplayPolicy, push};
1407
1408        if prefixes.is_empty() {
1409            // Same guard as watch_prefixes: an empty filter set must not become
1410            // an unfiltered whole-bucket consumer.
1411            return Ok(());
1412        }
1413        let revision = match cursor.as_u64() {
1414            Some(rev) if rev > 0 => rev,
1415            _ => return self.watch_prefixes(prefixes, tx).await,
1416        };
1417
1418        // async-nats has `watch_many` (multi-filter) and `watch_from_revision`
1419        // (seek) but no combination of the two, so build the multi-filter
1420        // ordered push consumer ourselves — the exact consumer
1421        // `watch_many_with_deliver_policy` would build, with
1422        // `ByStartSequence(cursor+1)` for the delta seek. The ordered-consumer
1423        // machinery (gap detection, auto-recreate from the last delivered
1424        // sequence) comes with `OrderedConfig` for free.
1425        let bucket = self.bucket.as_str();
1426        let kv_prefix = format!("$KV.{bucket}.");
1427        let filter_subjects: Vec<String> = prefixes
1428            .iter()
1429            .map(|p| format!("{kv_prefix}{p}>"))
1430            .collect();
1431
1432        let stream = timed(self.js.get_stream(format!("KV_{bucket}")))
1433            .await?
1434            .map_err(|e| KvError::WatchError(format!("get KV stream: {e}")))?;
1435
1436        // Same proactive expiry detection as `check_resume_window` (NATS
1437        // silently clamps a below-head ByStartSequence; see that method's
1438        // docs) — checked on the stream handle this path already fetched,
1439        // via the shared protocol kernel.
1440        let first = stream.cached_info().state.first_sequence;
1441        if !crate::protocol::resume_window_ok(revision, first) {
1442            warn!(
1443                revision,
1444                first_sequence = first,
1445                ?prefixes,
1446                "resume cursor is below the stream's first retained sequence; cursor expired"
1447            );
1448            return Err(KvError::CursorExpired);
1449        }
1450
1451        let consumer = match timed(stream.create_consumer(push::OrderedConfig {
1452            deliver_subject: self.client.new_inbox(),
1453            description: Some("kv multi-prefix resume consumer".to_string()),
1454            filter_subjects,
1455            replay_policy: ReplayPolicy::Instant,
1456            deliver_policy: DeliverPolicy::ByStartSequence {
1457                start_sequence: revision + 1,
1458            },
1459            ..Default::default()
1460        }))
1461        .await?
1462        {
1463            Ok(c) => c,
1464            Err(e) => {
1465                // Same expiry classification as watch_all_from: a start sequence
1466                // the stream has compacted past surfaces as a consumer-create
1467                // error whose message names the sequence problem.
1468                let err_str = e.to_string();
1469                if is_cursor_expired_error(&err_str) {
1470                    warn!(revision, ?prefixes, error = %err_str, "cursor expired for multi-prefix watch, caller should fall back");
1471                    return Err(KvError::CursorExpired);
1472                }
1473                return Err(KvError::WatchError(err_str));
1474            }
1475        };
1476
1477        // Re-check AFTER the consumer exists (fresh stream info, not the
1478        // handle's cached copy): closes the check→create eviction window,
1479        // same as the single-filter resume paths.
1480        self.check_resume_window(revision).await?;
1481
1482        let mut messages = timed(consumer.messages())
1483            .await?
1484            .map_err(|e| KvError::WatchError(e.to_string()))?;
1485
1486        info!(
1487            revision,
1488            ?prefixes,
1489            "resumed multi-prefix watch from cursor"
1490        );
1491        while let Some(msg) = messages.next().await {
1492            match msg {
1493                Ok(msg) => {
1494                    // A subject-filtered consumer only delivers in-keyspace
1495                    // subjects; `None` here would be a server bug, skipped to
1496                    // match kv::Watch's tolerance.
1497                    let Some(update) = kv_message_to_update(&msg, &kv_prefix) else {
1498                        continue;
1499                    };
1500                    if tx.send(update).await.is_err() {
1501                        debug!("watch receiver closed");
1502                        break;
1503                    }
1504                }
1505                Err(e) => {
1506                    error!(error = %e, "NATS KV multi-prefix watch error");
1507                    return Err(KvError::WatchError(e.to_string()));
1508                }
1509            }
1510        }
1511        Ok(())
1512    }
1513}
1514
1515struct NatsKvWriterImpl {
1516    kv: Store,
1517}
1518
1519#[async_trait]
1520impl KvWriter for NatsKvWriterImpl {
1521    async fn put(&self, key: &str, value: &[u8]) -> Result<VersionToken, KvError> {
1522        let rev = timed(self.kv.put(key, value.to_vec().into()))
1523            .await?
1524            .map_err(|e| KvError::OperationFailed(e.to_string()))?;
1525        Ok(VersionToken::from_u64(rev))
1526    }
1527
1528    async fn delete(&self, key: &str) -> Result<bool, KvError> {
1529        // NATS delete doesn't tell us if key existed, so we always return true
1530        timed(self.kv.delete(key))
1531            .await?
1532            .map_err(|e| KvError::OperationFailed(e.to_string()))?;
1533        Ok(true)
1534    }
1535
1536    async fn create(&self, key: &str, value: &[u8]) -> Result<VersionToken, KvError> {
1537        use async_nats::jetstream::kv::CreateErrorKind;
1538        timed(self.kv.create(key, value.to_vec().into()))
1539            .await?
1540            .map(VersionToken::from_u64)
1541            .map_err(|e| {
1542                if e.kind() == CreateErrorKind::AlreadyExists {
1543                    KvError::AlreadyExists
1544                } else {
1545                    KvError::OperationFailed(e.to_string())
1546                }
1547            })
1548    }
1549
1550    async fn update(
1551        &self,
1552        key: &str,
1553        value: &[u8],
1554        expected: &VersionToken,
1555    ) -> Result<VersionToken, KvError> {
1556        use async_nats::jetstream::kv::UpdateErrorKind;
1557        let rev = expected.as_u64().ok_or_else(|| {
1558            KvError::OperationFailed("invalid version token for NATS update".into())
1559        })?;
1560        timed(self.kv.update(key, value.to_vec().into(), rev))
1561            .await?
1562            .map(VersionToken::from_u64)
1563            .map_err(|e| {
1564                if e.kind() == UpdateErrorKind::WrongLastRevision {
1565                    KvError::RevisionMismatch
1566                } else {
1567                    KvError::OperationFailed(e.to_string())
1568                }
1569            })
1570    }
1571
1572    async fn delete_with_version(
1573        &self,
1574        key: &str,
1575        expected: &VersionToken,
1576    ) -> Result<bool, KvError> {
1577        use async_nats::jetstream::kv::UpdateErrorKind;
1578        let rev = expected.as_u64().ok_or_else(|| {
1579            KvError::OperationFailed("invalid version token for NATS delete".into())
1580        })?;
1581        // Write empty value with CAS — logically deletes while preserving conflict detection
1582        timed(self.kv.update(key, Vec::new().into(), rev))
1583            .await?
1584            .map(|_| true)
1585            .map_err(|e| {
1586                if e.kind() == UpdateErrorKind::WrongLastRevision {
1587                    KvError::RevisionMismatch
1588                } else {
1589                    KvError::OperationFailed(e.to_string())
1590                }
1591            })
1592    }
1593}
1594
1595impl std::fmt::Debug for NatsConnection {
1596    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1597        f.debug_struct("NatsConnection")
1598            .field("url", &self.config.url)
1599            // `Acquire` to match every other read of `healthy` — a `Relaxed`
1600            // outlier here reads like a deliberate exception during an atomics
1601            // audit, and the fmt path is far too cold for the ordering to cost
1602            // anything.
1603            .field("healthy", &self.healthy.load(Ordering::Acquire))
1604            .finish()
1605    }
1606}
1607
1608#[cfg(test)]
1609mod tests {
1610    use super::*;
1611
1612    #[test]
1613    fn raw_create_success_has_no_error() {
1614        // A successful STREAM.CREATE echoes back the stream config, no "error".
1615        let payload = br#"{"type":"io.nats.jetstream.api.v1.stream_create_response","config":{"name":"KV_certs"}}"#;
1616        assert_eq!(
1617            classify_raw_create_response(payload),
1618            RawCreateOutcome::Created
1619        );
1620    }
1621
1622    #[test]
1623    fn raw_create_swallows_stream_already_exists() {
1624        // 10058 = stream name already in use → the bucket already exists, OK.
1625        let payload =
1626            br#"{"error":{"code":400,"err_code":10058,"description":"stream name already in use"}}"#;
1627        assert_eq!(
1628            classify_raw_create_response(payload),
1629            RawCreateOutcome::AlreadyExists
1630        );
1631    }
1632
1633    #[test]
1634    fn raw_create_swallows_stream_limit() {
1635        // Synadia Cloud returns 400 + "maximum number of streams" at the limit,
1636        // but the bucket may already exist — treat as non-fatal.
1637        let payload =
1638            br#"{"error":{"code":400,"description":"maximum number of streams reached"}}"#;
1639        assert_eq!(
1640            classify_raw_create_response(payload),
1641            RawCreateOutcome::StreamLimit
1642        );
1643    }
1644
1645    #[test]
1646    fn raw_create_propagates_unknown_error() {
1647        // Any other JetStream error is fatal and must surface code + description.
1648        let payload = br#"{"error":{"code":403,"description":"insufficient permissions"}}"#;
1649        match classify_raw_create_response(payload) {
1650            RawCreateOutcome::Failed { code, description } => {
1651                assert_eq!(code, 403);
1652                assert_eq!(description, "insufficient permissions");
1653            }
1654            other => panic!("expected Failed, got {other:?}"),
1655        }
1656    }
1657
1658    #[test]
1659    fn raw_create_400_without_stream_limit_is_fatal() {
1660        // A bare 400 that isn't the stream-limit message must NOT be swallowed,
1661        // otherwise a genuine bad-config rejection would masquerade as success.
1662        let payload = br#"{"error":{"code":400,"description":"invalid stream config"}}"#;
1663        match classify_raw_create_response(payload) {
1664            RawCreateOutcome::Failed { code, description } => {
1665                assert_eq!(code, 400);
1666                assert!(description.contains("invalid stream config"));
1667            }
1668            other => panic!("expected Failed, got {other:?}"),
1669        }
1670    }
1671
1672    #[test]
1673    fn raw_create_unparseable_payload_is_treated_as_success() {
1674        // The caller re-verifies with get_key_value, so a garbled body must not
1675        // be reported as a hard failure here.
1676        assert_eq!(
1677            classify_raw_create_response(b"not json at all"),
1678            RawCreateOutcome::Created
1679        );
1680    }
1681
1682    #[test]
1683    fn ack_subject_legacy_format() {
1684        // $JS.ACK.<stream>.<consumer>.<delivered>.<stream_seq>.<consumer_seq>.<ts>.<pending>
1685        let reply = "$JS.ACK.KV_certs.cons.1.42.7.1700000000000000000.0";
1686        assert_eq!(stream_sequence_from_ack(reply), Some(42));
1687    }
1688
1689    #[test]
1690    fn ack_subject_modern_format_with_domain_and_account() {
1691        // $JS.ACK.<domain>.<account>.<stream>.<consumer>.<delivered>.<stream_seq>.<consumer_seq>.<ts>.<pending>
1692        let reply = "$JS.ACK.hub.AABBCC.KV_certs.cons.1.42.7.1700000000000000000.0";
1693        assert_eq!(stream_sequence_from_ack(reply), Some(42));
1694    }
1695
1696    #[test]
1697    fn ack_subject_modern_format_with_trailing_token() {
1698        // Some servers append a random trailing token (12 tokens total).
1699        let reply = "$JS.ACK.hub.AABBCC.KV_certs.cons.1.99.7.1700000000000000000.0.rng";
1700        assert_eq!(stream_sequence_from_ack(reply), Some(99));
1701    }
1702
1703    #[test]
1704    fn ack_subject_last_token_is_not_the_sequence() {
1705        // Regression guard: the final token is num_pending, never the sequence.
1706        // The old code returned this (0), corrupting every scanned entry's version.
1707        let reply = "$JS.ACK.KV_certs.cons.1.42.7.1700000000000000000.0";
1708        assert_ne!(stream_sequence_from_ack(reply), Some(0));
1709    }
1710
1711    #[test]
1712    fn ack_subject_rejects_garbage() {
1713        assert_eq!(stream_sequence_from_ack(""), None);
1714        assert_eq!(stream_sequence_from_ack("not.an.ack.subject"), None);
1715        assert_eq!(stream_sequence_from_ack("$JS.ACK.too.few.tokens"), None);
1716        // Right shape, non-numeric sequence field.
1717        assert_eq!(stream_sequence_from_ack("$JS.ACK.s.c.1.notnum.7.0.0"), None);
1718    }
1719
1720    #[test]
1721    fn cursor_expired_matches_known_nats_error_strings() {
1722        // These substrings come from async-nats error messages. If the library
1723        // rewrites them, watch_all_from would return WatchError instead of
1724        // CursorExpired, breaking callers that fall back to watch_all() on expiry.
1725        assert!(is_cursor_expired_error(
1726            "consumer start sequence is too old"
1727        ));
1728        assert!(is_cursor_expired_error("first sequence is 42, requested 1"));
1729        assert!(is_cursor_expired_error("sequence not found in stream"));
1730        // "too old" on its own (no "sequence" wording) must still be caught.
1731        assert!(is_cursor_expired_error("requested revision is too old"));
1732        // Case-insensitive: a capitalization change upstream must not slip past.
1733        assert!(is_cursor_expired_error("Consumer Start Sequence Too Old"));
1734        assert!(!is_cursor_expired_error("connection refused"));
1735        assert!(!is_cursor_expired_error("permission denied"));
1736        assert!(!is_cursor_expired_error("stream not found"));
1737    }
1738
1739    fn raw_kv_msg(
1740        subject: &str,
1741        reply: Option<&str>,
1742        payload: &[u8],
1743        op: Option<&str>,
1744    ) -> async_nats::Message {
1745        let headers = op.map(|op| {
1746            let mut h = async_nats::HeaderMap::new();
1747            h.insert("KV-Operation", op);
1748            h
1749        });
1750        async_nats::Message {
1751            subject: subject.to_string().into(),
1752            reply: reply.map(|r| r.to_string().into()),
1753            payload: payload.to_vec().into(),
1754            headers,
1755            status: None,
1756            description: None,
1757            length: 0,
1758        }
1759    }
1760
1761    const ACK_42: &str = "$JS.ACK.KV_certs.cons.1.42.7.1700000000000000000.0";
1762
1763    #[test]
1764    fn kv_message_decodes_put_without_operation_header() {
1765        // The common case: a put carries no KV-Operation header at all.
1766        let msg = raw_kv_msg("$KV.certs.node.a", Some(ACK_42), b"v1", None);
1767        match kv_message_to_update(&msg, "$KV.certs.").expect("in keyspace") {
1768            KvUpdate::Put(e) => {
1769                assert_eq!(e.key, "node.a");
1770                assert_eq!(e.value, b"v1");
1771                assert_eq!(e.version.as_u64(), Some(42));
1772            }
1773            other => panic!("expected Put, got {other:?}"),
1774        }
1775    }
1776
1777    #[test]
1778    fn kv_message_decodes_delete_and_purge_markers() {
1779        let msg = raw_kv_msg("$KV.certs.node.a", Some(ACK_42), b"", Some("DEL"));
1780        assert!(matches!(
1781            kv_message_to_update(&msg, "$KV.certs.").expect("in keyspace"),
1782            KvUpdate::Delete { ref key, ref version } if key == "node.a" && version.as_u64() == Some(42)
1783        ));
1784
1785        let msg = raw_kv_msg("$KV.certs.node.a", Some(ACK_42), b"", Some("PURGE"));
1786        assert!(matches!(
1787            kv_message_to_update(&msg, "$KV.certs.").expect("in keyspace"),
1788            KvUpdate::Purge { ref key, .. } if key == "node.a"
1789        ));
1790    }
1791
1792    #[test]
1793    fn kv_message_outside_keyspace_is_skipped() {
1794        // A subject-filtered consumer should never deliver this; the decode
1795        // skips rather than mis-keys it.
1796        let msg = raw_kv_msg("$KV.other.node.a", Some(ACK_42), b"v", None);
1797        assert!(kv_message_to_update(&msg, "$KV.certs.").is_none());
1798    }
1799
1800    #[test]
1801    fn kv_message_without_reply_gets_unknown_version() {
1802        // No ACK reply subject → revision unparseable → the UNKNOWN token,
1803        // never a fabricated revision 0. A parseable `Some(0)` would be
1804        // adopted by watch_applied as a real batch high-water and regress
1805        // the persisted cursor to 0 (full replay on next restart); unknown
1806        // is skipped by the cursor-authority loop instead.
1807        let msg = raw_kv_msg("$KV.certs.node.a", None, b"v", None);
1808        match kv_message_to_update(&msg, "$KV.certs.").expect("in keyspace") {
1809            KvUpdate::Put(e) => {
1810                assert!(e.version.is_unknown());
1811                assert_eq!(e.version.as_u64(), None);
1812            }
1813            other => panic!("expected Put, got {other:?}"),
1814        }
1815    }
1816
1817    #[test]
1818    fn raw_create_already_exists_when_10058_in_code_field() {
1819        // Some Synadia Cloud deployments echo 10058 in `code` rather than
1820        // `err_code`. Both paths must return AlreadyExists, not Failed.
1821        let payload = br#"{"error":{"code":10058,"description":"stream name already in use"}}"#;
1822        assert_eq!(
1823            classify_raw_create_response(payload),
1824            RawCreateOutcome::AlreadyExists
1825        );
1826    }
1827
1828    #[test]
1829    fn raw_create_error_without_code_defaults_to_zero() {
1830        // Defensive: a malformed error object still classifies as Failed rather
1831        // than silently passing, with code defaulting to 0.
1832        let payload = br#"{"error":{"description":"mystery"}}"#;
1833        match classify_raw_create_response(payload) {
1834            RawCreateOutcome::Failed { code, description } => {
1835                assert_eq!(code, 0);
1836                assert_eq!(description, "mystery");
1837            }
1838            other => panic!("expected Failed, got {other:?}"),
1839        }
1840    }
1841}
1842
1843/// Live-server conformance tests for the floor guard
1844/// ([`stream_watch_floor_guarded`]) — these drive the guarded loop DIRECTLY
1845/// with a deliberately clamped `Watch`, which reproduces exactly the state
1846/// retention leaves behind when it overruns a live consumer (the watcher
1847/// methods' resume-time checks can't be raced deterministically from
1848/// outside, but the guarded loop neither knows nor cares how its watch got
1849/// clamped). Spawns a throwaway `nats-server` (mise-installed, same pattern
1850/// as tests/common).
1851#[cfg(test)]
1852mod floor_guard_tests {
1853    use super::*;
1854    use std::process::{Child, Command, Stdio};
1855
1856    struct TestServer {
1857        child: Child,
1858        url: String,
1859        _dir: tempfile::TempDir,
1860    }
1861
1862    impl Drop for TestServer {
1863        fn drop(&mut self) {
1864            let _ = self.child.kill();
1865            let _ = self.child.wait();
1866        }
1867    }
1868
1869    async fn start_server() -> TestServer {
1870        let bin = std::env::var("NATS_SERVER_BIN").unwrap_or_else(|_| "nats-server".into());
1871        let port = std::net::TcpListener::bind("127.0.0.1:0")
1872            .unwrap()
1873            .local_addr()
1874            .unwrap()
1875            .port();
1876        let dir = tempfile::tempdir().unwrap();
1877        let child = Command::new(&bin)
1878            .args([
1879                "--jetstream",
1880                "--addr",
1881                "127.0.0.1",
1882                "--port",
1883                &port.to_string(),
1884                "--store_dir",
1885                dir.path().to_str().unwrap(),
1886            ])
1887            .stdout(Stdio::null())
1888            .stderr(Stdio::null())
1889            .spawn()
1890            .unwrap_or_else(|e| panic!("spawn {bin}: {e}; run `mise install`"));
1891        let server = TestServer {
1892            child,
1893            url: format!("nats://127.0.0.1:{port}"),
1894            _dir: dir,
1895        };
1896        for _ in 0..100 {
1897            if async_nats::connect(&server.url).await.is_ok() {
1898                return server;
1899            }
1900            tokio::time::sleep(Duration::from_millis(100)).await;
1901        }
1902        panic!("nats-server never became ready");
1903    }
1904
1905    /// `(js, kv store)` with five revisions across five subjects (history 1).
1906    async fn seeded_bucket(
1907        url: &str,
1908    ) -> (
1909        async_nats::jetstream::Context,
1910        async_nats::jetstream::kv::Store,
1911    ) {
1912        let client = async_nats::connect(url).await.unwrap();
1913        let js = async_nats::jetstream::new(client);
1914        let kv = js
1915            .create_key_value(async_nats::jetstream::kv::Config {
1916                bucket: "guard".into(),
1917                history: 1,
1918                ..Default::default()
1919            })
1920            .await
1921            .unwrap();
1922        for i in 1..=5u8 {
1923            kv.put(format!("k{i}"), vec![i].into()).await.unwrap();
1924        }
1925        (js, kv)
1926    }
1927
1928    /// TRUE POSITIVE: the watch was clamped past evicted revisions (purge
1929    /// advanced first_seq beyond the frontier) — the first gapped delivery
1930    /// must trip the guard BEFORE the entry is processed, never silently
1931    /// folding past the lost range. This is the live twin of the model's
1932    /// `GuardRepair`-only-progress gate.
1933    #[tokio::test(flavor = "multi_thread")]
1934    async fn gapped_delivery_with_advanced_floor_trips() {
1935        let server = start_server().await;
1936        let (js, kv) = seeded_bucket(&server.url).await;
1937
1938        // Evict revisions 1-3 outright: first_sequence becomes 4.
1939        let mut stream = js.get_stream("KV_guard").await.unwrap();
1940        stream.purge().sequence(4).await.unwrap();
1941        assert_eq!(stream.info().await.unwrap().state.first_sequence, 4);
1942
1943        // A consumer resuming from revision 1 gets CLAMPED to revision 4
1944        // (NATS's silent skip, pinned by tests/resync.rs). Hand that watch
1945        // to the guarded loop as a live consumer whose retention just
1946        // overran it.
1947        let watch = kv.watch_all_from_revision(2).await.unwrap();
1948        let (tx, mut rx) = tokio::sync::mpsc::channel(64);
1949        let drain = tokio::spawn(async move { while rx.recv().await.is_some() {} });
1950
1951        // The 5s bound pins IN-BAND detection: the trip must come from the
1952        // gapped-delivery check itself, not the 30s no-traffic backstop. A
1953        // regression to periodic-only detection (the design the model
1954        // checker rejected — catch-up between probes erases the evidence)
1955        // fails this bound.
1956        let err = tokio::time::timeout(
1957            Duration::from_secs(5),
1958            stream_watch_floor_guarded(watch, &tx, 1, &js, "guard"),
1959        )
1960        .await
1961        .expect("the trip must be IN-BAND (immediate), not backstop-paced")
1962        .expect_err("a gapped delivery over an advanced floor must trip");
1963        assert!(
1964            err.to_string().contains("retention overran live watch"),
1965            "{err}"
1966        );
1967        drop(tx);
1968        let _ = drain.await;
1969    }
1970
1971    /// NO FALSE POSITIVE: interior (per-subject) eviction also gaps the
1972    /// delivered revisions, but the floor stays at or below the frontier —
1973    /// benign for a last-write-wins fold, and the guard must let it
1974    /// through. (Every existing bootstrap e2e also rides this path on its
1975    /// resume; this pins the discrimination explicitly.)
1976    #[tokio::test(flavor = "multi_thread")]
1977    async fn benign_interior_gap_passes() {
1978        let server = start_server().await;
1979        let (js, kv) = seeded_bucket(&server.url).await;
1980
1981        // Overwrite k2 and k3: revisions 2 and 3 are interior-evicted
1982        // (history 1), revisions 6 and 7 replace them. first_sequence stays
1983        // 1 (k1's revision is retained).
1984        kv.put("k2", vec![22].into()).await.unwrap();
1985        kv.put("k3", vec![33].into()).await.unwrap();
1986        let mut stream = js.get_stream("KV_guard").await.unwrap();
1987        assert_eq!(stream.info().await.unwrap().state.first_sequence, 1);
1988
1989        // Resume from revision 1: deliveries jump 2 and 3 — gapped, benign.
1990        let watch = kv.watch_all_from_revision(2).await.unwrap();
1991        let (tx, mut rx) = tokio::sync::mpsc::channel(64);
1992        let guard =
1993            tokio::spawn(
1994                async move { stream_watch_floor_guarded(watch, &tx, 1, &js, "guard").await },
1995            );
1996
1997        let mut got = Vec::new();
1998        while got.len() < 4 {
1999            let update = tokio::time::timeout(Duration::from_secs(5), rx.recv())
2000                .await
2001                .expect("deliveries continue past benign gaps")
2002                .expect("watch alive");
2003            got.push(update.version().as_u64().unwrap());
2004        }
2005        assert_eq!(got, vec![4, 5, 6, 7], "interior gaps jumped, tail dense");
2006        guard.abort(); // endless live watch; the assertion above is the test
2007    }
2008}