cf-chat-engine 0.2.1

Chat Engine module: multi-tenant conversational infrastructure with plugin-driven backends
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
//! REST API surface for `cf-chat-engine`.
//!
//! Phase 14 assembles every per-feature handler (Phases 4-13) into a
//! single cohesive [`axum::Router`] via [`OperationBuilder`]. The wiring
//! is split across:
//!
//! - [`dto`] — wire-shape DTOs (`utoipa::ToSchema`).
//! - [`error`] — RFC-9457 mapping (`From<ChatEngineError> for CanonicalError`).
//! - [`handlers`] — thin axum handlers (Phases 4-12).
//! - [`routes`] — `register_routes` and the per-endpoint `OperationBuilder` chains.
//! - [`mod@self`] — SSE delta streaming helper + `WebhookEmitter` trait.
//!
//! ## SSE delta streaming
//!
//! The streaming endpoints (`POST messages`, `POST messages/recreate`,
//! `POST sessions/{id}/summarize`, `GET messages/{id}/stream`) emit the
//! `start`/`delta`/`complete`/`error` delta protocol (FR-024) over
//! `text/event-stream`. See [`sse_delta_stream_response`] (live projection)
//! and [`stream_reader::sse_buffer_reader_response`] (resume reader) for the
//! response builders.
//!
//! ## Webhook emitter
//!
//! The DESIGN webhook protocol (§Webhook Protocol) declares one event
//! type per lifecycle / message transition. The [`WebhookEmitter`] trait
//! defined here exposes a typed method per event so the production wiring
//! in Phase 15 can journal events into a transactional outbox without
//! every call site repeating the `WebhookEvent` enum match. The trait is
//! a strict extension of the domain-layer
//! [`crate::domain::service::WebhookEmitter`] used by session / message
//! services since Phase 4 — the legacy emitter remains the canonical
//! sink and is automatically blanket-impl'd for every implementor of
//! [`WebhookEmitter`] declared here, so no service-layer change is
//! required.
//
// @cpt-cf-chat-engine-api-rest-root:p14
// @cpt-cf-chat-engine-adr-http-client-protocol:p14

pub mod dto;
pub mod error;
pub mod handlers;
pub mod routes;
pub(crate) mod stream_reader;

pub use routes::register_routes;

use std::convert::Infallible;

use async_trait::async_trait;
use axum::body::Body;
use axum::http::{HeaderValue, StatusCode, header};
use axum::response::Response;
use futures::stream::StreamExt;
use uuid::Uuid;

use crate::domain::error::ChatEngineError;
use crate::domain::service::webhook::{
    NoopWebhookEmitter as DomainNoopWebhookEmitter, WebhookEmitter as DomainWebhookEmitter,
    WebhookEvent,
};

// ===========================================================================
// SSE delta streaming helper
// ===========================================================================

/// Build a `text/event-stream` (Server-Sent Events) **delta** response from an
/// infallible `StreamingEvent` stream — the shape returned by the message /
/// variant services (`SendMessageStream`). The plugin's
/// `Start`/`Chunk`/`Complete`/`Error` events are projected by
/// [`DeltaProjector`](crate::domain::stream_delta::DeltaProjector) into the
/// client-facing `start`/`delta`/`complete`/`error` protocol (FR-024); each
/// wire event is emitted as one SSE frame (`id:` = `seq`, `event:` = type,
/// `data:` = JSON). Mid-stream errors travel as an `error` event, never a
/// `Result::Err`.
///
/// Under true live-tail (FR-024) this response does **not** own a
/// cancellation guard: dropping the body (client disconnect) stops delivery
/// but the detached driver keeps generating and buffering, so a reconnect via
/// `Last-Event-ID` resumes the stream.
pub(crate) fn sse_delta_stream_response(
    stream: crate::domain::service::message_service::SendMessageStream,
) -> Response {
    use crate::domain::stream_delta::DeltaProjector;
    use futures::stream;

    // True live-tail (FR-024): a client disconnect does NOT cancel the driver.
    // The driver runs to completion, buffering every event, so a reconnect via
    // `Last-Event-ID` resumes seamlessly. Hence no `drop_guard` here — dropping
    // this response body just stops *delivery*, not *generation*.
    //
    // The projector below is independent of the driver's buffer projector but
    // sees the identical `StreamingEvent` sequence, so the `seq` it stamps on
    // the wire matches the buffer — the client's `Last-Event-ID` lines up on
    // reconnect.
    let wire = stream
        .scan(DeltaProjector::new(), |proj, evt| {
            std::future::ready(Some(stream::iter(proj.project(evt))))
        })
        .flatten();

    let body_stream = wire.map(|w| std::result::Result::<_, Infallible>::Ok(sse_frame(&w)));

    Response::builder()
        .status(StatusCode::OK)
        .header(
            header::CONTENT_TYPE,
            HeaderValue::from_static("text/event-stream"),
        )
        .header(header::CACHE_CONTROL, HeaderValue::from_static("no-cache"))
        .header("x-accel-buffering", HeaderValue::from_static("no"))
        .body(Body::from_stream(body_stream))
        .unwrap_or_else(|err| {
            tracing::error!(error = %err, "failed to build SSE stream response");
            let mut resp = Response::new(Body::empty());
            *resp.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
            resp
        })
}

