bedrock-agentcore 0.1.0

Amazon Bedrock AgentCore SDK for Rust
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
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
//! Tests that need a real socket: binding, serving, graceful shutdown and raw HTTP.

mod common;

use std::{
    net::SocketAddr,
    sync::{
        Arc,
        atomic::{AtomicUsize, Ordering},
    },
    time::Duration,
};

use bedrock_agentcore::{
    ErrorKind, RequestContext, context,
    runtime::{BedrockAgentCoreApp, Response, WarmupHook},
};
use common::*;
use futures_util::stream;
use reqwest::StatusCode;
use serde_json::{Value, json};
use tokio::{
    io::{AsyncReadExt, AsyncWriteExt},
    sync::mpsc,
    time::timeout,
};

async fn echo(payload: Value, ctx: RequestContext) -> Result<Value, BoxError> {
    Ok(json!({ "echo": payload, "session_id": ctx.session_id(), "request_id": ctx.request_id() }))
}

/// Reports what the handler sees in its context.
fn describe(ctx: &RequestContext) -> Value {
    let headers: serde_json::Map<_, _> =
        ctx.headers().iter().map(|(name, value)| (name.to_string(), json!(value.to_str().unwrap()))).collect();
    json!({
        "session_id": ctx.session_id(),
        "request_id": ctx.request_id(),
        "workload_access_token": ctx.workload_access_token().map(|token| token.expose()),
        "oauth2_callback_url": ctx.oauth2_callback_url(),
        "headers": headers,
    })
}

async fn context_report(_payload: Value, ctx: RequestContext) -> Result<Value, BoxError> {
    let ambient = context::current().ok_or("no ambient context in the handler")?;
    assert_eq!(describe(&ambient), describe(&ctx));
    Ok(describe(&ctx))
}

/// The API sets no pattern for a session ID, and AgentCore Runtime passes its bytes on.
#[tokio::test]
async fn header_names_are_case_insensitive_and_a_session_id_is_any_utf8_text() {
    let server = Server::start(BedrockAgentCoreApp::builder().invocation(context_report)).await;
    let body = r#"{"sessionId":"from-body"}"#;
    let send = |session: &'static [u8]| {
        let mut request = format!(
            "POST /invocations HTTP/1.1\r\nHost: test\r\nConnection: close\r\nContent-Length: {}\r\n\
             X-AMZN-Bedrock-AgentCore-Runtime-Request-ID: Req-1\r\nAUTHORIZATION: Bearer abc\r\n\
             X-Amzn-Bedrock-AgentCore-Runtime-CUSTOM-Tenant: Acme\r\nX-Amzn-Bedrock-AgentCore-Runtime-Session-Id: ",
            body.len()
        )
        .into_bytes();
        request.extend_from_slice(session);
        request.extend_from_slice(b"\r\n\r\n");
        request.extend_from_slice(body.as_bytes());
        let server = &server;
        async move {
            let response = server.raw(&request).await;
            let reply: Value = serde_json::from_str(&response[response.find("\r\n\r\n").unwrap()..]).unwrap();
            (response, reply)
        }
    };

    let (response, reply) = send("caf\u{e9}-\u{2713}-session".as_bytes()).await;
    assert!(response.starts_with("HTTP/1.1 200"), "{response}");
    let ids = (reply["session_id"].as_str(), reply["request_id"].as_str());
    assert_eq!(ids, (Some("caf\u{e9}-\u{2713}-session"), Some("Req-1")));
    assert_eq!(reply["headers"], json!({ "authorization": "Bearer abc", CUSTOM: "Acme" }));

    // Bytes that are not UTF-8 are refused. The session of the body does not replace them.
    let (response, reply) = send(b"\xff\xfe").await;
    assert!(response.starts_with("HTTP/1.1 400"), "{response}");
    assert!(reply["error"].as_str().unwrap().starts_with("Invalid sessionId"), "{reply}");
    server.stop().await;
}

