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    /// Maximum time to allow existing connections to drain during graceful shutdown.
16    pub drain_timeout_ms: u64,
17    /// Channel topology definitions declared by the operator.
18    pub channels: Vec<ChannelDef>,
19    /// Declarative routing rules that connect configured channels.
20    pub routing_rules: Vec<RoutingRuleDef>,
21    /// Optional filesystem location for durable server state.
22    ///
23    /// A fresh boot surfaces `ConfigValidation` unless this path's PARENT
24    /// directory already exists: the haematite engine creates the store dir
25    /// exactly one level below a pre-existing parent it can fence (never
26    /// `create_dir_all` — deliberate upstream hardening). Create the parent;
27    /// the engine fences into it.
28    pub persistence_path: Option<PathBuf>,
29    /// Optional beamr distribution cluster membership configuration.
30    pub cluster: Option<ClusterConfig>,
31    /// Optional connection authentication configuration.
32    ///
33    /// When present, every client `Connect` handshake must carry a matching
34    /// `auth_token`; when absent the server is open (byte-identical to the
35    /// pre-auth behaviour). Not an ACL system — a single shared bearer token.
36    #[serde(default)]
37    pub auth: Option<AuthConfig>,
38    /// Service construction profile. Absent `[services]` (or an absent `profile`
39    /// key within it) defaults to `"full"`, so existing deployments build exactly
40    /// what they build today.
41    #[serde(default)]
42    pub services: ServicesConfig,
43    /// Operational bounds (§5). Absent `[limits]` (or any absent key within it)
44    /// defaults to the certifying-pair-signed numbers, so an operator who sets
45    /// nothing still runs bounded — "unlimited-by-silence is no longer a legal
46    /// state" (§5). Every value is a hard cap enforced by a typed refusal; a
47    /// zero (or otherwise invalid) value is a config validation error, never a
48    /// silent "unlimited".
49    #[serde(default)]
50    pub limits: LimitsConfig,
51    /// Optional WebSocket transport acceptor (LP-WS-TRANSPORT R1).
52    ///
53    /// When present the server binds a sibling WebSocket listener carrying the
54    /// canonical liminal wire protocol (one binary message per canonical frame)
55    /// alongside the main TCP listener. When absent NO HTTP/WebSocket listener
56    /// is started and the server behaves byte-identically to the pre-WebSocket
57    /// build. Every field inside is a deployment decision; the origin allow-list
58    /// FAILS CLOSED (an absent or empty list refuses every Origin-bearing
59    /// upgrade) and the keepalive ping interval is disabled unless explicitly
60    /// configured.
61    #[serde(default)]
62    pub websocket: Option<WebSocketConfig>,
63    /// Participant lifecycle activation (LP gap closure, Part B).
64    ///
65    /// When present the server installs the production participant semantic
66    /// handler and advertises the participant capability bit on every
67    /// connection. Every field inside is REQUIRED and carries NO default:
68    /// participant lifecycle values are deployment decisions, and an absent
69    /// field is a typed startup error rather than an assumed number. When the
70    /// section is absent the participant capability stays disabled and the
71    /// server behaves byte-identically to the pre-activation build.
72    #[serde(default)]
73    pub participant: Option<ParticipantConfig>,
74}
75
76impl ServerConfig {
77    /// Returns the configured graceful-shutdown drain timeout.
78    #[must_use]
79    pub const fn drain_timeout(&self) -> Duration {
80        Duration::from_millis(self.drain_timeout_ms)
81    }
82}
83
84/// Declarative channel definition loaded from server configuration.
85#[derive(Debug, Clone, serde::Deserialize)]
86#[serde(deny_unknown_fields)]
87pub struct ChannelDef {
88    /// Unique channel name used by routing rules and operators.
89    pub name: String,
90    /// Filesystem path to a JSON Schema document that validates every message
91    /// published to this channel.
92    ///
93    /// The path is resolved relative to the directory containing the config file
94    /// (absolute paths are used verbatim). Config validation reads and parses the
95    /// referenced document and stores the result in [`Self::loaded_schema`]; a
96    /// missing file, an unreadable file, or a file that is not valid JSON is an
97    /// accumulated validation error that stops startup.
98    ///
99    /// `None` means the channel has no schema: it keeps the permissive empty
100    /// schema (`{}`) that accepts any JSON payload.
101    #[serde(default)]
102    pub schema_ref: Option<PathBuf>,
103    /// Whether this channel requires durable persistence.
104    pub durable: bool,
105    /// Schema document loaded and parsed from [`Self::schema_ref`] during config
106    /// validation. Populated only by [`crate::config::validate`]; a directly
107    /// constructed [`ChannelDef`] that skips validation carries `None` here and is
108    /// therefore built with the permissive empty schema regardless of
109    /// [`Self::schema_ref`]. Never deserialized from the config file.
110    #[serde(skip)]
111    pub loaded_schema: Option<LoadedSchema>,
112}
113
114/// A channel's JSON Schema document as loaded from disk during config validation.
115///
116/// Carries both the parsed document (fed to the validation engine when the channel
117/// is built) and the raw file bytes (hashed into the protocol schema id advertised
118/// at subscribe time, so an SDK deriving ids from the same schema bytes converges).
119#[derive(Debug, Clone)]
120pub struct LoadedSchema {
121    /// Raw bytes of the schema file, hashed to derive the protocol schema id.
122    pub bytes: Vec<u8>,
123    /// Parsed JSON Schema document, fed to the channel's validation engine.
124    pub document: serde_json::Value,
125}
126
127/// Declarative routing rule definition loaded from server configuration.
128#[derive(Debug, Clone, serde::Deserialize)]
129#[serde(deny_unknown_fields)]
130pub struct RoutingRuleDef {
131    /// Source channel name from which messages are routed.
132    pub source_channel: String,
133    /// Target channel name to which matching messages are routed.
134    pub target_channel: String,
135    /// Optional predicate expression that filters routed messages.
136    pub predicate: Option<String>,
137}
138
139/// Default beamr distribution handshake cookie, used when the operator does not
140/// configure one. Mirrors beamr's own [`beamr::distribution::DEFAULT_COOKIE`].
141pub const DEFAULT_COOKIE: &str = "beamr-cookie";
142
143/// Beamr distribution cluster configuration for standalone deployment.
144#[derive(Debug, Clone, serde::Deserialize)]
145#[serde(deny_unknown_fields)]
146pub struct ClusterConfig {
147    /// Unique node name advertised to the beamr distribution cluster.
148    pub node_name: String,
149    /// Socket address this node binds for inbound distribution links from peers.
150    ///
151    /// This is distinct from [`ServerConfig::listen_address`] (the client wire
152    /// port): a clustered node listens on two ports — one for clients, one for
153    /// peer distribution traffic.
154    pub listen_address: SocketAddr,
155    /// Seed node socket addresses used to join an existing cluster.
156    pub seed_nodes: Vec<SocketAddr>,
157    /// Shared distribution handshake cookie. Every node in a cluster MUST use the
158    /// same cookie or the OTP handshake is rejected. Defaults to
159    /// [`DEFAULT_COOKIE`] when omitted.
160    #[serde(default = "default_cookie")]
161    pub cookie: String,
162}
163
164fn default_cookie() -> String {
165    DEFAULT_COOKIE.to_owned()
166}
167
168/// Connection authentication configuration.
169///
170/// A single shared bearer token compared (constant-time) against the `auth_token`
171/// carried on every client `Connect` handshake. This is the table-stakes access
172/// gate, not an ACL system: one token grants full access, its absence (no `[auth]`
173/// section) leaves the server open.
174#[derive(Debug, Clone, serde::Deserialize)]
175#[serde(deny_unknown_fields)]
176pub struct AuthConfig {
177    /// Shared secret token a client must present in its `Connect` handshake. Must
178    /// be non-empty when the `[auth]` section is present (an empty token is a
179    /// config validation error, since it would gate nothing).
180    pub token: String,
181}
182
183/// WebSocket transport acceptor configuration (`[websocket]`, LP-WS-TRANSPORT R1).
184///
185/// The sibling WebSocket route is an explicit opt-in: the section itself must be
186/// present for any HTTP/WebSocket listener to start, and inside it the listen
187/// address and the single exact upgrade path are required with no defaults.
188///
189/// The deployment TLS contract (tear ruling Q1) is raw `ws://` behind a named
190/// TLS-terminating proxy that owns public `wss://` and certificates; liminal
191/// grows no TLS stack. Origin validation nonetheless belongs to this acceptor:
192/// [`Self::allowed_origins`] is the explicit allow-list checked on every
193/// Origin-bearing upgrade, and there is NO default list — absent or empty
194/// configuration fails closed for browser-origin upgrades while a native client
195/// that sends no `Origin` header may still upgrade (F6).
196///
197/// OPERATOR NOTE — the same deployment contract covers the pre-upgrade window
198/// (domain-owner ruling, 2026-07-18): the fronting proxy must ALSO enforce
199/// pre-upgrade read timeouts, handshake concurrency limits, and connection
200/// rate limits. Between TCP accept and a completed WebSocket upgrade this
201/// listener does not count the socket against `[limits] max_connections` and
202/// applies no read deadline of its own (only the fixed request-head size
203/// bound), so a deployment that exposes this port without the named proxy is
204/// out of contract on untrusted networks. A named handshake read-deadline
205/// config plus an in-flight handshake cap derived from the configured
206/// `max_connections` value is the ledgered post-demo hardening.
207#[derive(Debug, Clone, serde::Deserialize)]
208#[serde(deny_unknown_fields)]
209pub struct WebSocketConfig {
210    /// Socket address the WebSocket acceptor binds. Required; distinct from the
211    /// main wire listener, the health listener, and any cluster listener.
212    pub listen_address: SocketAddr,
213    /// The single exact HTTP request path that accepts WebSocket upgrades.
214    /// Required; must start with `/`. Every other path — and every ordinary
215    /// HTTP request — receives a small fixed non-success response and closes.
216    pub path: String,
217    /// Explicit browser-origin allow-list checked on every Origin-bearing
218    /// upgrade (F6). Entries are compared byte-exact against the request's
219    /// serialized `Origin` header value (RFC 6454 ASCII serialization, e.g.
220    /// `https://app.example.com`). Absent or empty means NO browser origin is
221    /// accepted (fail closed); native clients sending no `Origin` header are
222    /// unaffected.
223    #[serde(default)]
224    pub allowed_origins: Vec<String>,
225    /// Q-A transport-liveness keepalive: the server-side WebSocket Ping
226    /// interval in milliseconds. This is a precise LAW-1 carve-out — liveness
227    /// pings never mint application events, never re-arm application state, and
228    /// never serve as a source of truth; failure detection remains the socket's
229    /// typed terminal events. The bound is one ping per interval per
230    /// connection, so the idle cost is `interval x connection-count`. Absent
231    /// means pings are DISABLED, accepting proxy-idle-disconnect churn as the
232    /// documented consequence. A configured zero is a validation error.
233    #[serde(default)]
234    pub ping_interval_ms: Option<u64>,
235}
236
237/// Service construction profile selection (D2).
238///
239/// The `profile` value is carried as a raw string here rather than a typed enum so
240/// an unrecognised value is a config *validation* error with a helpful message
241/// (via [`Self::profile`]) rather than an opaque deserialization failure — matching
242/// how every other semantic config check surfaces. Absent `profile` defaults to
243/// `"full"`.
244#[derive(Debug, Clone, serde::Deserialize)]
245#[serde(deny_unknown_fields)]
246pub struct ServicesConfig {
247    /// Construction profile: `"full"` (the default, unchanged behaviour) or
248    /// `"worker-front-door"` (capability-scoped worker deployments).
249    #[serde(default = "default_service_profile")]
250    pub profile: String,
251}
252
253impl Default for ServicesConfig {
254    fn default() -> Self {
255        Self {
256            profile: default_service_profile(),
257        }
258    }
259}
260
261impl ServicesConfig {
262    /// Resolves the raw `profile` string into a typed [`ServiceProfile`].
263    ///
264    /// # Errors
265    /// Returns [`ServerError::ConfigValidation`] when the value is not a recognised
266    /// profile.
267    pub fn profile(&self) -> Result<ServiceProfile, ServerError> {
268        ServiceProfile::parse(&self.profile)
269    }
270}
271
272fn default_service_profile() -> String {
273    ServiceProfile::FULL.to_owned()
274}
275
276/// Operational bounds (§5, scout Q4 — rule-2 items).
277///
278/// Each field is a hard per-scope cap with a typed refusal and a
279/// certifying-pair-signed default (the numbers below are §5's). The struct is
280/// the single wire surface for `[limits]`; [`LimitsConfig::validate`] rejects any
281/// zero value as a typed config error (a zero cap would gate nothing — the exact
282/// unlimited-by-silence state §5 outlaws). Defaults come from the `default_*`
283/// free functions so an absent key resolves to the signed number, not zero.
284#[derive(Debug, Clone, Copy, serde::Deserialize)]
285#[serde(deny_unknown_fields)]
286pub struct LimitsConfig {
287    /// Total live connections the listener admits before refusing (§5: 256 — a
288    /// worker-bus, an order of magnitude above any observed fleet).
289    #[serde(default = "default_max_connections")]
290    pub max_connections: usize,
291    /// Subscriptions one connection may hold (§5: 32).
292    #[serde(default = "default_max_subscriptions_per_connection")]
293    pub max_subscriptions_per_connection: usize,
294    /// Open conversations one connection may hold (§5: 32).
295    #[serde(default = "default_max_conversations_per_connection")]
296    pub max_conversations_per_connection: usize,
297    /// In-flight server→client correlated pushes per connection (§5: 32).
298    #[serde(default = "default_max_pending_pushes_per_connection")]
299    pub max_pending_pushes_per_connection: usize,
300    /// Entries in the per-connection pending-reply table (§1.2(3b)/§5: 32 —
301    /// distinct from server-push slots).
302    #[serde(default = "default_max_pending_conversation_replies_per_connection")]
303    pub max_pending_conversation_replies_per_connection: usize,
304    /// Per-conversation sub-cap that confines tombstone ambiguity to its own
305    /// conversation (§1.2(3b)/§5: 8). Pending entries count against BOTH this and
306    /// the connection table; tombstones against THIS alone.
307    #[serde(default = "default_max_pending_replies_per_conversation")]
308    pub max_pending_replies_per_conversation: usize,
309    /// One shared inbox-byte budget per connection, spent across ALL its
310    /// subscription inboxes (§5: 4 MiB — deliberately mirroring the outbound 4 MiB
311    /// bound). Accounting unit: serialized envelope bytes as admitted, charged at
312    /// enqueue and released at dequeue.
313    #[serde(default = "default_max_connection_inbox_bytes")]
314    pub max_connection_inbox_bytes: usize,
315    /// Per-inbox envelope-count secondary fairness trip (§5: 256) — stops one
316    /// subscription starving its siblings inside the shared byte budget; no longer
317    /// load-bearing for the signed bound.
318    #[serde(default = "default_max_subscription_inbox_depth")]
319    pub max_subscription_inbox_depth: usize,
320    /// Runtime-registered channels this deployment admits.
321    ///
322    /// # Why this cap departs the uniform pattern
323    ///
324    /// Every other field here carries `#[serde(default = "…")]` naming a §5
325    /// constant, because each of those numbers is a signed §5 bound. **There is
326    /// no signed §5 bound for channel count**, and inventing one is barred: a
327    /// number nobody certified, presented in the same shape as eight numbers
328    /// somebody did, is a forged citation. So the type is `Option<usize>` and
329    /// the serde default is the ABSENCE itself (`None`), never a value —
330    /// `#[serde(default)]` here resolves a missing key to "no bound declared",
331    /// which is a different statement from any number.
332    ///
333    /// Nor may this be a `usize` with a large default: unbounded-by-default is
334    /// not a bound, it is the gap wearing a number.
335    ///
336    /// `None` refuses every runtime channel registration with a typed error
337    /// naming this key, so a deployment that wants runtime registration declares
338    /// its own bound and a deployment that never registers needs no config
339    /// change at all. The cap bounds RUNTIME-registered channels only:
340    /// `[[channels]]` entries are the bound the operator already wrote.
341    ///
342    /// `Some(0)` is a validation error like every other zero cap here — see
343    /// [`LimitsConfig::collect_errors`].
344    #[serde(default)]
345    pub max_channels: Option<usize>,
346}
347
348impl LimitsConfig {
349    /// §5 default: total live connections before the listener refuses.
350    pub const DEFAULT_MAX_CONNECTIONS: usize = 256;
351    /// §5 default: subscriptions per connection.
352    pub const DEFAULT_MAX_SUBSCRIPTIONS_PER_CONNECTION: usize = 32;
353    /// §5 default: open conversations per connection.
354    pub const DEFAULT_MAX_CONVERSATIONS_PER_CONNECTION: usize = 32;
355    /// §5 default: in-flight server pushes per connection.
356    pub const DEFAULT_MAX_PENDING_PUSHES_PER_CONNECTION: usize = 32;
357    /// §5 default: pending-reply table entries per connection.
358    pub const DEFAULT_MAX_PENDING_CONVERSATION_REPLIES_PER_CONNECTION: usize = 32;
359    /// §5 default: per-conversation pending-reply sub-cap.
360    pub const DEFAULT_MAX_PENDING_REPLIES_PER_CONVERSATION: usize = 8;
361    /// §5 default: shared per-connection inbox byte budget (4 MiB).
362    pub const DEFAULT_MAX_CONNECTION_INBOX_BYTES: usize = 4 * 1024 * 1024;
363    /// §5 default: per-inbox envelope-count fairness trip.
364    pub const DEFAULT_MAX_SUBSCRIPTION_INBOX_DEPTH: usize = 256;
365
366    /// Validates the caps: every value must be non-zero (a zero cap gates nothing
367    /// — the unlimited-by-silence state §5 outlaws). Errors are accumulated into
368    /// `errors` (one per offending field) so an operator sees every bad cap at
369    /// once, matching the rest of config validation.
370    pub(crate) fn collect_errors(&self, errors: &mut Vec<String>) {
371        let checks: [(&str, usize); 8] = [
372            ("max_connections", self.max_connections),
373            (
374                "max_subscriptions_per_connection",
375                self.max_subscriptions_per_connection,
376            ),
377            (
378                "max_conversations_per_connection",
379                self.max_conversations_per_connection,
380            ),
381            (
382                "max_pending_pushes_per_connection",
383                self.max_pending_pushes_per_connection,
384            ),
385            (
386                "max_pending_conversation_replies_per_connection",
387                self.max_pending_conversation_replies_per_connection,
388            ),
389            (
390                "max_pending_replies_per_conversation",
391                self.max_pending_replies_per_conversation,
392            ),
393            (
394                "max_connection_inbox_bytes",
395                self.max_connection_inbox_bytes,
396            ),
397            (
398                "max_subscription_inbox_depth",
399                self.max_subscription_inbox_depth,
400            ),
401        ];
402        for (field, value) in checks {
403            if value == 0 {
404                errors.push(zero_cap_error(field));
405            }
406        }
407        // `max_channels` is checked BESIDE the array rather than inside it,
408        // because it is the one optional cap and the array's element type has no
409        // way to say "absent". Forcing it in would need a stand-in value for
410        // `None` — a number standing where a declaration is not — and any
411        // stand-in would either invent a bound or make an undeclared cap look
412        // declared. So the shape stays honest and the RULE stays uniform: a
413        // declared zero is refused with the same message as the other eight.
414        //
415        // The parenthetical about unlimited-by-silence is the other eight caps'
416        // ground; for this one a zero would refuse every registration rather
417        // than admit every registration. The message is kept identical anyway:
418        // an operator reading nine cap errors should learn one rule — zero is
419        // not a legal cap value anywhere in this section — not two.
420        if self.max_channels == Some(0) {
421            errors.push(zero_cap_error("max_channels"));
422        }
423    }
424}
425
426/// The typed refusal for a zero-valued cap, shared by every field in `[limits]`
427/// so the wording cannot drift between them.
428fn zero_cap_error(field: &str) -> String {
429    format!(
430        "limits.{field}: must be greater than zero (a zero cap would be \
431         unlimited-by-silence, which §5 forbids)"
432    )
433}
434
435impl Default for LimitsConfig {
436    fn default() -> Self {
437        Self {
438            max_connections: default_max_connections(),
439            max_subscriptions_per_connection: default_max_subscriptions_per_connection(),
440            max_conversations_per_connection: default_max_conversations_per_connection(),
441            max_pending_pushes_per_connection: default_max_pending_pushes_per_connection(),
442            max_pending_conversation_replies_per_connection:
443                default_max_pending_conversation_replies_per_connection(),
444            max_pending_replies_per_conversation: default_max_pending_replies_per_conversation(),
445            max_connection_inbox_bytes: default_max_connection_inbox_bytes(),
446            max_subscription_inbox_depth: default_max_subscription_inbox_depth(),
447            // No signed bound exists for this cap, so the default is the
448            // absence of a declaration — never a number.
449            max_channels: None,
450        }
451    }
452}
453
454const fn default_max_connections() -> usize {
455    LimitsConfig::DEFAULT_MAX_CONNECTIONS
456}
457const fn default_max_subscriptions_per_connection() -> usize {
458    LimitsConfig::DEFAULT_MAX_SUBSCRIPTIONS_PER_CONNECTION
459}
460const fn default_max_conversations_per_connection() -> usize {
461    LimitsConfig::DEFAULT_MAX_CONVERSATIONS_PER_CONNECTION
462}
463const fn default_max_pending_pushes_per_connection() -> usize {
464    LimitsConfig::DEFAULT_MAX_PENDING_PUSHES_PER_CONNECTION
465}
466const fn default_max_pending_conversation_replies_per_connection() -> usize {
467    LimitsConfig::DEFAULT_MAX_PENDING_CONVERSATION_REPLIES_PER_CONNECTION
468}
469const fn default_max_pending_replies_per_conversation() -> usize {
470    LimitsConfig::DEFAULT_MAX_PENDING_REPLIES_PER_CONVERSATION
471}
472const fn default_max_connection_inbox_bytes() -> usize {
473    LimitsConfig::DEFAULT_MAX_CONNECTION_INBOX_BYTES
474}
475const fn default_max_subscription_inbox_depth() -> usize {
476    LimitsConfig::DEFAULT_MAX_SUBSCRIPTION_INBOX_DEPTH
477}
478
479/// Participant lifecycle configuration (`[participant]`).
480///
481/// Present iff the deployment activates the participant protocol. Every field
482/// is required — serde carries no defaults here, so a missing field fails
483/// config loading with a typed error naming the field, and
484/// [`ParticipantConfig::collect_errors`] rejects semantically impossible
485/// values during the same accumulated validation pass as the rest of the
486/// config. All values are deployment-owner decisions (no assumed defaults).
487///
488/// Every field here is consumed by the live production handler. Frontier and
489/// retention limits are required inputs; there are no deployment defaults.
490#[derive(Debug, Clone, Copy, serde::Deserialize)]
491#[serde(deny_unknown_fields)]
492pub struct ParticipantConfig {
493    /// Complete participant wire-frame limit (`WF`) negotiated with every
494    /// participant-capable connection. Must be at least the protocol's
495    /// minimum complete frame; enforced by the shared codec at service
496    /// construction and pre-checked during config validation.
497    pub wire_frame_limit: u64,
498    /// Secret-bearing attach/enrollment receipt lifetime in milliseconds.
499    pub attach_receipt_ttl_ms: u64,
500    /// Non-secret receipt-provenance lifetime in milliseconds. Must be at
501    /// least `attach_receipt_ttl_ms` (provenance explains the receipt and
502    /// cannot expire first).
503    pub receipt_provenance_ttl_ms: u64,
504    /// Server-wide cap on live secret-bearing receipts (enrollment and
505    /// credential-attach receipt bodies inside their own receipt windows,
506    /// across every conversation). R-D1 stage-8 scope `LiveReceiptServer`:
507    /// enrollment and credential attach refuse with the typed
508    /// `ReceiptCapacityExceeded` when reserving one more would exceed it.
509    pub max_live_attach_receipts_server: u64,
510    /// Per-participant cap on live secret-bearing receipts (stage-8 scope
511    /// `LiveReceiptParticipant`). A participant holds at most its enrollment
512    /// receipt plus its current attach receipt live at once, so values below
513    /// 3 refuse rotation while the enrollment receipt is still live.
514    pub max_live_attach_receipts_per_participant: u64,
515    /// Server-wide cap on retained non-secret provenance fingerprints
516    /// (stage-8 scope `ProvenanceServer`). A fingerprint exists from its
517    /// operation's commit through its own provenance deadline.
518    pub max_receipt_provenance_server: u64,
519    /// Per-conversation provenance-fingerprint cap (stage-8 scope
520    /// `ProvenanceConversation`).
521    pub max_receipt_provenance_per_conversation: u64,
522    /// Per-participant provenance-fingerprint cap (stage-8 scope
523    /// `ProvenanceParticipant`).
524    pub max_receipt_provenance_per_participant: u64,
525    /// Server-wide identity-slot limit (the contract's
526    /// `max_retired_identity_slots` server scope): the total number of
527    /// participant identities — live or retired — mintable across ALL
528    /// conversations. Enrollment refuses with server-scope
529    /// `IdentityCapacityExceeded` (tested BEFORE the conversation scope)
530    /// when every slot is reserved.
531    pub max_retired_identity_slots_server: u64,
532    /// Per-CONVERSATION identity limit `I` (the contract's half-open
533    /// `0..=I` bound on permanent participant ordinals — the conversation
534    /// scope of `max_retired_identity_slots`, NOT a per-participant
535    /// reservation). Enrollment assigns monotone participant indices in
536    /// `0..I` within one conversation and refuses with conversation-scope
537    /// `IdentityCapacityExceeded` when occupancy reaches this value; slots
538    /// and ids are never reused. The server-wide companion is
539    /// [`Self::max_retired_identity_slots_server`].
540    pub identity_slots: u64,
541    /// Maximum entries one observer-recovery handshake batch may name.
542    pub observer_recovery_max_entries: u64,
543    /// Semantic conversations one connection may track — the protocol's
544    /// signed connection-conversation limit. Consumed on BOTH of its contract
545    /// paths: the stage-6 capacity gate every conversation-scoped semantic
546    /// operation runs (register row 5641) and the observer-recovery batch
547    /// preflight (register row 5642), over one shared per-connection
548    /// dispatch map.
549    pub max_semantic_conversations_per_connection: u64,
550    /// Maximum canonical entries in one ordinary retained-record row.
551    pub max_ordinary_record_entries: u64,
552    /// Maximum canonical bytes in one ordinary retained-record row.
553    pub max_ordinary_record_bytes: u64,
554    /// Maximum canonical entries in one generated marker row.
555    pub max_generated_marker_entries: u64,
556    /// Maximum canonical bytes in one generated marker row.
557    pub max_generated_marker_bytes: u64,
558    /// Entry component of the mandatory transaction envelope `Q`.
559    pub mandatory_transaction_bound_entries: u64,
560    /// Byte component of the mandatory transaction envelope `Q`.
561    pub mandatory_transaction_bound_bytes: u64,
562    /// Entry component of the full recovery claim `K`.
563    pub full_recovery_claim_entries: u64,
564    /// Byte component of the full recovery claim `K`.
565    pub full_recovery_claim_bytes: u64,
566    /// Total retained durable entry capacity per conversation.
567    pub retained_capacity_entries: u64,
568    /// Total retained canonical-byte capacity per conversation.
569    pub retained_capacity_bytes: u64,
570    /// Maximum retained causal-record rows restored for one conversation.
571    pub max_retained_record_rows: u64,
572    /// Maximum closure churn cycles in one episode.
573    pub closure_episode_churn_limit: u64,
574}
575
576impl ParticipantConfig {
577    /// Accumulates semantic validation errors for the participant section.
578    ///
579    /// Zero is rejected wherever it would be unlimited-by-silence, gate
580    /// nothing, or violate a protocol precondition; the TTL ordering mirrors
581    /// the protocol's own frozen configuration precedence.
582    pub(crate) fn collect_errors(&self, errors: &mut Vec<String>) {
583        // The receipt/identity block follows the contract's frozen nine-field
584        // validation order: both TTLs, the five receipt/provenance caps, the
585        // server identity limit, then the conversation identity limit.
586        let nonzero: [(&str, u64); 23] = [
587            ("wire_frame_limit", self.wire_frame_limit),
588            ("attach_receipt_ttl_ms", self.attach_receipt_ttl_ms),
589            ("receipt_provenance_ttl_ms", self.receipt_provenance_ttl_ms),
590            (
591                "max_live_attach_receipts_server",
592                self.max_live_attach_receipts_server,
593            ),
594            (
595                "max_live_attach_receipts_per_participant",
596                self.max_live_attach_receipts_per_participant,
597            ),
598            (
599                "max_receipt_provenance_server",
600                self.max_receipt_provenance_server,
601            ),
602            (
603                "max_receipt_provenance_per_conversation",
604                self.max_receipt_provenance_per_conversation,
605            ),
606            (
607                "max_receipt_provenance_per_participant",
608                self.max_receipt_provenance_per_participant,
609            ),
610            (
611                "max_retired_identity_slots_server",
612                self.max_retired_identity_slots_server,
613            ),
614            ("identity_slots", self.identity_slots),
615            (
616                "observer_recovery_max_entries",
617                self.observer_recovery_max_entries,
618            ),
619            (
620                "max_semantic_conversations_per_connection",
621                self.max_semantic_conversations_per_connection,
622            ),
623            (
624                "max_ordinary_record_entries",
625                self.max_ordinary_record_entries,
626            ),
627            ("max_ordinary_record_bytes", self.max_ordinary_record_bytes),
628            (
629                "max_generated_marker_entries",
630                self.max_generated_marker_entries,
631            ),
632            (
633                "max_generated_marker_bytes",
634                self.max_generated_marker_bytes,
635            ),
636            (
637                "mandatory_transaction_bound_entries",
638                self.mandatory_transaction_bound_entries,
639            ),
640            (
641                "mandatory_transaction_bound_bytes",
642                self.mandatory_transaction_bound_bytes,
643            ),
644            (
645                "full_recovery_claim_entries",
646                self.full_recovery_claim_entries,
647            ),
648            ("full_recovery_claim_bytes", self.full_recovery_claim_bytes),
649            ("retained_capacity_entries", self.retained_capacity_entries),
650            ("retained_capacity_bytes", self.retained_capacity_bytes),
651            ("max_retained_record_rows", self.max_retained_record_rows),
652        ];
653        for (field, value) in nonzero {
654            if value == 0 {
655                errors.push(format!("participant.{field}: must be greater than zero"));
656            }
657        }
658        if self.receipt_provenance_ttl_ms < self.attach_receipt_ttl_ms {
659            errors.push(
660                "participant.receipt_provenance_ttl_ms: must be at least \
661                 attach_receipt_ttl_ms (provenance cannot expire before the receipt it explains)"
662                    .to_owned(),
663            );
664        }
665        if self.full_recovery_claim_entries != self.mandatory_transaction_bound_entries {
666            errors.push(
667                "participant.full_recovery_claim_entries: must equal \
668                 mandatory_transaction_bound_entries"
669                    .to_owned(),
670            );
671        }
672        if self.full_recovery_claim_bytes != self.mandatory_transaction_bound_bytes {
673            errors.push(
674                "participant.full_recovery_claim_bytes: must equal \
675                 mandatory_transaction_bound_bytes"
676                    .to_owned(),
677            );
678        }
679        if !(2..=u64::from(u32::MAX)).contains(&self.closure_episode_churn_limit) {
680            errors.push(
681                "participant.closure_episode_churn_limit: must be in 2..=u32::MAX".to_owned(),
682            );
683        }
684        self.collect_unit2_derived_errors(errors);
685    }
686
687    fn collect_unit2_derived_errors(&self, errors: &mut Vec<String>) {
688        if self
689            .max_retained_record_rows
690            .checked_mul(self.identity_slots)
691            .is_none()
692        {
693            errors.push("participant.UNIT2_MAX_LIVE_RECIPIENT_OBLIGATIONS: max_retained_record_rows * identity_slots overflows u64".to_owned());
694        }
695    }
696}
697
698/// Which connection-services adapter the server constructs (D2).
699#[derive(Debug, Clone, Copy, PartialEq, Eq)]
700pub enum ServiceProfile {
701    /// Full channel/conversation/durability services — the default. Constructs the
702    /// haematite store, channel supervisor, conversation supervisor, and dedup
703    /// cache exactly as before.
704    Full,
705    /// Capability-scoped worker front door: the connection supervisor only, with no
706    /// channel/conversation/haematite machinery. Backs worker registration,
707    /// correlated push/reply, and notifier-consumed reserved publishes; ordinary
708    /// channel and conversation frames are rejected with a typed error frame.
709    WorkerFrontDoor,
710}
711
712impl ServiceProfile {
713    /// Config value selecting the full-service profile.
714    pub const FULL: &'static str = "full";
715    /// Config value selecting the worker-front-door profile.
716    pub const WORKER_FRONT_DOOR: &'static str = "worker-front-door";
717
718    /// Parses a `[services] profile` value into a typed profile.
719    ///
720    /// # Errors
721    /// Returns [`ServerError::ConfigValidation`] for any value other than
722    /// [`Self::FULL`] or [`Self::WORKER_FRONT_DOOR`].
723    pub fn parse(value: &str) -> Result<Self, ServerError> {
724        match value {
725            Self::FULL => Ok(Self::Full),
726            Self::WORKER_FRONT_DOOR => Ok(Self::WorkerFrontDoor),
727            other => Err(ServerError::ConfigValidation {
728                message: format!(
729                    "services.profile: unknown profile '{other}'; expected \"{}\" or \"{}\"",
730                    Self::FULL,
731                    Self::WORKER_FRONT_DOOR
732                ),
733            }),
734        }
735    }
736}