/// Serialize one wire delta event into an SSE frame:
/// `id: <seq>\nevent: <type>\ndata: <json>\n\n`.
fn sse_frame(evt: &crate::domain::stream_delta::WireStreamEvent) -> Vec<u8> {
    let data = serde_json::to_string(evt).unwrap_or_else(|err| {
        tracing::error!(error = %err, "failed to serialize wire delta event");
        r#"{"type":"message.error","error":"internal serialization failure"}"#.to_string()
    });
    format!(
        "id: {}\nevent: {}\ndata: {}\n\n",
        evt.seq(),
        evt.event_name(),
        data
    )
    .into_bytes()
}

// ===========================================================================
// WebhookEmitter (REST-layer expansion)
// ===========================================================================

/// Typed webhook emitter used by REST handlers and services.
///
/// This trait is an extension of
/// [`crate::domain::service::webhook::WebhookEmitter`]: every implementor
/// of [`WebhookEmitter`] automatically satisfies the domain trait via the
/// blanket impl at the bottom of this file. The split exists so
/// Phase 15's transactional outbox implementation can have ergonomic
/// per-event methods on the wire side while session / message services
/// (Phases 4-12) continue to use the single-method `emit(WebhookEvent)`
/// API they were built against.
///
/// Method coverage (DESIGN §Webhook Protocol):
///
/// - [`emit_session_created`](Self::emit_session_created)
/// - [`emit_message_new`](Self::emit_message_new)
/// - [`emit_message_recreate`](Self::emit_message_recreate)
/// - [`emit_message_aborted`](Self::emit_message_aborted)
/// - [`emit_session_deleted`](Self::emit_session_deleted)
/// - [`emit_session_summary`](Self::emit_session_summary)
/// - [`emit_session_type_health_check`](Self::emit_session_type_health_check)
///
/// Production wiring lands in Phase 15.
#[async_trait]
pub trait WebhookEmitter: Send + Sync {
    async fn emit_session_created(
        &self,
        session_id: Uuid,
        tenant_id: &str,
        user_id: &str,
        session_type_id: Option<Uuid>,
    ) -> Result<(), ChatEngineError>;

    async fn emit_message_new(
        &self,
        session_id: Uuid,
        message_id: Uuid,
        tenant_id: &str,
        user_id: &str,
    ) -> Result<(), ChatEngineError>;

    async fn emit_message_recreate(
        &self,
        session_id: Uuid,
        message_id: Uuid,
        tenant_id: &str,
        user_id: &str,
    ) -> Result<(), ChatEngineError>;

    async fn emit_message_aborted(
        &self,
        session_id: Uuid,
        message_id: Uuid,
        tenant_id: &str,
        user_id: &str,
    ) -> Result<(), ChatEngineError>;

    async fn emit_session_deleted(
        &self,
        session_id: Uuid,
        tenant_id: &str,
        user_id: &str,
        hard: bool,
    ) -> Result<(), ChatEngineError>;

    async fn emit_session_summary(
        &self,
        session_id: Uuid,
        tenant_id: &str,
        user_id: &str,
    ) -> Result<(), ChatEngineError>;

    async fn emit_session_type_health_check(
        &self,
        session_type_id: Uuid,
    ) -> Result<(), ChatEngineError>;
}

/// No-op REST-layer webhook emitter used by tests and bring-up.
/// Forwards lifecycle events to the domain-layer [`DomainNoopWebhookEmitter`]
/// so downstream metrics / tracing remain consistent across the two
/// trait surfaces.
#[derive(Debug, Default, Clone)]
pub struct NoopWebhookEmitter {
    inner: DomainNoopWebhookEmitter,
}

#[async_trait]
impl WebhookEmitter for NoopWebhookEmitter {
    async fn emit_session_created(
        &self,
        session_id: Uuid,
        tenant_id: &str,
        user_id: &str,
        session_type_id: Option<Uuid>,
    ) -> Result<(), ChatEngineError> {
        self.inner
            .emit(WebhookEvent::SessionCreated {
                session_id,
                tenant_id: tenant_id.into(),
                user_id: user_id.into(),
                session_type_id,
            })
            .await
    }

    async fn emit_message_new(
        &self,
        session_id: Uuid,
        message_id: Uuid,
        tenant_id: &str,
        user_id: &str,
    ) -> Result<(), ChatEngineError> {
        tracing::debug!(
            event = "message.new",
            %session_id,
            %message_id,
            tenant_id,
            user_id,
            "webhook emitter (noop) \u{2014} event swallowed",
        );
        Ok(())
    }

