awaken-server 0.6.0

Multi-protocol HTTP server with SSE, mailbox, and protocol adapters 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
use super::*;
use async_trait::async_trait;
use awaken_runtime::{AgentRuntime, RuntimeError};
use awaken_server_contract::contract::durable_event_sink::{
    AgentEventNormalizationContext, AgentEventNormalizer, ScopedAgentEventNormalizer,
};
use awaken_server_contract::contract::event::AgentEvent;
use awaken_server_contract::contract::event_store::{AppendOptions, EventWriter};
use awaken_server_contract::contract::outbox::{OutboxMessageDraft, OutboxStatus, OutboxStore};
use awaken_server_contract::contract::protocol_replay_log::{
    ProtocolReplayDraft, ProtocolReplayReader, ProtocolReplayWriter, ProtocolStreamKey,
};
use awaken_server_contract::contract::storage::ThreadRunStore;
use awaken_stores::{
    InMemoryEventStore, InMemoryMailboxStore, InMemoryOutboxStore, InMemoryProtocolReplayLog,
    InMemoryStore,
};

use crate::app::{ServerConfig, ServerState};
use crate::mailbox::{Mailbox, MailboxConfig};
use crate::protocol_fanout::{
    ProtocolReplayFanoutError, ProtocolReplayFanoutMessage, ProtocolReplayFanoutPublisher,
};
use crate::protocol_projector::{AI_SDK_PROTOCOL, AI_SDK_PROTOCOL_VERSION};

struct StubResolver;

impl awaken_runtime::AgentResolver for StubResolver {
    fn resolve(&self, agent_id: &str) -> Result<awaken_runtime::ResolvedAgent, RuntimeError> {
        Err(RuntimeError::AgentNotFound {
            agent_id: agent_id.to_string(),
        })
    }
}

fn make_state() -> ServerState {
    let runtime = Arc::new(AgentRuntime::new(Arc::new(StubResolver)));
    let store = Arc::new(InMemoryStore::new());
    let mailbox_store = Arc::new(InMemoryMailboxStore::new());
    let mailbox = Arc::new(Mailbox::new(
        runtime.clone(),
        mailbox_store,
        store.clone(),
        "test".to_string(),
        MailboxConfig::default(),
    ));
    ServerState::new(
        runtime,
        mailbox,
        store as Arc<dyn ThreadRunStore>,
        Arc::new(StubResolver),
        ServerConfig::default(),
    )
}

async fn append_run_start(event_store: &InMemoryEventStore) -> String {
    let normalizer = ScopedAgentEventNormalizer::new(
        AgentEventNormalizationContext::new("thread-relay", "run-relay", "test").unwrap(),
    );
    let normalized = normalizer
        .normalize(&AgentEvent::RunStart {
            thread_id: "thread-relay".into(),
            run_id: "run-relay".into(),
            parent_run_id: None,
            identity: None,
        })
        .unwrap()
        .unwrap();
    event_store
        .append(normalized.draft, AppendOptions::default())
        .await
        .unwrap()
        .event
        .event_id
        .as_str()
        .to_string()
}

fn fast_config() -> ProtocolProjectorRelayConfig {
    ProtocolProjectorRelayConfig {
        idle_sleep: Duration::from_millis(1),
        error_sleep: Duration::from_millis(1),
        ..ProtocolProjectorRelayConfig::default()
    }
}

fn fast_fanout_config() -> ProtocolFanoutRelayConfig {
    ProtocolFanoutRelayConfig {
        idle_sleep: Duration::from_millis(1),
        error_sleep: Duration::from_millis(1),
        ..ProtocolFanoutRelayConfig::default()
    }
}

fn fast_a2a_push_config() -> A2aPushWebhookRelayConfig {
    A2aPushWebhookRelayConfig {
        idle_sleep: Duration::from_millis(1),
        error_sleep: Duration::from_millis(1),
        ..A2aPushWebhookRelayConfig::default()
    }
}

