greentic-runner-host 1.2.0

Host runtime shim for Greentic runner: config, pack loading, activity handling
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
//! Which stores a [`RunnerHost`](crate::RunnerHost) keeps its sessions and flow
//! state in.
//!
//! The default is unchanged from before this module existed: both stores are
//! in-memory, so a parked flow's [`SessionSnapshot`] dies with the process. That
//! is correct for a desktop run and for every test; it is wrong for a deployed
//! worker, where a revision rollout or a cold start silently restarts the
//! conversation. [`StorageConfig`] is how an embedding host asks for something
//! durable instead.
//!
//! # What the backing crates do about namespacing
//!
//! Scoping matters here: two deployments sharing one Redis must not read each
//! other's sessions. The two crates solve it differently, and the difference is
//! why only one of the two variants below carries a namespace.
//!
//! * **`greentic-session`** namespaces at the *store*. Its Redis backend keys a
//!   session entry as `<namespace>:session:<session key>`, where the session key
//!   is the runner's `<session hint>::<scope hash>` — and the session hint
//!   carries tenant, provider, channel, conversation and user but **not the
//!   environment**. The wait index keys (`<namespace>:waits:user:<env>:<tenant>:…`)
//!   do carry it, so a cross-environment collision does not leak a read: it
//!   makes [`find_wait_by_scope`] see a stored context whose `env` differs, drop
//!   the scope entry and return `None` — i.e. two environments sharing one
//!   keyspace would evict each other's parked flows. That is why
//!   [`SessionBackend::redis`] **requires** a namespace rather than accepting
//!   the crate's `greentic:session` default.
//! * **`greentic-state`** namespaces at the *key*. `RedisStateStore::from_url`
//!   takes no namespace and does not need one: every key goes through
//!   `greentic_state::key::fqn`, which composes
//!   `greentic:state:<env>:<tenant>[:<team>][:<user>]:<prefix>:<key>`, and this
//!   crate's own key adds `pack/<pack>/flow/<flow>/session/<hint>` on top. Env
//!   and tenant are therefore already in every key.
//!
//! Verified against `greentic-session 1.2.0-dev.35754484367` and
//! `greentic-state 1.2.0-dev.35754483639` — the versions this workspace's
//! `Cargo.lock` resolves. Re-read `backends/redis.rs` and `key.rs` before
//! trusting either paragraph after a bump.
//!
//! `RedisStateStore::del_prefix` runs an unbounded `SCAN MATCH` over the whole
//! keyspace, which would be a real hazard on a shared Redis. It is unreachable
//! from this crate: [`StateStoreHost::del_prefix`](crate::storage::state) is a
//! no-op and never forwards. `del_prefix_never_reaches_the_backing_store` pins
//! that, so a future implementation has to make the cost a deliberate decision.
//!
//! [`SessionSnapshot`]: crate::engine::host::SessionSnapshot
//! [`find_wait_by_scope`]: greentic_session::SessionStore::find_wait_by_scope

use std::fmt;
use std::time::Duration;

/// Environment variable naming the session backend (`memory` | `redis`).
pub const ENV_SESSION_BACKEND: &str = "GREENTIC_RUNNER_SESSION_BACKEND";
/// Environment variable naming the flow-state backend (`memory` | `redis`).
pub const ENV_STATE_BACKEND: &str = "GREENTIC_RUNNER_STATE_BACKEND";
/// Environment variable holding the Redis connection URL for both stores.
pub const ENV_REDIS_URL: &str = "GREENTIC_RUNNER_REDIS_URL";
/// Environment variable holding an explicit session keyspace prefix.
pub const ENV_SESSION_NAMESPACE: &str = "GREENTIC_RUNNER_SESSION_NAMESPACE";
/// Environment variable naming the deployment environment, used to derive a
/// session namespace when [`ENV_SESSION_NAMESPACE`] is unset.
pub const ENV_GREENTIC_ENV: &str = "GREENTIC_ENV";
/// Environment variable overriding how long a parked wait survives, in seconds.
/// `0` disables expiry — see [`SessionBackend::redis`].
pub const ENV_SESSION_WAIT_TTL_SECS: &str = "GREENTIC_RUNNER_SESSION_WAIT_TTL_SECS";

