fetchlet 0.1.1

Rust-hosted JavaScript functions and Fetch handlers with explicit host services
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
#![cfg(any(feature = "boa", feature = "quickjs", feature = "v8"))]

use std::num::NonZeroUsize;
use std::time::{Duration, Instant};

use std::future::poll_fn;
use std::pin::Pin;
use std::task::{Context, Poll};

use bytes::Bytes;
use http_body::{Body as _, Frame, SizeHint};
use serde_json::{Value, json};
use tokio::sync::mpsc;

use fetchlet::{
    App, AppHandle, Backend, Body, CancelledCalls, Error, Limits, Module, Response, WorkerOptions,
    http,
};

const SOURCE: &str = include_str!("fixtures/streaming.js");

fn backends() -> Vec<Backend> {
    vec![
        #[cfg(feature = "quickjs")]
        Backend::quickjs(),
        #[cfg(feature = "boa")]
        Backend::boa(),
        #[cfg(feature = "v8")]
        Backend::v8(),
    ]
}

fn limits(timeout: Duration, response_body_bytes: Option<usize>) -> Limits {
    Limits {
        timeout: Some(timeout),
        response_body_bytes,
        ..Limits::default()
    }
}

async fn spawn(backend: Backend, limits: Limits) -> fetchlet::Result<AppHandle> {
    App::builder(backend)
        .module(Module::new(SOURCE))
        .limits(limits)
        .spawn(WorkerOptions::new(NonZeroUsize::new(4).unwrap()))
        .await
}

fn get(path: &str) -> fetchlet::Request {
    http::Request::builder()
        .uri(format!("https://stream.test{path}"))
        .body(Body::empty())
        .unwrap()
}

/// A request body that the test feeds chunk by chunk.
struct ChannelBody {
    receiver: mpsc::Receiver<Bytes>,
    declared: Option<u64>,
}

impl http_body::Body for ChannelBody {
    type Data = Bytes;

    type Error = std::convert::Infallible;

    fn poll_frame(
        mut self: Pin<&mut Self>,
        context: &mut Context<'_>,
    ) -> Poll<Option<Result<Frame<Bytes>, Self::Error>>> {
        self.receiver
            .poll_recv(context)
            .map(|chunk| chunk.map(|chunk| Ok(Frame::data(chunk))))
    }

    fn size_hint(&self) -> SizeHint {
        self.declared.map(SizeHint::with_exact).unwrap_or_default()
    }
}

fn post(path: &str, declared: Option<u64>) -> (mpsc::Sender<Bytes>, fetchlet::Request) {
    let (sender, receiver) = mpsc::channel(1);
    let body = Body::from_http_body(ChannelBody { receiver, declared });
    let request = http::Request::builder()
        .method("POST")
        .uri(format!("https://stream.test{path}"))
        .body(body)
        .unwrap();
    (sender, request)
}

async fn released(sender: &mpsc::Sender<Bytes>) -> bool {
    tokio::time::timeout(Duration::from_secs(5), sender.closed())
        .await
        .is_ok()
}

async fn next_frame(body: &mut Body) -> Option<fetchlet::Result<Bytes>> {
    poll_fn(|context| Pin::new(&mut *body).poll_frame(context))
        .await
        .map(|frame| frame.map(|frame| frame.into_data().unwrap()))
}

async fn frames(response: Response) -> Vec<fetchlet::Result<Bytes>> {
    let mut body = response.into_body();
    let mut frames = Vec::new();
    while let Some(frame) = next_frame(&mut body).await {
        match frame {
            Ok(data) => frames.push(Ok(data)),
            Err(error) => {
                frames.push(Err(error));
                break;
            }
        }
    }
    frames
}

async fn number(handle: &AppHandle, export: &str) -> fetchlet::Result<u64> {
    Ok(handle.call_json(export, &[]).await?.as_u64().unwrap())
}

#[tokio::test(flavor = "current_thread")]
async fn a_handle_streams_frames_as_javascript_produces_them() -> anyhow::Result<()> {
    for backend in backends() {
        let handle = spawn(backend, limits(Duration::from_secs(5), None)).await?;
        let response = handle.fetch(get("/ticks?count=3&wait=20")).await?;
        assert_eq!(response.status(), 200);
        assert_eq!(response.headers()["content-type"], "text/plain");
        let frames: Vec<Bytes> = frames(response)
            .await
            .into_iter()
            .collect::<Result<_, _>>()?;
        assert_eq!(
            frames,
            [&b"tick-0;"[..], b"tick-1;", b"tick-2;"].map(Bytes::from_static),
        );
        // The invocation ended with its body: its timers are gone and the
        // same instance serves the next call.
        assert_eq!(number(&handle, "pendingTimers").await?, 0);
        assert_eq!(number(&handle, "sequence").await?, 1);
        assert_eq!(number(&handle, "cancelled").await?, 0);
        handle.shutdown().await?;
    }
    Ok(())
}

