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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
//! Wire-format DTOs for the Chat Engine REST surface.
//!
//! These are the only types that derive `utoipa::ToSchema` — domain models
//! in `domain/` and SDK models in `chat_engine_sdk::models` stay
//! transport-agnostic. Each DTO carries the exact field names / optionality
//! locked by `modules/chat-engine/api/http-protocol.json` and the SDK wire
//! formats sealed in Phase 5.
//!
//! The streaming event DTOs ([`StreamingStartDto`], [`StreamingChunkDto`],
//! [`StreamingCompleteDto`], [`StreamingErrorDto`]) and the discriminated
//! [`StreamingEventDto`] union are the canonical wire shapes for the NDJSON
//! response bodies. They are intentionally **flat** — `chunk` is a
//! `String`, `error` is a `String` — per §1.5 of
//! `docs/features/plugin-system.md`.
//
// @cpt-cf-chat-engine-api-dto:p14
// @cpt-cf-chat-engine-adr-http-client-protocol:p14

use serde_json::Value as JsonValue;
use toolkit_macros::api_dto;
use uuid::Uuid;

use chat_engine_sdk::models::{
    CapabilityValue, LifecycleState, Message as SdkMessage, MessagePart as SdkMessagePart,
    MessagePartInput as SdkMessagePartInput, MessagePartType, MessageRole, Session as SdkSession,
    SessionType as SdkSessionType, VariantInfo,
};

// ---------------------------------------------------------------------------
// Session DTOs
// ---------------------------------------------------------------------------

/// Wire-shape projection of [`SdkSession`]. The bearer `share_token` is
/// intentionally redacted from list / get responses; the only sanctioned
/// surface for the raw token is the dedicated share endpoint.
#[api_dto(request, response)]
#[derive(Debug, Clone)]
pub struct SessionDto {
    pub session_id: Uuid,
    pub tenant_id: String,
    pub user_id: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub client_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub session_type_id: Option<Uuid>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub enabled_capabilities: Option<JsonValue>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<JsonValue>,
    pub lifecycle_state: String,
    #[serde(with = "time::serde::rfc3339")]
    pub created_at: time::OffsetDateTime,
    #[serde(with = "time::serde::rfc3339")]
    pub updated_at: time::OffsetDateTime,
}

impl From<SdkSession> for SessionDto {
    fn from(s: SdkSession) -> Self {
        Self {
            session_id: s.session_id,
            tenant_id: s.tenant_id.to_string(),
            user_id: s.user_id.to_string(),
            client_id: s.client_id,
            session_type_id: s.session_type_id,
            enabled_capabilities: s.enabled_capabilities,
            metadata: s.metadata,
            lifecycle_state: s.lifecycle_state.as_str().to_owned(),
            created_at: s.created_at,
            updated_at: s.updated_at,
        }
    }
}

/// Body for `POST /chat-engine/v1/sessions`.
#[api_dto(request)]
#[derive(Debug, Clone)]
pub struct CreateSessionRequestDto {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub session_type_id: Option<Uuid>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub metadata: Option<JsonValue>,
}

/// Body for `POST /chat-engine/v1/sessions/{id}/switch-type`.
#[api_dto(request)]
#[derive(Debug, Clone)]
pub struct SwitchSessionTypeRequestDto {
    pub session_type_id: Uuid,
}

/// Cursor-paginated list envelope for `GET /chat-engine/v1/sessions`.
#[api_dto(response)]
#[derive(Debug, Clone)]
pub struct SessionListDto {
    pub items: Vec<SessionDto>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_cursor: Option<String>,
    pub has_more: bool,
}

// ---------------------------------------------------------------------------
// SessionType DTOs
// ---------------------------------------------------------------------------

/// Body for `POST /chat-engine/v1/session-types`.
#[api_dto(request)]
#[derive(Debug, Clone)]
pub struct RegisterSessionTypeRequestDto {
    /// Human-readable name (opaque to Chat Engine).
    pub name: String,
    /// GTS plugin instance ID to bind. `None` registers an unwired type.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub plugin_instance_id: Option<String>,
    /// Opaque plugin configuration JSON handed to the bound plugin.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub plugin_config: Option<JsonValue>,
}

