tilo-actions 0.5.0

The Tilo action model: resources, the actions on them, and their registry, with the plain resource vocabulary that needs no store, search index entries included.
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
//! A whole connection of the line wire, answered as one caller: what a local socket that keeps
//! state between lines serves.

use std::collections::HashMap;
use std::io::{BufRead, Write};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;

use tilo_lock::MutexRecover as _;

use super::{answer_message, frame_line, line_refusal};
use crate::outcome::InvocationId;
use crate::remote::refuse;
use crate::remote::{
    ActionCallError, ActionProvider, Caller, ContentGetAnswer, HostedContentPuts,
    MAX_REMOTE_ACTION_FRAME_BYTES, RemoteActionFrame, RemoteActionMessage,
};

/// How many requests that wait one connection keeps answering at once; one past them is answered
/// in turn, so a caller that floods waits slows only itself.
const WAITING_AT_ONCE: usize = 64;

/// Answer every line `input` reads as `tree` answers the frame it holds, `first` before them,
/// writing each answer to `output` until `input` ends or `output` closes.
///
/// `tree` names, for each frame, the provider it is asked of and the caller it is asked as: a
/// connection that serves every workspace its device holds answers each frame in the workspace
/// it names ([`RemoteActionFrame::workspace`]). A frame `tree` refuses is answered with that
/// refusal, and the connection goes on.
///
/// Uploads stay open between lines in `uploads` ([`HostedContentPuts`]), each answering only the
/// caller that began it: kept beyond the connection, one a lost connection cut is taken up on the
/// next. Content is read through the provider's [`ActionProvider::content_gets`]. A request that waits
/// ([`RemoteActionMessage::waits`]) is answered on a thread of its own, so the lines after it are
/// answered meanwhile; each answer names what it answers, so the order answers go out in is
/// theirs. A line that is no frame is refused, and the connection goes on.
///
/// A connection that ends cancels the calls it still waits on, through
/// [`ActionProvider::cancel`]: a call that outlives its caller is told it stopped.
pub fn serve_lines<H: ActionProvider + Clone + Send + Sync + 'static>(
    tree: impl FnMut(&RemoteActionFrame) -> Result<(H, Caller), ActionCallError>,
    uploads: &HostedContentPuts,
    first: Option<Vec<u8>>,
    input: impl BufRead,
    output: impl Write + Send + 'static,
    slack: Duration,
) {
    serve_lines_with(tree, uploads, first, input, output, slack, None);
}

/// What a host's own lane did with a frame.
pub enum Take {
    /// The frame is not the lane's: the provider answers it as any other.
    NotCall,
    /// The lane took it and answers nothing.
    Silent,
    /// The lane's answer, as the line to write.
    Answer(String),
}

/// A host's own frames on a connection it serves, beside the action wire: a call lane on an
/// app's connection ([`crate::remote::call`]). The host answers them itself and may write
/// pushes of its own to the same connection; a frame it does not take goes to the provider.
pub trait CallLanes: Send + Sync {
    /// Take `message` as the lane's, or say it is the provider's.
    fn take(&self, message: &RemoteActionMessage) -> Take;
}