#[tokio::test(flavor = "current_thread")]
async fn an_app_collects_a_streamed_body() -> anyhow::Result<()> {
    for backend in backends() {
        let mut app = App::builder(backend)
            .module(Module::new(SOURCE))
            .limits(limits(Duration::from_secs(5), None))
            .build()?;
        let response = app.fetch(get("/ticks?count=3&wait=5")).await?;
        assert_eq!(
            response.into_body().collect(64).await?.as_ref(),
            b"tick-0;tick-1;tick-2;"
        );
        assert!(app.is_reusable());
        assert_eq!(app.call_json("pendingTimers", &[]).await?, json!(0));
        let response = app.fetch(get("/large?count=3")).await?;
        assert_eq!(response.into_body().collect(120_000).await?.len(), 120_000);
        assert!(app.is_reusable());
    }
    Ok(())
}

#[tokio::test(flavor = "current_thread")]
async fn the_response_budget_covers_the_whole_streamed_body() -> anyhow::Result<()> {
    for backend in backends() {
        let handle = spawn(backend, limits(Duration::from_secs(5), Some(100_000))).await?;
        let response = handle.fetch(get("/large?count=5")).await?;
        let frames = frames(response).await;
        assert!(matches!(
            frames.last(),
            Some(Err(Error::LimitExceeded("response body bytes")))
        ));
        let delivered: usize = frames.iter().flatten().map(Bytes::len).sum();
        assert!(delivered <= 100_000);
        // The JavaScript stream was cancelled and the instance kept.
        assert_eq!(number(&handle, "cancelled").await?, 1);
        assert_eq!(number(&handle, "sequence").await?, 1);

        let mut app = App::builder(backend)
            .module(Module::new(SOURCE))
            .limits(limits(Duration::from_secs(5), Some(100_000)))
            .build()?;
        assert!(matches!(
            app.fetch(get("/large?count=5")).await,
            Err(Error::LimitExceeded("response body bytes"))
        ));
        assert_eq!(app.call_json("cancelled", &[]).await?, json!(1));
        handle.shutdown().await?;
    }
    Ok(())
}

#[tokio::test(flavor = "current_thread")]
async fn the_deadline_covers_the_whole_streamed_body() -> anyhow::Result<()> {
    for backend in backends() {
        let handle = spawn(backend, limits(Duration::from_millis(150), None)).await?;
        let response = handle.fetch(get("/forever?wait=10")).await?;
        let frames = frames(response).await;
        assert!(frames.len() > 1);
        assert!(
            matches!(frames.last(), Some(Err(Error::DeadlineExceeded))),
            "{backend:?}: the body ended with {:?}",
            frames.last()
        );
        // A fresh instance serves the next call.
        assert_eq!(number(&handle, "sequence").await?, 1);
        handle.shutdown().await?;
    }
    Ok(())
}

#[tokio::test(flavor = "current_thread")]
async fn a_consumer_that_stalls_past_the_deadline_reads_deadline_exceeded() -> anyhow::Result<()> {
    for backend in backends() {
        let handle = spawn(backend, limits(Duration::from_millis(150), None)).await?;
        let response = handle.fetch(get("/forever?wait=10")).await?;
        // The queue fills while nothing reads, so the deadline passes while the
        // worker waits for room rather than while JavaScript produces a chunk.
        tokio::time::sleep(Duration::from_millis(400)).await;
        let frames = frames(response).await;
        assert!(
            matches!(frames.last(), Some(Err(Error::DeadlineExceeded))),
            "{backend:?}: the body ended with {:?}",
            frames.last()
        );
        assert_eq!(number(&handle, "sequence").await?, 1);
        handle.shutdown().await?;
    }
    Ok(())
}