/// Wire-shape projection of [`SdkSessionType`].
#[api_dto(request, response)]
#[derive(Debug, Clone)]
pub struct SessionTypeDto {
    pub session_type_id: Uuid,
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub plugin_instance_id: Option<String>,
    #[serde(with = "time::serde::rfc3339")]
    pub created_at: time::OffsetDateTime,
    #[serde(with = "time::serde::rfc3339")]
    pub updated_at: time::OffsetDateTime,
}

impl From<SdkSessionType> for SessionTypeDto {
    fn from(t: SdkSessionType) -> Self {
        Self {
            session_type_id: t.session_type_id,
            name: t.name,
            plugin_instance_id: t.plugin_instance_id,
            created_at: t.created_at,
            updated_at: t.updated_at,
        }
    }
}

// ---------------------------------------------------------------------------
// Message DTOs
// ---------------------------------------------------------------------------

/// Wire-shape of a persisted message part (FR-022).
#[api_dto(request, response)]
#[derive(Debug, Clone)]
pub struct MessagePartDto {
    pub id: Uuid,
    #[serde(rename = "type")]
    pub part_type: String,
    pub content: JsonValue,
    pub number: u32,
    /// Document citations attached to a `text` part (FR-023), serialized
    /// verbatim. Omitted from the wire when empty.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub file_citations: Vec<JsonValue>,
    /// Web-page citations attached to a `text` part. Omitted when empty.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub link_citations: Vec<JsonValue>,
    /// URL references attached to a `text` part. Omitted when empty.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub references: Vec<JsonValue>,
}

impl From<SdkMessagePart> for MessagePartDto {
    fn from(p: SdkMessagePart) -> Self {
        Self {
            id: p.id,
            part_type: part_type_to_wire(p.part_type).to_owned(),
            content: p.content,
            number: p.number,
            file_citations: p
                .file_citations
                .iter()
                .filter_map(|c| serde_json::to_value(c).ok())
                .collect(),
            link_citations: p
                .link_citations
                .iter()
                .filter_map(|c| serde_json::to_value(c).ok())
                .collect(),
            references: p
                .references
                .iter()
                .filter_map(|r| serde_json::to_value(r).ok())
                .collect(),
        }
    }
}

/// Wire-shape of an inbound message part (no `id`/`number`; assigned on persist).
#[api_dto(request, response)]
#[derive(Debug, Clone)]
pub struct MessagePartInputDto {
    #[serde(rename = "type")]
    pub part_type: String,
    pub content: JsonValue,
}

impl From<MessagePartInputDto> for SdkMessagePartInput {
    fn from(d: MessagePartInputDto) -> Self {
        let part_type = part_type_from_wire(&d.part_type);
        Self {
            content: normalize_part_content(part_type, d.content),
            part_type,
            // Citations/references are plugin-produced (assistant side); the
            // inbound user-message wire shape does not carry them.
            file_citations: Vec::new(),
            link_citations: Vec::new(),
            references: Vec::new(),
        }
    }
}

/// Canonicalize inbound part content to the persisted/streamed wire shape so
/// user and assistant parts of the same type serialize identically.
///
/// A `text` part's canonical content is the object `{ "text": "<body>" }`
/// (see [`MessagePart::text`](chat_engine_sdk::models::MessagePart::text) and
/// the streamed assistant form). Clients commonly send a bare JSON string for
/// convenience; wrap it so it matches the assistant side. Already-canonical
/// objects and every other part type pass through untouched — per-type shape
/// validation stays in the service/plugin layer.
fn normalize_part_content(part_type: MessagePartType, content: JsonValue) -> JsonValue {
    match (part_type, content) {
        (MessagePartType::Text, JsonValue::String(text)) => {
            serde_json::json!({ "text": text })
        }
        (_, content) => content,
    }
}

/// Total, lossless mapping of a part type to its wire string.
fn part_type_to_wire(t: MessagePartType) -> &'static str {
    match t {
        MessagePartType::Text => "text",
        MessagePartType::Code => "code",
        MessagePartType::Images => "images",
        MessagePartType::Videos => "videos",
        MessagePartType::Links => "links",
        MessagePartType::Statuses => "statuses",
    }
}