/// How long a parked wait survives on a durable session store when nothing says
/// otherwise.
///
/// Twenty-four hours, and the number is a judgement rather than a measurement.
/// Two bounds set it:
///
/// * **Long enough that the feature works.** The conversation this store exists
///   to preserve is one a human parked. Someone who answers the next morning
///   must still resume; an hour — the in-process
///   [`SessionSnapshot::new`](crate::engine::host::SessionSnapshot) default —
///   would silently drop exactly the case a durable store was added for. That
///   default governs a session the process would lose on restart anyway, so it
///   is not a precedent for one whose whole point is surviving a restart.
/// * **Short enough that abandonment is bounded.** Without an expiry every
///   parked-and-never-resumed conversation is a permanent key. A deployment
///   accumulates them for as long as it runs, and nothing reports it.
///
/// Override with [`ENV_SESSION_WAIT_TTL_SECS`] when a deployment knows better.
pub const DEFAULT_WAIT_TTL: Duration = Duration::from_secs(24 * 60 * 60);

/// A storage backend was asked for and could not be honoured.
///
/// Every variant is a refusal taken *before* any store is handed out, so a
/// misconfigured durable backend can never degrade into a silent in-memory one.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum StorageConfigError {
    /// A Redis backend was named but no URL was supplied.
    MissingRedisUrl { store: &'static str },
    /// A session Redis backend was named but no keyspace could be resolved.
    MissingSessionNamespace,
    /// The backend name was not one this build understands.
    UnknownBackend { store: &'static str, value: String },
}

impl fmt::Display for StorageConfigError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::MissingRedisUrl { store } => write!(
                f,
                "{store} backend 'redis' was requested but no Redis URL was supplied \
                 (set {ENV_REDIS_URL}); refusing rather than falling back to in-memory, \
                 which would silently lose every parked conversation"
            ),
            Self::MissingSessionNamespace => write!(
                f,
                "session backend 'redis' was requested but no keyspace could be resolved: \
                 set {ENV_SESSION_NAMESPACE} explicitly, or {ENV_GREENTIC_ENV} to derive one. \
                 A session entry key carries no environment, so sharing the crate default \
                 keyspace lets two environments evict each other's parked flows"
            ),
            Self::UnknownBackend { store, value } => write!(
                f,
                "unknown {store} backend '{value}' (expected 'memory' or 'redis')"
            ),
        }
    }
}

impl std::error::Error for StorageConfigError {}

/// Where parked-flow sessions live.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub enum SessionBackend {
    /// Process-local. A parked flow does not survive the process.
    #[default]
    InMemory,
    /// Redis, under a keyspace unique to this deployment environment.
    Redis {
        /// Connection URL, e.g. `redis://127.0.0.1:6379`.
        url: String,
        /// Keyspace prefix every key of this store is written under.
        namespace: String,
        /// How long a parked wait survives. `None` means no expiry, which is an
        /// operator's deliberate choice to grow the keyspace without bound.
        wait_ttl: Option<Duration>,
    },
}

/// Where per-session flow state lives.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub enum StateBackend {
    /// Process-local. Flow state does not survive the process.
    #[default]
    InMemory,
    /// Redis. Keys are scoped by environment and tenant by `greentic-state`
    /// itself — see this module's header.
    Redis {
        /// Connection URL, e.g. `redis://127.0.0.1:6379`.
        url: String,
    },
}

impl SessionBackend {
    /// Redis-backed sessions under `namespace`.
    ///
    /// The namespace is required, not defaulted: see this module's header for
    /// what two environments sharing one keyspace do to each other.
    pub fn redis(
        url: impl Into<String>,
        namespace: impl Into<String>,
    ) -> Result<Self, StorageConfigError> {
        Self::redis_with_ttl(url, namespace, Some(DEFAULT_WAIT_TTL))
    }

