awaken-server-contract 0.6.0

Server and store boundary contracts for Awaken
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
//! Protocol wire replay log contracts.

use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use thiserror::Error;

use super::event_store::{CanonicalEventId, EventCursor, EventScope};
use crate::contract::scope::{ScopeId, scoped_key, unscoped_key};
use std::sync::Arc;

/// Errors returned by protocol replay log implementations.
#[derive(Debug, Error, Clone, PartialEq, Eq)]
pub enum ProtocolReplayError {
    /// The provided input violates the replay-log contract.
    #[error("validation error: {0}")]
    Validation(String),
    /// The wire event already exists for the protocol stream with different data.
    #[error("conflict: {0}")]
    Conflict(String),
    /// The requested cursor is outside retained replay history.
    #[error("cursor expired: {0}")]
    CursorExpired(String),
    /// Replay history is missing a row that should still be retained.
    #[error("integrity error: {0}")]
    Integrity(String),
    /// An I/O error occurred.
    #[error("io error: {0}")]
    Io(String),
    /// A serialization or deserialization error occurred.
    #[error("serialization error: {0}")]
    Serialization(String),
}

/// Stable protocol replay row identifier assigned by a [`ProtocolReplayWriter`].
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct ProtocolReplayId(String);

impl ProtocolReplayId {
    pub fn new(value: impl Into<String>) -> Result<Self, ProtocolReplayError> {
        let value = value.into();
        reject_blank("protocol_replay_id", &value)?;
        Ok(Self(value))
    }

    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

/// Opaque cursor for a single protocol replay stream.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct ProtocolReplayCursor(String);

impl ProtocolReplayCursor {
    pub fn new(value: impl Into<String>) -> Result<Self, ProtocolReplayError> {
        let value = value.into();
        reject_blank("protocol_replay_cursor", &value)?;
        Ok(Self(value))
    }

    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

/// Redaction state of a replay row.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ProtocolReplayRedactionState {
    /// The payload is replayable as stored.
    #[default]
    Clear,
    /// The original payload was replaced by a redacted/tombstone payload.
    Redacted,
}

/// Canonical event cursor referenced by a protocol replay row.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SourceEventCursor {
    pub event_id: CanonicalEventId,
    pub scope: EventScope,
    pub cursor: EventCursor,
}

impl SourceEventCursor {
    #[must_use]
    pub fn new(event_id: CanonicalEventId, scope: EventScope, cursor: EventCursor) -> Self {
        Self {
            event_id,
            scope,
            cursor,
        }
    }
}

/// ProtocolReplayLog append input. Store-assigned fields are intentionally absent.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ProtocolReplayDraft {
    pub stream_id: String,
    pub protocol: String,
    pub protocol_version: String,
    pub projector_version: String,
    pub wire_event_id: String,
    pub wire_event_type: String,
    pub wire_payload_bytes: Vec<u8>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub wire_payload_json: Option<Value>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub source_event_ids: Vec<CanonicalEventId>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub source_event_cursors: Vec<SourceEventCursor>,
    #[serde(default)]
    pub redaction_state: ProtocolReplayRedactionState,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expires_at: Option<u64>,
}

impl ProtocolReplayDraft {
    /// Create and validate a replay draft.
    pub fn new(
        stream_id: impl Into<String>,
        protocol: impl Into<String>,
        protocol_version: impl Into<String>,
        projector_version: impl Into<String>,
        wire_event_id: impl Into<String>,
        wire_event_type: impl Into<String>,
        wire_payload_bytes: Vec<u8>,
    ) -> Result<Self, ProtocolReplayError> {
        let draft = Self {
            stream_id: stream_id.into(),
            protocol: protocol.into(),
            protocol_version: protocol_version.into(),
            projector_version: projector_version.into(),
            wire_event_id: wire_event_id.into(),
            wire_event_type: wire_event_type.into(),
            wire_payload_bytes,
            wire_payload_json: None,
            source_event_ids: Vec::new(),
            source_event_cursors: Vec::new(),
            redaction_state: ProtocolReplayRedactionState::default(),
            expires_at: None,
        };
        draft.validate()?;
        Ok(draft)
    }