/// Parse a wire part-type string, defaulting unknown values to `text` so a
/// malformed body never panics. Strict validation lives in the service layer.
fn part_type_from_wire(s: &str) -> MessagePartType {
    match s {
        "code" => MessagePartType::Code,
        "images" => MessagePartType::Images,
        "videos" => MessagePartType::Videos,
        "links" => MessagePartType::Links,
        "statuses" => MessagePartType::Statuses,
        _ => MessagePartType::Text,
    }
}

/// Convenience: convert wire parts to the SDK input shape.
#[must_use]
pub fn parts_into_sdk(parts: Vec<MessagePartInputDto>) -> Vec<SdkMessagePartInput> {
    parts.into_iter().map(SdkMessagePartInput::from).collect()
}

/// Wire-shape projection of [`SdkMessage`].
#[api_dto(request, response)]
#[derive(Debug, Clone)]
pub struct MessageDto {
    pub message_id: Uuid,
    pub session_id: Uuid,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parent_message_id: Option<Uuid>,
    pub variant_index: u32,
    pub is_active: bool,
    pub role: String,
    #[serde(default)]
    pub parts: Vec<MessagePartDto>,
    #[serde(default)]
    pub file_ids: Vec<Uuid>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<JsonValue>,
    pub is_complete: bool,
    pub is_hidden_from_user: bool,
    pub is_hidden_from_backend: bool,
    #[serde(with = "time::serde::rfc3339")]
    pub created_at: time::OffsetDateTime,
    #[serde(with = "time::serde::rfc3339")]
    pub updated_at: time::OffsetDateTime,
}

impl From<SdkMessage> for MessageDto {
    fn from(m: SdkMessage) -> Self {
        Self {
            message_id: m.message_id,
            session_id: m.session_id,
            parent_message_id: m.parent_message_id,
            variant_index: m.variant_index,
            is_active: m.is_active,
            role: role_to_wire(&m.role).to_owned(),
            parts: m.parts.into_iter().map(MessagePartDto::from).collect(),
            file_ids: m.file_ids,
            metadata: m.metadata,
            is_complete: m.is_complete,
            is_hidden_from_user: m.is_hidden_from_user,
            is_hidden_from_backend: m.is_hidden_from_backend,
            created_at: m.created_at,
            updated_at: m.updated_at,
        }
    }
}

fn role_to_wire(role: &MessageRole) -> &'static str {
    match role {
        MessageRole::User => "user",
        MessageRole::Assistant => "assistant",
        MessageRole::System => "system",
    }
}

/// Body for `POST /chat-engine/v1/sessions/{id}/messages`.
#[api_dto(request)]
#[derive(Debug, Clone)]
pub struct SendMessageRequestDto {
    #[serde(default)]
    pub parts: Vec<MessagePartInputDto>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub file_ids: Option<Vec<Uuid>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub parent_message_id: Option<Uuid>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub capabilities: Option<Vec<CapabilityValueDto>>,
}

/// Body for `POST /chat-engine/v1/messages/{id}/recreate`.
#[api_dto(request)]
#[derive(Debug, Clone, Default)]
pub struct RecreateMessageRequestDto {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub enabled_capabilities: Option<Vec<CapabilityValueDto>>,
}

/// Wire projection of [`CapabilityValue`].
#[api_dto(request, response)]
#[derive(Debug, Clone)]
pub struct CapabilityValueDto {
    pub name: String,
    pub value: JsonValue,
}

impl From<CapabilityValueDto> for CapabilityValue {
    fn from(v: CapabilityValueDto) -> Self {
        Self {
            name: v.name,
            value: v.value,
        }
    }
}

impl From<CapabilityValue> for CapabilityValueDto {
    fn from(v: CapabilityValue) -> Self {
        Self {
            name: v.name,
            value: v.value,
        }
    }
}

/// Convenience: convert a wire-typed `Vec<CapabilityValueDto>` to the SDK
/// shape used by the service layer.
#[must_use]
pub fn capabilities_into_sdk(values: Vec<CapabilityValueDto>) -> Vec<CapabilityValue> {
    values.into_iter().map(CapabilityValue::from).collect()
}

/// List response envelope for `GET /chat-engine/v1/sessions/{id}/messages`.
#[api_dto(response)]
#[derive(Debug, Clone)]
pub struct MessageListDto {
    pub items: Vec<MessageDto>,
}