/// [`serve_lines`], with `lanes` answering the frames it owns before the provider sees them.
pub fn serve_lines_with<H: ActionProvider + Clone + Send + Sync + 'static>(
    mut tree: impl FnMut(&RemoteActionFrame) -> Result<(H, Caller), ActionCallError>,
    uploads: &HostedContentPuts,
    first: Option<Vec<u8>>,
    mut input: impl BufRead,
    output: impl Write + Send + 'static,
    slack: Duration,
    lanes: Option<&dyn CallLanes>,
) {
    let connection = Arc::new(Connection {
        output: Mutex::new(output),
        waiting: AtomicUsize::new(0),
        in_flight: Mutex::default(),
    });
    let mut next = first;
    loop {
        let line = match next.take() {
            Some(line) => line,
            None => match read_line(&mut input) {
                Ok(Some(line)) => line,
                Ok(None) | Err(_) => break,
            },
        };
        let frame = match RemoteActionFrame::decode(&line) {
            Ok(frame) => frame,
            Err(error) => {
                if !write_line(
                    &connection.output,
                    &line_refusal("parse_error", &error.to_string()),
                ) {
                    break;
                }
                continue;
            }
        };
        if let Some(lanes) = lanes {
            match lanes.take(&frame.message) {
                Take::NotCall => {}
                Take::Silent => continue,
                Take::Answer(answer) => {
                    if !write_line(&connection.output, &answer) {
                        break;
                    }
                    continue;
                }
            }
        }
        let (provider, caller) = match tree(&frame) {
            Ok(served) => served,
            Err(refusal) => {
                let answer = refuse(&frame.message, refusal).map_or_else(
                    || line_refusal("parse_error", "a frame sent here asks something"),
                    frame_line,
                );
                if !write_line(&connection.output, &answer) {
                    break;
                }
                continue;
            }
        };
        let (provider, caller) = (&provider, &caller);
        let invocation = invocation_of(&frame.message);
        if let Some(invocation) = invocation {
            connection
                .in_flight
                .lock_recover()
                .insert(invocation, (provider.clone(), caller.clone()));
        }
        match answer_frame(
            provider,
            caller,
            uploads,
            frame.message,
            slack,
            &connection,
            invocation,
        ) {
            Answered::Spawned => {}
            Answered::Ended => break,
            Answered::Line(answer) => {
                if !write_line(&connection.output, &answer) {
                    break;
                }
            }
        }
    }
    // The connection ended: what it was still waiting on is cancelled, as its caller's call.
    let running: Vec<(InvocationId, H, Caller)> = connection
        .in_flight
        .lock_recover()
        .drain()
        .map(|(invocation, (provider, caller))| (invocation, provider, caller))
        .collect();
    for (invocation, provider, caller) in running {
        let _cancelling = provider.cancel(&caller, &invocation);
    }
}

/// What one connection keeps while it serves: where answers go, how many frames wait at once, and
/// the calls it still waits on, each cancelled when the connection ends.
struct Connection<H, W> {
    output: Mutex<W>,
    waiting: AtomicUsize,
    in_flight: Mutex<HashMap<InvocationId, (H, Caller)>>,
}

/// What became of the answer to one frame.
enum Answered {
    /// A thread of its own answers it, so the lines after it are answered meanwhile.
    Spawned,
    /// The line to write now.
    Line(String),
    /// It could not be answered: the connection ends.
    Ended,
}

/// Answer the frame `message` as `provider` and `caller`, keeping `invocation` as the
/// connection's call until an answer ends it.
fn answer_frame<H: ActionProvider + Clone + Send + Sync + 'static, W: Write + Send + 'static>(
    provider: &H,
    caller: &Caller,
    uploads: &HostedContentPuts,
    message: RemoteActionMessage,
    slack: Duration,
    connection: &Arc<Connection<H, W>>,
    invocation: Option<InvocationId>,
) -> Answered {
    let line = match message {
        RemoteActionMessage::ContentPutRequest { correlation, step } => {
            let result = uploads.step(&|target| provider.content_puts_for(target), caller, step);
            frame_line(RemoteActionMessage::ContentPutResponse {
                correlation,
                result,
            })
        }
        RemoteActionMessage::ContentGetRequest {
            correlation,
            content,
            offset,
            length,
        } => {
            let result = provider
                .content_gets()
                .ok_or_else(no_content_store)
                .and_then(|store| store.get(caller, &content, offset, length))
                .and_then(ContentGetAnswer::new);
            frame_line(RemoteActionMessage::ContentGetResponse {
                correlation,
                result,
            })
        }
        message
            if message.waits() && connection.waiting.load(Ordering::Relaxed) < WAITING_AT_ONCE =>
        {
            connection.waiting.fetch_add(1, Ordering::Relaxed);
            let (provider, caller) = (provider.clone(), caller.clone());
            let connection = Arc::clone(connection);
            let spawned = std::thread::Builder::new()
                .name("tilo-line-wait".into())
                .spawn(move || {
                    let answer = answer_message(&provider, &caller, message, slack);
                    if let Some(invocation) = invocation
                        && answers_the_end(&answer)
                    {
                        connection.in_flight.lock_recover().remove(&invocation);
                    }
                    write_line(&connection.output, &answer);
                    connection.waiting.fetch_sub(1, Ordering::Relaxed);
                });
            return if spawned.is_err() {
                Answered::Ended
            } else {
                Answered::Spawned
            };
        }
        message => answer_message(provider, caller, message, slack),
    };
    if let Some(invocation) = invocation
        && answers_the_end(&line)
    {
        connection.in_flight.lock_recover().remove(&invocation);
    }
    Answered::Line(line)
}