    /// Redis-backed sessions with an explicit wait lifetime.
    ///
    /// `wait_ttl: None` disables expiry. That is a real choice — a deployment
    /// that archives its own keys may want it — but it is not the default,
    /// because the failure it produces is invisible: every parked-and-abandoned
    /// conversation becomes a permanent key and nothing reports the growth.
    pub fn redis_with_ttl(
        url: impl Into<String>,
        namespace: impl Into<String>,
        wait_ttl: Option<Duration>,
    ) -> Result<Self, StorageConfigError> {
        let url = url.into();
        let namespace = namespace.into();
        if url.trim().is_empty() {
            return Err(StorageConfigError::MissingRedisUrl { store: "session" });
        }
        if namespace.trim().is_empty() {
            return Err(StorageConfigError::MissingSessionNamespace);
        }
        // A zero duration would expire the key before the turn that wrote it
        // could resume against it, which reads as "durable storage does not
        // work". Treat it as the disable it plainly means.
        let wait_ttl = wait_ttl.filter(|ttl| !ttl.is_zero());
        Ok(Self::Redis {
            url,
            namespace,
            wait_ttl,
        })
    }

    /// The conventional keyspace for `env`: `greentic:session:<env>`.
    ///
    /// Environment is the scope the crate's own session entry key omits, so it
    /// is the minimum a namespace must carry.
    ///
    /// **It is not automatically sufficient.** The namespace has to be unique
    /// per ISOLATION DOMAIN, and an embedding host may have a finer one than
    /// the environment. greentic-start is the case in point: `revision_boot`
    /// gives every pack REVISION its own session store on purpose, so that two
    /// revisions serving the same tenant/user/conversation cannot resume each
    /// other's snapshot against a different flow graph (its own
    /// `shared_revision_store_leaks_across_revisions` test calls that "the
    /// bug"). A host like that must fold its revision key into the namespace;
    /// one environment-wide keyspace would re-create exactly what its
    /// per-revision stores prevent.
    ///
    /// Durability and that isolation are not in tension — they answer different
    /// questions. A per-revision namespace still survives a process restart and
    /// a cold start, which is what a durable store is for; what it does not do
    /// is carry a half-finished conversation onto a different flow graph.
    pub fn namespace_for_env(env: &str) -> Result<String, StorageConfigError> {
        let env = env.trim();
        if env.is_empty() {
            return Err(StorageConfigError::MissingSessionNamespace);
        }
        Ok(format!("greentic:session:{env}"))
    }

    /// `true` when this backend performs network I/O and must not be called
    /// directly from a tokio worker.
    pub fn is_durable(&self) -> bool {
        matches!(self, Self::Redis { .. })
    }

    /// How long a parked wait survives, or `None` for no expiry.
    pub fn wait_ttl(&self) -> Option<Duration> {
        match self {
            Self::InMemory => None,
            Self::Redis { wait_ttl, .. } => *wait_ttl,
        }
    }

    /// A log-safe description: the backend name and, for Redis, the keyspace.
    ///
    /// Never the URL. A Redis URL may carry `redis://user:password@host`, and
    /// the `Debug` impl would print it verbatim into whatever log the operator
    /// ships off the box.
    pub fn describe(&self) -> String {
        match self {
            Self::InMemory => "in-memory".to_string(),
            Self::Redis {
                namespace,
                wait_ttl,
                ..
            } => {
                let ttl = match wait_ttl {
                    Some(ttl) => format!("{}s", ttl.as_secs()),
                    None => "none".to_string(),
                };
                format!("redis (namespace '{namespace}', wait ttl {ttl})")
            }
        }
    }
}

impl StateBackend {
    /// Redis-backed flow state.
    pub fn redis(url: impl Into<String>) -> Result<Self, StorageConfigError> {
        let url = url.into();
        if url.trim().is_empty() {
            return Err(StorageConfigError::MissingRedisUrl { store: "state" });
        }
        Ok(Self::Redis { url })
    }

    /// `true` when this backend performs network I/O and must not be called
    /// directly from a tokio worker.
    pub fn is_durable(&self) -> bool {
        matches!(self, Self::Redis { .. })
    }

    /// A log-safe description. Never the URL — see
    /// [`SessionBackend::describe`].
    pub fn describe(&self) -> &'static str {
        match self {
            Self::InMemory => "in-memory",
            Self::Redis { .. } => "redis",
        }
    }
}