// ---------------------------------------------------------------------------
// Variants
// ---------------------------------------------------------------------------

/// Wire projection of [`VariantInfo`].
#[api_dto(request, response)]
#[derive(Debug, Clone)]
pub struct VariantInfoDto {
    pub message_id: Uuid,
    pub variant_index: u32,
    pub total_variants: u32,
    pub is_active: bool,
}

impl From<VariantInfo> for VariantInfoDto {
    fn from(v: VariantInfo) -> Self {
        Self {
            message_id: v.message_id,
            variant_index: v.variant_index,
            total_variants: v.total_variants,
            is_active: v.is_active,
        }
    }
}

/// `GET /chat-engine/v1/messages/{id}/variants` response envelope.
#[api_dto(response)]
#[derive(Debug, Clone)]
pub struct VariantListDto {
    pub variants: Vec<VariantInfoDto>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub current_index: Option<u32>,
}

// ---------------------------------------------------------------------------
// Search
// ---------------------------------------------------------------------------

/// Body for `POST /chat-engine/v1/sessions/{id}/search` and
/// `POST /chat-engine/v1/sessions/search`.
#[api_dto(request)]
#[derive(Debug, Clone)]
pub struct SearchRequestDto {
    pub query: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub offset: Option<u32>,
}

/// Response shape for search endpoints.
#[api_dto(response)]
#[derive(Debug, Clone)]
pub struct SearchResultsDto {
    pub results: Vec<JsonValue>,
}

// ---------------------------------------------------------------------------
// Reactions
// ---------------------------------------------------------------------------

/// Body for `POST /chat-engine/v1/messages/{id}/reactions`.
#[api_dto(request)]
#[derive(Debug, Clone)]
pub struct ReactionRequestDto {
    pub kind: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub value: Option<JsonValue>,
}

/// Single reaction record.
#[api_dto(response)]
#[derive(Debug, Clone)]
pub struct ReactionDto {
    pub kind: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub value: Option<JsonValue>,
    pub user_id: String,
    #[serde(with = "time::serde::rfc3339")]
    pub created_at: time::OffsetDateTime,
}

/// `GET /chat-engine/v1/messages/{id}/reactions` envelope.
#[api_dto(response)]
#[derive(Debug, Clone)]
pub struct ReactionListDto {
    pub reactions: Vec<ReactionDto>,
}

// ---------------------------------------------------------------------------
// Export / Share
// ---------------------------------------------------------------------------

/// Body for `POST /chat-engine/v1/sessions/{id}/export`.
#[api_dto(request)]
#[derive(Debug, Clone, Default)]
pub struct ExportRequestDto {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub format: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub include_plugin_metadata: Option<bool>,
}

/// Response for `POST /chat-engine/v1/sessions/{id}/export`.
#[api_dto(response)]
#[derive(Debug, Clone)]
pub struct ExportAcceptedDto {
    pub session_id: Uuid,
    pub format: String,
    pub download_url: String,
    pub message_count: u32,
    #[serde(with = "time::serde::rfc3339")]
    pub expires_at: time::OffsetDateTime,
}

/// Body for `POST /chat-engine/v1/sessions/{id}/share`.
#[api_dto(request)]
#[derive(Debug, Clone, Default)]
pub struct ShareRequestDto {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expires_in_hours: Option<u32>,
}

/// Response for `POST /chat-engine/v1/sessions/{id}/share`.
#[api_dto(response)]
#[derive(Debug, Clone)]
pub struct ShareResponseDto {
    pub session_id: Uuid,
    pub share_token: String,
    pub share_url: String,
    #[serde(default, skip_serializing_if = "Option::is_none", with = "rfc3339_opt")]
    pub expires_at: Option<time::OffsetDateTime>,
}

/// Response for `POST /chat-engine/v1/shared/{share_token}`.
#[api_dto(response)]
#[derive(Debug, Clone)]
pub struct SharedSessionDto {
    pub session_id: Uuid,
    pub messages: Vec<MessageDto>,
    pub read_only: bool,
}

// ---------------------------------------------------------------------------
// Summarization
// ---------------------------------------------------------------------------