/// The invocation a message waits on, when it is one a connection keeps waiting on.
fn invocation_of(message: &RemoteActionMessage) -> Option<InvocationId> {
    match message {
        RemoteActionMessage::Invoke(request) => Some(request.invocation),
        _ => None,
    }
}

/// Whether the answer to an invocation ends it: one that runs on is kept as the connection's call
/// until it ends or the connection does, and an answer this cannot read is its end.
fn answers_the_end(answer: &str) -> bool {
    let Ok(frame) = RemoteActionFrame::decode(answer.as_bytes()) else {
        return true;
    };
    match frame.message {
        RemoteActionMessage::Receipt(receipt) => receipt.status.is_terminal(),
        RemoteActionMessage::Update { state, .. } => state.is_none_or(|state| state.is_terminal()),
        _ => true,
    }
}

/// What a connection is told whose provider keeps no content.
fn no_content_store() -> ActionCallError {
    ActionCallError::Unavailable {
        reason: "no content store is open here".into(),
    }
}

/// Write `line` and its end; whether the other side still reads.
fn write_line(output: &Mutex<impl Write>, line: &str) -> bool {
    let mut output = output.lock_recover();
    writeln!(output, "{line}")
        .and_then(|()| output.flush())
        .is_ok()
}

/// The next line of `input`, without its end; `None` once it ended. A line longer than any
/// frame is read past and answered as the empty line, which is no frame.
fn read_line(input: &mut impl BufRead) -> std::io::Result<Option<Vec<u8>>> {
    let mut line = Vec::new();
    let limit = u64::try_from(MAX_REMOTE_ACTION_FRAME_BYTES.saturating_add(1)).unwrap_or(u64::MAX);
    let read = std::io::Read::take(&mut *input, limit).read_until(b'\n', &mut line)?;
    if read == 0 {
        return Ok(None);
    }
    if line.last() == Some(&b'\n') {
        line.pop();
        return Ok(Some(line));
    }
    if line.len() <= MAX_REMOTE_ACTION_FRAME_BYTES {
        // The input ended within its last line.
        return Ok(Some(line));
    }
    // Too long: what is left of it is read and dropped.
    let mut rest = Vec::new();
    loop {
        rest.clear();
        let read = std::io::Read::take(&mut *input, limit).read_until(b'\n', &mut rest)?;
        if read == 0 || rest.last() == Some(&b'\n') {
            return Ok(Some(Vec::new()));
        }
    }
}

#[cfg(test)]
#[cfg(unix)]
mod tests {
    use super::*;
    use crate::api::ActionAddress;
    use crate::outcome::{ActionOutput, InvocationId};
    use crate::remote::{
        CataloguePage, CatalogueQuery, Completer, ContentGets, ContentPiece, ContentPut,
        ContentPuts, InvocationReceipt, InvocationState, InvokeRequest, LineClient, Pending,
        ReceiptStatus, RemoteActionTarget, TestProvider, pending,
    };
    use std::collections::HashMap;
    use std::io::BufReader;
    use std::os::unix::net::UnixStream;

    /// A provider that keeps content in memory, its actions [`TestProvider`]'s.
    #[derive(Clone)]
    struct Kept {
        actions: Arc<TestProvider>,
        store: Arc<Mutex<HashMap<String, Vec<u8>>>>,
    }

    struct Upload {
        store: Arc<Mutex<HashMap<String, Vec<u8>>>>,
        size: u64,
        bytes: Vec<u8>,
    }