/// The pair of stores a host is built over.
///
/// [`StorageConfig::default()`] is both-in-memory, which is what
/// [`HostBuilder::build`](crate::HostBuilder::build) uses when no storage is
/// named — so every caller that predates this type keeps exactly the behaviour
/// it had.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct StorageConfig {
    /// Parked-flow sessions.
    pub session: SessionBackend,
    /// Per-session flow state.
    pub state: StateBackend,
}

impl StorageConfig {
    /// Both stores in memory — the default.
    pub fn in_memory() -> Self {
        Self::default()
    }

    /// Both stores on one Redis, sessions under `namespace`.
    pub fn redis(
        url: impl Into<String>,
        namespace: impl Into<String>,
    ) -> Result<Self, StorageConfigError> {
        Self::redis_with_ttl(url, namespace, Some(DEFAULT_WAIT_TTL))
    }

    /// Both stores on one Redis, with an explicit wait lifetime. See
    /// [`SessionBackend::redis_with_ttl`].
    pub fn redis_with_ttl(
        url: impl Into<String>,
        namespace: impl Into<String>,
        wait_ttl: Option<Duration>,
    ) -> Result<Self, StorageConfigError> {
        let url = url.into();
        Ok(Self {
            session: SessionBackend::redis_with_ttl(url.clone(), namespace, wait_ttl)?,
            state: StateBackend::redis(url)?,
        })
    }

    /// Resolve from the process environment.
    ///
    /// Deliberately NOT called by `HostBuilder::build`: reading the environment
    /// there would move an existing embedder's sessions to Redis the moment
    /// these variables appeared for some other reason. An embedder that wants
    /// this asks for it.
    ///
    /// Precedence mirrors `runner::aw_backends::select_state_backend` with one
    /// deliberate difference: an explicitly-named Redis backend with
    /// no URL is an `Err` here, not a quiet disable. A worker that cannot reach
    /// its state store should not start.
    ///
    /// A backend that is not named at all resolves to memory — never to Redis
    /// just because a URL happens to be present.
    pub fn from_env() -> Result<Self, StorageConfigError> {
        Self::from_vars(
            std::env::var(ENV_SESSION_BACKEND).ok().as_deref(),
            std::env::var(ENV_STATE_BACKEND).ok().as_deref(),
            std::env::var(ENV_REDIS_URL).ok().as_deref(),
            std::env::var(ENV_SESSION_NAMESPACE).ok().as_deref(),
            std::env::var(ENV_GREENTIC_ENV).ok().as_deref(),
            std::env::var(ENV_SESSION_WAIT_TTL_SECS).ok().as_deref(),
        )
    }

    /// The pure half of [`from_env`](Self::from_env), so the precedence is
    /// testable without touching process-global state.
    pub fn from_vars(
        session_backend: Option<&str>,
        state_backend: Option<&str>,
        redis_url: Option<&str>,
        session_namespace: Option<&str>,
        greentic_env: Option<&str>,
        wait_ttl_secs: Option<&str>,
    ) -> Result<Self, StorageConfigError> {
        let url = redis_url.map(str::trim).filter(|value| !value.is_empty());
        // An unparseable value falls back to the default rather than refusing:
        // a typo in a tuning knob must not stop a worker booting, and the
        // default is safe. `0` is a legitimate value meaning "no expiry".
        let wait_ttl = match named(wait_ttl_secs).and_then(|raw| raw.parse::<u64>().ok()) {
            Some(0) => None,
            Some(secs) => Some(Duration::from_secs(secs)),
            None => Some(DEFAULT_WAIT_TTL),
        };

        let session = match named(session_backend) {
            None | Some("memory") => SessionBackend::InMemory,
            Some("redis") => {
                let url = url.ok_or(StorageConfigError::MissingRedisUrl { store: "session" })?;
                let namespace = match named(session_namespace) {
                    Some(explicit) => explicit.to_string(),
                    None => SessionBackend::namespace_for_env(
                        named(greentic_env).ok_or(StorageConfigError::MissingSessionNamespace)?,
                    )?,
                };
                SessionBackend::redis_with_ttl(url, namespace, wait_ttl)?
            }
            Some(other) => {
                return Err(StorageConfigError::UnknownBackend {
                    store: "session",
                    value: other.to_string(),
                });
            }
        };

        let state = match named(state_backend) {
            None | Some("memory") => StateBackend::InMemory,
            Some("redis") => {
                let url = url.ok_or(StorageConfigError::MissingRedisUrl { store: "state" })?;
                StateBackend::redis(url)?
            }
            Some(other) => {
                return Err(StorageConfigError::UnknownBackend {
                    store: "state",
                    value: other.to_string(),
                });
            }
        };

        Ok(Self { session, state })
    }

