Skip to main content

liminal_server/
error.rs

1use std::net::SocketAddr;
2
3use crate::server::participant::ParticipantServiceFatal;
4
5const RESERVED_NAMESPACE_MESSAGE: &str =
6    "SELF_STREAM_NAMESPACE_REFUSED: connection publication to reserved namespace";
7
8/// Error taxonomy for standalone liminal server deployment failures.
9#[derive(Debug, thiserror::Error)]
10pub enum ServerError {
11    /// The configuration file could not be read or parsed.
12    #[error("configuration load failed: {message}")]
13    ConfigLoad { message: String },
14
15    /// The configuration file was read but failed semantic validation.
16    #[error("configuration validation failed: {message}")]
17    ConfigValidation { message: String },
18
19    /// A connection tried to publish into the server-owned namespace.
20    #[error("{RESERVED_NAMESPACE_MESSAGE}: {channel}")]
21    ReservedNamespace {
22        /// Reserved channel the connection addressed.
23        channel: String,
24    },
25
26    /// The server could not bind its configured listener address.
27    #[error("listener bind failed for {address}: {source}")]
28    ListenerBind {
29        /// Address the server attempted to bind.
30        address: SocketAddr,
31        /// Underlying operating-system bind failure.
32        #[source]
33        source: std::io::Error,
34    },
35
36    /// The server listener failed while accepting an inbound connection.
37    #[error("listener accept failed: {message}")]
38    ListenerAccept { message: String },
39
40    /// A prior publisher finish consumed the original error.
41    #[error("self-stream publisher already finished with an error: {first_error}")]
42    SelfStreamPublisherAlreadyFinished {
43        /// Full diagnostic returned by the first finish.
44        first_error: String,
45    },
46
47    /// Durable participant-incarnation startup or allocation failed before its
48    /// result could be published.
49    #[error("participant incarnation {phase} failed: {message}")]
50    ParticipantIncarnation {
51        /// Exact server seam that failed.
52        phase: &'static str,
53        /// Underlying durable or bounded-bridge diagnostic.
54        message: String,
55    },
56
57    /// A durable connection-fate Open could not be completed in this process.
58    ///
59    /// The normal runtime shutdown path returns this typed fatal only after it has
60    /// stopped both listeners and run the ordinary connection drain/flush sequence.
61    #[error("participant service fatal: {fatal}")]
62    ParticipantServiceFatal {
63        /// First process-wide post-Open failure; later failures cannot replace it.
64        fatal: ParticipantServiceFatal,
65    },
66
67    /// Startup found durable connection-fate work that the Decision A/C producer must complete
68    /// before listener or semantic-service publication.
69    #[error(
70        "participant startup requires recovery of {open_count} connection-fate Opens beginning at sequence {first_open_sequence}"
71    )]
72    ConnectionFateRecoveryRequired {
73        /// Number of replay-validated unmatched Opens.
74        open_count: usize,
75        /// Lowest unmatched Open sequence.
76        first_open_sequence: u64,
77    },
78
79    /// The durable server-incarnation namespace has no successor.
80    #[error("participant server-incarnation namespace is exhausted")]
81    ServerIncarnationExhausted,
82
83    /// Production participant startup restore failed: the durable
84    /// conversation streams could not be scanned or replayed, so the
85    /// server-scope capacity ledger cannot be made exact and the server
86    /// refuses to start over state it cannot account for.
87    #[error("participant startup restore failed: {message}")]
88    ParticipantStartupRestore {
89        /// Underlying durable, replay, or bridge diagnostic.
90        message: String,
91    },
92
93    /// The current durable server incarnation has no collision-free connection
94    /// ordinal left, so the accepted socket was not admitted.
95    #[error(
96        "connection incarnation exhausted for server incarnation {attempted_server_incarnation}"
97    )]
98    ConnectionIncarnationExhausted {
99        /// Server incarnation whose complete ordinal suffix was examined.
100        attempted_server_incarnation: u64,
101    },
102
103    /// A connection registration found a record already present under its pid.
104    /// Enforces the pids-fresh-per-spawn supervision invariant loudly: a silent
105    /// replace would drop the displaced record's teardown-held fd guard outside
106    /// the single record-removal funnel (orphaning a live connection's stream)
107    /// and increment the `liminal_connections_active` gauge a second time with
108    /// no paired decrement. The whole registration is refused instead, leaving
109    /// the prior record — and its teardown route — intact.
110    #[error("connection registration refused: pid {pid} already has a live registry record")]
111    ConnectionPidCollision {
112        /// The connection pid that already owned a registry record.
113        pid: u64,
114    },
115
116    /// A frame requested an operation the configured services profile does not
117    /// serve (e.g. ordinary publish/subscribe/conversation traffic against the
118    /// capability-scoped worker front door). Server-internal taxonomy, not wire
119    /// vocabulary: the connection process renders it as the operation's existing
120    /// typed error frame with this error's text as the message.
121    #[error("{operation} is not supported by the {profile} services profile")]
122    UnsupportedOperation {
123        /// Human-readable description of the refused operation.
124        operation: String,
125        /// The configured services profile that refused it.
126        profile: &'static str,
127    },
128
129    /// A server→client push reply slot was dropped before a correlated reply
130    /// arrived — the connection closed (the prompt worker-death signal). Distinct
131    /// from [`Self::PushReplyTimeout`] so consumers can tell a worker that DIED
132    /// (fast failover) from one that is merely SLOW, by type rather than message.
133    #[error(
134        "push correlation {correlation_id} did not complete: the connection closed before sending a correlated push reply"
135    )]
136    PushReplyDisconnected {
137        /// Correlation id of the push whose reply will never arrive.
138        correlation_id: u64,
139    },
140
141    /// A server→client push reply did not arrive within the awaiter's timeout —
142    /// the worker is still connected but did not reply in this wait quantum. This
143    /// is BENIGN: the reply slot survives untouched and the caller may re-arm
144    /// [`PushReplyAwaiter::receive`](crate::server::connection::PushReplyAwaiter::receive)
145    /// indefinitely. It is not a worker-death signal.
146    #[error(
147        "push correlation {correlation_id} did not complete: no correlated push reply arrived within the timeout"
148    )]
149    PushReplyTimeout {
150        /// Correlation id of the push whose wait quantum elapsed.
151        correlation_id: u64,
152    },
153
154    /// A server→client push carrying an explicit reply deadline (via
155    /// [`push_to_connection_with_deadline`](crate::server::connection::ConnectionSupervisor::push_to_connection_with_deadline))
156    /// reached that deadline before a correlated reply arrived. Unlike
157    /// [`Self::PushReplyTimeout`] this is TERMINAL: the reply slot has been
158    /// removed and its §5 `max_pending_pushes_per_connection` cap admission
159    /// released. Returned PROMPTLY once the deadline is due — a `receive` call
160    /// does not hold a due expiry until its caller's quantum ends, so the
161    /// terminal outcome is independent of how the caller polls. Distinct
162    /// variant so callers classify by type, not message.
163    #[error(
164        "push correlation {correlation_id} did not complete: its reply deadline passed before a correlated push reply arrived"
165    )]
166    PushReplyExpired {
167        /// Correlation id of the push whose reply deadline passed.
168        correlation_id: u64,
169    },
170
171    /// A server→client push was never queued for the wire: its encoded frame is
172    /// larger than the WHOLE of the connection's bounded outbound buffer, so no
173    /// amount of draining could ever make room for it. TERMINAL and CERTAIN — the
174    /// reply slot is removed, its §5 `max_pending_pushes_per_connection` admission
175    /// released, and the client never saw a `Push` frame for this correlation id.
176    ///
177    /// Deliberately NARROW. A frame that would fit an empty buffer but not the
178    /// current free space is CONGESTION, not a size defect: it keeps the
179    /// connection-teardown path and its retryable
180    /// [`Self::PushReplyDisconnected`] reading, because waiting is the correct
181    /// answer there. Sharing one outcome between the certain case and the
182    /// recoverable one would leave the caller unable to tell them apart — which
183    /// is the exact fault this variant exists to end. Distinct variant so callers
184    /// classify by type, not message.
185    ///
186    /// The WORDS carry the bound's value and say the bound was chosen, because a
187    /// reader who meets this without that context blames the server for a number
188    /// an operator set. Since every outbound bound now comes from
189    /// [`max_connection_outbound_bytes`](crate::config::types::LimitsConfig::max_connection_outbound_bytes),
190    /// that sentence is true on every occurrence rather than usually.
191    #[error(
192        "push correlation {correlation_id} was never sent: its {needed}-byte frame exceeds this \
193         connection's whole outbound buffer of {capacity} bytes, which is operator-set by \
194         `limits.max_connection_outbound_bytes`"
195    )]
196    PushFrameExceedsOutboundCapacity {
197        /// Correlation id of the push that could not be queued.
198        correlation_id: u64,
199        /// Encoded size of the rejected frame. Exceeds `capacity` on its own.
200        needed: usize,
201        /// The outbound buffer's whole capacity, which `needed` exceeds.
202        capacity: usize,
203        /// Bytes already queued when the frame was rejected. Context for the log
204        /// only: the decision is `needed` against `capacity` alone, so this frame
205        /// would not have fitted an empty buffer either.
206        queued: usize,
207    },
208
209    /// The server could not join the configured beamr distribution cluster.
210    #[error("cluster join failed: {message}")]
211    ClusterJoin { message: String },
212
213    /// Cluster state propagation through beamr distribution failed.
214    #[error("cluster sync failed: {message}")]
215    ClusterSync { message: String },
216
217    /// Graceful shutdown did not drain within the configured timeout.
218    #[error("shutdown timed out: {message}")]
219    ShutdownTimeout { message: String },
220
221    /// Durable state could not be flushed during graceful shutdown.
222    #[error("shutdown flush failed: {message}")]
223    ShutdownFlush { message: String },
224
225    /// A clean stop could not complete every connection fate parked on
226    /// candidate-lane `Precedence`. Each named durable Open is reconciled by
227    /// the next boot instead, so the stop was not clean.
228    #[error(
229        "shutdown left connection fates unsettled for the next boot to reconcile: durable Opens \
230         {open_sequences:?}"
231    )]
232    ShutdownUnsettledConnectionFates {
233        /// Durable Open sequences still parked when the stop finished.
234        open_sequences: Vec<u64>,
235    },
236
237    /// The health endpoint failed to start or serve requests.
238    #[error("health endpoint failed: {message}")]
239    HealthEndpoint { message: String },
240
241    /// A new connection was refused because the configured `max_connections`
242    /// cap (§5) is already reached. The listener drops the freshly accepted
243    /// stream, refusing the connection, rather than admitting an unbounded fleet.
244    #[error(
245        "connection refused: the configured max_connections limit of {limit} live connections is reached"
246    )]
247    ConnectionLimitReached {
248        /// The configured `max_connections` cap that was hit.
249        limit: usize,
250    },
251
252    /// An admission-time per-connection cap (§5) refused an operation: too many
253    /// subscriptions, conversations, in-flight pushes, or pending conversation
254    /// replies on one connection. The connection process renders it as the
255    /// operation's existing typed error frame with this text as the message.
256    #[error("{operation} refused: the per-connection {cap} limit of {limit} is reached")]
257    ConnectionCapReached {
258        /// Human-readable description of the refused operation.
259        operation: String,
260        /// The name of the cap that refused it (a `limits.*` config key).
261        cap: &'static str,
262        /// The configured cap value that was hit.
263        limit: usize,
264    },
265
266    /// A publish whose append outcome is not known: the server cannot tell
267    /// whether the row was stored. Distinct from every definite publish failure
268    /// so the connection process answers it with its own reason code
269    /// (`PUBLISH_UNRESOLVED_CODE`) and a producer classifies it by type, never
270    /// by message; it is never a Reject, a Defer or a backpressure signal.
271    #[error(
272        "publish to channel {channel} is unresolved{}: {message}",
273        UnresolvedPublishDetail(.idempotency_key, .sequence)
274    )]
275    PublishUnresolved {
276        /// Channel the unresolved publish was addressed to.
277        channel: String,
278        /// Idempotency key the publish carried, when it carried one.
279        idempotency_key: Option<String>,
280        /// Sequence the append expected, when one was assigned.
281        sequence: Option<u64>,
282        /// The underlying append diagnostic, kept as evidence.
283        message: String,
284    },
285
286    /// The offline participant log migration refused.
287    #[error(transparent)]
288    ParticipantLogMigration(#[from] crate::server::participant::ParticipantLogMigrationError),
289}
290
291/// Renders the optional idempotency key and sequence of
292/// [`ServerError::PublishUnresolved`], naming each only when it is present.
293struct UnresolvedPublishDetail<'a>(&'a Option<String>, &'a Option<u64>);
294
295impl std::fmt::Display for UnresolvedPublishDetail<'_> {
296    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
297        if let Some(key) = self.0 {
298            write!(formatter, " (idempotency key {key})")?;
299        }
300        if let Some(sequence) = self.1 {
301            write!(formatter, " (sequence {sequence})")?;
302        }
303        Ok(())
304    }
305}