#[tokio::test(flavor = "current_thread")]
async fn dropping_a_body_cancels_the_javascript_stream() -> anyhow::Result<()> {
    for backend in backends() {
        let handle = spawn(backend, limits(Duration::from_secs(5), None)).await?;

        // Dropped while the worker waits for a read that never settles: the
        // abandoned evaluation retires the instance.
        let mut body = handle.fetch(get("/pending")).await?.into_body();
        let first = next_frame(&mut body).await.unwrap()?;
        assert_eq!(first.as_ref(), b"start;");
        // The head carried the first chunk; let the worker enter the pull
        // that never settles before dropping the body.
        tokio::time::sleep(Duration::from_millis(100)).await;
        drop(body);
        assert_eq!(number(&handle, "sequence").await?, 1);
        assert_eq!(number(&handle, "cancelled").await?, 0);

        // Dropped while the worker waits for queue room, between pulls: the
        // stream is cancelled cooperatively and the instance stays.
        let mut body = handle.fetch(get("/burst")).await?.into_body();
        assert!(!next_frame(&mut body).await.unwrap()?.is_empty());
        tokio::time::sleep(Duration::from_millis(200)).await;
        drop(body);
        assert_eq!(number(&handle, "sequence").await?, 2);
        assert_eq!(number(&handle, "cancelled").await?, 1);
        assert_eq!(number(&handle, "pendingTimers").await?, 0);
        // The handler saw its request abort before the body was cancelled.
        assert_eq!(number(&handle, "aborts").await?, 1);
        handle.shutdown().await?;
    }
    Ok(())
}

#[tokio::test(flavor = "current_thread")]
async fn a_stream_error_reaches_the_body_consumer() -> anyhow::Result<()> {
    for backend in backends() {
        let handle = spawn(backend, limits(Duration::from_secs(5), None)).await?;
        let frames = frames(handle.fetch(get("/error?wait=5")).await?).await;
        assert_eq!(frames.len(), 2);
        assert_eq!(frames[0].as_ref().unwrap().as_ref(), b"ok;");
        assert!(
            matches!(&frames[1], Err(Error::JavaScript(message)) if message.contains("stream failure"))
        );
        assert_eq!(number(&handle, "sequence").await?, 1);
        assert_eq!(
            handle.call_json("pendingTimers", &[]).await?,
            Value::from(0)
        );
        handle.shutdown().await?;
    }
    Ok(())
}

#[tokio::test(flavor = "current_thread")]
async fn a_body_not_handed_to_the_host_ends_with_its_invocation() -> anyhow::Result<()> {
    for backend in backends() {
        let handle = spawn(backend, limits(Duration::from_secs(5), None)).await?;
        let response = handle.fetch(get("/withheld")).await?;
        let id: u64 = response.headers()["x-body"].to_str()?.parse()?;
        assert!(response.into_body().collect(0).await?.is_empty());
        // Nothing from that invocation stays reachable by a later one.
        assert_eq!(number(&handle, "openBodies").await?, 0);
        assert_eq!(number(&handle, "pendingTimers").await?, 0);
        assert_eq!(handle.call_json("probe", &[json!(id)]).await?, Value::Null);
        assert_eq!(number(&handle, "cancelled").await?, 1);

        // A later Fetch call cannot name an earlier body as its own.
        let open = handle.fetch(get("/forever?wait=10")).await?;
        drop(open);
        assert_eq!(
            handle.call_json("probe", &[json!(id + 1)]).await?,
            Value::Null
        );
        handle.shutdown().await?;
    }
    Ok(())
}

#[tokio::test(flavor = "current_thread")]
async fn a_request_body_streams_into_javascript_as_it_arrives() -> anyhow::Result<()> {
    for backend in backends() {
        let handle = spawn(backend, limits(Duration::from_secs(5), None)).await?;
        let (sender, request) = post("/echo", None);
        let response = handle.fetch(request).await?;
        let mut body = response.into_body();
        // Each chunk reaches the handler, and comes back, before the next exists.
        for chunk in [&b"first;"[..], b"second;"] {
            sender.send(Bytes::from_static(chunk)).await?;
            assert_eq!(next_frame(&mut body).await.unwrap()?.as_ref(), chunk);
        }
        drop(sender);
        assert!(next_frame(&mut body).await.is_none());
        assert_eq!(number(&handle, "sequence").await?, 1);
        handle.shutdown().await?;
    }
    Ok(())
}