/// A body that produces its frames over time is read on the runtime of the
/// application. When it panics, the client gets a reply that was cut, not one that
/// looks complete.
#[tokio::test]
async fn panic_in_a_streaming_body_cuts_the_reply_of_an_invocation_and_of_a_customer_route() {
    fn panics() -> axum::body::Body {
        let frames = stream::poll_fn(|_| -> std::task::Poll<Option<Result<String, BoxError>>> {
            panic!("the body failed");
        });
        axum::body::Body::from_stream(frames)
    }
    let handler =
        |_payload: Value| async { Ok::<_, BoxError>(Response::from_http(axum::http::Response::new(panics()))) };
    let routes = axum::Router::new().route("/cut", axum::routing::get(|| async { panics() }));
    let server = Server::start(BedrockAgentCoreApp::builder().invocation(handler).routes(routes)).await;
    for (method, path) in [("POST", "/invocations"), ("GET", "/cut")] {
        let method = reqwest::Method::from_bytes(method.as_bytes()).unwrap();
        let request = client().request(method, format!("{}{path}", server.base)).header(SESSION, "s").body("{}");
        // The server can close the connection before or after it has sent the status.
        let complete = match request.send().await {
            Ok(response) => response.bytes().await.is_ok(),
            Err(_) => false,
        };
        assert!(!complete, "{path}: the reply looks complete");
    }
    // The server still answers.
    assert_eq!(server.ping().await["status"], "Healthy");
    server.stop().await;
}

/// A raw body that knows its length and blocks its thread when it is polled.
struct BlockingBody(Option<Box<dyn FnOnce() + Send>>);

impl axum::body::HttpBody for BlockingBody {
    type Data = axum::body::Bytes;
    type Error = BoxError;

    fn poll_frame(
        mut self: std::pin::Pin<&mut Self>,
        _cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Option<Result<http_body::Frame<Self::Data>, BoxError>>> {
        std::task::Poll::Ready(self.0.take().map(|block| {
            block();
            Ok(http_body::Frame::data("done".into()))
        }))
    }

    fn size_hint(&self) -> http_body::SizeHint {
        http_body::SizeHint::with_exact(if self.0.is_some() { 4 } else { 0 })
    }
}

/// The server and `GET /ping` have a thread of their own. This runtime has one
/// worker thread, and the handler, its stream or its raw body blocks it.
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn ping_answers_while_a_handler_its_stream_or_its_raw_body_blocks_its_thread() {
    const BLOCK: Duration = Duration::from_secs(1);
    let (entered_tx, entered) = std::sync::mpsc::channel();
    let handler = move |payload: Value| {
        let entered = entered_tx.clone();
        let block = move || {
            let _ = entered.send(());
            std::thread::sleep(BLOCK);
        };
        async move {
            if payload == "stream" {
                let item = futures_util::stream::once(async move {
                    block();
                    Ok::<_, BoxError>("done")
                });
                return Ok::<_, BoxError>(Response::stream(item));
            }
            if payload == "raw" {
                let body = axum::body::Body::new(BlockingBody(Some(Box::new(block))));
                return Ok(Response::from_http(axum::http::Response::new(body)));
            }
            block();
            Ok(Response::json("done"))
        }
    };
    let server = Server::start(BedrockAgentCoreApp::builder().invocation(handler)).await;
    let address = server.base.trim_start_matches("http://").to_owned();
    // A client on a thread of its own: the runtime of this test is blocked with the handler.
    let request = move |head: String, body: &'static str| {
        use std::io::{Read, Write};
        let mut stream = std::net::TcpStream::connect(&address).unwrap();
        stream.set_read_timeout(Some(DEADLINE)).unwrap();
        write!(stream, "{head} HTTP/1.1\r\nHost: test\r\nConnection: close\r\n{SESSION}: s\r\n").unwrap();
        write!(stream, "Content-Length: {}\r\n\r\n{body}", body.len()).unwrap();
        let mut response = String::new();
        stream.read_to_string(&mut response).unwrap();
        response
    };

    for body in ["\"json\"", "\"stream\"", "\"raw\""] {
        let invoke = request.clone();
        let invocation = std::thread::spawn(move || invoke("POST /invocations".to_owned(), body));
        entered.recv_timeout(DEADLINE).expect("the handler did not start");
        let started = std::time::Instant::now();
        let ping = request("GET /ping".to_owned(), "");
        let waited = started.elapsed();
        assert!(ping.starts_with("HTTP/1.1 200") && ping.contains("Healthy"), "{body}: {ping}");
        assert!(waited < BLOCK / 2, "{body}: the ping waited {waited:?} for the blocked thread");
        let reply = invocation.join().unwrap();
        assert!(reply.starts_with("HTTP/1.1 200") && reply.contains("done"), "{body}: {reply}");
        // A body that knows its length keeps it, although the server reads it elsewhere.
        assert_eq!(reply.contains("content-length: 4\r\n"), body == "\"raw\"", "{body}: {reply}");
    }
    server.stop().await;
}

