Skip to main content

aion_server/config/
sections.rs

1//! Typed `[section]` sub-configurations that make up [`ServerConfig`].
2//!
3//! Each struct/enum here maps one `[section]` (or nested value) of the server
4//! TOML surface, with its `serde` attributes, `Default` impl, and the small
5//! amount of per-section validation that belongs with the type
6//! ([`WebSocketConfig::validate`]). They are re-exported from the `config`
7//! module so every existing `crate::config::X` path resolves identically.
8//!
9//! [`ServerConfig`]: super::ServerConfig
10
11use std::{net::SocketAddr, path::PathBuf, time::Duration};
12
13use serde::{Deserialize, Deserializer, de};
14
15use crate::error::ServerError;
16
17use super::{
18    config_error,
19    defaults::{
20        CLUSTER_BROADCAST_CAPACITY_REQUIRED, DEFAULT_GRPC_ADDRESS, DEFAULT_HTTP_ADDRESS,
21        DEFAULT_MAX_IN_FLIGHT_ACTIVITIES, DEFAULT_MCP_DISCOVER_TTL_MS,
22        DEFAULT_MCP_TASK_POLL_INTERVAL_MS, DEFAULT_MCP_TOOLS_LIST_TTL_MS,
23        DEFAULT_OBSERVABILITY_MAX_EVENT_BYTES, DEFAULT_OBSERVABILITY_MAX_STREAM_EVENTS,
24        EVENT_BROADCAST_CAPACITY_REQUIRED, MCP_TASK_POLL_INTERVAL_REQUIRED,
25        OBSERVABILITY_MAX_EVENT_BYTES_REQUIRED, OBSERVABILITY_MAX_STREAM_EVENTS_REQUIRED,
26    },
27};
28
29/// Public transport listener addresses from `[server]`.
30#[derive(Clone, Debug, Deserialize)]
31#[serde(default, deny_unknown_fields)]
32pub struct ServerSection {
33    /// HTTP/JSON and dashboard listener.
34    pub listen_address: SocketAddr,
35    /// gRPC API and worker-protocol listener.
36    pub grpc_address: SocketAddr,
37    /// Browser origins allowed to make cross-origin (CORS) requests to the
38    /// public HTTP API. Empty (the default) is the SECURE default: no
39    /// cross-origin request is permitted and no `CorsLayer` is installed, so a
40    /// same-origin deployment behaves byte-identically to before this field
41    /// existed. When set, each entry is an exact origin (scheme + host + port,
42    /// e.g. `http://localhost:5173`) the browser dashboard is served from; the
43    /// router then answers preflight and emits `Access-Control-Allow-Origin`
44    /// for exactly those origins. There is no wildcard/allow-all default
45    /// (ADR-001): cross-origin access is an explicit operator decision, and the
46    /// layer never pairs `Any` with credentials.
47    #[serde(default)]
48    pub cors_allowed_origins: Vec<String>,
49}
50
51/// Supported event-store backend names.
52///
53/// Deliberately NOT `Deserialize`. `StoreConfigWire` parses the operator's
54/// spelling itself, case-insensitively, so that the file door and the
55/// `AION_STORE_BACKEND` door accept exactly the same set — a derived
56/// `rename_all = "lowercase"` impl was a second, case-SENSITIVE parser for the
57/// same value that nothing called and that disagreed with the one that runs.
58#[derive(Clone, Copy, Debug, Eq, PartialEq)]
59pub enum StoreBackend {
60    /// In-memory store for local development.
61    Memory,
62    /// haematite durable store (single-node, shardable).
63    Haematite,
64}
65
66/// A store-selection input that named the retired libSQL backend.
67///
68/// Recorded at parse/overlay time and refused by `ServerConfig::validate`, which
69/// names the input it found and prescribes haematite. Recorded rather than
70/// refused on the spot so all five doors converge on ONE refusal with one
71/// remedy, instead of five differently-worded errors from five parsers.
72#[derive(Clone, Copy, Debug, Eq, PartialEq)]
73pub(crate) enum RetiredStoreInput {
74    /// `backend = "libsql"` in the config file's `[store]` section.
75    Backend,
76    /// `AION_STORE_BACKEND=libsql` in the environment.
77    BackendEnvironment,
78    /// `url = ...` in the config file's `[store]` section.
79    Url,
80    /// The `AION_STORE_URL` environment variable.
81    Environment,
82    /// The `--store-url` command-line flag.
83    Flag,
84}
85
86/// Event-store backend configuration from `[store]`.
87#[derive(Clone, Debug)]
88pub struct StoreConfig {
89    /// Selected backing store implementation.
90    pub backend: StoreBackend,
91    pub(crate) retired_input: Option<RetiredStoreInput>,
92    /// Static distribution-shard assignment for this node (multi-shard
93    /// active-active). When empty (the default) the node owns ALL shards — the
94    /// single-node default, byte-identical to today. When set, the engine boot
95    /// path scopes recovery and enumeration to exactly these shards. The
96    /// single-shard memory backend ignores the assignment; it is meaningful only
97    /// for a sharded backend. No election is performed: assignment is static
98    /// config.
99    pub owned_shards: Vec<usize>,
100    /// Filesystem data directory for the haematite backend. Required when
101    /// `backend = haematite`; ignored by every other backend. The directory is
102    /// opened if it already holds a haematite database, otherwise created.
103    pub data_dir: Option<String>,
104    /// Number of haematite shards to create on a fresh database. Defaults to 64.
105    ///
106    /// This is an IMMUTABLE virtual-shard count: nodes own shard *ranges* and
107    /// routing is `BLAKE3(key) % shard_count` with no reshard path, so a
108    /// single-node deployment can later grow into a cluster WITHOUT a data
109    /// migration — but only up to `shard_count` nodes, and the value is fixed
110    /// at create.
111    ///
112    /// The default was briefly 4096 on the premise that lazy shard-actor
113    /// materialization (haematite >= 0.4.0) made a high count ~free. That
114    /// premise fails in practice (#187): aion-server's boot restores
115    /// packages/routes/namespaces via full-prefix scans, which materialize
116    /// EVERY shard, and haematite 0.4.0 then fans each commit out to every
117    /// materialized shard with an unconditional fsync — ~2 fsyncs x 4096 per
118    /// logical commit — blowing the 5s shard-actor timeout and bricking
119    /// deploy/start/timers/outbox on a fresh server. Re-raise only after
120    /// haematite makes commit O(dirty shards) and the scaffold e2es pass at
121    /// the new default. Set explicitly (config or `AION_STORE_SHARD_COUNT`)
122    /// to override. Ignored by every other backend, and ignored when opening
123    /// an existing haematite database (the on-disk shard count wins).
124    pub shard_count: usize,
125    /// Optional distributed-cluster membership for the haematite backend (SS-2).
126    ///
127    /// Absent (the default) selects the SINGLE-NODE haematite path, byte-identical
128    /// to today: no endpoint is bound, no shard is elected, the store owns
129    /// everything locally. Present selects the DISTRIBUTED path: the boot path
130    /// binds a replication endpoint, builds a quorum membership from `members` +
131    /// `peers`, and the engine boot path elects (`acquire_shard_and_serve`) this
132    /// node's `owned_shards` before recovery. Ignored by every non-haematite
133    /// backend.
134    pub cluster: Option<ClusterConfig>,
135    /// The byte ceiling the haematite node caches may hold.
136    /// **Required; no default** — the haematite boot path refuses to start
137    /// without it. Ignored by every other backend (only haematite has a node
138    /// cache), which is why it is required where it is USED rather than at
139    /// parse time: a `memory` deployment is not asked to rule on a cache it does
140    /// not have.
141    ///
142    /// A node is not a fixed-size thing — under byte-aware chunking a leaf
143    /// reaches the ~96KB class — so a cache bounded only by `max_entries`
144    /// carries a standing footprint of `entries x (whatever a node weighs)`,
145    /// unbounded in bytes by construction. This is the missing bound, and
146    /// haematite 0.8.2 refuses a `DatabaseConfig` that does not carry it.
147    ///
148    /// Deserialized through haematite's own wire shape, so there is exactly one
149    /// parser for this value estate-wide:
150    ///
151    /// ```toml
152    /// [store]
153    /// node_cache_budget = { bytes = 1073741824 }  # 1 GiB
154    /// # or, the pre-budget behaviour said out loud:
155    /// node_cache_budget = "unlimited"
156    /// ```
157    ///
158    /// Absent fails startup with [`STORE_NODE_CACHE_BUDGET_REQUIRED`]; a zero
159    /// byte count is refused by haematite at parse time (a zero ceiling admits
160    /// nothing, which is "disable the cache" and must be spelled differently).
161    ///
162    /// [`STORE_NODE_CACHE_BUDGET_REQUIRED`]: super::STORE_NODE_CACHE_BUDGET_REQUIRED
163    pub node_cache_budget: Option<haematite::NodeCacheBudget>,
164    /// Maximum time production boot may spend acquiring an existing
165    /// haematite data-directory writer lock. Required for haematite; no default.
166    pub lock_acquisition_patience_ms: Option<u64>,
167    /// Cadence between production writer-lock attempts. Required together with
168    /// `lock_acquisition_patience_ms`; no default.
169    pub lock_acquisition_retry_cadence_ms: Option<u64>,
170}
171
172#[derive(Default, Deserialize)]
173#[serde(default, deny_unknown_fields)]
174struct StoreConfigWire {
175    backend: Option<String>,
176    /// Retired: recorded so `validate` can refuse it. Kept on the wire — and
177    /// NOT left to `deny_unknown_fields` — so an operator carrying a 0.15
178    /// config is told the key is retired and what replaces it, rather than
179    /// getting an unknown-field parse error that names no remedy.
180    url: Option<String>,
181    owned_shards: Vec<usize>,
182    data_dir: Option<String>,
183    shard_count: Option<usize>,
184    cluster: Option<ClusterConfig>,
185    node_cache_budget: Option<haematite::NodeCacheBudget>,
186    lock_acquisition_patience_ms: Option<u64>,
187    lock_acquisition_retry_cadence_ms: Option<u64>,
188}
189
190impl<'de> Deserialize<'de> for StoreConfig {
191    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
192    where
193        D: Deserializer<'de>,
194    {
195        let wire = StoreConfigWire::deserialize(deserializer)?;
196        let mut config = Self::default();
197        if let Some(backend) = wire.backend.as_deref() {
198            match backend.to_ascii_lowercase().as_str() {
199                "memory" => config.backend = StoreBackend::Memory,
200                "haematite" => config.backend = StoreBackend::Haematite,
201                "libsql" => config.retired_input = Some(RetiredStoreInput::Backend),
202                _ => {
203                    return Err(de::Error::custom(
204                        "store.backend must be one of: memory, haematite",
205                    ));
206                }
207            }
208        }
209        if wire.url.is_some() && config.retired_input.is_none() {
210            config.retired_input = Some(RetiredStoreInput::Url);
211        }
212        config.owned_shards = wire.owned_shards;
213        config.data_dir = wire.data_dir;
214        if let Some(shard_count) = wire.shard_count {
215            config.shard_count = shard_count;
216        }
217        config.cluster = wire.cluster;
218        config.node_cache_budget = wire.node_cache_budget;
219        config.lock_acquisition_patience_ms = wire.lock_acquisition_patience_ms;
220        config.lock_acquisition_retry_cadence_ms = wire.lock_acquisition_retry_cadence_ms;
221        Ok(config)
222    }
223}
224
225/// Distributed-cluster membership for the haematite backend, from `[store.cluster]`.
226///
227/// This is the minimal, well-defaulted seam that turns the single-node haematite
228/// store into a distributed one (SS-2). A "cluster of one" — `node_id` set,
229/// `members` either empty or naming only `node_id`, and no `peers` — is a valid,
230/// non-flaky configuration: election self-quorums (quorum denominator 1) and the
231/// node boots through the production builder as the fenced owner of its shards.
232#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
233#[serde(deny_unknown_fields)]
234pub struct ClusterConfig {
235    /// This node's globally-unique distribution name (e.g. `node-0@127.0.0.1`).
236    /// Used as the local endpoint name and the local membership identity.
237    pub node_id: String,
238    /// The replication endpoint listen address this node binds for peer
239    /// quorum/election traffic (e.g. `127.0.0.1:7000`).
240    pub bind_address: SocketAddr,
241    /// The FULL cluster membership by node id — the quorum DENOMINATOR. Never the
242    /// reachable subset. May be empty or omit peers for a cluster of one, in which
243    /// case it is treated as `[node_id]` (denominator 1). `node_id` is always
244    /// counted in the denominator whether or not it appears here.
245    #[serde(default)]
246    pub members: Vec<String>,
247    /// Dialable peers (name + address) this node connects to for replication. A
248    /// cluster of one leaves this empty. Peers not in `members` do not inflate the
249    /// quorum denominator.
250    #[serde(default)]
251    pub peers: Vec<ClusterPeer>,
252    /// SS-5b automatic-failover poll interval in milliseconds: how often the
253    /// cluster supervisor checks each watched peer's replication liveness.
254    /// Defaults to [`DEFAULT_FAILOVER_POLL_INTERVAL_MS`] when omitted.
255    ///
256    /// [`DEFAULT_FAILOVER_POLL_INTERVAL_MS`]: super::DEFAULT_FAILOVER_POLL_INTERVAL_MS
257    #[serde(default)]
258    pub failover_poll_interval_ms: Option<u64>,
259    /// SS-5b debounce: the number of CONSECUTIVE polls a peer must be observed
260    /// disconnected before its shards are adopted, so a transient blip does not
261    /// trigger a disruptive failover. Defaults to
262    /// [`DEFAULT_FAILOVER_CONFIRMATIONS`] when omitted; must be at least one.
263    ///
264    /// [`DEFAULT_FAILOVER_CONFIRMATIONS`]: super::DEFAULT_FAILOVER_CONFIRMATIONS
265    #[serde(default)]
266    pub failover_confirmations: Option<u32>,
267}
268
269/// One dialable cluster peer: its distribution name and replication address.
270#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
271#[serde(deny_unknown_fields)]
272pub struct ClusterPeer {
273    /// The peer's globally-unique distribution name (matches its `node_id`).
274    pub name: String,
275    /// The peer's replication endpoint address to dial.
276    pub address: SocketAddr,
277    /// The peer's gRPC client-API address, for request forwarding (R-2/R-3).
278    /// This is DISTINCT from `address` (the replication/quorum endpoint): a
279    /// forwarded client `signal`/`query`/`cancel` is dialed here, not on the
280    /// replication port. Absent (the default) means the peer is not
281    /// forwardable — its shards still resolve to a remote owner, but routing
282    /// falls back to returning the typed `NotOwner` instead of forwarding (R-3).
283    #[serde(default)]
284    pub grpc_address: Option<SocketAddr>,
285    /// The distribution shards this peer owns. Empty (the default) means the
286    /// operator did not declare the peer's shards, so the SS-5b cluster
287    /// supervisor cannot adopt them automatically when the peer dies — automatic
288    /// failover for a peer requires its `owned_shards` to be declared here so the
289    /// survivor knows exactly which shards to elect + resume. Declaring them does
290    /// not change replication or quorum; it only tells the supervisor what to
291    /// adopt on this peer's death.
292    #[serde(default)]
293    pub owned_shards: Vec<usize>,
294}
295
296/// Engine runtime settings from `[runtime]`.
297#[derive(Clone, Debug, Deserialize)]
298#[serde(default, deny_unknown_fields)]
299pub struct RuntimeSection {
300    /// Number of scheduler worker threads.
301    pub scheduler_threads: usize,
302    /// JIT compilation threshold: recorded calls to one
303    /// `(module, function, arity)` before beamr compiles it.
304    ///
305    /// Absent means beamr applies its own default; the server invents no value.
306    /// Read `aion::RuntimeConfig::jit_threshold` before setting it — a large
307    /// value defers compilation past any realistic workload but is **not** a
308    /// JIT off-switch.
309    pub jit_threshold: Option<u32>,
310    /// Engine reply deadline for workflow queries, in milliseconds.
311    /// REQUIRED — the server always mounts `/workflows/query`, so the query
312    /// reply deadline must be an explicit operator decision; there is no
313    /// default. The engine builder is equally explicit-no-default.
314    pub query_timeout_ms: Option<u64>,
315}
316
317/// Graceful drain settings from `[drain]`.
318#[derive(Clone, Debug, Deserialize)]
319#[serde(default, deny_unknown_fields)]
320pub struct DrainConfig {
321    /// Maximum drain duration in seconds.
322    pub timeout_seconds: u64,
323}
324
325/// Authentication configuration applied at adapter boundaries.
326#[derive(Clone, Debug, Deserialize)]
327#[serde(default, deny_unknown_fields)]
328pub struct AuthConfig {
329    /// Whether authentication is enabled.
330    pub enabled: bool,
331    /// JWKS URL used by AO-006 auth validation.
332    pub jwks_url: Option<String>,
333    /// JWKS refresh interval in seconds.
334    pub jwks_refresh_seconds: u64,
335}
336
337/// Metrics endpoint settings from `[metrics]`.
338#[derive(Clone, Debug, Deserialize)]
339#[serde(default, deny_unknown_fields)]
340pub struct MetricsConfig {
341    /// Whether metrics are exposed.
342    pub enabled: bool,
343}
344
345/// Namespace defaults from `[namespaces]`.
346#[derive(Clone, Debug, Deserialize)]
347#[serde(default, deny_unknown_fields)]
348pub struct NamespacesConfig {
349    /// Default namespace used for local callers and worker dispatch.
350    pub default: String,
351    /// Minted-on-use policy: whether referencing an unseen namespace at worker
352    /// registration durably mints it ([`AutoCreate::Open`], the zero-config
353    /// default) or is rejected ([`AutoCreate::Closed`]).
354    pub auto_create: AutoCreate,
355    /// Platform-wide default for a namespace's **cluster-wide** concurrent
356    /// in-flight-activity ceiling, applied when a namespace record carries no
357    /// explicit `max_in_flight_activities` override (Control-Plane Phase 2,
358    /// P2-Q1). This is the GENEROUS platform default, NOT a low hard cap: it is
359    /// a cluster-wide tenant contract (never "per-node × N"), so a tenant is
360    /// promised ≈this many concurrent activities across the whole cluster.
361    /// Defaults to [`DEFAULT_MAX_IN_FLIGHT_ACTIVITIES`].
362    ///
363    /// **Stored-only in this slice.** Nothing enforces it yet — the outbox
364    /// dispatcher's keyed backpressure (P2-Q2) consults it in a later slice.
365    ///
366    /// [`DEFAULT_MAX_IN_FLIGHT_ACTIVITIES`]: super::DEFAULT_MAX_IN_FLIGHT_ACTIVITIES
367    pub max_in_flight_activities: u32,
368}
369
370/// Minted-on-use namespace policy (Control-Plane Phase 1).
371///
372/// Governs what happens when a worker registers for a namespace that has no
373/// durable registry record. Defaults to [`AutoCreate::Open`] to preserve the
374/// zero-ceremony, no-pre-provision model: a namespace comes into being on first
375/// reference.
376#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq)]
377#[serde(rename_all = "snake_case")]
378pub enum AutoCreate {
379    /// A worker registering for an unseen namespace durably mints it (an
380    /// idempotent upsert through the registry). Zero-config default.
381    #[default]
382    Open,
383    /// A worker registering for a namespace with no durable registry record is
384    /// rejected; the namespace is never created at the registration hook. The
385    /// escape hatch for locked-down deployments is an explicit create
386    /// (`POST /namespaces`).
387    Closed,
388}
389
390/// Public transport listener addresses retained for existing adapter code.
391#[derive(Clone, Debug, Deserialize)]
392#[serde(default, deny_unknown_fields)]
393pub struct ListenConfig {
394    /// gRPC API and worker-protocol listener.
395    pub grpc: SocketAddr,
396    /// HTTP/JSON and dashboard listener.
397    pub http: SocketAddr,
398}
399
400/// TLS certificate and private-key material.
401#[derive(Clone, Debug, Deserialize)]
402#[serde(deny_unknown_fields)]
403pub struct TlsConfig {
404    /// Certificate chain path supplied by the operator.
405    pub certificate_chain_path: PathBuf,
406    /// Private-key path supplied by the operator.
407    pub private_key_path: PathBuf,
408}
409
410/// Static ops-console asset configuration.
411#[derive(Clone, Debug, Deserialize)]
412#[serde(default, deny_unknown_fields)]
413pub struct OpsConsoleConfig {
414    /// Operator-selected bundle source.
415    pub source: OpsConsoleAssetSource,
416}
417
418/// Static ops-console bundle source.
419#[derive(Clone, Debug, Deserialize)]
420pub enum OpsConsoleAssetSource {
421    /// Serve the built bundle from an operator-supplied directory.
422    FileSystem {
423        /// Directory containing `index.html` and built asset files.
424        asset_path: PathBuf,
425    },
426    /// Serve the compile-time embedded bundle.
427    Embedded,
428}
429
430/// Namespace resolver construction mode.
431#[derive(Clone, Debug, Deserialize)]
432#[serde(default, deny_unknown_fields)]
433pub struct NamespaceConfig {
434    /// Deployment-selected namespace mapping mode.
435    pub mode: NamespaceMode,
436}
437
438/// Supported namespace mapping modes.
439#[derive(Clone, Debug, Deserialize)]
440pub enum NamespaceMode {
441    /// All authorized namespaces share the configured engine instance.
442    SharedEngine,
443    /// Namespace authorization is disabled only for single-tenant deployments.
444    SingleTenant {
445        /// The only namespace accepted by the deployment.
446        namespace: String,
447    },
448}
449
450/// Remote worker heartbeat configuration.
451#[derive(Clone, Debug, Deserialize)]
452#[serde(default, deny_unknown_fields)]
453pub struct WorkerConfig {
454    /// Window after which a silent worker is considered lost.
455    #[serde(with = "duration_millis")]
456    pub heartbeat_window: Duration,
457    /// R1 queue-service policies and clocks (`[worker.queue_service]`).
458    ///
459    /// Absent, every queue is served `strict` with no clocks: structural
460    /// unservability refuses, everything else waits — loudly, typed, and
461    /// queryable. Writing a deadline is how an operator declares how long a
462    /// dispatch may wait; writing a `durable_pending` override is how a queue
463    /// declares that its runs park rather than refuse.
464    #[serde(default)]
465    pub queue_service: crate::worker::queue_service::QueueServiceConfig,
466}
467
468/// WebSocket stream configuration.
469#[derive(Clone, Debug, Deserialize)]
470#[serde(default, deny_unknown_fields)]
471pub struct WebSocketConfig {
472    /// Per-connection outbound buffer bound.
473    pub outbound_buffer_bound: usize,
474    /// Capacity of the engine-global event broadcast channel that backs
475    /// `/events/stream`. REQUIRED — the server always mounts the streaming
476    /// endpoint, so streaming capacity must be an explicit operator decision;
477    /// there is no default. Lag is filter-blind, so size this for global event
478    /// volume across all namespaces, not per-subscription volume.
479    pub event_broadcast_capacity: Option<usize>,
480    /// Capacity of the deployment-global cluster topology/ownership broadcast
481    /// channel that backs the WS3 `cluster` subscription on `/events/stream`.
482    /// REQUIRED with the same non-zero startup guard as
483    /// [`Self::event_broadcast_capacity`]: the cluster channel uses the same
484    /// lag -> one-error-frame -> close contract, which has no defined buffer to
485    /// lag against unless a capacity is configured. Cluster events are low-rate
486    /// (peer/shard/worker topology deltas), so this is typically far smaller
487    /// than the workflow event capacity.
488    pub cluster_broadcast_capacity: Option<usize>,
489}
490
491impl WebSocketConfig {
492    /// Validate the three unconditionally-mounted WebSocket seams: the
493    /// per-connection buffer bound, the workflow event broadcast capacity, and
494    /// the WS3 cluster broadcast capacity. The two broadcast capacities are
495    /// explicit-no-default with a non-zero guard, since both back a lag ->
496    /// one-error-frame -> close contract that needs a defined buffer to lag
497    /// against.
498    pub(super) fn validate(&self) -> Result<(), ServerError> {
499        if self.outbound_buffer_bound == 0 {
500            return config_error("websocket.outbound_buffer_bound must be greater than zero");
501        }
502        match self.event_broadcast_capacity {
503            None | Some(0) => return config_error(EVENT_BROADCAST_CAPACITY_REQUIRED),
504            Some(_) => {}
505        }
506        match self.cluster_broadcast_capacity {
507            None | Some(0) => return config_error(CLUSTER_BROADCAST_CAPACITY_REQUIRED),
508            Some(_) => {}
509        }
510        Ok(())
511    }
512}
513
514/// Model Context Protocol surface settings from `[mcp]`.
515///
516/// The surface is DARK by default: with `enabled = false` (or the section
517/// absent) the `/mcp` route is not mounted and the path is a plain 404. An MCP
518/// endpoint hands a model the ability to start and cancel durable executions,
519/// so commissioning it is an explicit operator decision, never a side effect of
520/// upgrading.
521///
522/// `allowed_origins` is EMPTY by default and empty means "no browser origin".
523/// A programmatic client sends no `Origin` header and is unaffected; a page in
524/// a browser always sends one, so the empty list refuses every browser-borne
525/// request. That is the DNS-rebinding defence the transport requires, and it is
526/// a real policy rather than an unset value.
527#[derive(Clone, Debug, Default, Deserialize, PartialEq, Eq)]
528#[serde(default, deny_unknown_fields)]
529pub struct McpConfig {
530    /// Whether the `/mcp` endpoint is mounted. Defaults to false.
531    pub enabled: bool,
532    /// Browser origins permitted to reach the MCP endpoint. Empty permits none.
533    pub allowed_origins: Vec<String>,
534    /// `ttlMs` on the `server/discover` result.
535    ///
536    /// Defaults to [`DEFAULT_MCP_DISCOVER_TTL_MS`] when omitted and
537    /// `enabled = true`, so switching the surface on does not force sizing two
538    /// cache lifetimes first.
539    ///
540    /// [`DEFAULT_MCP_DISCOVER_TTL_MS`]: super::DEFAULT_MCP_DISCOVER_TTL_MS
541    pub discover_ttl_ms: Option<u64>,
542    /// `ttlMs` on the `tools/list` result. Defaults to
543    /// [`DEFAULT_MCP_TOOLS_LIST_TTL_MS`].
544    ///
545    /// [`DEFAULT_MCP_TOOLS_LIST_TTL_MS`]: super::DEFAULT_MCP_TOOLS_LIST_TTL_MS
546    pub tools_list_ttl_ms: Option<u64>,
547    /// The `pollIntervalMs` advertised on a created task. Defaults to
548    /// [`DEFAULT_MCP_TASK_POLL_INTERVAL_MS`].
549    ///
550    /// A hint to the client and nothing more: no server behaviour depends on
551    /// it. There is no task lifetime beside it, because an MCP task here is a
552    /// projection of a durable run and has nothing to expire.
553    ///
554    /// [`DEFAULT_MCP_TASK_POLL_INTERVAL_MS`]: super::DEFAULT_MCP_TASK_POLL_INTERVAL_MS
555    pub task_poll_interval_ms: Option<u64>,
556}
557
558impl McpConfig {
559    /// Refuse a zero poll interval at startup.
560    ///
561    /// Only meaningful when the surface is enabled: a dark surface's knobs are
562    /// never read, so refusing a boot over one would be refusing over a value
563    /// nothing uses.
564    ///
565    /// # Errors
566    ///
567    /// [`ServerError::Config`] when an explicitly-set interval is zero. A zero
568    /// poll interval is a busy loop, not a fast one, and the operator is told
569    /// so rather than being handed one.
570    pub(super) fn validate(&self) -> Result<(), ServerError> {
571        if !self.enabled {
572            return Ok(());
573        }
574        if self.task_poll_interval_ms == Some(0) {
575            return config_error(MCP_TASK_POLL_INTERVAL_REQUIRED);
576        }
577        Ok(())
578    }
579
580    /// Resolve every omitted knob to its default.
581    ///
582    /// A zero poll interval resolves to the DEFAULT rather than to zero.
583    /// [`Self::validate`] has already refused it on any loaded configuration,
584    /// so this arm is reachable only from a hand-constructed config that
585    /// skipped validation — and for that case a documented default is the safe
586    /// direction, where a literal zero would be a busy loop.
587    #[must_use]
588    pub fn resolved(&self) -> ResolvedMcpConfig {
589        ResolvedMcpConfig {
590            enabled: self.enabled,
591            allowed_origins: self.allowed_origins.clone(),
592            discover_ttl_ms: self.discover_ttl_ms.unwrap_or(DEFAULT_MCP_DISCOVER_TTL_MS),
593            tools_list_ttl_ms: self
594                .tools_list_ttl_ms
595                .unwrap_or(DEFAULT_MCP_TOOLS_LIST_TTL_MS),
596            task_poll_interval_ms: self
597                .task_poll_interval_ms
598                .filter(|value| *value > 0)
599                .unwrap_or(DEFAULT_MCP_TASK_POLL_INTERVAL_MS),
600        }
601    }
602}
603
604impl Default for ResolvedMcpConfig {
605    /// The dark surface: not mounted, no origin permitted, every lifetime at
606    /// its documented default. This is what an embedder that never configures
607    /// MCP gets, and it serves nothing.
608    fn default() -> Self {
609        McpConfig::default().resolved()
610    }
611}
612
613/// The `[mcp]` section with every omitted knob resolved.
614///
615/// Held in [`RuntimeConfig`](super::RuntimeConfig) so the mount reads settled
616/// values rather than re-deriving defaults at each composition point.
617#[derive(Clone, Debug, PartialEq, Eq)]
618pub struct ResolvedMcpConfig {
619    /// Whether the `/mcp` endpoint is mounted.
620    pub enabled: bool,
621    /// Browser origins permitted to reach the endpoint.
622    pub allowed_origins: Vec<String>,
623    /// `ttlMs` on `server/discover`.
624    pub discover_ttl_ms: u64,
625    /// `ttlMs` on `tools/list`.
626    pub tools_list_ttl_ms: u64,
627    /// Advertised client poll interval for a task.
628    pub task_poll_interval_ms: u64,
629}
630
631/// Agent-observability transcript settings from `[observability]`: retention
632/// bounds, and the transcript drain's flush policy.
633///
634/// The two RETENTION knobs default (they guard the durable `O` keyspace against
635/// unbounded growth): `max_event_bytes` truncates one oversized transcript event
636/// before it is persisted, and `max_stream_events` caps how many events one
637/// `(workflow, activity, attempt)` stream retains (one marker record is
638/// persisted at the cap; live streaming continues).
639///
640/// The two FLUSH knobs have **no default and are required** — see
641/// [`Self::max_batch_events`].
642#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq)]
643#[serde(default, deny_unknown_fields)]
644pub struct ObservabilityConfig {
645    /// Ceiling on one persisted transcript event's serialized size, bytes.
646    pub max_event_bytes: usize,
647    /// Ceiling on retained events per `(workflow, activity, attempt)` stream.
648    pub max_stream_events: u64,
649    /// Maximum transcript events the drain commits in ONE durable append.
650    /// **Required; no default** — the server refuses to start without it.
651    ///
652    /// Every durable commit re-persists its whole containing storage leaf as a
653    /// new permanent blob, so committing one event at a time made the store cost
654    /// of a run linear in event COUNT: measured 2026-08-17, a 136 KB status
655    /// sweep left 73.7 MB of permanent store (540x) and a single 2,359-byte
656    /// append bought a 2,303,416-byte blob. Batching divides that count by (up
657    /// to) this number.
658    ///
659    /// There is deliberately no shipped value: the trade between store cost and
660    /// how many events one refused commit can lose is the operator's, and an
661    /// invented default would silently make it for them. Absent or zero fails
662    /// startup with [`OBSERVABILITY_MAX_BATCH_EVENTS_REQUIRED`], the same
663    /// explicit-no-default guard `websocket.cluster_broadcast_capacity` uses.
664    ///
665    /// [`OBSERVABILITY_MAX_BATCH_EVENTS_REQUIRED`]: super::OBSERVABILITY_MAX_BATCH_EVENTS_REQUIRED
666    pub max_batch_events: Option<usize>,
667    /// How long, in milliseconds, the drain may hold a PARTIAL batch open
668    /// waiting for it to fill. **Required; no default** — but `0` is a valid,
669    /// meaningful setting: never wait, commit whatever is already queued.
670    ///
671    /// This is the only knob here that touches durability timing. Transcript
672    /// events already wait in an in-memory queue before they are committed, and
673    /// everything queued there is lost if the process dies; this value bounds
674    /// how much LONGER an event may wait, and therefore how much transcript a
675    /// kill-9 can cost. It buys commits: at `0` only events that genuinely
676    /// arrived together share a commit. The `O` keyspace is observability, never
677    /// workflow replay authority, which is why the trade is offered at all.
678    ///
679    /// Absent fails startup with [`OBSERVABILITY_MAX_BATCH_HOLD_MS_REQUIRED`].
680    ///
681    /// [`OBSERVABILITY_MAX_BATCH_HOLD_MS_REQUIRED`]: super::OBSERVABILITY_MAX_BATCH_HOLD_MS_REQUIRED
682    pub max_batch_hold_ms: Option<u64>,
683}
684
685impl ObservabilityConfig {
686    /// The default retention bounds with the REQUIRED flush policy stated.
687    ///
688    /// For an embedder that builds its `ServerConfig` in code rather than from
689    /// a file: [`Default`] deliberately leaves the flush policy unruled (so a
690    /// server built from it refuses to start), and this is how such a caller
691    /// states its ruling in one line. `max_batch_hold_ms` of `0` means the drain
692    /// never holds a partial batch open.
693    #[must_use]
694    pub fn with_flush_policy(max_batch_events: usize, max_batch_hold_ms: u64) -> Self {
695        Self {
696            max_batch_events: Some(max_batch_events),
697            max_batch_hold_ms: Some(max_batch_hold_ms),
698            ..Self::default()
699        }
700    }
701
702    /// Validate the retention bounds: both must be positive — a zero event
703    /// ceiling truncates every event to nothing and a zero stream cap retains
704    /// no transcript at all, so each is a genuine misconfiguration caught at
705    /// startup with an operator-facing message (the `WebSocketConfig` pattern).
706    pub(super) fn validate(&self) -> Result<(), ServerError> {
707        if self.max_event_bytes == 0 {
708            return config_error(OBSERVABILITY_MAX_EVENT_BYTES_REQUIRED);
709        }
710        if self.max_stream_events == 0 {
711            return config_error(OBSERVABILITY_MAX_STREAM_EVENTS_REQUIRED);
712        }
713        // The FLUSH policy is deliberately not checked here. Both retention
714        // bounds have documented defaults, so an omitted value is a resolved
715        // value and this function can decide it at parse time; the flush policy
716        // has no default at all, and a parsed `ServerConfig` is not yet a
717        // running server (embedders and `aion config` inspect one without
718        // booting). It is required where it is USED — at publisher
719        // construction on the server boot path, `state.rs`'s
720        // `required_transcript_batch_policy` — which is the same seam
721        // `websocket.cluster_broadcast_capacity` is finally required at, and
722        // which fails startup loudly, naming the missing key.
723        Ok(())
724    }
725}
726
727impl Default for ObservabilityConfig {
728    /// The retention bounds fall back to their documented defaults; the flush
729    /// policy does NOT — `None` here is "the operator has not ruled", which the
730    /// boot path turns into a refusal to start, not into a guess.
731    fn default() -> Self {
732        Self {
733            max_event_bytes: DEFAULT_OBSERVABILITY_MAX_EVENT_BYTES,
734            max_stream_events: DEFAULT_OBSERVABILITY_MAX_STREAM_EVENTS,
735            max_batch_events: None,
736            max_batch_hold_ms: None,
737        }
738    }
739}
740
741/// Operator deploy API settings from `[deploy]`.
742///
743/// The deploy surface is dark by default: with `enabled = false` (or the
744/// section absent) neither the `/deploy/*` HTTP routes nor the gRPC
745/// `DeployService` are mounted, so a workflow server that is not a deploy
746/// target exposes no deploy attack surface at all.
747#[derive(Clone, Debug, Default, Deserialize)]
748#[serde(default, deny_unknown_fields)]
749pub struct DeployConfig {
750    /// Whether the deploy surface is mounted. Defaults to false.
751    pub enabled: bool,
752    /// Upload-size ceiling for `.aion` archives, in bytes. Defaults to
753    /// [`DEFAULT_DEPLOY_MAX_ARCHIVE_BYTES`] when omitted and `enabled = true`,
754    /// so turning deploy on does not force sizing a security ceiling; the
755    /// operator overrides it for their packages.
756    ///
757    /// [`DEFAULT_DEPLOY_MAX_ARCHIVE_BYTES`]: super::DEFAULT_DEPLOY_MAX_ARCHIVE_BYTES
758    pub max_archive_bytes: Option<u64>,
759    /// Inflate ceiling for uploaded archive contents, in bytes: the total
760    /// decompressed size of all archive entries an upload may extract to
761    /// (DEFLATE bombs inflate ~1000:1 past `max_archive_bytes`). Defaults to
762    /// [`DEFAULT_DEPLOY_MAX_INFLATED_BYTES`] when omitted and `enabled = true`;
763    /// must be at least `max_archive_bytes`.
764    ///
765    /// [`DEFAULT_DEPLOY_MAX_INFLATED_BYTES`]: super::DEFAULT_DEPLOY_MAX_INFLATED_BYTES
766    pub max_inflated_bytes: Option<u64>,
767}
768
769/// Local dev-server surface settings from `[dev]`.
770///
771/// The dev surface is dark by default, gated on `enabled`: with it false (the
772/// section absent or `enabled = false`) the `/dev/*` routes are not mounted,
773/// the engine installs the bare production activity dispatcher (no mocking
774/// decorator), and nothing dev-specific is ever reachable. Setting `enabled =
775/// true` mounts the dev endpoints and installs the per-run activity-mock
776/// decorator — a development affordance, never on in production. It adds no
777/// arbitrary defaults (ADR-001): the only knob is the on/off gate.
778#[derive(Clone, Debug, Default, Deserialize)]
779#[serde(default, deny_unknown_fields)]
780pub struct DevConfig {
781    /// Whether the local dev-server surface is mounted. Defaults to false.
782    pub enabled: bool,
783}
784
785/// Durable-outbox fan-out dispatcher settings from `[outbox]`.
786///
787/// The outbox dispatcher is dark by default, gated on `enabled`: with it false
788/// (the section absent or `enabled = false`) the non-replayed background task
789/// that claims pending outbox rows and dispatches them to connected workers is
790/// never spawned, so default server behaviour is unchanged and the live
791/// workflow dispatch path is the only dispatch path. Setting `enabled = true`
792/// commissions the dispatcher; its operational knobs below — poll interval,
793/// claim batch size, retry budget, and the backoff curve — are pure tuning, so
794/// each resolves to a sane default when omitted rather than forcing the
795/// operator to hand-author tuning values just to turn the feature on. An
796/// explicitly set value (including a misconfigured `0`) is still validated.
797///
798/// Scope: this Phase-2 dispatcher dispatches claimed rows and marks each row's
799/// terminal outbox state (done / retry / failed). Routing the worker completion
800/// back into workflow history through the Recorder is Phase 3 and is not wired
801/// here; with the flag off there is no behavioural difference at all.
802#[derive(Clone, Debug, Default, Deserialize)]
803#[serde(default, deny_unknown_fields)]
804pub struct OutboxConfig {
805    /// Whether the outbox dispatcher background task is spawned. Defaults to
806    /// false, leaving the dispatcher dark and server behaviour unchanged.
807    pub enabled: bool,
808    /// Interval between successive claim sweeps, in milliseconds. Defaults to
809    /// [`DEFAULT_OUTBOX_POLL_INTERVAL_MS`] when omitted and `enabled = true`;
810    /// override to size the poll cadence for fan-out volume and latency budget.
811    ///
812    /// [`DEFAULT_OUTBOX_POLL_INTERVAL_MS`]: super::DEFAULT_OUTBOX_POLL_INTERVAL_MS
813    pub poll_interval_ms: Option<u64>,
814    /// Maximum number of pending rows claimed per sweep. Defaults to
815    /// [`DEFAULT_OUTBOX_BATCH_SIZE`] when omitted and `enabled = true`.
816    ///
817    /// [`DEFAULT_OUTBOX_BATCH_SIZE`]: super::DEFAULT_OUTBOX_BATCH_SIZE
818    pub batch_size: Option<u32>,
819    /// Dispatch attempts before a row is dead-lettered to `failed`. Defaults to
820    /// [`DEFAULT_OUTBOX_MAX_ATTEMPTS`] when omitted and `enabled = true`. Must
821    /// be at least one.
822    ///
823    /// [`DEFAULT_OUTBOX_MAX_ATTEMPTS`]: super::DEFAULT_OUTBOX_MAX_ATTEMPTS
824    pub max_attempts: Option<u32>,
825    /// Base retry backoff applied to the first retry, in milliseconds. Defaults
826    /// to [`DEFAULT_OUTBOX_BACKOFF_BASE_MS`] when omitted and `enabled = true`.
827    /// Successive retries multiply this by `backoff_multiplier` raised to the
828    /// prior-attempt count, capped at `backoff_max_ms`.
829    ///
830    /// [`DEFAULT_OUTBOX_BACKOFF_BASE_MS`]: super::DEFAULT_OUTBOX_BACKOFF_BASE_MS
831    pub backoff_base_ms: Option<u64>,
832    /// Geometric growth factor applied to the backoff per prior attempt.
833    /// Defaults to [`DEFAULT_OUTBOX_BACKOFF_MULTIPLIER`] when omitted and
834    /// `enabled = true`. Must be at least one so backoff never shrinks.
835    ///
836    /// [`DEFAULT_OUTBOX_BACKOFF_MULTIPLIER`]: super::DEFAULT_OUTBOX_BACKOFF_MULTIPLIER
837    pub backoff_multiplier: Option<u32>,
838    /// Upper bound on a single retry's backoff, in milliseconds. Defaults to
839    /// [`DEFAULT_OUTBOX_BACKOFF_MAX_MS`] when omitted and `enabled = true`. Must
840    /// be at least `backoff_base_ms`.
841    ///
842    /// [`DEFAULT_OUTBOX_BACKOFF_MAX_MS`]: super::DEFAULT_OUTBOX_BACKOFF_MAX_MS
843    pub backoff_max_ms: Option<u64>,
844    /// Interval between live stale-claim reconciliation sweeps, in milliseconds. When both
845    /// reconciliation knobs are absent the live sweep remains dark; setting either knob opts into
846    /// reconciliation and requires both values to be positive.
847    pub reconcile_interval_ms: Option<u64>,
848    /// Age after which a durable `claimed` outbox row is considered stranded, in milliseconds. The
849    /// reconciler re-arms only rows with `claimed_at` older than this threshold, preserving their
850    /// attempt count.
851    pub reconcile_stale_after_ms: Option<u64>,
852    /// Wire transport the dispatcher uses to place a claimed row with a worker.
853    /// Defaults to [`OutboxTransport::Liminal`] whenever the `liminal-transport`
854    /// Cargo feature is compiled (the default ablative-stack build), so an
855    /// outbox-enabled server uses the liminal cross-node transport out of the box;
856    /// a slim build without that feature defaults to [`OutboxTransport::Grpc`].
857    /// Selecting `liminal` in a build without the feature is a configuration error
858    /// surfaced at spawn. The transport only matters when `outbox.enabled = true`.
859    pub transport: OutboxTransport,
860    /// Address (`host:port`) the aion-server LISTENS on for inbound liminal
861    /// worker connections, used only when `transport = liminal`. REQUIRED in that
862    /// mode; ignored otherwise.
863    ///
864    /// The aion-server HOSTS the liminal listener: a remote `LiminalActivityWorker`
865    /// connects IN to this address and self-registers in-band, so the server's
866    /// [`ConnectionSupervisor`](liminal_server::server::connection::ConnectionSupervisor)
867    /// owns the worker's connection and can push a dispatch out on it
868    /// (`push_to_connection`). This replaces the superseded 13-0 spike's
869    /// client-connect address: the dispatcher no longer *connects out* to publish
870    /// to a channel — it pushes to a connected worker the server already owns.
871    ///
872    /// The dispatch *channel* is not configured here: it is derived per-row from
873    /// each row's durable `(namespace, task_queue)` via `dispatch_channel_name`
874    /// (NSTQ-5), so one listener fans different worker pools out by selection.
875    pub liminal_listen_address: Option<String>,
876}
877
878/// Wire transport selected for outbox dispatch.
879///
880/// `liminal` (the default whenever the `liminal-transport` feature is compiled —
881/// which it is in the default ablative-stack build) routes the dispatch over the
882/// liminal cross-node bus. `grpc` keeps the connected-worker registry path. A
883/// slim build compiled WITHOUT `liminal-transport` falls back to `grpc` as the
884/// default so the default is always constructible under the active feature set.
885#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Deserialize)]
886#[serde(rename_all = "lowercase")]
887pub enum OutboxTransport {
888    /// Dispatch over the in-process connected-worker gRPC registry. The default
889    /// in a slim build compiled WITHOUT `liminal-transport`, which cannot
890    /// construct the liminal path.
891    // The default variant is feature-selected: gRPC when the liminal transport is
892    // absent (it is the only constructible path), liminal otherwise.
893    #[cfg_attr(not(feature = "liminal-transport"), default)]
894    Grpc,
895    /// Dispatch over the liminal cross-node bus (requires `liminal-transport`).
896    /// The out-of-box default whenever `liminal-transport` is compiled (the
897    /// default ablative-stack feature set), so an outbox-enabled server uses the
898    /// ablative messaging transport without extra configuration.
899    #[cfg_attr(feature = "liminal-transport", default)]
900    Liminal,
901}
902
903/// Server-side authoring settings from `[authoring]`.
904///
905/// The AWL studio is on by default, rooted at `<AION_HOME>/authoring`, so a
906/// stock `aion server` provides its document, layout, check, deploy, revision,
907/// run, and scaffold surfaces without preliminary configuration. Operators can
908/// override it explicitly.
909///
910/// Only the separate Gleam authoring loop remains dark by default: without
911/// `gleam_path`, `/authoring/*` is not mounted and nothing invokes `gleam`
912/// (CN7). Setting `gleam_path` commissions that loop and makes `project_root`
913/// required.
914#[derive(Clone, Debug, Default, Deserialize)]
915#[serde(default, deny_unknown_fields)]
916pub struct AuthoringConfig {
917    /// Path to the external `gleam` binary the toolchain spawns. `None`
918    /// (the default) leaves only the Gleam authoring loop dark; setting it gates
919    /// the `/authoring/*` endpoints on. There is no default binary — the
920    /// operator names it explicitly.
921    pub gleam_path: Option<PathBuf>,
922    /// Built Gleam workflow project root submitted source is written into and
923    /// packaged from. REQUIRED when `gleam_path` is set; no default (house
924    /// rule) — a Gleam project needs `gleam.toml`, the `aion_flow` dependency,
925    /// `workflow.toml`, and `schemas/`, so the operator provisions and names
926    /// the project root.
927    pub project_root: Option<PathBuf>,
928    /// Root directory exposed by the full AWL studio surface. The merged server
929    /// loader defaults this to `<AION_HOME>/authoring` after config and
930    /// environment overlays. `authoring.workspace_dir` or
931    /// `AION_AUTHORING_WORKSPACE_DIR` therefore overrides it explicitly.
932    pub workspace_dir: Option<PathBuf>,
933}
934
935impl Default for ServerSection {
936    fn default() -> Self {
937        Self {
938            listen_address: DEFAULT_HTTP_ADDRESS,
939            grpc_address: DEFAULT_GRPC_ADDRESS,
940            cors_allowed_origins: Vec::new(),
941        }
942    }
943}
944
945impl Default for StoreConfig {
946    fn default() -> Self {
947        Self {
948            // The ablative stack is the out-of-box durable default: an empty
949            // config selects the haematite backend. The merged loader fills
950            // `<AION_HOME>/data`; `memory` remains an explicit dev choice.
951            backend: StoreBackend::Haematite,
952            retired_input: None,
953            owned_shards: Vec::new(),
954            data_dir: None,
955            // NOT a default: `None` is "the operator has not ruled", which the
956            // haematite boot path turns into a refusal to start, not a guess.
957            node_cache_budget: None,
958            lock_acquisition_patience_ms: None,
959            lock_acquisition_retry_cadence_ms: None,
960            // 64, NOT 4096 (#187): raising the default to 4096 bricked every
961            // fresh server — engine boot's scan_prefix materializes every
962            // shard, then each haematite 0.4.0 commit fans out one thread +
963            // fsync PER MATERIALIZED SHARD (~8k fsyncs/commit), blowing the
964            // 5s shard-actor timeout on deploy/start/timers/outbox. Re-raise
965            // only after haematite makes commit O(dirty shards) and the
966            // scaffold e2es pass at the new default (see #187 fix plan).
967            shard_count: 64,
968            cluster: None,
969        }
970    }
971}
972
973impl Default for RuntimeSection {
974    fn default() -> Self {
975        Self {
976            scheduler_threads: 1,
977            // Absent on purpose, for a different reason than the deadline
978            // below: this one is deferred to beamr's own default rather than
979            // demanded from the operator. The server must not name a
980            // compilation threshold it did not choose.
981            jit_threshold: None,
982            // Deliberately absent: validation fails loudly until the operator
983            // sets the workflow query reply deadline for the deployment.
984            query_timeout_ms: None,
985        }
986    }
987}
988
989impl Default for DrainConfig {
990    fn default() -> Self {
991        Self {
992            timeout_seconds: 30,
993        }
994    }
995}
996
997impl Default for AuthConfig {
998    fn default() -> Self {
999        Self {
1000            enabled: false,
1001            jwks_url: None,
1002            jwks_refresh_seconds: 300,
1003        }
1004    }
1005}
1006
1007impl Default for MetricsConfig {
1008    fn default() -> Self {
1009        Self { enabled: true }
1010    }
1011}
1012
1013impl Default for NamespacesConfig {
1014    fn default() -> Self {
1015        Self {
1016            default: "default".to_owned(),
1017            auto_create: AutoCreate::default(),
1018            max_in_flight_activities: DEFAULT_MAX_IN_FLIGHT_ACTIVITIES,
1019        }
1020    }
1021}
1022
1023impl Default for ListenConfig {
1024    fn default() -> Self {
1025        Self {
1026            grpc: DEFAULT_GRPC_ADDRESS,
1027            http: DEFAULT_HTTP_ADDRESS,
1028        }
1029    }
1030}
1031
1032impl Default for OpsConsoleConfig {
1033    fn default() -> Self {
1034        Self {
1035            source: OpsConsoleAssetSource::Embedded,
1036        }
1037    }
1038}
1039
1040impl Default for NamespaceConfig {
1041    fn default() -> Self {
1042        Self {
1043            mode: NamespaceMode::SharedEngine,
1044        }
1045    }
1046}
1047
1048impl Default for WorkerConfig {
1049    fn default() -> Self {
1050        Self {
1051            heartbeat_window: Duration::from_secs(30),
1052            queue_service: crate::worker::queue_service::QueueServiceConfig::default(),
1053        }
1054    }
1055}
1056
1057impl Default for WebSocketConfig {
1058    fn default() -> Self {
1059        Self {
1060            outbound_buffer_bound: 32,
1061            // Deliberately absent: validation fails loudly until the operator
1062            // sizes the engine-global broadcast channel for the deployment.
1063            event_broadcast_capacity: None,
1064            // Deliberately absent for the same reason: the cluster channel has
1065            // no defined lag buffer until sized.
1066            cluster_broadcast_capacity: None,
1067        }
1068    }
1069}
1070
1071mod duration_millis {
1072    use std::time::Duration;
1073
1074    use serde::{Deserialize, Deserializer};
1075
1076    pub(super) fn deserialize<'de, D>(deserializer: D) -> Result<Duration, D::Error>
1077    where
1078        D: Deserializer<'de>,
1079    {
1080        let millis = u64::deserialize(deserializer)?;
1081        Ok(Duration::from_millis(millis))
1082    }
1083}