#[tokio::test(flavor = "current_thread")]
async fn the_request_budget_covers_the_streamed_body() -> anyhow::Result<()> {
    for backend in backends() {
        let limits = Limits {
            request_body_bytes: Some(4),
            ..limits(Duration::from_secs(5), None)
        };
        let handle = spawn(backend, limits).await?;

        // Chunks arrive as the producer sends them, within the budget.
        let (sender, request) = post("/count", None);
        let feed = async {
            for chunk in [&b"ab"[..], b"cd"] {
                sender.send(Bytes::from_static(chunk)).await.unwrap();
            }
            drop(sender);
        };
        let (response, ()) = tokio::join!(handle.fetch(request), feed);
        assert_eq!(response?.into_body().collect(64).await?.as_ref(), b"2:4");

        // The budget applies to the bytes read so far.
        let (sender, request) = post("/count", None);
        let feed = async {
            for chunk in [&b"abc"[..], b"def"] {
                if sender.send(Bytes::from_static(chunk)).await.is_err() {
                    break;
                }
            }
        };
        let (response, ()) = tokio::join!(handle.fetch(request), feed);
        let response = response?;
        assert_eq!(response.status(), 500);
        assert_eq!(
            response.into_body().collect(64).await?.as_ref(),
            b"LIMIT_EXCEEDED"
        );

        // A declared length over the budget fails before JavaScript runs.
        let (_sender, request) = post("/count", Some(5));
        assert!(matches!(
            handle.fetch(request).await,
            Err(Error::LimitExceeded("request body bytes"))
        ));
        assert_eq!(number(&handle, "sequence").await?, 1);
        handle.shutdown().await?;
    }
    Ok(())
}

#[tokio::test(flavor = "current_thread")]
async fn an_unread_request_body_is_released_with_its_invocation() -> anyhow::Result<()> {
    for backend in backends() {
        let handle = spawn(backend, limits(Duration::from_secs(5), None)).await?;
        let (sender, request) = post("/ignore", None);
        let response = handle.fetch(request).await?;
        assert!(response.into_body().collect(0).await?.is_empty());
        assert!(released(&sender).await);

        // Dropping a response that reads the request body releases it too.
        let (sender, request) = post("/echo", None);
        let mut body = handle.fetch(request).await?.into_body();
        sender.send(Bytes::from_static(b"x")).await?;
        assert_eq!(next_frame(&mut body).await.unwrap()?.as_ref(), b"x");
        drop(body);
        assert!(released(&sender).await);
        assert_eq!(number(&handle, "sequence").await?, 1);
        handle.shutdown().await?;
    }
    Ok(())
}

/// An App whose outbound fetch answers with a body the test feeds.
async fn spawn_with_upstream(
    backend: Backend,
    limits: Limits,
) -> anyhow::Result<(AppHandle, mpsc::Sender<Bytes>)> {
    let (sender, receiver) = mpsc::channel(1);
    let receiver = std::sync::Arc::new(std::sync::Mutex::new(Some(receiver)));
    let transport = fetchlet::transport_fn(move |_| {
        let receiver = receiver.lock().unwrap().take();
        async move {
            let receiver = receiver.ok_or(Error::Transport("one upstream call".into()))?;
            let body = ChannelBody {
                receiver,
                declared: None,
            };
            Ok(Response::new(Body::from_http_body(body)))
        }
    });
    let policy = fetchlet::FetchPolicy::deny_all().allow_origin("https://upstream.test")?;
    let services =
        fetchlet::HostServices::new().outbound(fetchlet::FetchService::new(transport, policy));
    let handle = App::builder(backend)
        .module(Module::new(SOURCE))
        .limits(limits)
        .host_services(services)
        .spawn(WorkerOptions::new(NonZeroUsize::new(4).unwrap()))
        .await?;
    Ok((handle, sender))
}

#[tokio::test(flavor = "current_thread")]
async fn an_upstream_body_streams_through_the_handler() -> anyhow::Result<()> {
    for backend in backends() {
        let (handle, upstream) =
            spawn_with_upstream(backend, limits(Duration::from_secs(5), None)).await?;
        let response = handle.fetch(get("/proxy")).await?;
        assert_eq!(response.status(), 200);
        let mut body = response.into_body();
        // Each upstream chunk reaches the client before the next exists.
        for chunk in [&b"up-1;"[..], b"up-2;"] {
            upstream.send(Bytes::from_static(chunk)).await?;
            assert_eq!(next_frame(&mut body).await.unwrap()?.as_ref(), chunk);
        }
        drop(upstream);
        assert!(next_frame(&mut body).await.is_none());
        assert_eq!(number(&handle, "sequence").await?, 1);
        handle.shutdown().await?;
    }
    Ok(())
}