#[tokio::test]
async fn warmup_call_without_a_body_succeeds_and_ping_answers_while_its_handler_waits() {
    let (entered, mut was_entered) = mpsc::channel(1);
    let (release, released) = tokio::sync::watch::channel(false);
    let memory = move || {
        let (entered, mut released) = (entered.clone(), released.clone());
        async move {
            entered.send(()).await?;
            released.wait_for(|released| *released).await?;
            Ok::<(), BoxError>(())
        }
    };
    let hook = WarmupHook::new("/warmup").memory(memory);
    let server = Server::start(BedrockAgentCoreApp::builder().invocation(echo).warmup_hook(hook)).await;

    // As the service sends it: no body, no Content-Type and no Content-Length.
    let mut stream = tokio::net::TcpStream::connect(server.base.trim_start_matches("http://")).await.unwrap();
    let request = "POST /warmup HTTP/1.1\r\nHost: test\r\nConnection: close\r\n\
                   X-Amzn-Bedrock-AgentCore-Runtime-Warmup-Type: memory\r\n\r\n";
    stream.write_all(request.as_bytes()).await.unwrap();
    timeout(DEADLINE, was_entered.recv()).await.expect("the handler did not start").unwrap();
    assert_eq!(server.ping().await["status"], "Healthy");

    release.send(true).unwrap();
    let response = String::from_utf8(read_until_closed(&mut stream).await).unwrap();
    assert!(response.starts_with("HTTP/1.1 200"), "{response}");
    let reply: Value = serde_json::from_str(&response[response.find("\r\n\r\n").unwrap()..]).unwrap();
    assert_eq!(reply, json!({ "status": "ok", "type": "memory", "result": "completed" }));
    server.stop().await;
}

#[tokio::test]
async fn body_limit_applies_to_a_chunked_body_without_content_length() {
    let server = Server::start(BedrockAgentCoreApp::builder().invocation(echo).body_limit(32)).await;
    // No Content-Length: the limit applies to the bytes that arrive.
    let chunk = "x".repeat(40);
    let chunked = format!(
        "POST /invocations HTTP/1.1\r\nHost: test\r\nConnection: close\r\n{SESSION}: s\r\n\
         Transfer-Encoding: chunked\r\n\r\n{:x}\r\n{chunk}\r\n0\r\n\r\n",
        chunk.len()
    );
    let response = server.raw(chunked.as_bytes()).await;
    assert!(response.starts_with("HTTP/1.1 413") && response.contains("Request body is too large"), "{response}");
    server.stop().await;
}