    impl ContentPut for Upload {
        fn size(&self) -> u64 {
            self.size
        }
        fn written(&self) -> u64 {
            self.bytes.len() as u64
        }
        fn append(&mut self, offset: u64, chunk: &[u8]) -> Result<u64, ActionCallError> {
            if offset != self.written() {
                return Err(ActionCallError::InvalidRequest {
                    reason: "a piece out of order".into(),
                });
            }
            self.bytes.extend_from_slice(chunk);
            Ok(self.written())
        }
        fn finish(self: Box<Self>) -> Result<String, ActionCallError> {
            if self.written() != self.size {
                return Err(ActionCallError::InvalidRequest {
                    reason: "an upload finished short".into(),
                });
            }
            let content = format!("tilo.content:{}", blake3::hash(&self.bytes).to_hex());
            self.store
                .lock_recover()
                .insert(content.clone(), self.bytes);
            Ok(content)
        }
    }

    impl ContentPuts for Kept {
        fn begin(&self, _: &Caller, size: u64) -> Result<Box<dyn ContentPut>, ActionCallError> {
            Ok(Box::new(Upload {
                store: Arc::clone(&self.store),
                size,
                bytes: Vec::new(),
            }))
        }
        fn have(&self, _: &Caller, hashes: &[String]) -> Result<Vec<bool>, ActionCallError> {
            let store = self.store.lock_recover();
            Ok(hashes
                .iter()
                .map(|hash| store.contains_key(&format!("tilo.content:{hash}")))
                .collect())
        }
    }

    impl ContentGets for Kept {
        fn get(
            &self,
            _: &Caller,
            content: &str,
            offset: u64,
            length: u64,
        ) -> Result<ContentPiece, ActionCallError> {
            let bytes = self
                .store
                .lock_recover()
                .get(content)
                .cloned()
                .ok_or_else(|| ActionCallError::InvalidRequest {
                    reason: "no such content".into(),
                })?;
            let length = if length == 0 {
                300_000
            } else {
                length.min(300_000)
            };
            let start = usize::try_from(offset).unwrap().min(bytes.len());
            let end = start
                .saturating_add(usize::try_from(length).unwrap())
                .min(bytes.len());
            Ok(ContentPiece {
                size: bytes.len() as u64,
                offset,
                bytes: bytes[start..end].to_vec(),
            })
        }
    }

    impl ActionProvider for Kept {
        fn query(
            &self,
            caller: &Caller,
            query: CatalogueQuery,
        ) -> Pending<Result<CataloguePage, ActionCallError>> {
            self.actions.query(caller, query)
        }
        fn invoke(
            &self,
            caller: &Caller,
            request: InvokeRequest,
        ) -> Pending<Result<InvocationReceipt, ActionCallError>> {
            self.actions.invoke(caller, request)
        }
        fn observe(&self, caller: &Caller, id: &InvocationId) -> Option<InvocationState> {
            self.actions.observe(caller, id)
        }
        fn cancel(
            &self,
            caller: &Caller,
            id: &InvocationId,
        ) -> Pending<Result<(), ActionCallError>> {
            self.actions.cancel(caller, id)
        }
        fn content_puts(&self) -> Option<Arc<dyn ContentPuts>> {
            Some(Arc::new(self.clone()))
        }
        fn content_gets(&self) -> Option<Arc<dyn ContentGets>> {
            Some(Arc::new(self.clone()))
        }
    }