async fn replay_count(log: &InMemoryProtocolReplayLog) -> usize {
    log.list_replay(
        ProtocolStreamKey::new(
            "thread:thread-relay",
            AI_SDK_PROTOCOL,
            AI_SDK_PROTOCOL_VERSION,
        )
        .unwrap(),
        None,
        10,
    )
    .await
    .unwrap()
    .records
    .len()
}

#[derive(Default)]
struct RecordingFanoutPublisher {
    replay_ids: Mutex<Vec<String>>,
}

#[async_trait]
impl ProtocolReplayFanoutPublisher for RecordingFanoutPublisher {
    async fn publish(
        &self,
        message: ProtocolReplayFanoutMessage,
    ) -> Result<(), ProtocolReplayFanoutError> {
        self.replay_ids
            .lock()
            .push(message.record.protocol_replay_id.as_str().to_string());
        Ok(())
    }
}

#[tokio::test]
async fn protocol_projector_relay_projects_attached_outbox_in_background() {
    let event_store = Arc::new(InMemoryEventStore::new());
    let replay_log = Arc::new(InMemoryProtocolReplayLog::new());
    let outbox = Arc::new(InMemoryOutboxStore::new());
    let event_id = append_run_start(&event_store).await;
    let mut draft = OutboxMessageDraft::new(
        OUTBOX_LANE_CANONICAL,
        OUTBOX_TARGET_PROTOCOL_PROJECTOR,
        serde_json::json!({ "event_id": event_id }),
    )
    .unwrap();
    draft.dedupe_key = Some(format!("canonical/{event_id}"));
    outbox.enqueue_outbox(draft).await.unwrap();
    let state = with_protocol_replay_log(make_state(), replay_log.clone());
    let state = with_protocol_projector_relay(
        state,
        outbox.clone(),
        event_store as Arc<dyn EventLookup>,
        replay_log.clone() as Arc<dyn ProtocolReplayWriter>,
        fast_config(),
    )
    .unwrap();
    assert!(protocol_replay_log(&state).is_some());

    let handle = start_protocol_projector_relay(&state).unwrap().unwrap();
    for _ in 0..50 {
        if replay_count(&replay_log).await == 2 {
            break;
        }
        tokio::time::sleep(Duration::from_millis(10)).await;
    }
    handle.shutdown().await;

    assert_eq!(replay_count(&replay_log).await, 2);
    let delivered = outbox
        .list_outbox(Some(OutboxStatus::Delivered), 10)
        .await
        .unwrap();
    assert_eq!(delivered.len(), 1);
}

#[tokio::test]
async fn with_protocol_migrates_relay_attachments_to_new_buffers() {
    use crate::app::ProtocolModuleState;

    let event_store = Arc::new(InMemoryEventStore::new());
    let replay_log = Arc::new(InMemoryProtocolReplayLog::new());
    let outbox = Arc::new(InMemoryOutboxStore::new());

    // Configure a projector relay *before* replacing the protocol module.
    let state = with_protocol_replay_log(make_state(), replay_log.clone());
    let state = with_protocol_projector_relay(
        state,
        outbox,
        event_store as Arc<dyn EventLookup>,
        replay_log as Arc<dyn ProtocolReplayWriter>,
        fast_config(),
    )
    .unwrap();

    // Replacing the protocol module swaps replay-buffer identity. The projector
    // attachment and replay log must migrate so the relay still starts instead
    // of being silently orphaned under the previous buffers.
    let state = state.with_protocol(ProtocolModuleState::new());

    assert!(
        protocol_replay_log(&state).is_some(),
        "replay log configured before with_protocol must survive the swap"
    );
    let handle = start_protocol_projector_relay(&state)
        .unwrap()
        .expect("projector relay configured before with_protocol must survive the swap");
    handle.shutdown().await;
}

