liminal-server 0.3.0

Standalone server for the liminal messaging bus
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
//! Participant transport-to-semantics dispatch boundary.
//!
//! This module contains no lifecycle rules. The shared protocol crate gates and
//! decodes inbound frames, while an injected semantic handler returns one typed
//! protocol value. The server then performs only generic-frame encoding.

use std::collections::BTreeSet;
use std::sync::Arc;

use liminal::durability::DurableStore;
use liminal::protocol::Frame;
use liminal_protocol::lifecycle::ConnectionConversationTracking;
use liminal_protocol::wire::{
    BindingEpoch, ClientRequest, CodecError, ConnectionIncarnation, ConversationId,
    ObserverRecoveryHandshake, ParticipantId, ServerValue, ValidatedFrameLimit,
};

use super::transport::{
    ParticipantIngress, ParticipantSession, encode_server_value, gate_generic_frame,
    normalize_configured_frame_limit,
};
use super::{
    ObserverPublicationTarget, ParticipantOfferedProgress, ParticipantPublication,
    ParticipantPublicationInbox, ParticipantPublicationRegistry,
};

/// Connection-local semantic-conversation dispatch map (contract R-D1: the
/// connection's binding/interest/dispatch maps are bounded by the signed
/// `max_semantic_conversations_per_connection`).
///
/// One value lives in each connection process's state for the connection's
/// lifetime and is dropped with it. A conversation enters the map exactly
/// when a semantic operation for it COMMITS on this connection (the crate's
/// `ConnectionConversationCapacityCommit::newly_tracked` verdict) or when an
/// observer-recovery batch arms its refusal-only recipient; refusals and
/// replays leave the map untouched, exactly as the crate's stage-6 selector
/// leaves its counter unchanged. Growth is therefore bounded by the signed
/// limit the stage-6 selector enforces.
#[derive(Debug, Default)]
pub struct ParticipantConnectionConversations {
    tracked: BTreeSet<ConversationId>,
}

impl ParticipantConnectionConversations {
    /// Stage-6 tracking fact for one conversation on this connection.
    #[must_use]
    pub fn tracking(&self, conversation_id: ConversationId) -> ConnectionConversationTracking {
        if self.tracked.contains(&conversation_id) {
            ConnectionConversationTracking::AlreadyTracked
        } else {
            ConnectionConversationTracking::Untracked
        }
    }

    /// Current connection-conversation occupancy.
    #[must_use]
    pub fn occupied(&self) -> u64 {
        // `usize` fits `u64` on every supported target; if that ever stopped
        // holding, saturating at MAX fails CLOSED (capacity reads as full)
        // rather than silently under-counting occupancy.
        u64::try_from(self.tracked.len()).unwrap_or(u64::MAX)
    }

    /// Installs one conversation slot after a capacity-committing operation.
    pub fn track(&mut self, conversation_id: ConversationId) {
        self.tracked.insert(conversation_id);
    }

    /// Sorted tracked conversations (the observer-recovery preflight's
    /// current-occupancy input).
    #[must_use]
    pub fn tracked_conversations(&self) -> Vec<ConversationId> {
        self.tracked.iter().copied().collect()
    }
}

/// Connection-scoped authority facts supplied to participant semantics.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ParticipantConnectionContext {
    connection_incarnation: ConnectionIncarnation,
}

impl ParticipantConnectionContext {
    /// Captures the durably allocated incarnation of the receiving connection.
    #[must_use]
    pub const fn new(connection_incarnation: ConnectionIncarnation) -> Self {
        Self {
            connection_incarnation,
        }
    }

    /// Returns the durably allocated receiving-connection incarnation.
    #[must_use]
    pub const fn connection_incarnation(self) -> ConnectionIncarnation {
        self.connection_incarnation
    }
}

/// Non-wire semantic service failure.
///
/// A failure is terminal to the connection attempt. It is deliberately not
/// convertible to [`ServerValue`], preventing the server from inventing a
/// lifecycle response when the protocol-owned transition did not produce one.
#[derive(Clone, Debug, thiserror::Error, PartialEq, Eq)]
pub enum ParticipantSemanticError {
    /// The complete semantic service is not installed.
    #[error("participant semantic service is unavailable")]
    Unavailable,
    /// Durable state or a protocol invariant prevented semantic completion.
    #[error("participant semantic service failed: {message}")]
    Internal {
        /// Diagnostic text for server logs; never placed on the participant wire.
        message: String,
    },
}