#[tokio::test]
async fn interrupted_upload_does_not_reach_the_handler() {
    let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
    let counter = calls.clone();
    let handler = move |payload: Value| {
        counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
        async move { Ok::<_, BoxError>(payload) }
    };
    let server = Server::start(BedrockAgentCoreApp::builder().invocation(handler)).await;

    // The client declares 100 bytes, sends 9 and closes.
    let partial =
        format!("POST /invocations HTTP/1.1\r\nHost: test\r\n{SESSION}: s\r\nContent-Length: 100\r\n\r\n{{\"n\":1}}  ");
    let mut stream = tokio::net::TcpStream::connect(server.base.trim_start_matches("http://")).await.unwrap();
    stream.write_all(partial.as_bytes()).await.unwrap();
    stream.shutdown().await.unwrap();
    read_until_closed(&mut stream).await;
    assert_eq!(server.invoke(&[(SESSION, "s")], r#"{"n":2}"#).await, (StatusCode::OK, json!({ "n": 2 })));
    assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 1);
    server.stop().await;
}

/// Two Accept fields mean the same as one field that lists both media types.
#[tokio::test]
async fn repeated_accept_fields_are_one_list() {
    let handler = |_payload: Value| async { Ok::<_, BoxError>("text") };
    let server = Server::start(BedrockAgentCoreApp::builder().invocation(handler)).await;
    // (Accept fields, content type, body)
    let cases = [
        (vec!["text/plain", "application/json"], "application/json", "\"text\""),
        (vec!["application/json", "text/plain"], "application/json", "\"text\""),
        (vec!["text/plain", "application/octet-stream"], "text/plain; charset=utf-8", "text"),
    ];
    for (accept, content_type, body) in cases {
        let fields: String = accept.iter().map(|value| format!("Accept: {value}\r\n")).collect();
        let request = format!(
            "POST /invocations HTTP/1.1\r\nHost: test\r\nConnection: close\r\n{SESSION}: s\r\n{fields}Content-Length: 2\r\n\r\n{{}}"
        );
        let response = server.raw(request.as_bytes()).await;
        assert!(response.starts_with("HTTP/1.1 200"), "{response}");
        assert!(response.contains(&format!("content-type: {content_type}\r\n")), "{accept:?}: {response}");
        assert!(response.ends_with(&format!("\r\n\r\n{body}")), "{accept:?}: {response}");
    }
    server.stop().await;
}

/// Tells the test when the server drops the source of a stream.
struct SignalOnDrop(mpsc::Sender<()>);

impl Drop for SignalOnDrop {
    fn drop(&mut self) {
        let _ = self.0.try_send(());
    }
}

/// Opens a streaming invocation over the socket.
async fn open_stream(server: &Server) -> reqwest::Response {
    let response = server.send("POST", "/invocations", &[(SESSION, "s"), ("accept", "text/event-stream")], "{}").await;
    assert_eq!(response.status(), StatusCode::OK);
    assert_eq!(response.headers()["content-type"], "text/event-stream");
    response
}

/// Reads one transport chunk of a stream that has not ended.
async fn read_some(response: &mut reqwest::Response) {
    timeout(DEADLINE, response.chunk()).await.expect("no data arrived").unwrap().expect("the stream ended");
}

/// The record reader must not depend on how the transport cuts the bytes.
#[test]
fn sse_records_are_assembled_from_fragmented_and_coalesced_bytes() {
    let stream = "data: \"é\"\n\n:\n\nevent: error\ndata: {}\n\ndata: tail".as_bytes();
    let records = ["data: \"é\"", ":", "event: error\ndata: {}"];
    // Every way to cut the bytes in two, including inside "é" and inside a blank line.
    for cut in 0..=stream.len() {
        let (mut buffer, mut seen) = (Vec::new(), Vec::new());
        for fragment in [&stream[..cut], &stream[cut..]] {
            buffer.extend_from_slice(fragment);
            while let Some(record) = take_sse_record(&mut buffer) {
                seen.push(record);
            }
        }
        assert_eq!(seen, records, "cut at {cut}");
        assert_eq!(buffer, b"data: tail", "cut at {cut}");
    }
}

#[tokio::test]
async fn stream_reaches_the_client_before_the_source_continues_and_stops_on_disconnect() {
    let (items, receiver) = mpsc::channel::<u32>(1);
    let receiver = Arc::new(std::sync::Mutex::new(Some(receiver)));
    let (dropped, mut source_dropped) = mpsc::channel::<()>(1);
    let handler = move |_payload: Value| {
        let state = (receiver.lock().unwrap().take().expect("one invocation"), SignalOnDrop(dropped.clone()));
        let events = stream::unfold(state, |(mut receiver, dropped)| async move {
            receiver.recv().await.map(|n| (Ok::<_, BoxError>(json!({ "n": n })), (receiver, dropped)))
        });
        std::future::ready(Ok::<_, BoxError>(Response::stream(events)))
    };
    let server = Server::start(BedrockAgentCoreApp::builder().invocation(handler)).await;
    let mut events = SseReader::new(open_stream(&server).await);

    // The client holds event 1 while the source has not produced event 2 yet.
    for n in [1, 2] {
        items.send(n).await.unwrap();
        assert_eq!(events.next().await, Some(format!("data: {{\"n\":{n}}}")));
    }

    // The source now waits for an item that never comes. The client disconnects.
    drop(events);
    assert_eq!(timeout(DEADLINE, source_dropped.recv()).await.expect("the source was not dropped"), Some(()));
    server.stop().await;
}

/// The server pulls from the source only as fast as the connection takes data.
#[tokio::test]
async fn slow_reader_stops_the_producer_and_reading_resumes_it() {
    let produced = Arc::new(AtomicUsize::new(0));
    let counter = produced.clone();
    let handler = move |_payload: Value| {
        let counter = counter.clone();
        // An endless stream of 64 KiB items.
        let events = stream::repeat_with(move || {
            counter.fetch_add(1, Ordering::SeqCst);
            Ok::<_, BoxError>("x".repeat(64 * 1024))
        });
        std::future::ready(Ok::<_, BoxError>(Response::stream(events)))
    };
    let server = Server::start(BedrockAgentCoreApp::builder().invocation(handler)).await;
    let mut response = open_stream(&server).await;
    // This test counts production, not events, so it reads raw transport chunks.
    read_some(&mut response).await;

    // The client reads nothing. Production must stop once the transport buffers are full.
    let stalled_at = async {
        loop {
            let before = produced.load(Ordering::SeqCst);
            tokio::time::sleep(Duration::from_millis(200)).await;
            if produced.load(Ordering::SeqCst) == before {
                return before;
            }
        }
    };
    let stalled_at = timeout(DEADLINE, stalled_at).await.expect("the producer never stopped");
    assert!(stalled_at < 2_000, "{stalled_at} items of 64 KiB were produced for a client that reads nothing");

    // Reading again lets the producer continue.
    let resumed = async {
        while produced.load(Ordering::SeqCst) <= stalled_at {
            read_some(&mut response).await;
        }
    };
    timeout(DEADLINE, resumed).await.expect("the producer did not resume");
    drop(response);
    server.stop().await;
}

const GRACE: Duration = Duration::from_millis(300);

/// A handler for the shutdown tests. The payload selects what it does.
#[derive(Clone)]
struct Work {
    /// Completes what waits when the test sends `true`.
    release: tokio::sync::watch::Receiver<bool>,
    /// Tells the test that a handler or a stream source was dropped.
    dropped: mpsc::Sender<()>,
    /// The number of invocations that have reached the handler.
    entered: Arc<AtomicUsize>,
}

impl Work {
    fn new() -> (Self, tokio::sync::watch::Sender<bool>, mpsc::Receiver<()>) {
        let (release, released) = tokio::sync::watch::channel(false);
        let (dropped, was_dropped) = mpsc::channel(8);
        (Self { release: released, dropped, entered: Arc::default() }, release, was_dropped)
    }

    async fn released(mut self) {
        let _ = self.release.wait_for(|released| *released).await;
    }

    async fn handle(self, payload: Value, ctx: RequestContext) -> Result<Response, BoxError> {
        let on_drop = SignalOnDrop(self.dropped.clone());
        self.entered.fetch_add(1, Ordering::SeqCst);
        Ok(match payload.as_str() {
            // Replies when released.
            Some("slow") => {
                self.released().await;
                std::mem::forget(on_drop);
                Response::json("slow done")
            }
            // One event at once, one more when released, then the end.
            Some("stream") => {
                let events = stream::unfold((0, self, on_drop), |(n, work, on_drop)| async move {
                    match n {
                        0 => Some((Ok::<_, BoxError>(n), (1, work, on_drop))),
                        1 => {
                            work.clone().released().await;
                            Some((Ok(n), (2, work, on_drop)))
                        }
                        _ => {
                            std::mem::forget(on_drop);
                            None
                        }
                    }
                });
                Response::stream(events)
            }
            // An endless stream of 64 KiB items.
            Some("flood") => Response::stream(stream::repeat_with(move || {
                let _held = &on_drop;
                Ok::<_, BoxError>("x".repeat(64 * 1024))
            })),
            // A tracked background task that ends when released. The reply is immediate.
            Some("job") => {
                let guard = ctx.tasks().track("job");
                tokio::spawn(async move {
                    // The signal is sent when the task ends, by release or by cancellation.
                    let (_guard, _on_drop) = (guard, on_drop);
                    self.released().await;
                });
                Response::json("job started")
            }
            _ => Response::json("ok"),
        })
    }
}

fn work_app(work: &Work) -> bedrock_agentcore::runtime::Builder {
    let work = work.clone();
    BedrockAgentCoreApp::builder()
        .invocation(move |payload: Value, ctx: RequestContext| work.clone().handle(payload, ctx))
        .shutdown_grace(GRACE)
}

/// Sends a request with a JSON string body and returns the open connection.
async fn raw_request(server: &Server, headers: &str, body: &str) -> tokio::net::TcpStream {
    let mut stream = tokio::net::TcpStream::connect(server.base.trim_start_matches("http://")).await.unwrap();
    let request = format!("POST /invocations HTTP/1.1\r\nHost: test\r\n{SESSION}: s\r\n{headers}\r\n{body}");
    stream.write_all(request.as_bytes()).await.unwrap();
    stream
}

/// Reads until the server closes the connection, and returns what arrived.
async fn read_until_closed(stream: &mut tokio::net::TcpStream) -> Vec<u8> {
    let mut received = Vec::new();
    let closed = async {
        let mut buffer = vec![0; 256 * 1024];
        // A reset connection is closed too.
        while let Ok(read @ 1..) = stream.read(&mut buffer).await {
            received.extend_from_slice(&buffer[..read]);
        }
    };
    timeout(DEADLINE, closed).await.expect("the server did not close the connection");
    received
}

#[tokio::test]
async fn server_runs_longer_than_its_grace_period_until_the_signal() {
    let (work, _release, _dropped) = Work::new();
    let server = Server::start(work_app(&work)).await;
    // The grace period limits the shutdown, not the uptime.
    tokio::time::sleep(GRACE + Duration::from_millis(200)).await;
    assert_eq!(server.invoke(&[(SESSION, "s")], "null").await, (StatusCode::OK, json!("ok")));
    let (result, _) = server.shut_down().await;
    result.unwrap();

    // The longest grace period cannot be added to the clock. It means no deadline.
    let server = Server::start(work_app(&work).shutdown_grace(Duration::MAX)).await;
    let (result, _) = server.shut_down().await;
    result.unwrap();
}

#[tokio::test]
async fn shutdown_waits_for_requests_streams_and_tracked_tasks_that_finish_in_time() {
    let (work, release, _dropped) = Work::new();
    let builder = work_app(&work).shutdown_grace(DEADLINE);
    let Server { base, shutdown, mut task } = Server::start(builder).await;
    let post = |body: &'static str, accept: &'static str| {
        client().post(format!("{base}/invocations")).header(SESSION, "s").header("accept", accept).body(body).send()
    };

    let slow = tokio::spawn(post("\"slow\"", "application/json"));
    let mut events = SseReader::new(post("\"stream\"", "text/event-stream").await.unwrap());
    assert_eq!(events.next().await.as_deref(), Some("data: 0"));
    assert_eq!(post("\"job\"", "application/json").await.unwrap().json::<Value>().await.unwrap(), "job started");

    shutdown.send(()).unwrap();
    // The server must still be draining. This interval is the behavior under test.
    assert!(
        timeout(Duration::from_millis(200), &mut task).await.is_err(),
        "the server stopped while work was in flight"
    );

    release.send(true).unwrap();
    assert_eq!(slow.await.unwrap().unwrap().json::<Value>().await.unwrap(), "slow done");
    assert_eq!((events.next().await.as_deref(), events.next().await), (Some("data: 1"), None));
    timeout(DEADLINE, task).await.expect("server did not stop").unwrap().unwrap();
    assert!(client().get(format!("{base}/ping")).send().await.is_err(), "server still accepts connections");
}

/// At the end of the grace period the server ends what is still running and returns
/// `ShutdownTimeout`. Each case leaves one thing running.
#[tokio::test]
async fn shutdown_deadline_ends_connections_that_are_still_open() {
    // (case, request headers, request body, the server must drop a handler or stream source)
    let cases = [
        ("handler that does not return", "Content-Length: 6\r\n", "\"slow\"", true),
        ("stream that does not end", "Accept: text/event-stream\r\nContent-Length: 8\r\n", "\"stream\"", true),
        // The client stops reading while the server writes an endless stream. The server
        // drops the stream once the client reads again or the connection closes.
        ("reader that does not read", "Accept: text/event-stream\r\nContent-Length: 7\r\n", "\"flood\"", true),
        // The client declares 1000 bytes and sends 6.
        ("upload that does not finish", "Content-Length: 1000\r\n", "\"slow\"", false),
    ];
    for (case, headers, body, drops_work) in cases {
        let (work, _release, mut dropped) = Work::new();
        let server = Server::start(work_app(&work)).await;
        let mut connection = raw_request(&server, headers, body).await;
        // The deadline counts from the signal, so an uptime beyond the grace period changes nothing.
        tokio::time::sleep(GRACE + Duration::from_millis(100)).await;

        let (result, elapsed) = server.shut_down().await;
        assert_eq!(result.unwrap_err().kind(), ErrorKind::ShutdownTimeout, "{case}");
        assert!(elapsed >= GRACE && elapsed < GRACE + Duration::from_secs(2), "{case}: shutdown took {elapsed:?}");

        // The server has returned. Its connection is closed and its work is dropped.
        read_until_closed(&mut connection).await;
        if drops_work {
            assert_eq!(timeout(DEADLINE, dropped.recv()).await.expect(case), Some(()), "{case}");
        }
    }
}

/// The request waits inside a layer of the customer, which never calls the app. The
/// deadline must cancel the layer itself.
#[tokio::test]
async fn shutdown_deadline_cancels_a_request_that_waits_inside_a_layer() {
    let (entered, mut was_entered) = mpsc::channel(1);
    let (dropped, mut was_dropped) = mpsc::channel(1);
    let layer = axum::middleware::from_fn(move |_request: axum::extract::Request, _next: axum::middleware::Next| {
        let (entered, on_drop) = (entered.clone(), SignalOnDrop(dropped.clone()));
        async move {
            let _on_drop = on_drop;
            entered.send(()).await.unwrap();
            std::future::pending::<StatusCode>().await
        }
    });
    let server =
        Server::start(BedrockAgentCoreApp::builder().invocation(echo).layer(layer).shutdown_grace(GRACE)).await;
    let reply =
        tokio::spawn(client().post(format!("{}/invocations", server.base)).header(SESSION, "s").body("{}").send());
    assert_eq!(timeout(DEADLINE, was_entered.recv()).await.expect("the request did not reach the layer"), Some(()));

    let (result, _) = server.shut_down().await;
    assert_eq!(result.unwrap_err().kind(), ErrorKind::ShutdownTimeout);
    assert_eq!(reply.await.unwrap().unwrap().status(), StatusCode::SERVICE_UNAVAILABLE);
    assert_eq!(timeout(DEADLINE, was_dropped.recv()).await.expect("the layer was not dropped"), Some(()));
}

/// HTTP/2 runs each request as a stream of one connection. At the deadline both
/// requests of the connection are ended.
#[tokio::test]
async fn shutdown_deadline_ends_concurrent_streams_of_one_http2_connection() {
    let (work, _release, mut dropped) = Work::new();
    let server = Server::start(work_app(&work)).await;
    let http2 = reqwest::Client::builder().http2_prior_knowledge().timeout(DEADLINE).build().unwrap();
    let post = |body: &'static str, accept: &'static str| {
        http2
            .post(format!("{}/invocations", server.base))
            .header(SESSION, "s")
            .header("accept", accept)
            .body(body)
            .send()
    };

    // A stream that does not end and a handler that does not return, at the same time.
    let stream = post("\"stream\"", "text/event-stream").await.unwrap();
    assert_eq!(stream.version(), reqwest::Version::HTTP_2);
    let mut events = SseReader::new(stream);
    assert_eq!(events.next().await.as_deref(), Some("data: 0"));
    let slow = tokio::spawn(post("\"slow\"", "application/json"));
    let both_running = async {
        while work.entered.load(Ordering::SeqCst) < 2 {
            tokio::task::yield_now().await;
        }
    };
    timeout(DEADLINE, both_running).await.expect("the second request did not reach its handler");
    // A third stream of the same client is answered while the other two are open.
    let ping = http2.get(format!("{}/ping", server.base)).send().await.unwrap();
    assert_eq!((ping.version(), ping.status()), (reqwest::Version::HTTP_2, StatusCode::OK));

    let (result, elapsed) = server.shut_down().await;
    assert_eq!(result.unwrap_err().kind(), ErrorKind::ShutdownTimeout);
    assert!(elapsed >= GRACE && elapsed < GRACE + Duration::from_secs(2), "shutdown took {elapsed:?}");

    // The server dropped the stream source and the handler. The request that had no
    // reply yet gets a 503.
    for _ in 0..2 {
        assert_eq!(timeout(DEADLINE, dropped.recv()).await.expect("a request outlived the server"), Some(()));
    }
    assert_eq!(slow.await.unwrap().unwrap().status(), StatusCode::SERVICE_UNAVAILABLE);
}

/// An application that stops polling the server future, for example by aborting its
/// task, must not leave connections of the server behind.
#[tokio::test]
async fn dropping_the_server_future_ends_its_connections() {
    let (work, _release, mut dropped) = Work::new();
    let Server { base, shutdown: _never_signalled, task } = Server::start(work_app(&work)).await;
    let server = Server { base, shutdown: tokio::sync::oneshot::channel().0, task: tokio::spawn(async { Ok(()) }) };
    let mut connection = raw_request(&server, "Content-Length: 6\r\n", "\"slow\"").await;
    // The handler is running: it holds a drop signal that has not fired.
    let entered = async {
        while work.entered.load(Ordering::SeqCst) == 0 {
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
    };
    timeout(DEADLINE, entered).await.expect("the request did not reach the handler");
    assert!(dropped.try_recv().is_err());

    task.abort();
    assert!(task.await.unwrap_err().is_cancelled());
    read_until_closed(&mut connection).await;
    assert_eq!(timeout(DEADLINE, dropped.recv()).await.expect("the handler outlived the server"), Some(()));
}

/// The server does not own a tracked task. It waits for it and reports it, and the
/// task keeps running.
#[tokio::test]
async fn shutdown_reports_a_tracked_task_that_outlasts_the_grace_period() {
    let (work, release, mut dropped) = Work::new();
    let server = Server::start(work_app(&work)).await;
    assert_eq!(server.invoke(&[(SESSION, "s")], "\"job\"").await.1, "job started");

    // No connection is open. Only the background task holds the shutdown back.
    let (result, elapsed) = server.shut_down().await;
    let error = result.unwrap_err();
    assert_eq!(error.kind(), ErrorKind::ShutdownTimeout);
    // No request was in flight, so the text names the task only.
    assert_eq!(
        error.to_string(),
        format!("shutdown did not finish within {GRACE:?}: 1 tracked background task is still active")
    );
    assert!(elapsed >= GRACE && elapsed < GRACE + Duration::from_secs(2), "shutdown took {elapsed:?}");

    // The task was not cancelled: it is still running and ends when it is released.
    assert!(dropped.try_recv().is_err(), "the server ended a task that it does not own");
    release.send(true).unwrap();
    assert_eq!(timeout(DEADLINE, dropped.recv()).await.expect("the task did not finish"), Some(()));
}

/// Work that the customer spawned without tracking it does not delay the shutdown
/// and is not stopped by it.
#[tokio::test]
async fn untracked_work_neither_delays_shutdown_nor_is_stopped_by_it() {
    let (finish, finished) = tokio::sync::oneshot::channel::<()>();
    let (done, was_done) = tokio::sync::oneshot::channel::<&'static str>();
    let channels = Arc::new(std::sync::Mutex::new(Some((finished, done))));
    let handler = move |_payload: Value| {
        let (finished, done) = channels.lock().unwrap().take().expect("one invocation");
        tokio::spawn(async move {
            let _ = finished.await;
            let _ = done.send("untracked work finished");
        });
        std::future::ready(Ok::<_, BoxError>("started"))
    };
    let server = Server::start(BedrockAgentCoreApp::builder().invocation(handler).shutdown_grace(DEADLINE)).await;
    assert_eq!(server.invoke(&[(SESSION, "s")], "{}").await.1, "started");

    let (result, elapsed) = server.shut_down().await;
    result.unwrap();
    assert!(elapsed < Duration::from_secs(2), "shutdown waited {elapsed:?} for work that is not tracked");
    finish.send(()).unwrap();
    assert_eq!(
        timeout(DEADLINE, was_done).await.expect("the untracked work was stopped"),
        Ok("untracked work finished")
    );
}

#[tokio::test]
async fn run_binds_the_configured_address_and_reports_an_occupied_one() {
    let occupied = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr: SocketAddr = occupied.local_addr().unwrap();

    let error = BedrockAgentCoreApp::builder().invocation(echo).bind(addr).build().unwrap().run().await.unwrap_err();
    assert_eq!(error.kind(), ErrorKind::Bind);
    assert!(error.to_string().contains(&addr.to_string()), "{error}");
    // The cause is kept as the source and is not repeated in the text.
    let cause = std::error::Error::source(&error).expect("the bind error has a source").to_string();
    assert!(!error.to_string().contains(&cause), "{error} repeats {cause}");

    // `run` stops only on a process signal, so this test aborts and awaits its task.
    drop(occupied);
    let task = tokio::spawn(BedrockAgentCoreApp::builder().invocation(echo).bind(addr).build().unwrap().run());
    let deadline = tokio::time::Instant::now() + DEADLINE;
    while client().get(format!("http://{addr}/ping")).send().await.is_err() {
        assert!(tokio::time::Instant::now() < deadline && !task.is_finished(), "server did not start on {addr}");
        tokio::time::sleep(Duration::from_millis(20)).await;
    }
    let request = client().post(format!("http://{addr}/invocations")).header(SESSION, "s").body(r#"{"n":1}"#);
    let reply: Value = request.send().await.unwrap().json().await.unwrap();
    assert_eq!((&reply["echo"], &reply["session_id"]), (&json!({ "n": 1 }), &json!("s")));
    task.abort();
    assert!(task.await.unwrap_err().is_cancelled());
}