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}
321
322impl LimitsConfig {
323    /// §5 default: total live connections before the listener refuses.
324    pub const DEFAULT_MAX_CONNECTIONS: usize = 256;
325    /// §5 default: subscriptions per connection.
326    pub const DEFAULT_MAX_SUBSCRIPTIONS_PER_CONNECTION: usize = 32;
327    /// §5 default: open conversations per connection.
328    pub const DEFAULT_MAX_CONVERSATIONS_PER_CONNECTION: usize = 32;
329    /// §5 default: in-flight server pushes per connection.
330    pub const DEFAULT_MAX_PENDING_PUSHES_PER_CONNECTION: usize = 32;
331    /// §5 default: pending-reply table entries per connection.
332    pub const DEFAULT_MAX_PENDING_CONVERSATION_REPLIES_PER_CONNECTION: usize = 32;
333    /// §5 default: per-conversation pending-reply sub-cap.
334    pub const DEFAULT_MAX_PENDING_REPLIES_PER_CONVERSATION: usize = 8;
335    /// §5 default: shared per-connection inbox byte budget (4 MiB).
336    pub const DEFAULT_MAX_CONNECTION_INBOX_BYTES: usize = 4 * 1024 * 1024;
337    /// §5 default: per-inbox envelope-count fairness trip.
338    pub const DEFAULT_MAX_SUBSCRIPTION_INBOX_DEPTH: usize = 256;
339
340    /// Validates the caps: every value must be non-zero (a zero cap gates nothing
341    /// — the unlimited-by-silence state §5 outlaws). Errors are accumulated into
342    /// `errors` (one per offending field) so an operator sees every bad cap at
343    /// once, matching the rest of config validation.
344    pub(crate) fn collect_errors(&self, errors: &mut Vec<String>) {
345        let checks: [(&str, usize); 8] = [
346            ("max_connections", self.max_connections),
347            (
348                "max_subscriptions_per_connection",
349                self.max_subscriptions_per_connection,
350            ),
351            (
352                "max_conversations_per_connection",
353                self.max_conversations_per_connection,
354            ),
355            (
356                "max_pending_pushes_per_connection",
357                self.max_pending_pushes_per_connection,
358            ),
359            (
360                "max_pending_conversation_replies_per_connection",
361                self.max_pending_conversation_replies_per_connection,
362            ),
363            (
364                "max_pending_replies_per_conversation",
365                self.max_pending_replies_per_conversation,
366            ),
367            (
368                "max_connection_inbox_bytes",
369                self.max_connection_inbox_bytes,
370            ),
371            (
372                "max_subscription_inbox_depth",
373                self.max_subscription_inbox_depth,
374            ),
375        ];
376        for (field, value) in checks {
377            if value == 0 {
378                errors.push(format!(
379                    "limits.{field}: must be greater than zero (a zero cap would be \
380                     unlimited-by-silence, which §5 forbids)"
381                ));
382            }
383        }
384    }
385}
386
387impl Default for LimitsConfig {
388    fn default() -> Self {
389        Self {
390            max_connections: default_max_connections(),
391            max_subscriptions_per_connection: default_max_subscriptions_per_connection(),
392            max_conversations_per_connection: default_max_conversations_per_connection(),
393            max_pending_pushes_per_connection: default_max_pending_pushes_per_connection(),
394            max_pending_conversation_replies_per_connection:
395                default_max_pending_conversation_replies_per_connection(),
396            max_pending_replies_per_conversation: default_max_pending_replies_per_conversation(),
397            max_connection_inbox_bytes: default_max_connection_inbox_bytes(),
398            max_subscription_inbox_depth: default_max_subscription_inbox_depth(),
399        }
400    }
401}
402
403const fn default_max_connections() -> usize {
404    LimitsConfig::DEFAULT_MAX_CONNECTIONS
405}
406const fn default_max_subscriptions_per_connection() -> usize {
407    LimitsConfig::DEFAULT_MAX_SUBSCRIPTIONS_PER_CONNECTION
408}
409const fn default_max_conversations_per_connection() -> usize {
410    LimitsConfig::DEFAULT_MAX_CONVERSATIONS_PER_CONNECTION
411}
412const fn default_max_pending_pushes_per_connection() -> usize {
413    LimitsConfig::DEFAULT_MAX_PENDING_PUSHES_PER_CONNECTION
414}
415const fn default_max_pending_conversation_replies_per_connection() -> usize {
416    LimitsConfig::DEFAULT_MAX_PENDING_CONVERSATION_REPLIES_PER_CONNECTION
417}
418const fn default_max_pending_replies_per_conversation() -> usize {
419    LimitsConfig::DEFAULT_MAX_PENDING_REPLIES_PER_CONVERSATION
420}
421const fn default_max_connection_inbox_bytes() -> usize {
422    LimitsConfig::DEFAULT_MAX_CONNECTION_INBOX_BYTES
423}
424const fn default_max_subscription_inbox_depth() -> usize {
425    LimitsConfig::DEFAULT_MAX_SUBSCRIPTION_INBOX_DEPTH
426}
427
428/// Participant lifecycle configuration (`[participant]`).
429///
430/// Present iff the deployment activates the participant protocol. Every field
431/// is required — serde carries no defaults here, so a missing field fails
432/// config loading with a typed error naming the field, and
433/// [`ParticipantConfig::collect_errors`] rejects semantically impossible
434/// values during the same accumulated validation pass as the rest of the
435/// config. All values are deployment-owner decisions (no assumed defaults).
436///
437/// Every field here is consumed by the live production handler. Frontier and
438/// retention limits are required inputs; there are no deployment defaults.
439#[derive(Debug, Clone, Copy, serde::Deserialize)]
440#[serde(deny_unknown_fields)]
441pub struct ParticipantConfig {
442    /// Complete participant wire-frame limit (`WF`) negotiated with every
443    /// participant-capable connection. Must be at least the protocol's
444    /// minimum complete frame; enforced by the shared codec at service
445    /// construction and pre-checked during config validation.
446    pub wire_frame_limit: u64,
447    /// Secret-bearing attach/enrollment receipt lifetime in milliseconds.
448    pub attach_receipt_ttl_ms: u64,
449    /// Non-secret receipt-provenance lifetime in milliseconds. Must be at
450    /// least `attach_receipt_ttl_ms` (provenance explains the receipt and
451    /// cannot expire first).
452    pub receipt_provenance_ttl_ms: u64,
453    /// Server-wide cap on live secret-bearing receipts (enrollment and
454    /// credential-attach receipt bodies inside their own receipt windows,
455    /// across every conversation). R-D1 stage-8 scope `LiveReceiptServer`:
456    /// enrollment and credential attach refuse with the typed
457    /// `ReceiptCapacityExceeded` when reserving one more would exceed it.
458    pub max_live_attach_receipts_server: u64,
459    /// Per-participant cap on live secret-bearing receipts (stage-8 scope
460    /// `LiveReceiptParticipant`). A participant holds at most its enrollment
461    /// receipt plus its current attach receipt live at once, so values below
462    /// 3 refuse rotation while the enrollment receipt is still live.
463    pub max_live_attach_receipts_per_participant: u64,
464    /// Server-wide cap on retained non-secret provenance fingerprints
465    /// (stage-8 scope `ProvenanceServer`). A fingerprint exists from its
466    /// operation's commit through its own provenance deadline.
467    pub max_receipt_provenance_server: u64,
468    /// Per-conversation provenance-fingerprint cap (stage-8 scope
469    /// `ProvenanceConversation`).
470    pub max_receipt_provenance_per_conversation: u64,
471    /// Per-participant provenance-fingerprint cap (stage-8 scope
472    /// `ProvenanceParticipant`).
473    pub max_receipt_provenance_per_participant: u64,
474    /// Server-wide identity-slot limit (the contract's
475    /// `max_retired_identity_slots` server scope): the total number of
476    /// participant identities — live or retired — mintable across ALL
477    /// conversations. Enrollment refuses with server-scope
478    /// `IdentityCapacityExceeded` (tested BEFORE the conversation scope)
479    /// when every slot is reserved.
480    pub max_retired_identity_slots_server: u64,
481    /// Per-CONVERSATION identity limit `I` (the contract's half-open
482    /// `0..=I` bound on permanent participant ordinals — the conversation
483    /// scope of `max_retired_identity_slots`, NOT a per-participant
484    /// reservation). Enrollment assigns monotone participant indices in
485    /// `0..I` within one conversation and refuses with conversation-scope
486    /// `IdentityCapacityExceeded` when occupancy reaches this value; slots
487    /// and ids are never reused. The server-wide companion is
488    /// [`Self::max_retired_identity_slots_server`].
489    pub identity_slots: u64,
490    /// Maximum entries one observer-recovery handshake batch may name.
491    pub observer_recovery_max_entries: u64,
492    /// Semantic conversations one connection may track — the protocol's
493    /// signed connection-conversation limit. Consumed on BOTH of its contract
494    /// paths: the stage-6 capacity gate every conversation-scoped semantic
495    /// operation runs (register row 5641) and the observer-recovery batch
496    /// preflight (register row 5642), over one shared per-connection
497    /// dispatch map.
498    pub max_semantic_conversations_per_connection: u64,
499    /// Maximum canonical entries in one ordinary retained-record row.
500    pub max_ordinary_record_entries: u64,
501    /// Maximum canonical bytes in one ordinary retained-record row.
502    pub max_ordinary_record_bytes: u64,
503    /// Maximum canonical entries in one generated marker row.
504    pub max_generated_marker_entries: u64,
505    /// Maximum canonical bytes in one generated marker row.
506    pub max_generated_marker_bytes: u64,
507    /// Entry component of the mandatory transaction envelope `Q`.
508    pub mandatory_transaction_bound_entries: u64,
509    /// Byte component of the mandatory transaction envelope `Q`.
510    pub mandatory_transaction_bound_bytes: u64,
511    /// Entry component of the full recovery claim `K`.
512    pub full_recovery_claim_entries: u64,
513    /// Byte component of the full recovery claim `K`.
514    pub full_recovery_claim_bytes: u64,
515    /// Total retained durable entry capacity per conversation.
516    pub retained_capacity_entries: u64,
517    /// Total retained canonical-byte capacity per conversation.
518    pub retained_capacity_bytes: u64,
519    /// Maximum retained causal-record rows restored for one conversation.
520    pub max_retained_record_rows: u64,
521    /// Maximum closure churn cycles in one episode.
522    pub closure_episode_churn_limit: u64,
523}
524
525impl ParticipantConfig {
526    /// Accumulates semantic validation errors for the participant section.
527    ///
528    /// Zero is rejected wherever it would be unlimited-by-silence, gate
529    /// nothing, or violate a protocol precondition; the TTL ordering mirrors
530    /// the protocol's own frozen configuration precedence.
531    pub(crate) fn collect_errors(&self, errors: &mut Vec<String>) {
532        // The receipt/identity block follows the contract's frozen nine-field
533        // validation order: both TTLs, the five receipt/provenance caps, the
534        // server identity limit, then the conversation identity limit.
535        let nonzero: [(&str, u64); 23] = [
536            ("wire_frame_limit", self.wire_frame_limit),
537            ("attach_receipt_ttl_ms", self.attach_receipt_ttl_ms),
538            ("receipt_provenance_ttl_ms", self.receipt_provenance_ttl_ms),
539            (
540                "max_live_attach_receipts_server",
541                self.max_live_attach_receipts_server,
542            ),
543            (
544                "max_live_attach_receipts_per_participant",
545                self.max_live_attach_receipts_per_participant,
546            ),
547            (
548                "max_receipt_provenance_server",
549                self.max_receipt_provenance_server,
550            ),
551            (
552                "max_receipt_provenance_per_conversation",
553                self.max_receipt_provenance_per_conversation,
554            ),
555            (
556                "max_receipt_provenance_per_participant",
557                self.max_receipt_provenance_per_participant,
558            ),
559            (
560                "max_retired_identity_slots_server",
561                self.max_retired_identity_slots_server,
562            ),
563            ("identity_slots", self.identity_slots),
564            (
565                "observer_recovery_max_entries",
566                self.observer_recovery_max_entries,
567            ),
568            (
569                "max_semantic_conversations_per_connection",
570                self.max_semantic_conversations_per_connection,
571            ),
572            (
573                "max_ordinary_record_entries",
574                self.max_ordinary_record_entries,
575            ),
576            ("max_ordinary_record_bytes", self.max_ordinary_record_bytes),
577            (
578                "max_generated_marker_entries",
579                self.max_generated_marker_entries,
580            ),
581            (
582                "max_generated_marker_bytes",
583                self.max_generated_marker_bytes,
584            ),
585            (
586                "mandatory_transaction_bound_entries",
587                self.mandatory_transaction_bound_entries,
588            ),
589            (
590                "mandatory_transaction_bound_bytes",
591                self.mandatory_transaction_bound_bytes,
592            ),
593            (
594                "full_recovery_claim_entries",
595                self.full_recovery_claim_entries,
596            ),
597            ("full_recovery_claim_bytes", self.full_recovery_claim_bytes),
598            ("retained_capacity_entries", self.retained_capacity_entries),
599            ("retained_capacity_bytes", self.retained_capacity_bytes),
600            ("max_retained_record_rows", self.max_retained_record_rows),
601        ];
602        for (field, value) in nonzero {
603            if value == 0 {
604                errors.push(format!("participant.{field}: must be greater than zero"));
605            }
606        }
607        if self.receipt_provenance_ttl_ms < self.attach_receipt_ttl_ms {
608            errors.push(
609                "participant.receipt_provenance_ttl_ms: must be at least \
610                 attach_receipt_ttl_ms (provenance cannot expire before the receipt it explains)"
611                    .to_owned(),
612            );
613        }
614        if self.full_recovery_claim_entries != self.mandatory_transaction_bound_entries {
615            errors.push(
616                "participant.full_recovery_claim_entries: must equal \
617                 mandatory_transaction_bound_entries"
618                    .to_owned(),
619            );
620        }
621        if self.full_recovery_claim_bytes != self.mandatory_transaction_bound_bytes {
622            errors.push(
623                "participant.full_recovery_claim_bytes: must equal \
624                 mandatory_transaction_bound_bytes"
625                    .to_owned(),
626            );
627        }
628        if !(2..=u64::from(u32::MAX)).contains(&self.closure_episode_churn_limit) {
629            errors.push(
630                "participant.closure_episode_churn_limit: must be in 2..=u32::MAX".to_owned(),
631            );
632        }
633        self.collect_unit2_derived_errors(errors);
634    }
635
636    fn collect_unit2_derived_errors(&self, errors: &mut Vec<String>) {
637        if self
638            .max_retained_record_rows
639            .checked_mul(self.identity_slots)
640            .is_none()
641        {
642            errors.push("participant.UNIT2_MAX_LIVE_RECIPIENT_OBLIGATIONS: max_retained_record_rows * identity_slots overflows u64".to_owned());
643        }
644    }
645}
646
647/// Which connection-services adapter the server constructs (D2).
648#[derive(Debug, Clone, Copy, PartialEq, Eq)]
649pub enum ServiceProfile {
650    /// Full channel/conversation/durability services — the default. Constructs the
651    /// haematite store, channel supervisor, conversation supervisor, and dedup
652    /// cache exactly as before.
653    Full,
654    /// Capability-scoped worker front door: the connection supervisor only, with no
655    /// channel/conversation/haematite machinery. Backs worker registration,
656    /// correlated push/reply, and notifier-consumed reserved publishes; ordinary
657    /// channel and conversation frames are rejected with a typed error frame.
658    WorkerFrontDoor,
659}
660
661impl ServiceProfile {
662    /// Config value selecting the full-service profile.
663    pub const FULL: &'static str = "full";
664    /// Config value selecting the worker-front-door profile.
665    pub const WORKER_FRONT_DOOR: &'static str = "worker-front-door";
666
667    /// Parses a `[services] profile` value into a typed profile.
668    ///
669    /// # Errors
670    /// Returns [`ServerError::ConfigValidation`] for any value other than
671    /// [`Self::FULL`] or [`Self::WORKER_FRONT_DOOR`].
672    pub fn parse(value: &str) -> Result<Self, ServerError> {
673        match value {
674            Self::FULL => Ok(Self::Full),
675            Self::WORKER_FRONT_DOOR => Ok(Self::WorkerFrontDoor),
676            other => Err(ServerError::ConfigValidation {
677                message: format!(
678                    "services.profile: unknown profile '{other}'; expected \"{}\" or \"{}\"",
679                    Self::FULL,
680                    Self::WORKER_FRONT_DOOR
681                ),
682            }),
683        }
684    }
685}