Skip to main content

liminal_server/config/
types.rs

1use std::net::SocketAddr;
2use std::path::PathBuf;
3use std::time::Duration;
4
5use crate::ServerError;
6
7/// Declarative configuration for the standalone liminal server wrapper.
8#[derive(Debug, Clone, serde::Deserialize)]
9#[serde(deny_unknown_fields)]
10pub struct ServerConfig {
11    /// Socket address where the standalone server will listen for client traffic.
12    pub listen_address: SocketAddr,
13    /// Socket address where the health endpoint server will listen for probes.
14    pub health_listen_address: SocketAddr,
15    /// IGNORED SINCE 0.14.3. Kept only so an existing config file still loads.
16    ///
17    /// This was the maximum time shutdown would wait for existing connections
18    /// to hang up by themselves before closing them. Nothing reads it now.
19    ///
20    /// A drain exists to let in-flight requests finish. In this server every
21    /// write is durable and flushed BEFORE it is acknowledged, so at the
22    /// instant shutdown begins there is no in-flight request to finish and
23    /// nothing for the wait to buy. What it did in practice, on a deployment
24    /// whose connections are long-lived idle clients that never hang up on
25    /// their own, was spend its whole budget on every restart and then close
26    /// the connections anyway — 5 s per restart, measured on Tom Whiting's
27    /// estate on 2026-09-14. Shutdown now stops accepting, closes every
28    /// connection itself (an orderly close each peer reads as a shutdown), and
29    /// flushes durable state, with no timer in that path.
30    ///
31    /// Any value parses, including zero. Setting it changes nothing.
32    pub drain_timeout_ms: u64,
33    /// Channel topology definitions declared by the operator.
34    pub channels: Vec<ChannelDef>,
35    /// Declarative routing rules that connect configured channels.
36    pub routing_rules: Vec<RoutingRuleDef>,
37    /// Optional filesystem location for durable server state.
38    ///
39    /// A fresh boot surfaces `ConfigValidation` unless this path's PARENT
40    /// directory already exists: the haematite engine creates the store dir
41    /// exactly one level below a pre-existing parent it can fence (never
42    /// `create_dir_all` — deliberate upstream hardening). Create the parent;
43    /// the engine fences into it.
44    pub persistence_path: Option<PathBuf>,
45    /// Optional beamr distribution cluster membership configuration.
46    pub cluster: Option<ClusterConfig>,
47    /// Optional connection authentication configuration.
48    ///
49    /// When present, every client `Connect` handshake must carry a matching
50    /// `auth_token`; when absent the server is open (byte-identical to the
51    /// pre-auth behaviour). Not an ACL system — a single shared bearer token.
52    #[serde(default)]
53    pub auth: Option<AuthConfig>,
54    /// Service construction profile. Absent `[services]` (or an absent `profile`
55    /// key within it) defaults to `"full"`, so existing deployments build exactly
56    /// what they build today.
57    #[serde(default)]
58    pub services: ServicesConfig,
59    /// Operational bounds (§5). Absent `[limits]` (or any absent key within it)
60    /// defaults to the certifying-pair-signed numbers, so an operator who sets
61    /// nothing still runs bounded — "unlimited-by-silence is no longer a legal
62    /// state" (§5). Every value is a hard cap enforced by a typed refusal; a
63    /// zero (or otherwise invalid) value is a config validation error, never a
64    /// silent "unlimited".
65    #[serde(default)]
66    pub limits: LimitsConfig,
67    /// Optional WebSocket transport acceptor (LP-WS-TRANSPORT R1).
68    ///
69    /// When present the server binds a sibling WebSocket listener carrying the
70    /// canonical liminal wire protocol (one binary message per canonical frame)
71    /// alongside the main TCP listener. When absent NO HTTP/WebSocket listener
72    /// is started and the server behaves byte-identically to the pre-WebSocket
73    /// build. Every field inside is a deployment decision; the origin allow-list
74    /// FAILS CLOSED (an absent or empty list refuses every Origin-bearing
75    /// upgrade) and the keepalive ping interval is disabled unless explicitly
76    /// configured.
77    #[serde(default)]
78    pub websocket: Option<WebSocketConfig>,
79    /// Participant lifecycle activation (LP gap closure, Part B).
80    ///
81    /// When present the server installs the production participant semantic
82    /// handler and advertises the participant capability bit on every
83    /// connection. Every field inside is REQUIRED and carries NO default:
84    /// participant lifecycle values are deployment decisions, and an absent
85    /// field is a typed startup error rather than an assumed number. When the
86    /// section is absent the participant capability stays disabled and the
87    /// server behaves byte-identically to the pre-activation build.
88    #[serde(default)]
89    pub participant: Option<ParticipantConfig>,
90}
91
92impl ServerConfig {
93    /// Returns the configured drain timeout, which shutdown IGNORES since
94    /// 0.14.3.
95    ///
96    /// Retained so an embedder that reads it keeps compiling, and so the value
97    /// an operator wrote can still be named in the shutdown log line that
98    /// reports it ignored. See [`ServerConfig::drain_timeout_ms`].
99    #[must_use]
100    pub const fn drain_timeout(&self) -> Duration {
101        Duration::from_millis(self.drain_timeout_ms)
102    }
103}
104
105/// Declarative channel definition loaded from server configuration.
106#[derive(Debug, Clone, serde::Deserialize)]
107#[serde(deny_unknown_fields)]
108pub struct ChannelDef {
109    /// Unique channel name used by routing rules and operators.
110    pub name: String,
111    /// Filesystem path to a JSON Schema document that validates every message
112    /// published to this channel.
113    ///
114    /// The path is resolved relative to the directory containing the config file
115    /// (absolute paths are used verbatim). Config validation reads and parses the
116    /// referenced document and stores the result in [`Self::loaded_schema`]; a
117    /// missing file, an unreadable file, or a file that is not valid JSON is an
118    /// accumulated validation error that stops startup.
119    ///
120    /// `None` means the channel has no schema: it keeps the permissive empty
121    /// schema (`{}`) that accepts any JSON payload.
122    #[serde(default)]
123    pub schema_ref: Option<PathBuf>,
124    /// Whether this channel requires durable persistence.
125    pub durable: bool,
126    /// Schema document loaded and parsed from [`Self::schema_ref`] during config
127    /// validation. Populated only by [`crate::config::validate`]; a directly
128    /// constructed [`ChannelDef`] that skips validation carries `None` here and is
129    /// therefore built with the permissive empty schema regardless of
130    /// [`Self::schema_ref`]. Never deserialized from the config file.
131    #[serde(skip)]
132    pub loaded_schema: Option<LoadedSchema>,
133}
134
135/// A channel's JSON Schema document as loaded from disk during config validation.
136///
137/// Carries both the parsed document (fed to the validation engine when the channel
138/// is built) and the raw file bytes (hashed into the protocol schema id advertised
139/// at subscribe time, so an SDK deriving ids from the same schema bytes converges).
140#[derive(Debug, Clone)]
141pub struct LoadedSchema {
142    /// Raw bytes of the schema file, hashed to derive the protocol schema id.
143    pub bytes: Vec<u8>,
144    /// Parsed JSON Schema document, fed to the channel's validation engine.
145    pub document: serde_json::Value,
146}
147
148/// Declarative routing rule definition loaded from server configuration.
149#[derive(Debug, Clone, serde::Deserialize)]
150#[serde(deny_unknown_fields)]
151pub struct RoutingRuleDef {
152    /// Source channel name from which messages are routed.
153    pub source_channel: String,
154    /// Target channel name to which matching messages are routed.
155    pub target_channel: String,
156    /// Optional predicate expression that filters routed messages.
157    pub predicate: Option<String>,
158}
159
160/// Default beamr distribution handshake cookie, used when the operator does not
161/// configure one. Mirrors beamr's own [`beamr::distribution::DEFAULT_COOKIE`].
162pub const DEFAULT_COOKIE: &str = "beamr-cookie";
163
164/// Beamr distribution cluster configuration for standalone deployment.
165#[derive(Debug, Clone, serde::Deserialize)]
166#[serde(deny_unknown_fields)]
167pub struct ClusterConfig {
168    /// Unique node name advertised to the beamr distribution cluster.
169    pub node_name: String,
170    /// Socket address this node binds for inbound distribution links from peers.
171    ///
172    /// This is distinct from [`ServerConfig::listen_address`] (the client wire
173    /// port): a clustered node listens on two ports — one for clients, one for
174    /// peer distribution traffic.
175    pub listen_address: SocketAddr,
176    /// Seed node socket addresses used to join an existing cluster.
177    pub seed_nodes: Vec<SocketAddr>,
178    /// Shared distribution handshake cookie. Every node in a cluster MUST use the
179    /// same cookie or the OTP handshake is rejected. Defaults to
180    /// [`DEFAULT_COOKIE`] when omitted.
181    #[serde(default = "default_cookie")]
182    pub cookie: String,
183}
184
185fn default_cookie() -> String {
186    DEFAULT_COOKIE.to_owned()
187}
188
189/// Connection authentication configuration.
190///
191/// A single shared bearer token compared (constant-time) against the `auth_token`
192/// carried on every client `Connect` handshake. This is the table-stakes access
193/// gate, not an ACL system: one token grants full access, its absence (no `[auth]`
194/// section) leaves the server open.
195#[derive(Clone, serde::Deserialize)]
196#[serde(deny_unknown_fields)]
197pub struct AuthConfig {
198    /// Shared secret token a client must present in its `Connect` handshake. Must
199    /// be non-empty when the `[auth]` section is present (an empty token is a
200    /// config validation error, since it would gate nothing).
201    pub token: String,
202    /// Optional registry-minted pass verifier, additive beside the bearer.
203    #[serde(default)]
204    pub pass: Option<PassConfig>,
205    /// The Lys pass as a second credential beside the wire pass (ACCESS-001
206    /// R2): when set, a `Connect` carrying a Lys pass record is verified
207    /// offline against the issuer's published keys and decided per message.
208    #[serde(default)]
209    pub lys: Option<LysConfig>,
210    /// Refuse every worker registration from a connection that proved no
211    /// holder (ACCESS-004 R3): a bearer connection, or one before any pass.
212    /// Off by default, so a worker that dials with the bearer, as aion's does,
213    /// keeps registering; turning it on is the operator's act, and it needs
214    /// `[auth.pass]`, without which no connection could prove a holder.
215    #[serde(default)]
216    pub require_verified_worker: bool,
217}
218
219/// The token is a credential: its `Debug` names its length only
220/// (ACCESS-004 R5).
221impl std::fmt::Debug for AuthConfig {
222    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
223        formatter
224            .debug_struct("AuthConfig")
225            .field("token", &crate::auth_pass::ByteLength(self.token.len()))
226            .field("pass", &self.pass)
227            .field("lys", &self.lys)
228            .field("require_verified_worker", &self.require_verified_worker)
229            .finish()
230    }
231}
232
233/// Registry pass verification configuration. Every field is required when present.
234#[derive(Debug, Clone, serde::Deserialize)]
235#[serde(deny_unknown_fields)]
236pub struct PassConfig {
237    /// Registry Ed25519 verifying key as exactly 64 hexadecimal characters.
238    pub registry_verifying_key: String,
239    /// Maximum admitted server-clock skew in seconds.
240    pub maximum_clock_skew_seconds: u64,
241}
242
243/// WebSocket transport acceptor configuration (`[websocket]`, LP-WS-TRANSPORT R1).
244///
245/// The sibling WebSocket route is an explicit opt-in: the section itself must be
246/// present for any HTTP/WebSocket listener to start, and inside it the listen
247/// address and the single exact upgrade path are required with no defaults.
248///
249/// The deployment TLS contract (tear ruling Q1) is raw `ws://` behind a named
250/// TLS-terminating proxy that owns public `wss://` and certificates; liminal
251/// grows no TLS stack. Origin validation nonetheless belongs to this acceptor:
252/// [`Self::allowed_origins`] is the explicit allow-list checked on every
253/// Origin-bearing upgrade, and there is NO default list — absent or empty
254/// configuration fails closed for browser-origin upgrades while a native client
255/// that sends no `Origin` header may still upgrade (F6).
256///
257/// OPERATOR NOTE — the same deployment contract covers the pre-upgrade window
258/// (domain-owner ruling, 2026-07-18): the fronting proxy must ALSO enforce
259/// pre-upgrade read timeouts, handshake concurrency limits, and connection
260/// rate limits. Between TCP accept and a completed WebSocket upgrade this
261/// listener does not count the socket against `[limits] max_connections` and
262/// applies no read deadline of its own (only the fixed request-head size
263/// bound), so a deployment that exposes this port without the named proxy is
264/// out of contract on untrusted networks. A named handshake read-deadline
265/// config plus an in-flight handshake cap derived from the configured
266/// `max_connections` value is the ledgered post-demo hardening.
267#[derive(Debug, Clone, serde::Deserialize)]
268#[serde(deny_unknown_fields)]
269pub struct WebSocketConfig {
270    /// Socket address the WebSocket acceptor binds. Required; distinct from the
271    /// main wire listener, the health listener, and any cluster listener.
272    pub listen_address: SocketAddr,
273    /// The single exact HTTP request path that accepts WebSocket upgrades.
274    /// Required; must start with `/`. Every other path — and every ordinary
275    /// HTTP request — receives a small fixed non-success response and closes.
276    pub path: String,
277    /// Explicit browser-origin allow-list checked on every Origin-bearing
278    /// upgrade (F6). Entries are compared byte-exact against the request's
279    /// serialized `Origin` header value (RFC 6454 ASCII serialization, e.g.
280    /// `https://app.example.com`). Absent or empty means NO browser origin is
281    /// accepted (fail closed); native clients sending no `Origin` header are
282    /// unaffected.
283    #[serde(default)]
284    pub allowed_origins: Vec<String>,
285    /// Q-A transport-liveness keepalive: the server-side WebSocket Ping
286    /// interval in milliseconds. This is a precise LAW-1 carve-out — liveness
287    /// pings never mint application events, never re-arm application state, and
288    /// never serve as a source of truth; failure detection remains the socket's
289    /// typed terminal events. The bound is one ping per interval per
290    /// connection, so the idle cost is `interval x connection-count`. Absent
291    /// means pings are DISABLED, accepting proxy-idle-disconnect churn as the
292    /// documented consequence. A configured zero is a validation error.
293    #[serde(default)]
294    pub ping_interval_ms: Option<u64>,
295}
296
297/// Service construction profile selection (D2).
298///
299/// The `profile` value is carried as a raw string here rather than a typed enum so
300/// an unrecognised value is a config *validation* error with a helpful message
301/// (via [`Self::profile`]) rather than an opaque deserialization failure — matching
302/// how every other semantic config check surfaces. Absent `profile` defaults to
303/// `"full"`.
304#[derive(Debug, Clone, serde::Deserialize)]
305#[serde(deny_unknown_fields)]
306pub struct ServicesConfig {
307    /// Construction profile: `"full"` (the default, unchanged behaviour) or
308    /// `"worker-front-door"` (capability-scoped worker deployments).
309    #[serde(default = "default_service_profile")]
310    pub profile: String,
311    /// Row bounds for the server-owned durable streams.
312    #[serde(default)]
313    pub self_streams: SelfStreamsConfig,
314}
315
316/// Retained row bounds for each server-owned durable stream.
317#[derive(Debug, Clone, Copy, serde::Deserialize)]
318#[serde(deny_unknown_fields)]
319pub struct SelfStreamsConfig {
320    /// Maximum retained cost records.
321    #[serde(default = "default_cost_rows")]
322    pub cost_rows: u64,
323    /// Maximum retained lifecycle and connection events.
324    #[serde(default = "default_events_rows")]
325    pub events_rows: u64,
326}
327
328impl Default for SelfStreamsConfig {
329    fn default() -> Self {
330        Self {
331            cost_rows: default_cost_rows(),
332            events_rows: default_events_rows(),
333        }
334    }
335}
336
337const fn default_cost_rows() -> u64 {
338    10_000
339}
340
341const fn default_events_rows() -> u64 {
342    100_000
343}
344
345impl Default for ServicesConfig {
346    fn default() -> Self {
347        Self {
348            profile: default_service_profile(),
349            self_streams: SelfStreamsConfig::default(),
350        }
351    }
352}
353
354impl ServicesConfig {
355    /// Resolves the raw `profile` string into a typed [`ServiceProfile`].
356    ///
357    /// # Errors
358    /// Returns [`ServerError::ConfigValidation`] when the value is not a recognised
359    /// profile.
360    pub fn profile(&self) -> Result<ServiceProfile, ServerError> {
361        ServiceProfile::parse(&self.profile)
362    }
363}
364
365fn default_service_profile() -> String {
366    ServiceProfile::FULL.to_owned()
367}
368
369/// Operational bounds (§5, scout Q4 — rule-2 items).
370///
371/// Each field is a hard per-scope cap with a typed refusal and a
372/// certifying-pair-signed default (the numbers below are §5's). The struct is
373/// the single wire surface for `[limits]`; [`LimitsConfig::validate`] rejects any
374/// zero value as a typed config error (a zero cap would gate nothing — the exact
375/// unlimited-by-silence state §5 outlaws). Defaults come from the `default_*`
376/// free functions so an absent key resolves to the signed number, not zero.
377#[derive(Debug, Clone, Copy, serde::Deserialize)]
378#[serde(deny_unknown_fields)]
379pub struct LimitsConfig {
380    /// Total live connections the listener admits before refusing (§5: 256 — a
381    /// worker-bus, an order of magnitude above any observed fleet).
382    #[serde(default = "default_max_connections")]
383    pub max_connections: usize,
384    /// Subscriptions one connection may hold (§5: 32).
385    #[serde(default = "default_max_subscriptions_per_connection")]
386    pub max_subscriptions_per_connection: usize,
387    /// Open conversations one connection may hold (§5: 32).
388    #[serde(default = "default_max_conversations_per_connection")]
389    pub max_conversations_per_connection: usize,
390    /// In-flight server→client correlated pushes per connection (§5: 32).
391    #[serde(default = "default_max_pending_pushes_per_connection")]
392    pub max_pending_pushes_per_connection: usize,
393    /// Entries in the per-connection pending-reply table (§1.2(3b)/§5: 32 —
394    /// distinct from server-push slots).
395    #[serde(default = "default_max_pending_conversation_replies_per_connection")]
396    pub max_pending_conversation_replies_per_connection: usize,
397    /// Per-conversation sub-cap that confines tombstone ambiguity to its own
398    /// conversation (§1.2(3b)/§5: 8). Pending entries count against BOTH this and
399    /// the connection table; tombstones against THIS alone.
400    #[serde(default = "default_max_pending_replies_per_conversation")]
401    pub max_pending_replies_per_conversation: usize,
402    /// One shared inbox-byte budget per connection, spent across ALL its
403    /// subscription inboxes (§5: 4 MiB — deliberately mirroring the outbound 4 MiB
404    /// bound). Accounting unit: serialized envelope bytes as admitted, charged at
405    /// enqueue and released at dequeue.
406    #[serde(default = "default_max_connection_inbox_bytes")]
407    pub max_connection_inbox_bytes: usize,
408    /// One outbound byte buffer per connection, holding every server-originated
409    /// frame (acks, errors, `Push`, `Deliver`, `Disconnect`, `Pong`) until the
410    /// connection's scheduler slice drains it to the socket.
411    ///
412    /// This is a DELIVERY bound, not a fairness one: a single frame larger than
413    /// the whole buffer can never be queued, so this value is the largest frame
414    /// the server can send on one connection. Raising it raises that ceiling at
415    /// the cost of per-connection memory; lowering it lowers the ceiling for
416    /// every connection at once.
417    #[serde(default = "default_max_connection_outbound_bytes")]
418    pub max_connection_outbound_bytes: usize,
419    /// Per-inbox envelope-count secondary fairness trip — stops one subscription
420    /// starving its siblings inside the shared byte budget. See
421    /// [`LimitsConfig::DEFAULT_MAX_SUBSCRIPTION_INBOX_DEPTH`] for why the default
422    /// is what it is; the short version is that this cap is the CRUDE bound and
423    /// [`LimitsConfig::max_connection_inbox_bytes`] is the real one.
424    #[serde(default = "default_max_subscription_inbox_depth")]
425    pub max_subscription_inbox_depth: usize,
426    /// Per-slice cap on `Deliver` frames one connection may enqueue across all of
427    /// its subscriptions, before the scheduler moves on to its peers.
428    ///
429    /// Operator-visible because P0 #55 proved it decides whether a subscriber
430    /// behind a burst survives — but see
431    /// [`LimitsConfig::DEFAULT_DELIVERY_SLICE_BUDGET`] for why the DEFAULT is not
432    /// raised. Raising it trades one starvation for another, and the measurement
433    /// that showed it moves the outcome could not see the starvation it causes.
434    #[serde(default = "default_delivery_slice_budget")]
435    pub delivery_slice_budget: usize,
436    /// Runtime-registered channels this deployment admits.
437    ///
438    /// # Why this cap departs the uniform pattern
439    ///
440    /// Every other field here carries `#[serde(default = "…")]` naming a §5
441    /// constant, because each of those numbers is a signed §5 bound. **There is
442    /// no signed §5 bound for channel count**, and inventing one is barred: a
443    /// number nobody certified, presented in the same shape as eight numbers
444    /// somebody did, is a forged citation. So the type is `Option<usize>` and
445    /// the serde default is the ABSENCE itself (`None`), never a value —
446    /// `#[serde(default)]` here resolves a missing key to "no bound declared",
447    /// which is a different statement from any number.
448    ///
449    /// Nor may this be a `usize` with a large default: unbounded-by-default is
450    /// not a bound, it is the gap wearing a number.
451    ///
452    /// `None` refuses every runtime channel registration with a typed error
453    /// naming this key, so a deployment that wants runtime registration declares
454    /// its own bound and a deployment that never registers needs no config
455    /// change at all. The cap bounds RUNTIME-registered channels only:
456    /// `[[channels]]` entries are the bound the operator already wrote.
457    ///
458    /// `Some(0)` is a validation error like every other zero cap here — see
459    /// [`LimitsConfig::collect_errors`].
460    #[serde(default)]
461    pub max_channels: Option<usize>,
462    /// How long a client's correlated conversation request waits for its reply
463    /// before the server answers it timed out, in milliseconds (default 5,000).
464    /// A zero would time every request out on its first slice.
465    #[serde(default = "default_reply_timeout_ms")]
466    pub reply_timeout_ms: u64,
467}
468
469impl LimitsConfig {
470    /// §5 default: total live connections before the listener refuses.
471    pub const DEFAULT_MAX_CONNECTIONS: usize = 256;
472    /// §5 default: subscriptions per connection.
473    pub const DEFAULT_MAX_SUBSCRIPTIONS_PER_CONNECTION: usize = 32;
474    /// §5 default: open conversations per connection.
475    pub const DEFAULT_MAX_CONVERSATIONS_PER_CONNECTION: usize = 32;
476    /// §5 default: in-flight server pushes per connection.
477    pub const DEFAULT_MAX_PENDING_PUSHES_PER_CONNECTION: usize = 32;
478    /// §5 default: pending-reply table entries per connection.
479    pub const DEFAULT_MAX_PENDING_CONVERSATION_REPLIES_PER_CONNECTION: usize = 32;
480    /// §5 default: per-conversation pending-reply sub-cap.
481    pub const DEFAULT_MAX_PENDING_REPLIES_PER_CONVERSATION: usize = 8;
482    /// §5 default: shared per-connection inbox byte budget (4 MiB).
483    pub const DEFAULT_MAX_CONNECTION_INBOX_BYTES: usize = 4 * 1024 * 1024;
484    /// Default per-connection OUTBOUND byte budget (4 MiB) — the twin the inbound
485    /// budget was always described as mirroring, now declared in its own right.
486    ///
487    /// It is the honest single-frame delivery bound: a frame up to this size is
488    /// delivered intact across as many scheduler slices as the peer's read rate
489    /// needs, and a frame LARGER than the whole buffer can never be queued at all.
490    /// The number is unchanged from the buffer's former private constant; what
491    /// changes is that an operator can now see it and set it, instead of meeting
492    /// it only as a connection that stopped carrying something.
493    pub const DEFAULT_MAX_CONNECTION_OUTBOUND_BYTES: usize = 4 * 1024 * 1024;
494    /// Default per-inbox envelope-count fairness trip.
495    ///
496    /// # Why 4096 and not the §5-era 256 (P0 #55)
497    ///
498    /// A subscription inbox is bounded TWICE: by
499    /// [`Self::DEFAULT_MAX_CONNECTION_INBOX_BYTES`] (4 MiB, shared across all of
500    /// one connection's inboxes) and by this envelope COUNT. Memory is the real
501    /// resource, so the byte budget is the bound that should bind and this one is
502    /// meant to be a fairness backstop behind it.
503    ///
504    /// Which one binds first is decided by record size. For a connection holding a
505    /// single subscription, the crossover — the record size at which the two caps
506    /// trip together — is `4 MiB / depth`:
507    ///
508    /// | depth | crossover record size  | binds first for a 1 KiB record |
509    /// |-------|------------------------|--------------------------------|
510    /// | 256   | 4194304/256 = 16 KiB   | the COUNT (at 256 KiB, 6% of 4 MiB) |
511    /// | 4096  | 4194304/4096 = 1 KiB   | the BYTES (as intended)        |
512    ///
513    /// At 256 the count cap therefore binds for every record smaller than 16 KiB —
514    /// which is nearly all real traffic — and it binds at a small fraction of the
515    /// memory the connection is actually permitted: at a 164-byte record, 256
516    /// envelopes is 41 KiB, ~1% of the 4 MiB budget. A replay burst is thousands of
517    /// SMALL records, which is precisely the shape that hits the crude bound while
518    /// the real bound sits untouched. That is the P0: a live subscriber shed for
519    /// exceeding a fairness trip it reached at 1% of its memory allowance.
520    ///
521    /// At 4096 the crossover falls to 1 KiB, so bytes bind for realistic records
522    /// and this cap returns to backstop duty.
523    ///
524    /// Honest bound on that arithmetic: the byte budget is per CONNECTION and this
525    /// cap is per SUBSCRIPTION, so with `S` subscriptions sharing one connection
526    /// the effective crossover is `4 MiB / S / depth`. The table above is the `S=1`
527    /// case. A connection holding many subscriptions of small records can still
528    /// reach the count cap first — which is exactly the sibling-starvation case
529    /// this cap exists to catch.
530    pub const DEFAULT_MAX_SUBSCRIPTION_INBOX_DEPTH: usize = 4096;
531    /// Default per-slice `Deliver` budget for one connection — the source of truth
532    /// for [`crate::config::LimitsConfig::delivery_slice_budget`] and for the
533    /// delivery pump's own `DELIVERY_SLICE_BUDGET`.
534    ///
535    /// # Why this is NOT raised (P0 #55)
536    ///
537    /// This is the cross-connection FAIRNESS bound: it caps how long one connection
538    /// may hold a shared scheduler thread before its peers get a turn. Raising it
539    /// makes a burst subscriber's own drain finish in fewer scheduling round trips,
540    /// and the P0 #55 2x2 measured exactly that — 0/192 boots lost a subscriber at
541    /// 256 against roughly half of them at 32.
542    ///
543    /// That experiment does not license raising the default. It ran two or three
544    /// connections, so the peer starvation a raise would CAUSE was unobservable BY
545    /// CONSTRUCTION: with no queue of waiting peers there is nothing for a longer
546    /// slice to delay. What was measured is that this knob moves the outcome, not
547    /// that moving it is safe.
548    ///
549    /// So the number stays 32 and becomes an operator DECISION instead: a
550    /// deployment that knows its connection count and its burst shape can raise it
551    /// deliberately. The default does not make that trade on anyone's behalf.
552    /// The P0's actual fix is [`Self::DEFAULT_MAX_SUBSCRIPTION_INBOX_DEPTH`].
553    pub const DEFAULT_DELIVERY_SLICE_BUDGET: usize = 32;
554    /// Default wait for a correlated conversation reply: 5 s, the bound a
555    /// client has always been answered within.
556    pub const DEFAULT_REPLY_TIMEOUT_MS: u64 = 5_000;
557
558    /// Validates the caps: every value must be non-zero (a zero cap gates nothing
559    /// — the unlimited-by-silence state §5 outlaws). Errors are accumulated into
560    /// `errors` (one per offending field) so an operator sees every bad cap at
561    /// once, matching the rest of config validation.
562    pub(crate) fn collect_errors(&self, errors: &mut Vec<String>) {
563        let checks: [(&str, usize); 10] = [
564            ("max_connections", self.max_connections),
565            (
566                "max_subscriptions_per_connection",
567                self.max_subscriptions_per_connection,
568            ),
569            (
570                "max_conversations_per_connection",
571                self.max_conversations_per_connection,
572            ),
573            (
574                "max_pending_pushes_per_connection",
575                self.max_pending_pushes_per_connection,
576            ),
577            (
578                "max_pending_conversation_replies_per_connection",
579                self.max_pending_conversation_replies_per_connection,
580            ),
581            (
582                "max_pending_replies_per_conversation",
583                self.max_pending_replies_per_conversation,
584            ),
585            (
586                "max_connection_inbox_bytes",
587                self.max_connection_inbox_bytes,
588            ),
589            // A zero here would leave a connection unable to queue ANY frame at
590            // all — every push and every delivery refused on its first byte.
591            (
592                "max_connection_outbound_bytes",
593                self.max_connection_outbound_bytes,
594            ),
595            (
596                "max_subscription_inbox_depth",
597                self.max_subscription_inbox_depth,
598            ),
599            // A zero here would make the delivery pump enqueue nothing on any
600            // slice — every subscription silently stalled forever, which is the
601            // unlimited-by-silence failure wearing the opposite sign.
602            ("delivery_slice_budget", self.delivery_slice_budget),
603        ];
604        for (field, value) in checks {
605            if value == 0 {
606                errors.push(zero_cap_error(field));
607            }
608        }
609        // `max_channels` is checked BESIDE the array rather than inside it,
610        // because it is the one optional cap and the array's element type has no
611        // way to say "absent". Forcing it in would need a stand-in value for
612        // `None` — a number standing where a declaration is not — and any
613        // stand-in would either invent a bound or make an undeclared cap look
614        // declared. So the shape stays honest and the RULE stays uniform: a
615        // declared zero is refused with the same message as the other eight.
616        //
617        // The parenthetical about unlimited-by-silence is the other eight caps'
618        // ground; for this one a zero would refuse every registration rather
619        // than admit every registration. The message is kept identical anyway:
620        // an operator reading nine cap errors should learn one rule — zero is
621        // not a legal cap value anywhere in this section — not two.
622        if self.max_channels == Some(0) {
623            errors.push(zero_cap_error("max_channels"));
624        }
625        // A duration, not a count, so it sits beside the array too; zero is
626        // refused by the same rule.
627        if self.reply_timeout_ms == 0 {
628            errors.push(zero_cap_error("reply_timeout_ms"));
629        }
630    }
631}
632
633/// The typed refusal for a zero-valued cap, shared by every field in `[limits]`
634/// so the wording cannot drift between them.
635fn zero_cap_error(field: &str) -> String {
636    format!(
637        "limits.{field}: must be greater than zero (a zero cap would be \
638         unlimited-by-silence, which §5 forbids)"
639    )
640}
641
642impl Default for LimitsConfig {
643    fn default() -> Self {
644        Self {
645            max_connections: default_max_connections(),
646            max_subscriptions_per_connection: default_max_subscriptions_per_connection(),
647            max_conversations_per_connection: default_max_conversations_per_connection(),
648            max_pending_pushes_per_connection: default_max_pending_pushes_per_connection(),
649            max_pending_conversation_replies_per_connection:
650                default_max_pending_conversation_replies_per_connection(),
651            max_pending_replies_per_conversation: default_max_pending_replies_per_conversation(),
652            max_connection_inbox_bytes: default_max_connection_inbox_bytes(),
653            max_connection_outbound_bytes: default_max_connection_outbound_bytes(),
654            max_subscription_inbox_depth: default_max_subscription_inbox_depth(),
655            delivery_slice_budget: default_delivery_slice_budget(),
656            // No signed bound exists for this cap, so the default is the
657            // absence of a declaration — never a number.
658            max_channels: None,
659            reply_timeout_ms: default_reply_timeout_ms(),
660        }
661    }
662}
663
664const fn default_max_connections() -> usize {
665    LimitsConfig::DEFAULT_MAX_CONNECTIONS
666}
667const fn default_max_subscriptions_per_connection() -> usize {
668    LimitsConfig::DEFAULT_MAX_SUBSCRIPTIONS_PER_CONNECTION
669}
670const fn default_max_conversations_per_connection() -> usize {
671    LimitsConfig::DEFAULT_MAX_CONVERSATIONS_PER_CONNECTION
672}
673const fn default_max_pending_pushes_per_connection() -> usize {
674    LimitsConfig::DEFAULT_MAX_PENDING_PUSHES_PER_CONNECTION
675}
676const fn default_max_pending_conversation_replies_per_connection() -> usize {
677    LimitsConfig::DEFAULT_MAX_PENDING_CONVERSATION_REPLIES_PER_CONNECTION
678}
679const fn default_max_pending_replies_per_conversation() -> usize {
680    LimitsConfig::DEFAULT_MAX_PENDING_REPLIES_PER_CONVERSATION
681}
682const fn default_max_connection_inbox_bytes() -> usize {
683    LimitsConfig::DEFAULT_MAX_CONNECTION_INBOX_BYTES
684}
685const fn default_max_connection_outbound_bytes() -> usize {
686    LimitsConfig::DEFAULT_MAX_CONNECTION_OUTBOUND_BYTES
687}
688const fn default_max_subscription_inbox_depth() -> usize {
689    LimitsConfig::DEFAULT_MAX_SUBSCRIPTION_INBOX_DEPTH
690}
691const fn default_delivery_slice_budget() -> usize {
692    LimitsConfig::DEFAULT_DELIVERY_SLICE_BUDGET
693}
694
695const fn default_reply_timeout_ms() -> u64 {
696    LimitsConfig::DEFAULT_REPLY_TIMEOUT_MS
697}
698
699/// Participant lifecycle configuration (`[participant]`).
700///
701/// Present iff the deployment activates the participant protocol. Every field
702/// is required — serde carries no defaults here, so a missing field fails
703/// config loading with a typed error naming the field, and
704/// [`ParticipantConfig::collect_errors`] rejects semantically impossible
705/// values during the same accumulated validation pass as the rest of the
706/// config. All values are deployment-owner decisions (no assumed defaults).
707///
708/// Every field here is consumed by the live production handler. Frontier and
709/// retention limits are required inputs; there are no deployment defaults.
710#[derive(Debug, Clone, Copy, serde::Deserialize)]
711#[serde(deny_unknown_fields)]
712pub struct ParticipantConfig {
713    /// Complete participant wire-frame limit (`WF`) negotiated with every
714    /// participant-capable connection. Must be at least the protocol's
715    /// minimum complete frame; enforced by the shared codec at service
716    /// construction and pre-checked during config validation.
717    pub wire_frame_limit: u64,
718    /// Secret-bearing attach/enrollment receipt lifetime in milliseconds.
719    pub attach_receipt_ttl_ms: u64,
720    /// Non-secret receipt-provenance lifetime in milliseconds. Must be at
721    /// least `attach_receipt_ttl_ms` (provenance explains the receipt and
722    /// cannot expire first).
723    pub receipt_provenance_ttl_ms: u64,
724    /// Reporting threshold for server-wide live secret-bearing receipts
725    /// (stage-8 shared scope `LiveReceiptServer`).
726    ///
727    /// Lane p0-39: this scope is NOT an admission gate. It is where an honest
728    /// third party would meet a number someone else's churn consumed, and no
729    /// configured refusal is tolerable there — retention is bounded by
730    /// `attach_receipt_ttl_ms` alone. This number is a TRIPWIRE: when
731    /// in-window occupancy reaches it, the server counts the observation and
732    /// warns on the rising edge. Nothing is ever refused because of it.
733    /// Setting it higher than the deployment's plausible steady state is the
734    /// point; a churn storm is what it is meant to disclose.
735    pub live_receipt_server_report_threshold: u64,
736    /// Per-participant WINDOW SIZE for live secret-bearing receipts (stage-8
737    /// scope `LiveReceiptParticipant`).
738    ///
739    /// Lane p0-39: this is a bound on retention, not a refusal threshold. At
740    /// a full window the participant's own oldest live receipt is displaced
741    /// and the new one lands, so a rotation can never be refused by the very
742    /// receipt it is about to end. Occupancy never exceeds this value.
743    pub max_live_attach_receipts_per_participant: u64,
744    /// Reporting threshold for server-wide retained non-secret provenance
745    /// fingerprints (stage-8 shared scope `ProvenanceServer`).
746    ///
747    /// Lane p0-39: a tripwire, never a gate — see
748    /// [`Self::live_receipt_server_report_threshold`]. Retention here is
749    /// bounded by `receipt_provenance_ttl_ms` alone.
750    ///
751    /// Board #37 (ruling 2026-08-12): a fingerprint occupies from the moment
752    /// the client proves it possesses the secret its receipt minted through
753    /// that receipt's own provenance deadline — not from the minting commit.
754    /// A receipt whose delivery was never observed classifies through its
755    /// window but is never counted here, so an enrol-and-crash cycle leaves
756    /// no provenance residue behind it.
757    pub receipt_provenance_server_report_threshold: u64,
758    /// Reporting threshold for per-conversation provenance fingerprints
759    /// (stage-8 shared scope `ProvenanceConversation`). A tripwire, never a
760    /// gate: one participant's churn must not refuse the next participant of
761    /// the same conversation.
762    pub receipt_provenance_per_conversation_report_threshold: u64,
763    /// Per-participant WINDOW SIZE for provenance fingerprints (stage-8 scope
764    /// `ProvenanceParticipant`).
765    ///
766    /// Lane p0-39: the participant's retained fingerprints — one per
767    /// committed rotation, plus its proven enrollment fingerprint — are held
768    /// to this many, oldest displaced first. Per-participant pressure is
769    /// self-inflicted, so the number bounds memory without refusing: the
770    /// (N+1)th honest fingerprint always lands, including on cold replay from
771    /// durable state. Occupancy never exceeds this value.
772    pub max_receipt_provenance_per_participant: u64,
773    /// Server-wide identity-slot limit (the contract's
774    /// `max_retired_identity_slots` server scope): the total number of
775    /// participant identities — live or retired — mintable across ALL
776    /// conversations. Enrollment refuses with server-scope
777    /// `IdentityCapacityExceeded` (tested BEFORE the conversation scope)
778    /// when every slot is reserved.
779    pub max_retired_identity_slots_server: u64,
780    /// Per-CONVERSATION identity limit `I` (the contract's half-open
781    /// `0..=I` bound on permanent participant ordinals — the conversation
782    /// scope of `max_retired_identity_slots`, NOT a per-participant
783    /// reservation). Enrollment assigns monotone participant indices in
784    /// `0..I` within one conversation and refuses with conversation-scope
785    /// `IdentityCapacityExceeded` when occupancy reaches this value; slots
786    /// and ids are never reused. The server-wide companion is
787    /// [`Self::max_retired_identity_slots_server`].
788    pub identity_slots: u64,
789    /// Maximum entries one observer-recovery handshake batch may name.
790    pub observer_recovery_max_entries: u64,
791    /// Semantic conversations one connection may track — the protocol's
792    /// signed connection-conversation limit. Consumed on BOTH of its contract
793    /// paths: the stage-6 capacity gate every conversation-scoped semantic
794    /// operation runs (register row 5641) and the observer-recovery batch
795    /// preflight (register row 5642), over one shared per-connection
796    /// dispatch map.
797    pub max_semantic_conversations_per_connection: u64,
798    /// Maximum canonical entries in one ordinary retained-record row.
799    pub max_ordinary_record_entries: u64,
800    /// Maximum canonical bytes in one ordinary retained-record row.
801    pub max_ordinary_record_bytes: u64,
802    /// Maximum canonical entries in one generated marker row.
803    pub max_generated_marker_entries: u64,
804    /// Maximum canonical bytes in one generated marker row.
805    pub max_generated_marker_bytes: u64,
806    /// Entry component of the mandatory transaction envelope `Q`.
807    pub mandatory_transaction_bound_entries: u64,
808    /// Byte component of the mandatory transaction envelope `Q`.
809    pub mandatory_transaction_bound_bytes: u64,
810    /// Entry component of the full recovery claim `K`.
811    pub full_recovery_claim_entries: u64,
812    /// Byte component of the full recovery claim `K`.
813    pub full_recovery_claim_bytes: u64,
814    /// Total retained durable entry capacity per conversation.
815    pub retained_capacity_entries: u64,
816    /// Total retained canonical-byte capacity per conversation.
817    pub retained_capacity_bytes: u64,
818    /// Maximum retained causal-record rows restored for one conversation.
819    pub max_retained_record_rows: u64,
820    /// `[participant.pruning]` (DUR-018): absent, no conversation row is
821    /// ever cut and the server says so once at start. Present, acknowledged
822    /// rows behind the newest checkpoint are cut, keeping this many.
823    #[serde(default)]
824    pub pruning: Option<PruningConfig>,
825    /// Maximum closure churn cycles in one episode.
826    pub closure_episode_churn_limit: u64,
827}
828
829impl ParticipantConfig {
830    /// Accumulates semantic validation errors for the participant section.
831    ///
832    /// Zero is rejected wherever it would be unlimited-by-silence, gate
833    /// nothing, or violate a protocol precondition; the TTL ordering mirrors
834    /// the protocol's own frozen configuration precedence.
835    pub(crate) fn collect_errors(&self, errors: &mut Vec<String>) {
836        // The receipt/identity block follows the contract's frozen nine-field
837        // validation order: both TTLs, the five receipt/provenance caps, the
838        // server identity limit, then the conversation identity limit.
839        let nonzero: [(&str, u64); 23] = [
840            ("wire_frame_limit", self.wire_frame_limit),
841            ("attach_receipt_ttl_ms", self.attach_receipt_ttl_ms),
842            ("receipt_provenance_ttl_ms", self.receipt_provenance_ttl_ms),
843            (
844                "live_receipt_server_report_threshold",
845                self.live_receipt_server_report_threshold,
846            ),
847            (
848                "max_live_attach_receipts_per_participant",
849                self.max_live_attach_receipts_per_participant,
850            ),
851            (
852                "receipt_provenance_server_report_threshold",
853                self.receipt_provenance_server_report_threshold,
854            ),
855            (
856                "receipt_provenance_per_conversation_report_threshold",
857                self.receipt_provenance_per_conversation_report_threshold,
858            ),
859            (
860                "max_receipt_provenance_per_participant",
861                self.max_receipt_provenance_per_participant,
862            ),
863            (
864                "max_retired_identity_slots_server",
865                self.max_retired_identity_slots_server,
866            ),
867            ("identity_slots", self.identity_slots),
868            (
869                "observer_recovery_max_entries",
870                self.observer_recovery_max_entries,
871            ),
872            (
873                "max_semantic_conversations_per_connection",
874                self.max_semantic_conversations_per_connection,
875            ),
876            (
877                "max_ordinary_record_entries",
878                self.max_ordinary_record_entries,
879            ),
880            ("max_ordinary_record_bytes", self.max_ordinary_record_bytes),
881            (
882                "max_generated_marker_entries",
883                self.max_generated_marker_entries,
884            ),
885            (
886                "max_generated_marker_bytes",
887                self.max_generated_marker_bytes,
888            ),
889            (
890                "mandatory_transaction_bound_entries",
891                self.mandatory_transaction_bound_entries,
892            ),
893            (
894                "mandatory_transaction_bound_bytes",
895                self.mandatory_transaction_bound_bytes,
896            ),
897            (
898                "full_recovery_claim_entries",
899                self.full_recovery_claim_entries,
900            ),
901            ("full_recovery_claim_bytes", self.full_recovery_claim_bytes),
902            ("retained_capacity_entries", self.retained_capacity_entries),
903            ("retained_capacity_bytes", self.retained_capacity_bytes),
904            ("max_retained_record_rows", self.max_retained_record_rows),
905        ];
906        for (field, value) in nonzero {
907            if value == 0 {
908                errors.push(format!("participant.{field}: must be greater than zero"));
909            }
910        }
911        if self.receipt_provenance_ttl_ms < self.attach_receipt_ttl_ms {
912            errors.push(
913                "participant.receipt_provenance_ttl_ms: must be at least \
914                 attach_receipt_ttl_ms (provenance cannot expire before the receipt it explains)"
915                    .to_owned(),
916            );
917        }
918        if self.full_recovery_claim_entries != self.mandatory_transaction_bound_entries {
919            errors.push(
920                "participant.full_recovery_claim_entries: must equal \
921                 mandatory_transaction_bound_entries"
922                    .to_owned(),
923            );
924        }
925        if self.full_recovery_claim_bytes != self.mandatory_transaction_bound_bytes {
926            errors.push(
927                "participant.full_recovery_claim_bytes: must equal \
928                 mandatory_transaction_bound_bytes"
929                    .to_owned(),
930            );
931        }
932        if !(2..=u64::from(u32::MAX)).contains(&self.closure_episode_churn_limit) {
933            errors.push(
934                "participant.closure_episode_churn_limit: must be in 2..=u32::MAX".to_owned(),
935            );
936        }
937        self.collect_unit2_derived_errors(errors);
938    }
939
940    fn collect_unit2_derived_errors(&self, errors: &mut Vec<String>) {
941        if self
942            .max_retained_record_rows
943            .checked_mul(self.identity_slots)
944            .is_none()
945        {
946            errors.push("participant.UNIT2_MAX_LIVE_RECIPIENT_OBLIGATIONS: max_retained_record_rows * identity_slots overflows u64".to_owned());
947        }
948    }
949}
950
951/// Which connection-services adapter the server constructs (D2).
952#[derive(Debug, Clone, Copy, PartialEq, Eq)]
953pub enum ServiceProfile {
954    /// Full channel/conversation/durability services — the default. Constructs the
955    /// haematite store, channel supervisor, conversation supervisor, and dedup
956    /// cache exactly as before.
957    Full,
958    /// Capability-scoped worker front door: the connection supervisor only, with no
959    /// channel/conversation/haematite machinery. Backs worker registration,
960    /// correlated push/reply, and notifier-consumed reserved publishes; ordinary
961    /// channel and conversation frames are rejected with a typed error frame.
962    WorkerFrontDoor,
963}
964
965impl ServiceProfile {
966    /// Config value selecting the full-service profile.
967    pub const FULL: &'static str = "full";
968    /// Config value selecting the worker-front-door profile.
969    pub const WORKER_FRONT_DOOR: &'static str = "worker-front-door";
970
971    /// Parses a `[services] profile` value into a typed profile.
972    ///
973    /// # Errors
974    /// Returns [`ServerError::ConfigValidation`] for any value other than
975    /// [`Self::FULL`] or [`Self::WORKER_FRONT_DOOR`].
976    pub fn parse(value: &str) -> Result<Self, ServerError> {
977        match value {
978            Self::FULL => Ok(Self::Full),
979            Self::WORKER_FRONT_DOOR => Ok(Self::WorkerFrontDoor),
980            other => Err(ServerError::ConfigValidation {
981                message: format!(
982                    "services.profile: unknown profile '{other}'; expected \"{}\" or \"{}\"",
983                    Self::FULL,
984                    Self::WORKER_FRONT_DOOR
985                ),
986            }),
987        }
988    }
989}
990
991/// `[auth.lys]`: the Lys issuer whose passes are admitted (ACCESS-001 R2).
992#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
993#[serde(deny_unknown_fields)]
994pub struct LysConfig {
995    /// The issuer URL exactly as the pass's `iss` names it.
996    pub issuer: String,
997    /// The Lys network liminal's subjects are placed under.
998    pub network_id: String,
999    /// Path to the issuer's published key set as JSON, read once at start.
1000    pub keys_path: std::path::PathBuf,
1001    /// Ask the issuer live for deliberate decisions (opening a link,
1002    /// deploying a service, an administrator's act) with the holder's own
1003    /// pass. Off, Lys cannot be asked and every deliberate route refuses by
1004    /// that name; it never falls back to the pass.
1005    #[serde(default)]
1006    pub live: bool,
1007    /// This liminal as a machine Lys knows, for links (ACCESS-002 R1).
1008    #[serde(default)]
1009    pub machine: Option<MachineConfig>,
1010    /// Argus's functions as liminal services, bound to Lys and the server's
1011    /// publish path (ACCESS-003 R1).
1012    #[serde(default)]
1013    pub services: Option<LysServicesConfig>,
1014    /// Channel membership from Lys's one shared membership contract
1015    /// (ACCESS-006 R1): the explicit product mapping of liminal channels to
1016    /// placed Lys resources, and the provider route it is asked through.
1017    /// Absent, no channel is membership-protected and every channel keeps
1018    /// its prior contract.
1019    #[serde(default)]
1020    pub membership: Option<MembershipConfig>,
1021}
1022
1023/// `[auth.lys.membership]`: channel membership bound to the verified holder
1024/// and the placed resource (ACCESS-006 R1).
1025///
1026/// The mapping is explicit: a channel is membership-protected only when it is
1027/// listed here with its workspace and placed resource, and a participant
1028/// conversation is placed under a channel only when it is listed here. No
1029/// mapping is guessed from a subject string, and a readable parent is never
1030/// taken as membership of a child. Every bound is required and positive;
1031/// none has a default. Validated whole when the membership gate is built at
1032/// start ([`crate::auth_membership::MembershipGate::new`]).
1033#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
1034#[serde(deny_unknown_fields)]
1035pub struct MembershipConfig {
1036    /// The membership contract version this liminal speaks; it must equal
1037    /// `lys_pass::membership::CONTRACT_VERSION`.
1038    pub contract: u32,
1039    /// The identity of the Lys grant log decisions are asked from.
1040    pub log_identity: String,
1041    /// The reset epoch of that grant log.
1042    pub log_epoch: u64,
1043    /// The product schema's workspace kind, as Lys places it.
1044    pub workspace_kind: String,
1045    /// The product schema's channel kind, as Lys places it.
1046    pub channel_kind: String,
1047    /// Path to this liminal's app credential for the Lys membership routes,
1048    /// read once at start. Its bytes never appear in a `Debug`.
1049    pub credential_path: std::path::PathBuf,
1050    /// Most rows one membership page carries; positive.
1051    pub page_rows: u32,
1052    /// Most encoded bytes one membership page carries; positive.
1053    pub page_bytes: u32,
1054    /// Most decisions the local membership index retains at once; positive.
1055    /// A decision past it is refused by name before anything is allocated
1056    /// for it, never evicted to make room.
1057    pub max_decisions: usize,
1058    /// The workspace a Lys-admitted `Connect` must hold a current grant in
1059    /// (scoped guest admission). Absent, `Connect` asks no admission and a
1060    /// protected channel is still decided per act.
1061    #[serde(default)]
1062    pub connect_workspace: Option<String>,
1063    /// The membership-protected channels.
1064    pub channels: Vec<MembershipChannelConfig>,
1065    /// Participant conversations placed under a protected channel.
1066    #[serde(default)]
1067    pub conversations: Vec<MembershipConversationConfig>,
1068}
1069
1070/// One membership-protected channel: the liminal channel name, the
1071/// workspace it is placed under and the placed resource id.
1072#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
1073#[serde(deny_unknown_fields)]
1074pub struct MembershipChannelConfig {
1075    /// The liminal channel (subject) name, matched exactly.
1076    pub channel: String,
1077    /// The workspace resource id the channel is placed under.
1078    pub workspace: String,
1079    /// The placed channel resource id.
1080    pub resource: String,
1081}
1082
1083/// One participant conversation placed under a protected channel.
1084#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
1085#[serde(deny_unknown_fields)]
1086pub struct MembershipConversationConfig {
1087    /// The participant conversation id.
1088    pub conversation: u64,
1089    /// The protected channel it is placed under, as listed in `channels`.
1090    pub channel: String,
1091}
1092
1093/// `[auth.lys.services]`: the production bindings of the ACCESS-003
1094/// services. They ask Lys as this machine, so `[auth.lys.machine]` is
1095/// required beside it.
1096#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
1097#[serde(deny_unknown_fields)]
1098pub struct LysServicesConfig {
1099    /// The machine id Lys records, on whose runner `seats.<name>` starts.
1100    pub machine: String,
1101    /// The host name service messages are published as (`liminal.<host>`).
1102    pub host: String,
1103    /// Run the context watch over the `context-watch` channel, reporting
1104    /// each reading to Lys.
1105    #[serde(default)]
1106    pub context_watch: bool,
1107}
1108
1109/// `[auth.lys.machine]`: this liminal as a machine Lys knows (ACCESS-002
1110/// R1).
1111///
1112/// Its links are keyed from the Ed25519 identity Lys recorded for it,
1113/// its own end of every crossing is decided from its own pass, and the
1114/// holders that may open links to it are named with the machine keys Lys
1115/// recorded for them.
1116#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
1117#[serde(deny_unknown_fields)]
1118pub struct MachineConfig {
1119    /// Path to this machine's Ed25519 seed, 64 hexadecimal digits, read once
1120    /// at start. The link handshake keys from its X25519 derivation.
1121    pub identity_path: std::path::PathBuf,
1122    /// Path to this machine's own Lys pass, verified at start like any
1123    /// other; its `link_export` and `link_import` rights decide this end.
1124    pub pass_path: std::path::PathBuf,
1125    /// The machine key Lys recorded for each holder that may open a link,
1126    /// holder id to Ed25519 public key as 64 hexadecimal digits.
1127    #[serde(default)]
1128    pub machines: std::collections::BTreeMap<String, String>,
1129}
1130
1131/// `[participant.pruning]`: the one bound pruning has (DUR-018 R1). It is a
1132/// bound on acknowledged rows behind a checkpoint, never on a conversation
1133/// log's row count or age.
1134#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize)]
1135#[serde(deny_unknown_fields)]
1136pub struct PruningConfig {
1137    /// Acknowledged rows kept behind the newest checkpoint; everything
1138    /// acknowledged below them is cut, once a receipt is written.
1139    pub keep_acknowledged_behind_checkpoint: u64,
1140}