#[tokio::test]
async fn protocol_fanout_relay_publishes_attached_outbox_in_background() {
    let replay_log = Arc::new(InMemoryProtocolReplayLog::new());
    let outbox = Arc::new(InMemoryOutboxStore::new());
    let publisher = Arc::new(RecordingFanoutPublisher::default());
    let record = replay_log
        .append_replay(
            ProtocolReplayDraft::new(
                "thread:thread-fanout-state",
                AI_SDK_PROTOCOL,
                AI_SDK_PROTOCOL_VERSION,
                "ai-sdk-projector-v1",
                "wire-fanout-state",
                "start",
                b"data: start\n\n".to_vec(),
            )
            .unwrap(),
        )
        .await
        .unwrap()
        .record;
    outbox
        .enqueue_outbox(
            OutboxMessageDraft::new(
                OUTBOX_LANE_PROTOCOL_REPLAY,
                OUTBOX_TARGET_PROTOCOL_FANOUT,
                serde_json::json!({
                    "protocol_replay_id": record.protocol_replay_id.as_str(),
                    "protocol": record.protocol.as_str(),
                    "protocol_version": record.protocol_version.as_str(),
                    "wire_event_id": record.wire_event_id.as_str(),
                }),
            )
            .unwrap(),
        )
        .await
        .unwrap();
    let state = with_protocol_fanout_relay(
        make_state(),
        outbox.clone(),
        replay_log,
        publisher.clone(),
        fast_fanout_config(),
    )
    .unwrap();

    let handles = start_protocol_relays(&state).await.unwrap();
    for _ in 0..50 {
        if publisher.replay_ids.lock().len() == 1 {
            break;
        }
        tokio::time::sleep(Duration::from_millis(10)).await;
    }
    handles.shutdown().await;

    assert_eq!(publisher.replay_ids.lock().len(), 1);
    let delivered = outbox
        .list_outbox(Some(OutboxStatus::Delivered), 10)
        .await
        .unwrap();
    assert_eq!(delivered.len(), 1);
}

#[tokio::test]
async fn a2a_push_webhook_relay_attaches_outbox_and_starts() {
    let outbox: Arc<dyn OutboxStore> = Arc::new(InMemoryOutboxStore::new());
    let state =
        with_a2a_push_webhook_relay(make_state(), outbox.clone(), fast_a2a_push_config()).unwrap();

    let attached = a2a_push_webhook_outbox_for_buffers(&state.protocol.replay_buffers).unwrap();
    assert!(Arc::ptr_eq(&attached, &outbox));

    let handle = start_a2a_push_webhook_relay(&state).unwrap().unwrap();
    handle.shutdown_with_timeout(Duration::from_secs(1)).await;
}

// Regression: previously `run_outbox_relay` raced `relay.tick()` against
// `cancel.cancelled()` in the same `select!`, so a shutdown that fired
// after `claim_outbox` but before `ack`/`nack` would drop the tick
// future and leave the row claimed until lease expiry. The relay now
// only observes cancellation between ticks; verify a slow handler
// completes its delivery before shutdown returns.
#[tokio::test]
async fn shutdown_does_not_drop_in_flight_tick() {
    use awaken_server_contract::contract::outbox::OutboxStore;
    use tokio::sync::Notify;

    struct GatedHandler {
        entered: Arc<Notify>,
        release: Arc<Notify>,
    }

    #[async_trait]
    impl crate::outbox_relay::OutboxRelayHandler for GatedHandler {
        async fn deliver(
            &self,
            _message: &awaken_server_contract::contract::outbox::OutboxMessage,
        ) -> Result<(), crate::outbox_relay::OutboxRelayError> {
            self.entered.notify_one();
            self.release.notified().await;
            Ok(())
        }
    }

    let outbox = Arc::new(InMemoryOutboxStore::new());
    let mut draft = OutboxMessageDraft::new(
        OUTBOX_LANE_CANONICAL,
        OUTBOX_TARGET_PROTOCOL_PROJECTOR,
        serde_json::json!({"event_id": "evt"}),
    )
    .unwrap();
    draft.dedupe_key = Some("dedupe".into());
    outbox.enqueue_outbox(draft).await.unwrap();

    let entered = Arc::new(Notify::new());
    let release = Arc::new(Notify::new());
    let handler = Arc::new(GatedHandler {
        entered: entered.clone(),
        release: release.clone(),
    });
    let relay = OutboxRelay::new(
        outbox.clone(),
        handler,
        OutboxRelayConfig {
            lane: OUTBOX_LANE_CANONICAL.to_string(),
            target: OUTBOX_TARGET_PROTOCOL_PROJECTOR.to_string(),
            consumer_id: "shutdown-test".into(),
            batch_limit: 10,
            lease_ms: 60_000,
            retry_delay_ms: 0,
            max_retry_delay_ms: 0,
        },
    )
    .unwrap();
    let cancel = CancellationToken::new();
    let mut task = tokio::spawn(run_outbox_relay(
        relay,
        Duration::from_millis(1),
        Duration::from_millis(1),
        "shutdown-test",
        cancel.clone(),
    ));

    // Wait until the handler is mid-deliver, then request shutdown.
    entered.notified().await;
    cancel.cancel();

    // While the handler is blocked, the relay task must still be alive:
    // cancel-safe shutdown means the tick future is not dropped, so the
    // task cannot exit until the handler returns.
    let early = tokio::time::timeout(Duration::from_millis(25), &mut task).await;
    assert!(
        early.is_err(),
        "relay task exited mid-deliver, lost cancel-safety"
    );

    // Let the handler complete; the relay should ack then observe the
    // cancellation between ticks and shut down cleanly.
    release.notify_one();
    tokio::time::timeout(Duration::from_secs(2), task)
        .await
        .expect("relay task did not shut down after handler released")
        .expect("relay task panicked");

    let delivered = outbox
        .list_outbox(Some(OutboxStatus::Delivered), 10)
        .await
        .unwrap();
    assert_eq!(delivered.len(), 1, "row must be acked, not stuck claimed");
}