/// Server-owned adapter from a decoded request to a protocol-owned value.
pub trait ParticipantSemanticHandler: core::fmt::Debug + Send + Sync {
    /// Applies one already authenticated and capability-gated request.
    ///
    /// `conversations` is the receiving connection's semantic-conversation
    /// dispatch map: the handler reads it for the crate's stage-6
    /// connection-conversation capacity facts and installs a slot exactly
    /// when an operation's capacity commit reports `newly_tracked`.
    ///
    /// # Errors
    ///
    /// Returns [`ParticipantSemanticError`] when no protocol value can be
    /// produced. The caller closes rather than fabricating a response.
    ///
    /// Production handlers override this with the signed
    /// `max_semantic_conversations_per_connection`; semantic-only fixtures own
    /// no publication conversations.
    fn publication_conversation_limit(&self) -> u64 {
        0
    }

    /// Resolves all live current bindings with pending durable obligations for
    /// one conversation. Production overrides this; semantic-only fixtures have
    /// no publication source.
    ///
    /// # Errors
    ///
    /// Returns a semantic fault when durable readiness cannot be resolved.
    fn ready_connection_incarnations(
        &self,
        _conversation_id: ConversationId,
    ) -> Result<Vec<ConnectionIncarnation>, ParticipantSemanticError> {
        Ok(Vec::new())
    }

    /// Selects the least durable recipient obligation for this incarnation,
    /// restarting from durable ack when `offered` names an older binding.
    ///
    /// # Errors
    ///
    /// Returns a semantic fault when the durable obligation owner is unavailable.
    fn next_publication(
        &self,
        _connection_incarnation: ConnectionIncarnation,
        _conversation_id: ConversationId,
        _offered: Option<ParticipantOfferedProgress>,
    ) -> Result<Option<ParticipantPublication>, ParticipantSemanticError> {
        Ok(None)
    }

    /// Checks that a held head still belongs to the exact current binding before
    /// it is offered after writable readiness.
    ///
    /// # Errors
    ///
    /// Returns a semantic fault when current binding authority cannot be read.
    fn publication_binding_is_current(
        &self,
        _conversation_id: ConversationId,
        _participant_id: ParticipantId,
        _binding_epoch: BindingEpoch,
    ) -> Result<bool, ParticipantSemanticError> {
        Ok(false)
    }

    /// Records exact successful marker enqueue testimony. Non-marker offers are
    /// ignored by production after validating their current binding.
    ///
    /// # Errors
    ///
    /// Returns a semantic fault when exact offer testimony cannot be recorded.
    fn record_publication_offer(
        &self,
        _publication: &ParticipantPublication,
    ) -> Result<(), ParticipantSemanticError> {
        Ok(())
    }

    /// Applies observer recovery with the weak exact-live-connection target
    /// captured by the installed service. Semantic-only handlers delegate to
    /// their ordinary request path and do not own observer publication.
    ///
    /// # Errors
    ///
    /// Returns [`ParticipantSemanticError`] under the same contract as
    /// [`Self::handle`].
    fn handle_observer_recovery(
        &self,
        context: ParticipantConnectionContext,
        conversations: &mut ParticipantConnectionConversations,
        request: ObserverRecoveryHandshake,
        target: Option<ObserverPublicationTarget>,
    ) -> Result<ServerValue, ParticipantSemanticError> {
        drop(target);
        self.handle(
            context,
            conversations,
            ClientRequest::ObserverRecovery(request),
        )
    }

    /// Applies one decoded participant request to protocol-owned authority.
    ///
    /// # Errors
    ///
    /// Returns [`ParticipantSemanticError`] when durable or protocol authority
    /// cannot produce a truthful terminal value. The connection fails rather
    /// than fabricating a response.
    fn handle(
        &self,
        context: ParticipantConnectionContext,
        conversations: &mut ParticipantConnectionConversations,
        request: ClientRequest,
    ) -> Result<ServerValue, ParticipantSemanticError>;
}