#[tokio::test(flavor = "current_thread")]
async fn the_response_budget_covers_a_streamed_upstream_body() -> anyhow::Result<()> {
    for backend in backends() {
        let (handle, upstream) =
            spawn_with_upstream(backend, limits(Duration::from_secs(5), Some(8))).await?;
        let mut body = handle.fetch(get("/proxy")).await?.into_body();
        upstream.send(Bytes::from_static(b"12345")).await?;
        assert_eq!(next_frame(&mut body).await.unwrap()?.as_ref(), b"12345");
        upstream.send(Bytes::from_static(b"67890")).await?;
        // The upstream read fails, which errors the handler's body.
        assert!(matches!(next_frame(&mut body).await, Some(Err(_))));
        assert!(released(&upstream).await);
        handle.shutdown().await?;
    }
    Ok(())
}

#[tokio::test(flavor = "current_thread")]
async fn cancelling_or_aborting_releases_the_upstream_body() -> anyhow::Result<()> {
    for backend in backends() {
        // The client drops the proxied body.
        let (handle, upstream) =
            spawn_with_upstream(backend, limits(Duration::from_secs(5), None)).await?;
        let mut body = handle.fetch(get("/proxy")).await?.into_body();
        upstream.send(Bytes::from_static(b"x")).await?;
        assert_eq!(next_frame(&mut body).await.unwrap()?.as_ref(), b"x");
        drop(body);
        assert!(released(&upstream).await);
        assert_eq!(number(&handle, "sequence").await?, 1);
        handle.shutdown().await?;

        // The handler aborts the fetch after the first chunk.
        let (handle, upstream) =
            spawn_with_upstream(backend, limits(Duration::from_secs(5), None)).await?;
        upstream.send(Bytes::from_static(b"first")).await?;
        let response = handle.fetch(get("/abort-upstream")).await?;
        assert_eq!(
            response.into_body().collect(64).await?.as_ref(),
            b"first|stopped"
        );
        assert!(released(&upstream).await);
        handle.shutdown().await?;
    }
    Ok(())
}

async fn spawn_finishing(backend: Backend, limits: Limits) -> fetchlet::Result<AppHandle> {
    let mut worker = WorkerOptions::new(NonZeroUsize::new(4).unwrap());
    worker.cancelled_calls = CancelledCalls::Finish;
    App::builder(backend)
        .module(Module::new(SOURCE))
        .limits(limits)
        .spawn(worker)
        .await
}

#[tokio::test(flavor = "current_thread")]
async fn a_cancelled_head_retires_the_instance_by_default() -> anyhow::Result<()> {
    for backend in backends() {
        let handle = spawn(backend, limits(Duration::from_secs(5), None)).await?;
        assert_eq!(number(&handle, "sequence").await?, 1);
        let cancelled =
            tokio::time::timeout(Duration::from_millis(50), handle.fetch(get("/slow-head")));
        assert!(cancelled.await.is_err());
        // The evaluation was abandoned with its instance.
        assert_eq!(number(&handle, "sequence").await?, 1);
        assert_eq!(number(&handle, "finished").await?, 0);
        handle.shutdown().await?;
    }
    Ok(())
}

#[tokio::test(flavor = "current_thread")]
async fn a_finishing_worker_completes_a_cancelled_head_and_keeps_the_instance() -> anyhow::Result<()>
{
    for backend in backends() {
        let handle = spawn_finishing(backend, limits(Duration::from_secs(5), None)).await?;
        assert_eq!(number(&handle, "sequence").await?, 1);
        let cancelled =
            tokio::time::timeout(Duration::from_millis(50), handle.fetch(get("/slow-head")));
        assert!(cancelled.await.is_err());
        // The next call waits for the cancelled one, which ran to its end.
        assert_eq!(number(&handle, "sequence").await?, 2);
        assert_eq!(number(&handle, "finished").await?, 1);
        assert_eq!(number(&handle, "pendingTimers").await?, 0);
        handle.shutdown().await?;
    }
    Ok(())
}

#[tokio::test(flavor = "current_thread")]
async fn a_finishing_worker_completes_a_cancelled_call() -> anyhow::Result<()> {
    for backend in backends() {
        let handle = spawn_finishing(backend, limits(Duration::from_secs(5), None)).await?;
        assert_eq!(number(&handle, "sequence").await?, 1);
        let cancelled =
            tokio::time::timeout(Duration::from_millis(50), handle.call_json("slowCall", &[]));
        assert!(cancelled.await.is_err());
        assert_eq!(number(&handle, "sequence").await?, 2);
        assert_eq!(number(&handle, "finished").await?, 1);
        handle.shutdown().await?;
    }
    Ok(())
}