#[tokio::test]
async fn shutdown_timeout_bounds_stuck_in_flight_tick() {
    use awaken_server_contract::contract::outbox::OutboxStore;
    use tokio::sync::Notify;

    struct StuckHandler {
        entered: Arc<Notify>,
    }

    #[async_trait]
    impl crate::outbox_relay::OutboxRelayHandler for StuckHandler {
        async fn deliver(
            &self,
            _message: &awaken_server_contract::contract::outbox::OutboxMessage,
        ) -> Result<(), crate::outbox_relay::OutboxRelayError> {
            self.entered.notify_one();
            std::future::pending::<()>().await;
            Ok(())
        }
    }

    let outbox = Arc::new(InMemoryOutboxStore::new());
    let mut draft = OutboxMessageDraft::new(
        OUTBOX_LANE_CANONICAL,
        OUTBOX_TARGET_PROTOCOL_PROJECTOR,
        serde_json::json!({"event_id": "evt-timeout"}),
    )
    .unwrap();
    draft.dedupe_key = Some("dedupe-timeout".into());
    outbox.enqueue_outbox(draft).await.unwrap();

    let entered = Arc::new(Notify::new());
    let relay = OutboxRelay::new(
        outbox.clone(),
        Arc::new(StuckHandler {
            entered: entered.clone(),
        }),
        OutboxRelayConfig {
            lane: OUTBOX_LANE_CANONICAL.to_string(),
            target: OUTBOX_TARGET_PROTOCOL_PROJECTOR.to_string(),
            consumer_id: "shutdown-timeout-test".into(),
            batch_limit: 10,
            lease_ms: 60_000,
            retry_delay_ms: 0,
            max_retry_delay_ms: 0,
        },
    )
    .unwrap();
    let cancel = CancellationToken::new();
    let handle = ProtocolRelayHandle {
        task: tokio::spawn(run_outbox_relay(
            relay,
            Duration::from_millis(1),
            Duration::from_millis(1),
            "shutdown-timeout-test",
            cancel.clone(),
        )),
        cancel,
        name: "shutdown-timeout-test",
    };

    entered.notified().await;
    tokio::time::timeout(
        Duration::from_secs(1),
        handle.shutdown_with_timeout(Duration::from_millis(25)),
    )
    .await
    .expect("shutdown timeout must bound a stuck handler");

    let claimed = outbox
        .list_outbox(Some(OutboxStatus::Claimed), 10)
        .await
        .unwrap();
    assert_eq!(claimed.len(), 1, "lease retry owns recovery after abort");
}