/// Server-sealed participant activation token installed on a connection
/// supervisor.
///
/// The semantic handler and its durable store form one value so participant
/// capability activation cannot observe one without the other. The supervisor
/// uses the store to durably allocate connection incarnations before spawning a
/// connection process, and the process uses the handler only after that exact
/// incarnation has been carried into its state. The token atomically carries the
/// pair declared by server composition; it does not independently prove storage
/// namespace identity.
///
/// Construction and access are server-private. Until a complete production
/// lifecycle handler exists, external [`ConnectionServices`](crate::server::connection::ConnectionServices)
/// implementations cannot manufacture an activation token or advertise the
/// participant capability.
#[derive(Clone, Debug)]
pub struct InstalledParticipantService {
    handler: Arc<dyn ParticipantSemanticHandler>,
    durable_store: Arc<dyn DurableStore>,
    frame_limit: ValidatedFrameLimit,
    publication_registry: Arc<ParticipantPublicationRegistry>,
}

impl InstalledParticipantService {
    /// Pairs a semantic handler, its declared durable store, and the raw
    /// configured participant wire-frame limit.
    ///
    /// Production construction happens exactly once, in the server's
    /// connection-services layer, from the deployment's `[participant]`
    /// configuration; tests construct it directly with fixture handlers.
    ///
    /// # Errors
    ///
    /// Returns the shared codec error when the configured limit is smaller than
    /// the protocol's minimum complete frame.
    pub(crate) fn new(
        handler: Arc<dyn ParticipantSemanticHandler>,
        durable_store: Arc<dyn DurableStore>,
        configured_wf: u64,
    ) -> Result<Self, CodecError> {
        Ok(Self {
            handler,
            durable_store,
            frame_limit: normalize_configured_frame_limit(configured_wf)?,
            publication_registry: Arc::new(ParticipantPublicationRegistry::default()),
        })
    }

    /// Clones the durable store used by the installed participant service.
    #[must_use]
    pub(crate) fn durable_store(&self) -> Arc<dyn DurableStore> {
        Arc::clone(&self.durable_store)
    }

    /// Returns the normalized configured complete-frame limit advertised by
    /// this installed participant service.
    #[must_use]
    pub(crate) const fn frame_limit(&self) -> ValidatedFrameLimit {
        self.frame_limit
    }

    /// Returns the signed semantic-conversation allowance shared by publication
    /// readiness and connection-held encoded heads.
    #[must_use]
    pub(crate) fn publication_conversation_limit(&self) -> u64 {
        self.handler.publication_conversation_limit()
    }

    /// Creates the strongly connection-owned ready inbox at process spawn.
    #[must_use]
    pub(crate) fn new_publication_inbox(&self) -> ParticipantPublicationInbox {
        ParticipantPublicationInbox::new(self.handler.publication_conversation_limit())
    }

    /// Returns the shared weak publication registry.
    #[must_use]
    pub(crate) fn publication_registry(&self) -> &ParticipantPublicationRegistry {
        &self.publication_registry
    }

    /// Selects one exact durable publication through the installed production
    /// source.
    pub(crate) fn next_publication(
        &self,
        connection_incarnation: ConnectionIncarnation,
        conversation_id: ConversationId,
        offered: Option<ParticipantOfferedProgress>,
    ) -> Result<Option<ParticipantPublication>, ParticipantSemanticError> {
        self.handler
            .next_publication(connection_incarnation, conversation_id, offered)
    }

    pub(crate) fn publication_binding_is_current(
        &self,
        conversation_id: ConversationId,
        participant_id: ParticipantId,
        binding_epoch: BindingEpoch,
    ) -> Result<bool, ParticipantSemanticError> {
        self.handler
            .publication_binding_is_current(conversation_id, participant_id, binding_epoch)
    }

    pub(crate) fn record_publication_offer(
        &self,
        publication: &ParticipantPublication,
    ) -> Result<(), ParticipantSemanticError> {
        self.handler.record_publication_offer(publication)
    }

    fn notify_ready(
        &self,
        conversation_id: ConversationId,
    ) -> Result<(), ParticipantSemanticError> {
        for incarnation in self
            .handler
            .ready_connection_incarnations(conversation_id)?
        {
            self.publication_registry
                .notify(incarnation, conversation_id)
                .map_err(|error| ParticipantSemanticError::Internal {
                    message: format!("participant publication wake failed: {error}"),
                })?;
        }
        Ok(())
    }
}