#[tokio::test(flavor = "current_thread")]
async fn a_finishing_worker_cancels_a_body_dropped_during_a_pull() -> anyhow::Result<()> {
    for backend in backends() {
        let handle = spawn_finishing(backend, limits(Duration::from_secs(5), None)).await?;
        assert_eq!(number(&handle, "sequence").await?, 1);
        let mut body = handle.fetch(get("/forever?wait=150")).await?.into_body();
        assert_eq!(next_frame(&mut body).await.unwrap()?.as_ref(), b"tick-0;");
        // The worker is in the pull that waits for the next tick.
        tokio::time::sleep(Duration::from_millis(50)).await;
        drop(body);
        // The pull returned, then the stream was cancelled, in the same
        // instance.
        assert_eq!(number(&handle, "sequence").await?, 2);
        assert_eq!(number(&handle, "cancelled").await?, 1);
        assert_eq!(number(&handle, "pendingTimers").await?, 0);
        handle.shutdown().await?;
    }
    Ok(())
}

#[tokio::test(flavor = "current_thread")]
async fn a_finishing_worker_retires_a_call_that_outlives_its_deadline() -> anyhow::Result<()> {
    for backend in backends() {
        let handle = spawn_finishing(backend, limits(Duration::from_millis(300), None)).await?;
        assert_eq!(number(&handle, "sequence").await?, 1);
        let mut body = handle.fetch(get("/pending")).await?.into_body();
        assert_eq!(next_frame(&mut body).await.unwrap()?.as_ref(), b"start;");
        tokio::time::sleep(Duration::from_millis(50)).await;
        drop(body);
        // The pull never settles; at the deadline the instance is replaced.
        let next = tokio::time::timeout(Duration::from_secs(5), number(&handle, "sequence"));
        assert_eq!(next.await??, 1);
        handle.shutdown().await?;
    }
    Ok(())
}

#[tokio::test(flavor = "current_thread")]
async fn a_finishing_worker_aborts_the_request_signal_of_a_cancelled_head() -> anyhow::Result<()> {
    for backend in backends() {
        let handle = spawn_finishing(backend, limits(Duration::from_secs(5), None)).await?;
        let started = Instant::now();
        let cancelled = tokio::time::timeout(
            Duration::from_millis(50),
            handle.fetch(get("/until-abort-head")),
        );
        assert!(cancelled.await.is_err());
        // The handler returned once its signal aborted, well before its own
        // two-second fallback, in the same instance.
        assert_eq!(number(&handle, "aborts").await?, 1);
        assert!(started.elapsed() < Duration::from_millis(1500));
        assert_eq!(number(&handle, "sequence").await?, 1);
        assert_eq!(number(&handle, "sequence").await?, 2);
        handle.shutdown().await?;
    }
    Ok(())
}

#[tokio::test(flavor = "current_thread")]
async fn a_finishing_worker_aborts_the_request_signal_during_a_pull() -> anyhow::Result<()> {
    for backend in backends() {
        let handle = spawn_finishing(backend, limits(Duration::from_secs(5), None)).await?;
        let mut body = handle.fetch(get("/until-abort-body")).await?.into_body();
        assert_eq!(next_frame(&mut body).await.unwrap()?.as_ref(), b"start;");
        tokio::time::sleep(Duration::from_millis(50)).await;
        let started = Instant::now();
        drop(body);
        // The pull waiting for the abort ended the body, and the instance
        // stays.
        assert_eq!(number(&handle, "aborts").await?, 1);
        assert!(started.elapsed() < Duration::from_millis(1500));
        assert_eq!(number(&handle, "sequence").await?, 1);
        assert_eq!(number(&handle, "pendingTimers").await?, 0);
        handle.shutdown().await?;
    }
    Ok(())
}

#[tokio::test(flavor = "current_thread")]
async fn a_completed_request_never_aborts() -> anyhow::Result<()> {
    for backend in backends() {
        let handle = spawn_finishing(backend, limits(Duration::from_secs(5), None)).await?;
        let frames = frames(handle.fetch(get("/ticks?count=2&wait=10")).await?).await;
        assert_eq!(frames.len(), 2);
        assert_eq!(handle.fetch(get("/slow-head")).await?.status(), 200);
        assert_eq!(number(&handle, "aborts").await?, 0);
        handle.shutdown().await?;
    }
    Ok(())
}