    /// A client of `provider`, served as `caller` on the other end of a socket.
    fn connected<H: ActionProvider + Clone + Send + Sync + 'static>(
        provider: H,
        caller: Caller,
    ) -> LineClient {
        let (near, far) = UnixStream::pair().unwrap();
        std::thread::spawn(move || {
            let output = far.try_clone().unwrap();
            serve_lines(
                |_| Ok((provider.clone(), caller.clone())),
                &HostedContentPuts::default(),
                None,
                BufReader::new(far),
                output,
                Duration::ZERO,
            );
        });
        LineClient::of_stream(near).unwrap()
    }

    fn target() -> RemoteActionTarget {
        RemoteActionTarget {
            provider: "notes".into(),
            address: ActionAddress::new("notes", "create"),
        }
    }

    /// Asked from any thread at once, each answer reaches the ask it answers, decided as the
    /// caller the serving end names, whoever the client says it is.
    #[test]
    fn answers_reach_their_asks_as_the_serving_ends_caller() {
        let actions = Arc::new(
            TestProvider::new()
                .with_catalogue(|_, query| {
                    Ok(CataloguePage {
                        revision: "r1".into(),
                        ..CataloguePage::from_rows("r1".into(), Vec::new(), &query)
                    })
                })
                .completing(|request| ActionOutput {
                    value: Some(serde_json::json!({ "asked": request.invocation.0.to_string() })),
                    resources: Vec::new(),
                }),
        );
        let served = Caller::local_app("notes").in_workspace("w");
        let client = connected(
            Kept {
                actions: Arc::clone(&actions),
                store: Arc::default(),
            },
            served.clone(),
        );
        let threads: Vec<_> = (0..8)
            .map(|_| {
                let client = client.clone();
                std::thread::spawn(move || {
                    let request = InvokeRequest::plain(target(), serde_json::Map::new());
                    let invocation = request.invocation;
                    let receipt = client
                        .invoke(&Caller::local_person("someone else"), request)
                        .wait_timeout(Duration::from_secs(10))
                        .ok()
                        .flatten()
                        .expect("answered")
                        .unwrap();
                    assert_eq!(receipt.invocation, invocation);
                    let ReceiptStatus::Completed { output } = receipt.status else {
                        panic!("not completed: {receipt:?}");
                    };
                    assert_eq!(
                        output.value.unwrap()["asked"],
                        invocation.0.to_string(),
                        "each receipt answers its own invocation"
                    );
                })
            })
            .collect();
        let page = client
            .query(
                &Caller::local_person("someone else"),
                CatalogueQuery::default(),
            )
            .wait_timeout(Duration::from_secs(10))
            .ok()
            .flatten()
            .expect("answered")
            .unwrap();
        assert_eq!(page.revision, "r1");
        for thread in threads {
            thread.join().unwrap();
        }
        assert_eq!(actions.asked().len(), 8);
        assert!(
            actions.callers().iter().all(|caller| *caller == served),
            "every call is the serving end's caller: {:?}",
            actions.callers()
        );
    }

    /// A file larger than a frame goes up in pieces on one open upload, small files go up
    /// together, and each comes back whole, read a piece at a time.
    #[test]
    fn content_goes_up_in_frames_and_comes_back_whole() {
        let kept = Kept {
            actions: Arc::new(TestProvider::new()),
            store: Arc::default(),
        };
        let client = connected(kept, Caller::local_person("ada"));
        let caller = Caller::local_person("ada");
        let large: Vec<u8> = (0..1_000_000_u32).map(|at| (at % 251) as u8).collect();
        let small = vec![b"one".to_vec(), b"two".to_vec(), large.clone()];
        let puts = client.content_puts().unwrap();
        let contents = puts.put_many(&caller, &small).unwrap();
        assert_eq!(contents.len(), 3);
        let present = puts
            .have(&caller, &[contents[0].clone(), "0".repeat(64)])
            .unwrap();
        assert_eq!(
            present,
            [true, false],
            "a put file is there, another is not"
        );
        let gets = client.content_gets().unwrap();
        let whole = gets
            .get(&caller, &contents[2], 0, large.len() as u64)
            .unwrap();
        assert_eq!(whole.size, large.len() as u64);
        assert!(whole.bytes == large, "the large file comes back whole");
        let first = gets.get(&caller, &contents[2], 10, 0).unwrap();
        assert_eq!(first.bytes.len(), 300_000, "zero asks for one piece");
        assert_eq!(first.bytes[..], large[10..300_010]);
        assert_eq!(gets.get(&caller, &contents[1], 0, 0).unwrap().bytes, b"two");
        let refused = gets.get(&caller, "tilo.content:nothing", 0, 0).unwrap_err();
        assert!(
            matches!(refused, ActionCallError::InvalidRequest { .. }),
            "{refused:?}"
        );
    }

    /// A connection the other end closes answers what waits on it, and every later ask, with
    /// why; a refusal line says it in the other end's words.
    #[test]
    fn a_closed_connection_answers_every_ask() {
        let (near, far) = UnixStream::pair().unwrap();
        let client = LineClient::of_stream(near).unwrap();
        let mut far_writer = far.try_clone().unwrap();
        let mut reader = BufReader::new(far);
        let asked = client.query(&Caller::local_person("ada"), CatalogueQuery::default());
        let mut line = String::new();
        reader.read_line(&mut line).unwrap();
        assert!(RemoteActionFrame::decode(line.trim_end().as_bytes()).is_ok());
        writeln!(far_writer, "{}", line_refusal("not_permitted", "not yours")).unwrap();
        let refused = asked
            .wait_timeout(Duration::from_secs(10))
            .ok()
            .flatten()
            .expect("answered")
            .unwrap_err();
        assert_eq!(
            refused,
            ActionCallError::Refused {
                reason: "not yours".into()
            }
        );
        let later = client
            .cancel(&Caller::local_person("ada"), &InvocationId::new())
            .wait_timeout(Duration::from_secs(10))
            .ok()
            .flatten()
            .expect("answered")
            .unwrap_err();
        assert_eq!(later, refused);
        // A client that goes closes its connection, so the other end hears it left.
        drop(client);
        let mut rest = String::new();
        assert_eq!(reader.read_line(&mut rest).unwrap(), 0, "{rest}");
    }

    /// What answers a call kept until it hears it stop.
    type Held = Completer<Result<InvocationReceipt, ActionCallError>>;

    /// A provider whose one call runs until it hears it stop, recording the stop.
    #[derive(Clone, Default)]
    struct Waiting {
        asked: Arc<Mutex<Vec<InvocationId>>>,
        cancels: Arc<Mutex<Vec<InvocationId>>>,
        held: Arc<Mutex<Vec<Held>>>,
    }

    impl ActionProvider for Waiting {
        fn query(
            &self,
            _: &Caller,
            _: CatalogueQuery,
        ) -> Pending<Result<CataloguePage, ActionCallError>> {
            Pending::ready(Ok(CataloguePage::default()))
        }

        fn invoke(
            &self,
            _: &Caller,
            request: InvokeRequest,
        ) -> Pending<Result<InvocationReceipt, ActionCallError>> {
            self.asked.lock_recover().push(request.invocation);
            let (complete, answer) = pending();
            self.held.lock_recover().push(complete);
            answer
        }

        fn observe(&self, _: &Caller, _: &InvocationId) -> Option<InvocationState> {
            None
        }

        fn cancel(&self, _: &Caller, id: &InvocationId) -> Pending<Result<(), ActionCallError>> {
            self.cancels.lock_recover().push(*id);
            Pending::ready(Ok(()))
        }
    }

    /// A connection that ends cancels the call it still waited on: one that outlives the
    /// connection that began it is told it stopped, rather than answered nobody.
    #[test]
    fn a_connection_that_ends_cancels_the_call_it_waited_on() {
        let provider = Waiting::default();
        let caller = Caller::local_app("notes").in_workspace("w");
        let (near, far) = UnixStream::pair().unwrap();
        let output = far.try_clone().unwrap();
        let serving = provider.clone();
        std::thread::spawn(move || {
            serve_lines(
                move |_| Ok((serving.clone(), caller.clone())),
                &HostedContentPuts::default(),
                None,
                BufReader::new(far),
                output,
                Duration::ZERO,
            );
        });
        let client = LineClient::of_stream(near).unwrap();
        let mut request = InvokeRequest::plain(target(), serde_json::Map::new());
        request.wait_ms = Some(0);
        let invocation = request.invocation;
        let pending = client.invoke(&Caller::local_person("ada"), request);
        tilo_test_env::wait_until("the provider to hold the call", || {
            provider.asked.lock_recover().contains(&invocation)
        });
        drop(client);
        tilo_test_env::wait_until("the call to be cancelled", || {
            provider.cancels.lock_recover().contains(&invocation)
        });
        drop(pending);
    }
}