    /// Validate replay-stream identity and payload presence.
    pub fn validate(&self) -> Result<(), ProtocolReplayError> {
        reject_blank("stream_id", &self.stream_id)?;
        reject_blank("protocol", &self.protocol)?;
        reject_blank("protocol_version", &self.protocol_version)?;
        reject_blank("projector_version", &self.projector_version)?;
        reject_blank("wire_event_id", &self.wire_event_id)?;
        reject_blank("wire_event_type", &self.wire_event_type)?;
        if self.wire_payload_bytes.is_empty() {
            return Err(ProtocolReplayError::Validation(
                "wire_payload_bytes is required".to_string(),
            ));
        }
        Ok(())
    }
}

/// Persisted protocol replay row.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ProtocolReplayRecord {
    pub protocol_replay_id: ProtocolReplayId,
    pub stream_id: String,
    pub protocol: String,
    pub protocol_version: String,
    pub projector_version: String,
    pub wire_event_id: String,
    pub wire_event_type: String,
    pub wire_payload_bytes: Vec<u8>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub wire_payload_json: Option<Value>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub source_event_ids: Vec<CanonicalEventId>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub source_event_cursors: Vec<SourceEventCursor>,
    pub protocol_replay_cursor: ProtocolReplayCursor,
    #[serde(default)]
    pub redaction_state: ProtocolReplayRedactionState,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expires_at: Option<u64>,
    pub created_at: u64,
}

impl ProtocolReplayRecord {
    /// Build a persisted replay row from an accepted draft and store output.
    pub fn from_append(
        protocol_replay_id: ProtocolReplayId,
        protocol_replay_cursor: ProtocolReplayCursor,
        created_at: u64,
        draft: ProtocolReplayDraft,
    ) -> Result<Self, ProtocolReplayError> {
        draft.validate()?;
        Ok(Self {
            protocol_replay_id,
            stream_id: draft.stream_id,
            protocol: draft.protocol,
            protocol_version: draft.protocol_version,
            projector_version: draft.projector_version,
            wire_event_id: draft.wire_event_id,
            wire_event_type: draft.wire_event_type,
            wire_payload_bytes: draft.wire_payload_bytes,
            wire_payload_json: draft.wire_payload_json,
            source_event_ids: draft.source_event_ids,
            source_event_cursors: draft.source_event_cursors,
            protocol_replay_cursor,
            redaction_state: draft.redaction_state,
            expires_at: draft.expires_at,
            created_at,
        })
    }
}

/// Protocol stream selection.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct ProtocolStreamKey {
    pub stream_id: String,
    pub protocol: String,
    pub protocol_version: String,
}

impl ProtocolStreamKey {
    pub fn new(
        stream_id: impl Into<String>,
        protocol: impl Into<String>,
        protocol_version: impl Into<String>,
    ) -> Result<Self, ProtocolReplayError> {
        let key = Self {
            stream_id: stream_id.into(),
            protocol: protocol.into(),
            protocol_version: protocol_version.into(),
        };
        key.validate()?;
        Ok(key)
    }

    pub fn validate(&self) -> Result<(), ProtocolReplayError> {
        reject_blank("stream_id", &self.stream_id)?;
        reject_blank("protocol", &self.protocol)?;
        reject_blank("protocol_version", &self.protocol_version)
    }
}

/// Result returned by an append call.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ProtocolReplayAppendResult {
    pub record: ProtocolReplayRecord,
}

impl ProtocolReplayAppendResult {
    #[must_use]
    pub fn protocol_replay_cursor(&self) -> &ProtocolReplayCursor {
        &self.record.protocol_replay_cursor
    }
}

/// Paged protocol replay response.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ProtocolReplayPage {
    pub records: Vec<ProtocolReplayRecord>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub next_cursor: Option<ProtocolReplayCursor>,
    pub has_more: bool,
}

/// Append protocol replay rows.
#[async_trait]
pub trait ProtocolReplayWriter: Send + Sync {
    async fn append_replay(
        &self,
        draft: ProtocolReplayDraft,
    ) -> Result<ProtocolReplayAppendResult, ProtocolReplayError>;
}

/// Read protocol replay history.
#[async_trait]
pub trait ProtocolReplayReader: Send + Sync {
    async fn list_replay(
        &self,
        stream: ProtocolStreamKey,
        from: Option<ProtocolReplayCursor>,
        limit: usize,
    ) -> Result<ProtocolReplayPage, ProtocolReplayError>;
}

/// Load a persisted protocol replay row by durable row identity.
#[async_trait]
pub trait ProtocolReplayLookup: Send + Sync {
    async fn load_replay(
        &self,
        protocol_replay_id: &ProtocolReplayId,
    ) -> Result<Option<ProtocolReplayRecord>, ProtocolReplayError>;
}