/// `POST /chat-engine/v1/sessions/{id}/summarize` accepted-envelope.
#[api_dto(response)]
#[derive(Debug, Clone)]
pub struct SummarizeAcceptedDto {
    pub session_id: Uuid,
    pub status_url: String,
}

// ---------------------------------------------------------------------------
// Streaming wire events (NDJSON)
// ---------------------------------------------------------------------------

/// `event: "start"` — begin streaming.
#[api_dto(request, response)]
#[derive(Debug, Clone)]
pub struct StreamingStartDto {
    pub message_id: Uuid,
}

/// `event: "chunk"` — append `chunk` (text fragment) to the assistant
/// message body. `chunk` is intentionally `String`, NOT a structured
/// payload.
#[api_dto(request, response)]
#[derive(Debug, Clone)]
pub struct StreamingChunkDto {
    pub message_id: Uuid,
    pub chunk: String,
}

/// `event: "complete"` — streaming finished successfully. `metadata` is a
/// plugin-defined object; it is OMITTED from the wire payload when
/// absent.
#[api_dto(request, response)]
#[derive(Debug, Clone)]
pub struct StreamingCompleteDto {
    pub message_id: Uuid,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<JsonValue>,
}

/// `event: "error"` — terminal streaming error. `error` is a single
/// human-readable string. Discriminator prefixes (`context_overflow:`,
/// `stream_interrupted:`, `deadline_exceeded:`) are surfaced verbatim per
/// ADR-0023. No further events follow.
#[api_dto(request, response)]
#[derive(Debug, Clone)]
pub struct StreamingErrorDto {
    pub message_id: Uuid,
    pub error: String,
}

/// Tagged-union of all streaming events. NDJSON serialization writes one
/// `StreamingEventDto` per line. The discriminator field is `type` per
/// the OpenAPI spec (`api/http-protocol.json`) — see
/// `StreamingStartEvent.type`, `StreamingChunkEvent.type`, …
#[api_dto(request, response)]
#[serde(tag = "type")]
pub enum StreamingEventDto {
    Start(StreamingStartDto),
    Chunk(StreamingChunkDto),
    Complete(StreamingCompleteDto),
    Error(StreamingErrorDto),
}

// The streaming DTOs derive `ResponseApiDto` via `#[api_dto(response)]`, so
// they can appear in `OperationBuilder::json_response_with_schema` directly.

// ---------------------------------------------------------------------------
// Domain → DTO conversions for the streaming events
// ---------------------------------------------------------------------------

use crate::domain::message::{
    StreamingChunkEvent, StreamingCompleteEvent, StreamingErrorEvent, StreamingStartEvent,
};

impl From<StreamingStartEvent> for StreamingStartDto {
    fn from(e: StreamingStartEvent) -> Self {
        Self {
            message_id: e.message_id,
        }
    }
}

impl From<StreamingChunkEvent> for StreamingChunkDto {
    fn from(e: StreamingChunkEvent) -> Self {
        Self {
            message_id: e.message_id,
            chunk: e.chunk,
        }
    }
}

impl From<StreamingCompleteEvent> for StreamingCompleteDto {
    fn from(e: StreamingCompleteEvent) -> Self {
        Self {
            message_id: e.message_id,
            metadata: e.metadata,
        }
    }
}

impl From<StreamingErrorEvent> for StreamingErrorDto {
    fn from(e: StreamingErrorEvent) -> Self {
        Self {
            message_id: e.message_id,
            error: e.error,
        }
    }
}

// ---------------------------------------------------------------------------
// Misc helpers
// ---------------------------------------------------------------------------

/// Convert a `LifecycleState` into its lowercase wire representation.
#[must_use]
pub fn lifecycle_to_wire(state: LifecycleState) -> &'static str {
    state.as_str()
}

mod rfc3339_opt {
    use serde::Serializer;
    use time::OffsetDateTime;
    use time::format_description::well_known::Rfc3339;

    // `&Option<_>` is mandated by serde's `serialize_with` signature contract.
    #[allow(clippy::ref_option)]
    pub fn serialize<S>(value: &Option<OffsetDateTime>, ser: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match value {
            Some(dt) => {
                let s = dt.format(&Rfc3339).map_err(serde::ser::Error::custom)?;
                ser.serialize_str(&s)
            }
            None => ser.serialize_none(),
        }
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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