    /// `true` when either store performs network I/O.
    pub fn is_durable(&self) -> bool {
        self.session.is_durable() || self.state.is_durable()
    }
}

fn named(value: Option<&str>) -> Option<&str> {
    value.map(str::trim).filter(|value| !value.is_empty())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn the_default_is_both_stores_in_memory() {
        let config = StorageConfig::default();
        assert_eq!(config.session, SessionBackend::InMemory);
        assert_eq!(config.state, StateBackend::InMemory);
        assert!(!config.is_durable());
    }

    #[test]
    fn an_unnamed_backend_stays_in_memory_even_when_a_url_is_present() {
        // Deliberately unlike `aw_backends::select_state_backend`, which
        // auto-selects Redis from a bare URL. A URL appearing in the
        // environment for some other reason must not move a host's sessions.
        let config =
            StorageConfig::from_vars(None, None, Some("redis://x"), None, Some("prod"), None)
                .expect("resolve");
        assert_eq!(config, StorageConfig::in_memory());
    }

    #[test]
    fn explicit_redis_without_a_url_is_refused_not_disabled() {
        let err = StorageConfig::from_vars(Some("redis"), None, None, Some("ns"), None, None)
            .expect_err("must refuse");
        assert_eq!(
            err,
            StorageConfigError::MissingRedisUrl { store: "session" }
        );

        let err = StorageConfig::from_vars(None, Some("redis"), None, None, None, None)
            .expect_err("must refuse");
        assert_eq!(err, StorageConfigError::MissingRedisUrl { store: "state" });
    }

    #[test]
    fn an_empty_url_reads_as_absent_rather_than_as_a_host_named_nothing() {
        let err =
            StorageConfig::from_vars(Some("redis"), None, Some("   "), Some("ns"), None, None)
                .expect_err("must refuse");
        assert_eq!(
            err,
            StorageConfigError::MissingRedisUrl { store: "session" }
        );
    }

    #[test]
    fn a_session_redis_backend_without_a_resolvable_namespace_is_refused() {
        let err =
            StorageConfig::from_vars(Some("redis"), None, Some("redis://x"), None, None, None)
                .expect_err("must refuse");
        assert_eq!(err, StorageConfigError::MissingSessionNamespace);
    }

    #[test]
    fn the_namespace_falls_back_to_the_environment_name() {
        let config = StorageConfig::from_vars(
            Some("redis"),
            None,
            Some("redis://x"),
            None,
            Some("prod"),
            None,
        )
        .expect("resolve");
        assert_eq!(
            config.session,
            SessionBackend::Redis {
                url: "redis://x".into(),
                namespace: "greentic:session:prod".into(),
                wait_ttl: Some(DEFAULT_WAIT_TTL),
            }
        );
    }

    #[test]
    fn an_explicit_namespace_beats_the_derived_one() {
        let config = StorageConfig::from_vars(
            Some("redis"),
            None,
            Some("redis://x"),
            Some("acme:sessions"),
            Some("prod"),
            None,
        )
        .expect("resolve");
        assert_eq!(
            config.session,
            SessionBackend::Redis {
                url: "redis://x".into(),
                namespace: "acme:sessions".into(),
                wait_ttl: Some(DEFAULT_WAIT_TTL),
            }
        );
    }

    #[test]
    fn two_environments_derive_different_namespaces() {
        let prod = SessionBackend::namespace_for_env("prod").expect("prod");
        let staging = SessionBackend::namespace_for_env("staging").expect("staging");
        assert_ne!(prod, staging);
    }

    #[test]
    fn an_unknown_backend_name_is_refused_rather_than_guessed() {
        let err = StorageConfig::from_vars(Some("cassandra"), None, None, None, None, None)
            .expect_err("must refuse");
        assert_eq!(
            err,
            StorageConfigError::UnknownBackend {
                store: "session",
                value: "cassandra".into(),
            }
        );
    }

    #[test]
    fn a_description_never_carries_the_connection_url() {
        let backend = SessionBackend::redis("redis://user:hunter2@redis:6379", "ns").expect("cfg");
        let described = backend.describe();
        assert!(
            !described.contains("hunter2"),
            "credential leaked: {described}"
        );
        assert!(!described.contains("redis://"), "url leaked: {described}");
        assert!(described.contains("ns"));

        let state = StateBackend::redis("redis://user:hunter2@redis:6379").expect("cfg");
        assert!(!state.describe().contains("hunter2"));
    }

    #[test]
    fn a_redis_session_backend_is_bounded_unless_an_operator_says_otherwise() {
        // The default is what a deployment that sets no TTL variable gets, and
        // it must not be "keep every abandoned conversation forever".
        let backend = SessionBackend::redis("redis://x", "ns").expect("cfg");
        assert_eq!(backend.wait_ttl(), Some(DEFAULT_WAIT_TTL));
        assert!(
            DEFAULT_WAIT_TTL >= Duration::from_secs(60 * 60),
            "a default under an hour would drop conversations a human parked"
        );

        let config = StorageConfig::from_vars(
            Some("redis"),
            None,
            Some("redis://x"),
            Some("ns"),
            None,
            None,
        )
        .expect("resolve");
        assert_eq!(config.session.wait_ttl(), Some(DEFAULT_WAIT_TTL));
    }

    #[test]
    fn the_wait_ttl_is_overridable_and_zero_disables_it() {
        let config = StorageConfig::from_vars(
            Some("redis"),
            None,
            Some("redis://x"),
            Some("ns"),
            None,
            Some("90"),
        )
        .expect("resolve");
        assert_eq!(config.session.wait_ttl(), Some(Duration::from_secs(90)));

        let disabled = StorageConfig::from_vars(
            Some("redis"),
            None,
            Some("redis://x"),
            Some("ns"),
            None,
            Some("0"),
        )
        .expect("resolve");
        assert_eq!(disabled.session.wait_ttl(), None);
    }

    #[test]
    fn an_unparseable_ttl_falls_back_to_the_bounded_default() {
        // A typo in a tuning knob must not boot an unbounded store, and must
        // not stop the worker booting either.
        let config = StorageConfig::from_vars(
            Some("redis"),
            None,
            Some("redis://x"),
            Some("ns"),
            None,
            Some("ten minutes"),
        )
        .expect("resolve");
        assert_eq!(config.session.wait_ttl(), Some(DEFAULT_WAIT_TTL));
    }

    #[test]
    fn a_zero_duration_reads_as_disabled_rather_than_as_instant_expiry() {
        // `Some(0)` through the typed door means the same as `0` through the
        // env door. Honouring it literally would expire a wait before the turn
        // that wrote it could resume, which reads as "durable storage is broken".
        let backend =
            SessionBackend::redis_with_ttl("redis://x", "ns", Some(Duration::ZERO)).expect("cfg");
        assert_eq!(backend.wait_ttl(), None);
    }

    #[test]
    fn the_description_reports_the_ttl_so_an_operator_can_see_it() {
        let bounded = SessionBackend::redis("redis://x", "ns").expect("cfg");
        assert!(bounded.describe().contains("86400s"));
        let unbounded = SessionBackend::redis_with_ttl("redis://x", "ns", None).expect("cfg");
        assert!(unbounded.describe().contains("none"));
    }

    #[test]
    fn every_refusal_names_the_variable_that_fixes_it() {
        assert!(
            StorageConfigError::MissingRedisUrl { store: "state" }
                .to_string()
                .contains(ENV_REDIS_URL)
        );
        let namespace = StorageConfigError::MissingSessionNamespace.to_string();
        assert!(namespace.contains(ENV_SESSION_NAMESPACE));
        assert!(namespace.contains(ENV_GREENTIC_ENV));
    }
}