/// Full protocol replay-log capability.
pub trait ProtocolReplayLog:
    ProtocolReplayWriter + ProtocolReplayReader + ProtocolReplayLookup
{
}

impl<T> ProtocolReplayLog for T where
    T: ProtocolReplayWriter + ProtocolReplayReader + ProtocolReplayLookup
{
}

fn reject_blank(field: &str, value: &str) -> Result<(), ProtocolReplayError> {
    if value.trim().is_empty() {
        return Err(ProtocolReplayError::Validation(format!(
            "{field} is required"
        )));
    }
    Ok(())
}

#[derive(Clone)]
pub struct ScopedProtocolReplayLog {
    inner: Arc<dyn ProtocolReplayLog>,
    scope_id: ScopeId,
}

impl ScopedProtocolReplayLog {
    pub fn new(inner: Arc<dyn ProtocolReplayLog>, scope_id: ScopeId) -> Self {
        Self { inner, scope_id }
    }

    pub fn scope_id(&self) -> &ScopeId {
        &self.scope_id
    }

    pub fn inner(&self) -> &dyn ProtocolReplayLog {
        self.inner.as_ref()
    }

    fn scoped(&self, value: &str) -> String {
        scoped_key(&self.scope_id, value)
    }

    fn unscoped<'a>(&self, value: &'a str) -> Option<&'a str> {
        unscoped_key(&self.scope_id, value)
    }

    fn encode_draft(&self, mut draft: ProtocolReplayDraft) -> ProtocolReplayDraft {
        draft.stream_id = self.scoped(&draft.stream_id);
        draft
    }

    fn encode_stream(&self, mut stream: ProtocolStreamKey) -> ProtocolStreamKey {
        stream.stream_id = self.scoped(&stream.stream_id);
        stream
    }

    fn decode_record(&self, mut record: ProtocolReplayRecord) -> Option<ProtocolReplayRecord> {
        record.stream_id = self.unscoped(&record.stream_id)?.to_string();
        Some(record)
    }
}

#[async_trait]
impl ProtocolReplayWriter for ScopedProtocolReplayLog {
    async fn append_replay(
        &self,
        draft: ProtocolReplayDraft,
    ) -> Result<ProtocolReplayAppendResult, ProtocolReplayError> {
        let result = self.inner.append_replay(self.encode_draft(draft)).await?;
        let record = self.decode_record(result.record).ok_or_else(|| {
            ProtocolReplayError::Integrity(
                "scoped replay log returned a record outside its scope".into(),
            )
        })?;
        Ok(ProtocolReplayAppendResult { record })
    }
}

#[async_trait]
impl ProtocolReplayReader for ScopedProtocolReplayLog {
    async fn list_replay(
        &self,
        stream: ProtocolStreamKey,
        from: Option<ProtocolReplayCursor>,
        limit: usize,
    ) -> Result<ProtocolReplayPage, ProtocolReplayError> {
        let mut page = self
            .inner
            .list_replay(self.encode_stream(stream), from, limit)
            .await?;
        page.records = page
            .records
            .into_iter()
            .filter_map(|record| self.decode_record(record))
            .collect();
        Ok(page)
    }
}