    async fn emit_message_recreate(
        &self,
        session_id: Uuid,
        message_id: Uuid,
        tenant_id: &str,
        user_id: &str,
    ) -> Result<(), ChatEngineError> {
        tracing::debug!(
            event = "message.recreate",
            %session_id,
            %message_id,
            tenant_id,
            user_id,
            "webhook emitter (noop) \u{2014} event swallowed",
        );
        Ok(())
    }

    async fn emit_message_aborted(
        &self,
        session_id: Uuid,
        message_id: Uuid,
        tenant_id: &str,
        user_id: &str,
    ) -> Result<(), ChatEngineError> {
        tracing::debug!(
            event = "message.aborted",
            %session_id,
            %message_id,
            tenant_id,
            user_id,
            "webhook emitter (noop) \u{2014} event swallowed",
        );
        Ok(())
    }

    async fn emit_session_deleted(
        &self,
        session_id: Uuid,
        tenant_id: &str,
        user_id: &str,
        hard: bool,
    ) -> Result<(), ChatEngineError> {
        let event = if hard {
            WebhookEvent::SessionHardDeleted {
                session_id,
                tenant_id: tenant_id.into(),
                user_id: user_id.into(),
            }
        } else {
            WebhookEvent::SessionSoftDeleted {
                session_id,
                tenant_id: tenant_id.into(),
                user_id: user_id.into(),
            }
        };
        self.inner.emit(event).await
    }

    async fn emit_session_summary(
        &self,
        session_id: Uuid,
        tenant_id: &str,
        user_id: &str,
    ) -> Result<(), ChatEngineError> {
        tracing::debug!(
            event = "session.summary",
            %session_id,
            tenant_id,
            user_id,
            "webhook emitter (noop) \u{2014} event swallowed",
        );
        Ok(())
    }

    async fn emit_session_type_health_check(
        &self,
        session_type_id: Uuid,
    ) -> Result<(), ChatEngineError> {
        tracing::debug!(
            event = "session_type.health_check",
            %session_type_id,
            "webhook emitter (noop) \u{2014} event swallowed",
        );
        Ok(())
    }
}

/// Bridge from the REST-layer [`WebhookEmitter`] to the legacy
/// domain-layer emitter via [`WebhookEmitterAdapter`]. Services that hold
/// an `Arc<dyn DomainWebhookEmitter>` can keep their old single-method
/// `emit(WebhookEvent)` signature; Phase 15 wraps any REST-layer emitter
/// in this adapter at module bootstrap.
pub struct WebhookEmitterAdapter<E: WebhookEmitter + ?Sized> {
    inner: std::sync::Arc<E>,
}

impl<E> WebhookEmitterAdapter<E>
where
    E: WebhookEmitter + ?Sized,
{
    #[must_use]
    pub fn new(inner: std::sync::Arc<E>) -> Self {
        Self { inner }
    }
}

#[async_trait]
impl<E> DomainWebhookEmitter for WebhookEmitterAdapter<E>
where
    E: WebhookEmitter + ?Sized + Send + Sync,
{
    async fn emit(&self, event: WebhookEvent) -> Result<(), ChatEngineError> {
        match event {
            WebhookEvent::SessionCreated {
                session_id,
                tenant_id,
                user_id,
                session_type_id,
            } => {
                self.inner
                    .emit_session_created(session_id, &tenant_id, &user_id, session_type_id)
                    .await
            }
            WebhookEvent::SessionArchived {
                session_id,
                tenant_id,
                user_id,
            }
            | WebhookEvent::SessionRestored {
                session_id,
                tenant_id,
                user_id,
            } => {
                tracing::debug!(
                    %session_id,
                    tenant_id,
                    user_id,
                    "lifecycle event (archived/restored) \u{2014} no dedicated webhook method",
                );
                Ok(())
            }
            WebhookEvent::SessionSoftDeleted {
                session_id,
                tenant_id,
                user_id,
            } => {
                self.inner
                    .emit_session_deleted(session_id, &tenant_id, &user_id, false)
                    .await
            }
            WebhookEvent::SessionHardDeleted {
                session_id,
                tenant_id,
                user_id,
            } => {
                self.inner
                    .emit_session_deleted(session_id, &tenant_id, &user_id, true)
                    .await
            }
            WebhookEvent::MessageDeleted {
                session_id,
                message_id,
                tenant_id,
                user_id,
                ..
            } => {
                self.inner
                    .emit_message_aborted(session_id, message_id, &tenant_id, &user_id)
                    .await
            }
        }
    }
}

// ===========================================================================
// Tests
// ===========================================================================

#[cfg(test)]
#[path = "mod_tests.rs"]
mod mod_tests;