impl ParticipantSemanticHandler for InstalledParticipantService {
    fn publication_conversation_limit(&self) -> u64 {
        self.handler.publication_conversation_limit()
    }

    fn handle(
        &self,
        context: ParticipantConnectionContext,
        conversations: &mut ParticipantConnectionConversations,
        request: ClientRequest,
    ) -> Result<ServerValue, ParticipantSemanticError> {
        if let ClientRequest::ObserverRecovery(request) = request {
            let target = self
                .publication_registry
                .observer_target(context.connection_incarnation())
                .map_err(|error| ParticipantSemanticError::Internal {
                    message: format!("observer publication target failed: {error}"),
                })?;
            return self
                .handler
                .handle_observer_recovery(context, conversations, request, target);
        }
        let conversation_id = request_conversation_id(&request);
        let value = self.handler.handle(context, conversations, request)?;
        if let Some(conversation_id) = conversation_id {
            self.notify_ready(conversation_id)?;
        }
        Ok(value)
    }
}

const fn request_conversation_id(request: &ClientRequest) -> Option<ConversationId> {
    match request {
        ClientRequest::Enrollment(request) => Some(request.conversation_id),
        ClientRequest::CredentialAttach(request) => Some(request.conversation_id),
        ClientRequest::Detach(request) => Some(request.conversation_id),
        ClientRequest::ParticipantAck(request) => Some(request.conversation_id),
        ClientRequest::Leave(request) => Some(request.conversation_id),
        ClientRequest::MarkerAck(request) => Some(request.conversation_id),
        ClientRequest::RecordAdmission(request) => Some(request.conversation_id),
        ClientRequest::ObserverRecovery(_) => None,
    }
}

/// Result of dispatching one generic frame through participant transport.
#[derive(Debug)]
pub enum ParticipantDispatch {
    /// The generic frame belongs to another protocol.
    NotParticipant,
    /// Exact encoded response selected by the shared gate or semantic handler.
    Respond(Frame),
    /// Exact crate-owned pre-semantic rejection, followed by connection close.
    RespondThenClose(Frame),
    /// No truthful participant response exists; the connection must fail closed.
    Fatal(ParticipantDispatchError),
}

/// Failure after a generic frame has entered participant dispatch.
#[derive(Debug, thiserror::Error)]
pub enum ParticipantDispatchError {
    /// The preserved generic frame could not represent a canonical participant frame.
    #[error("invalid generic participant frame")]
    InvalidGenericFrame,
    /// The semantic handler could not produce a protocol value.
    #[error(transparent)]
    Semantic(#[from] ParticipantSemanticError),
    /// The crate-produced value could not be encoded into the generic transport.
    #[error("failed to encode participant response: {0:?}")]
    Encode(CodecError),
}

/// Gates, decodes, semantically applies, and encodes one participant frame.
///
/// Transport rejection values originate in `liminal-protocol`; semantic values
/// originate only in `handler`. No lifecycle outcome is constructed here.
#[must_use]
pub fn dispatch_generic_frame(
    frame: &Frame,
    authenticated: bool,
    session: ParticipantSession,
    context: ParticipantConnectionContext,
    conversations: &mut ParticipantConnectionConversations,
    handler: &dyn ParticipantSemanticHandler,
) -> ParticipantDispatch {
    let (value, close_after_response) = match gate_generic_frame(frame, authenticated, session) {
        ParticipantIngress::NotParticipant => return ParticipantDispatch::NotParticipant,
        ParticipantIngress::Rejected(rejection) => {
            (ServerValue::ParticipantTransportRejected(rejection), true)
        }
        ParticipantIngress::InvalidGenericFrame => {
            return ParticipantDispatch::Fatal(ParticipantDispatchError::InvalidGenericFrame);
        }
        ParticipantIngress::Request(request) => {
            match handler.handle(context, conversations, request) {
                Ok(value) => (value, false),
                Err(error) => {
                    return ParticipantDispatch::Fatal(ParticipantDispatchError::Semantic(error));
                }
            }
        }
    };
    match encode_server_value(value) {
        Ok(frame) if close_after_response => ParticipantDispatch::RespondThenClose(frame),
        Ok(frame) => ParticipantDispatch::Respond(frame),
        Err(error) => ParticipantDispatch::Fatal(ParticipantDispatchError::Encode(error)),
    }
}