#[async_trait]
impl ProtocolReplayLookup for ScopedProtocolReplayLog {
    async fn load_replay(
        &self,
        protocol_replay_id: &ProtocolReplayId,
    ) -> Result<Option<ProtocolReplayRecord>, ProtocolReplayError> {
        Ok(self
            .inner
            .load_replay(protocol_replay_id)
            .await?
            .and_then(|record| self.decode_record(record)))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn replay_draft() -> ProtocolReplayDraft {
        ProtocolReplayDraft::new(
            "thread:t1",
            "ai-sdk",
            "v6",
            "projector-1",
            "evt_wire_1",
            "agent.message",
            br#"{"type":"agent.message"}"#.to_vec(),
        )
        .unwrap()
    }

    #[test]
    fn draft_requires_wire_payload_bytes() {
        let err = ProtocolReplayDraft::new(
            "thread:t1",
            "ai-sdk",
            "v6",
            "projector-1",
            "evt_wire_1",
            "agent.message",
            Vec::new(),
        )
        .unwrap_err();
        assert!(
            matches!(err, ProtocolReplayError::Validation(message) if message.contains("wire_payload"))
        );
    }

    #[test]
    fn stream_key_rejects_blank_protocol() {
        let err = ProtocolStreamKey::new("thread:t1", " ", "v6").unwrap_err();
        assert!(
            matches!(err, ProtocolReplayError::Validation(message) if message.contains("protocol"))
        );
    }

    #[test]
    fn persisted_record_preserves_byte_payload_and_cursor() {
        let mut draft = replay_draft();
        draft.wire_payload_json = Some(serde_json::json!({"type":"agent.message"}));
        let record = ProtocolReplayRecord::from_append(
            ProtocolReplayId::new("pr_1").unwrap(),
            ProtocolReplayCursor::new("prcur_1").unwrap(),
            42,
            draft,
        )
        .unwrap();

        assert_eq!(record.protocol_replay_id.as_str(), "pr_1");
        assert_eq!(record.protocol_replay_cursor.as_str(), "prcur_1");
        assert_eq!(record.wire_payload_bytes, br#"{"type":"agent.message"}"#);
        assert_eq!(record.wire_payload_json.unwrap()["type"], "agent.message");
    }

    #[test]
    fn opaque_replay_cursor_roundtrips() {
        let cursor = ProtocolReplayCursor::new("wirecur_opaque").unwrap();
        let encoded = serde_json::to_string(&cursor).unwrap();
        assert_eq!(encoded, "\"wirecur_opaque\"");
        let decoded: ProtocolReplayCursor = serde_json::from_str(&encoded).unwrap();
        assert_eq!(decoded.as_str(), "wirecur_opaque");
    }

    // ── scope isolation regression (the scoped lookup must not leak across
    //    scopes even when the durable id is known) ──

    #[derive(Default)]
    struct InMemReplay {
        rows: std::sync::Mutex<Vec<ProtocolReplayRecord>>,
    }

    #[async_trait]
    impl ProtocolReplayWriter for InMemReplay {
        async fn append_replay(
            &self,
            draft: ProtocolReplayDraft,
        ) -> Result<ProtocolReplayAppendResult, ProtocolReplayError> {
            let mut rows = self.rows.lock().unwrap();
            let n = rows.len() + 1;
            let record = ProtocolReplayRecord::from_append(
                ProtocolReplayId::new(format!("pr_{n}"))?,
                ProtocolReplayCursor::new(format!("prcur_{n}"))?,
                n as u64,
                draft,
            )?;
            rows.push(record.clone());
            Ok(ProtocolReplayAppendResult { record })
        }
    }

    #[async_trait]
    impl ProtocolReplayReader for InMemReplay {
        async fn list_replay(
            &self,
            _stream: ProtocolStreamKey,
            _from: Option<ProtocolReplayCursor>,
            _limit: usize,
        ) -> Result<ProtocolReplayPage, ProtocolReplayError> {
            Ok(ProtocolReplayPage {
                records: Vec::new(),
                next_cursor: None,
                has_more: false,
            })
        }
    }

    #[async_trait]
    impl ProtocolReplayLookup for InMemReplay {
        async fn load_replay(
            &self,
            protocol_replay_id: &ProtocolReplayId,
        ) -> Result<Option<ProtocolReplayRecord>, ProtocolReplayError> {
            Ok(self
                .rows
                .lock()
                .unwrap()
                .iter()
                .find(|r| r.protocol_replay_id.as_str() == protocol_replay_id.as_str())
                .cloned())
        }
    }

    #[tokio::test]
    async fn scoped_load_replay_rejects_cross_scope_id() {
        use std::sync::Arc;
        let inner = Arc::new(InMemReplay::default());
        let scope_a = ScopedProtocolReplayLog::new(inner.clone(), ScopeId::new("scope-a").unwrap());
        let appended = scope_a.append_replay(replay_draft()).await.unwrap();
        let id = appended.record.protocol_replay_id.clone();

        // Same scope resolves the record.
        assert!(scope_a.load_replay(&id).await.unwrap().is_some());

        // A different scope must NOT resolve it by id: the record's stream_id is
        // scoped to `scope-a`, so `decode_record` (unscope) fails and the scoped
        // lookup yields `None` — no cross-scope leak.
        let scope_b = ScopedProtocolReplayLog::new(inner, ScopeId::new("scope-b").unwrap());
        assert!(scope_b.load_replay(&id).await.unwrap().is_none());
    }
}