subc-client-rs 0.32.12

Shared serve + consume client for Rust subc modules.
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
751
752
753
754
755
756
757
758
759
use super::*;
use std::{future::poll_fn, task::Poll};

struct Echo;

#[async_trait]
impl ModuleHandler for Echo {
    async fn handle(&self, _ctx: RequestCtx, body: Vec<u8>) -> HandlerOutcome {
        HandlerOutcome::Response(body)
    }
}

fn handle_on(
    runtime: tokio::runtime::Handle,
    ops: &[&str],
) -> (ModuleHandle, mpsc::Receiver<Frame>) {
    let (writer, rx) = mpsc::channel(1);
    let ack = ModuleHelloAckBody {
        negotiated_ver: PROTOCOL_VERSION,
        subc_ops: ops.iter().map(|op| (*op).to_owned()).collect(),
        subc_capabilities: Vec::new(),
        storage: None,
        machine_id: None,
    };
    (
        ModuleHandle::new(&ack, writer, 1, CancellationToken::new(), runtime),
        rx,
    )
}

fn handle() -> (ModuleHandle, mpsc::Receiver<Frame>) {
    handle_on(tokio::runtime::Handle::current(), &[OPERATOR_CONFIRM_OP])
}

fn reply(ty: FrameType, corr: u64, body: serde_json::Value) -> Frame {
    Frame::build(
        ty,
        control_flags(),
        0,
        0,
        corr,
        serde_json::to_vec(&body).unwrap(),
    )
    .unwrap()
}

fn confirmed(corr: u64) -> Frame {
    reply(
        FrameType::Response,
        corr,
        serde_json::json!({"op": "operator.confirm", "outcome": "confirmed"}),
    )
}

fn pending_count(handle: &ModuleHandle) -> usize {
    handle.shared.lock_inner().pending_operator_confirms.len()
}

async fn still_pending<F: Future>(mut future: Pin<&mut F>) {
    poll_fn(|cx| {
        assert!(
            future.as_mut().poll(cx).is_pending(),
            "confirmation completed early"
        );
        Poll::Ready(())
    })
    .await;
}

fn fill_egress(handle: &ModuleHandle) {
    handle
        .shared
        .lock_inner()
        .writer
        .as_ref()
        .unwrap()
        .try_send(confirmed(999))
        .unwrap();
}

async fn assert_one_cancel(rx: &mut mpsc::Receiver<Frame>, corr: u64) {
    let cancel = timeout(Duration::from_secs(2), rx.recv())
        .await
        .unwrap()
        .unwrap();
    assert_eq!(cancel.header.ty, FrameType::Cancel);
    assert_eq!(cancel.header.channel, 0);
    assert_eq!(cancel.header.epoch, 0);
    assert_eq!(cancel.header.corr, corr);
    assert!(cancel.body.is_empty());
    tokio::task::yield_now().await;
    assert!(rx.try_recv().is_err(), "more than one Cancel was sent");
}

#[tokio::test]
async fn operator_confirm_fake_daemon_confirmed_reply_succeeds() {
    let mut served =
        super::stand_in::serve_against_stand_in_with_ops(|_| Echo, &[OPERATOR_CONFIRM_OP]).await;
    let route = served.handle.route_handle(7, 3);
    let mut call = Box::pin(served.handle.confirm_operator("Replace identity", &route));
    still_pending(call.as_mut()).await;
    let request = timeout(Duration::from_secs(2), read_frame(&mut served.daemon))
        .await
        .unwrap()
        .unwrap()
        .unwrap();
    assert_eq!(request.header.ty, FrameType::Request);
    assert_eq!(request.header.channel, 0);
    assert_eq!(request.header.epoch, 0);
    assert_eq!(
        serde_json::from_slice::<serde_json::Value>(&request.body).unwrap(),
        serde_json::json!({"op": "operator.confirm", "summary": "Replace identity",
            "route_channel": 7, "route_epoch": 3})
    );
    write_frame(&mut served.daemon, &confirmed(request.header.corr))
        .await
        .unwrap();
    served.daemon.flush().await.unwrap();
    assert_eq!(
        timeout(Duration::from_secs(2), &mut call).await.unwrap(),
        Ok(())
    );
    assert_eq!(pending_count(&served.handle), 0);
    drop(call);
    served.handle.close_connection();
    timeout(Duration::from_secs(3), served.serve)
        .await
        .unwrap()
        .unwrap()
        .unwrap();
}

#[tokio::test]
async fn operator_confirm_fake_daemon_close_wakes_before_deadline() {
    let mut served =
        super::stand_in::serve_against_stand_in_with_ops(|_| Echo, &[OPERATOR_CONFIRM_OP]).await;
    let route = served.handle.route_handle(7, 3);
    let mut call = Box::pin(served.handle.confirm_operator("Replace identity", &route));
    still_pending(call.as_mut()).await;
    let _ = timeout(Duration::from_secs(2), read_frame(&mut served.daemon))
        .await
        .unwrap()
        .unwrap()
        .unwrap();
    served.daemon.shutdown().await.unwrap();
    assert_eq!(
        timeout(Duration::from_secs(2), &mut call).await.unwrap(),
        Err(OperatorConfirmError::PresenceUnavailable)
    );
    assert_eq!(pending_count(&served.handle), 0);
    drop(call);
    timeout(Duration::from_secs(3), served.serve)
        .await
        .unwrap()
        .unwrap()
        .unwrap();
}

#[tokio::test]
async fn operator_confirm_unadvertised_is_unsupported_without_sending() {
    let (handle, mut rx) = handle_on(tokio::runtime::Handle::current(), &[]);
    assert_eq!(
        handle
            .confirm_operator("Replace identity", &handle.route_handle(7, 3))
            .await,
        Err(OperatorConfirmError::Unsupported)
    );
    assert_eq!(pending_count(&handle), 0);
    assert!(rx.try_recv().is_err());
}

#[tokio::test]
async fn operator_confirm_foreign_route_is_not_permitted_without_sending() {
    let (handle, mut rx) = handle();
    assert_eq!(
        handle
            .confirm_operator("Replace identity", &RouteHandle::new(7, 3, 2))
            .await,
        Err(OperatorConfirmError::NotPermitted)
    );
    assert_eq!(pending_count(&handle), 0);
    assert!(rx.try_recv().is_err());
}

#[tokio::test]
async fn operator_confirm_daemon_errors_map_to_unit_variants() {
    let cases = [
        ("operator_declined", OperatorConfirmError::Declined),
        (
            "operator_presence_unavailable",
            OperatorConfirmError::PresenceUnavailable,
        ),
        (
            "operator_summary_invalid",
            OperatorConfirmError::SummaryInvalid,
        ),
        (
            "operator_request_not_permitted",
            OperatorConfirmError::NotPermitted,
        ),
        ("not_registered", OperatorConfirmError::NotPermitted),
        (
            "unsupported_control_frame",
            OperatorConfirmError::Unsupported,
        ),
        ("unknown_code", OperatorConfirmError::PresenceUnavailable),
    ];
    for (code, expected) in cases {
        let (handle, mut rx) = handle();
        let route = handle.route_handle(7, 3);
        let mut call = Box::pin(handle.confirm_operator("Replace identity", &route));
        still_pending(call.as_mut()).await;
        let request = rx.recv().await.unwrap();
        assert!(handle.handle_control_reply(reply(FrameType::Error, request.header.corr,
            serde_json::json!({"code": code, "message": "refused", "detail": {"reason": "audit only"}}))));
        assert_eq!(call.await, Err(expected), "{code}");
        assert_eq!(pending_count(&handle), 0);
        assert!(
            rx.try_recv().is_err(),
            "terminal reply must disarm cancellation"
        );
    }
}

/// Only the exact code plus `detail.reason` `unsupported_platform` names the
/// missing prompt; every other presence failure, including that reason under
/// another code or a missing detail, stays `PresenceUnavailable`.
#[tokio::test]
async fn operator_confirm_unsupported_platform_is_distinct_from_other_presence_failures() {
    let cases = [
        (
            serde_json::json!({"code": "operator_presence_unavailable", "message": "refused",
                "detail": {"reason": "unsupported_platform"}}),
            OperatorConfirmError::PresenceUnsupportedPlatform,
        ),
        (
            serde_json::json!({"code": "operator_presence_unavailable", "message": "refused",
                "detail": {"reason": "provider_error"}}),
            OperatorConfirmError::PresenceUnavailable,
        ),
        (
            serde_json::json!({"code": "operator_presence_unavailable", "message": "refused"}),
            OperatorConfirmError::PresenceUnavailable,
        ),
        (
            serde_json::json!({"code": "some_new_code", "message": "refused",
                "detail": {"reason": "unsupported_platform"}}),
            OperatorConfirmError::PresenceUnavailable,
        ),
    ];
    for (body, expected) in cases {
        let (handle, mut rx) = handle();
        let route = handle.route_handle(7, 3);
        let mut call = Box::pin(handle.confirm_enrollment("Pair with Office PC", &route));
        still_pending(call.as_mut()).await;
        let request = rx.recv().await.unwrap();
        assert!(handle.handle_control_reply(reply(
            FrameType::Error,
            request.header.corr,
            body.clone()
        )));
        assert_eq!(call.await, Err(expected), "{body}");
        assert_eq!(pending_count(&handle), 0);
    }
}

#[tokio::test]
async fn operator_confirm_daemon_errors_map_backoff_detail() {
    let cases = [
        (
            serde_json::json!({"reason": "backoff", "retry_after_ms": 2_001}),
            OperatorConfirmError::Backoff {
                retry_after_ms: Some(2_001),
            },
        ),
        (
            serde_json::json!({"reason": "backoff"}),
            OperatorConfirmError::Backoff {
                retry_after_ms: None,
            },
        ),
        (
            serde_json::json!({"reason": "person"}),
            OperatorConfirmError::Declined,
        ),
    ];

    for (detail, expected) in cases {
        let (handle, mut rx) = handle();
        let route = handle.route_handle(7, 3);
        let mut call = Box::pin(handle.confirm_operator("Replace identity", &route));
        still_pending(call.as_mut()).await;
        let request = rx.recv().await.unwrap();
        assert!(handle.handle_control_reply(reply(
            FrameType::Error,
            request.header.corr,
            serde_json::json!({
                "code": "operator_declined",
                "message": "refused",
                "detail": detail
            })
        )));
        assert_eq!(call.await, Err(expected));
        assert_eq!(pending_count(&handle), 0);
    }

    assert_eq!(
        OperatorConfirmError::Backoff {
            retry_after_ms: Some(2_001)
        }
        .to_string(),
        "operator confirmation refused without asking: a recent decline holds new prompts for 3 s"
    );
    assert_eq!(
        OperatorConfirmError::Backoff {
            retry_after_ms: None
        }
        .to_string(),
        "operator confirmation refused without asking: a recent decline holds new prompts for a short time"
    );
}

#[tokio::test]
async fn operator_confirm_only_well_formed_confirmed_reply_succeeds() {
    let cases = [
        (
            FrameType::Response,
            serde_json::json!({"op": "operator.confirm", "outcome": "declined"}),
        ),
        (
            FrameType::Response,
            serde_json::json!({"op": "catalog.update", "outcome": "confirmed"}),
        ),
        (
            FrameType::Response,
            serde_json::json!({"outcome": "confirmed"}),
        ),
        (
            FrameType::Response,
            serde_json::json!({"op": "operator.confirm"}),
        ),
        (FrameType::Response, serde_json::json!(["not a reply"])),
        (
            FrameType::Error,
            serde_json::json!({"code": "operator_declined"}),
        ),
        (
            FrameType::Push,
            serde_json::json!({"op": "operator.confirm", "outcome": "confirmed"}),
        ),
    ];
    for (ty, body) in cases {
        let (handle, mut rx) = handle();
        let route = handle.route_handle(7, 3);
        let mut call = Box::pin(handle.confirm_operator("Replace identity", &route));
        still_pending(call.as_mut()).await;
        let request = rx.recv().await.unwrap();
        assert!(handle.handle_control_reply(reply(ty, request.header.corr, body)));
        assert_eq!(call.await, Err(OperatorConfirmError::PresenceUnavailable));
        assert!(rx.try_recv().is_err());
    }
}

#[tokio::test]
async fn operator_confirm_uses_separate_table_and_shared_corr_allocator() {
    let (handle, mut rx) = handle();
    let (catalog_corr, _, catalog_rx) = handle.shared.begin_catalog_update().unwrap();
    let route = handle.route_handle(7, 3);
    let mut call = Box::pin(handle.confirm_operator("Replace identity", &route));
    still_pending(call.as_mut()).await;
    let request = rx.recv().await.unwrap();
    assert!(request.header.corr > catalog_corr);
    assert_eq!(pending_count(&handle), 1);
    assert_eq!(handle.shared.lock_inner().pending_catalog_updates.len(), 1);
    handle.handle_control_reply(confirmed(request.header.corr));
    assert_eq!(call.await, Ok(()));
    handle.handle_control_reply(reply(
        FrameType::Response,
        catalog_corr,
        serde_json::json!({"op": "catalog.update"}),
    ));
    assert!(matches!(
        catalog_rx.await.unwrap(),
        Ok(ModuleControlResponseToModule::CatalogUpdate {})
    ));
}

#[tokio::test(start_paused = true)]
async fn operator_confirm_still_waits_after_eleven_seconds() {
    let (handle, mut rx) = handle();
    let route = handle.route_handle(7, 3);
    let mut call = Box::pin(handle.confirm_operator("Replace identity", &route));
    still_pending(call.as_mut()).await;
    let request = rx.recv().await.unwrap();
    tokio::time::advance(Duration::from_secs(11)).await;
    still_pending(call.as_mut()).await;
    handle.handle_control_reply(confirmed(request.header.corr));
    assert_eq!(call.await, Ok(()));
}

#[tokio::test(start_paused = true)]
async fn operator_confirm_deadline_includes_wait_for_egress_capacity() {
    let (handle, mut rx) = handle();
    fill_egress(&handle);
    let route = handle.route_handle(7, 3);
    let mut call = Box::pin(handle.confirm_operator_with_deadline(
        "Replace identity",
        &route,
        Duration::from_secs(5),
    ));
    still_pending(call.as_mut()).await;
    assert_eq!(pending_count(&handle), 1);
    tokio::time::advance(Duration::from_secs(5)).await;
    assert_eq!(
        timeout(Duration::from_secs(1), &mut call)
            .await
            .expect("deadline did not cover send"),
        Err(OperatorConfirmError::PresenceUnavailable)
    );
    assert_eq!(pending_count(&handle), 0);
    assert_eq!(rx.recv().await.unwrap().header.corr, 999);
    assert!(
        rx.try_recv().is_err(),
        "unaccepted request must not send Cancel"
    );
}

#[tokio::test(start_paused = true)]
async fn operator_confirm_capacity_wait_reduces_reply_budget() {
    let (handle, mut rx) = handle();
    fill_egress(&handle);
    let route = handle.route_handle(7, 3);
    let mut call = Box::pin(handle.confirm_operator_with_deadline(
        "Replace identity",
        &route,
        Duration::from_secs(100),
    ));
    still_pending(call.as_mut()).await;
    tokio::time::advance(Duration::from_secs(70)).await;
    assert_eq!(rx.recv().await.unwrap().header.corr, 999);
    still_pending(call.as_mut()).await;
    let request = rx.recv().await.unwrap();
    tokio::time::advance(Duration::from_secs(29)).await;
    still_pending(call.as_mut()).await;
    tokio::time::advance(Duration::from_secs(1)).await;
    assert_eq!(
        timeout(Duration::from_secs(1), &mut call)
            .await
            .expect("send reset the reply budget"),
        Err(OperatorConfirmError::PresenceUnavailable)
    );
    assert_eq!(pending_count(&handle), 0);
    assert_one_cancel(&mut rx, request.header.corr).await;
}

#[tokio::test]
async fn operator_confirm_drop_before_acceptance_cleans_table_without_cancel() {
    let (handle, mut rx) = handle();
    fill_egress(&handle);
    let route = handle.route_handle(7, 3);
    let mut call = Box::pin(handle.confirm_operator("Replace identity", &route));
    still_pending(call.as_mut()).await;
    assert_eq!(pending_count(&handle), 1);
    drop(call);
    assert_eq!(pending_count(&handle), 0);
    assert_eq!(rx.recv().await.unwrap().header.corr, 999);
    assert!(rx.try_recv().is_err());
}

#[tokio::test]
async fn operator_confirm_drop_after_acceptance_sends_one_cancel() {
    let (handle, mut rx) = handle();
    let route = handle.route_handle(7, 3);
    let mut call = Box::pin(handle.confirm_operator("Replace identity", &route));
    still_pending(call.as_mut()).await;
    let request = rx.recv().await.unwrap();
    drop(call);
    assert_eq!(pending_count(&handle), 0);
    assert_one_cancel(&mut rx, request.header.corr).await;
}

#[tokio::test]
async fn operator_confirm_drop_with_full_egress_sends_one_cancel_when_drained() {
    let (handle, mut rx) = handle();
    let route = handle.route_handle(7, 3);
    let mut call = Box::pin(handle.confirm_operator("Replace identity", &route));
    still_pending(call.as_mut()).await;
    let request = rx.recv().await.unwrap();
    fill_egress(&handle);
    drop(call);
    assert_eq!(pending_count(&handle), 0);
    assert_eq!(rx.recv().await.unwrap().header.corr, 999);
    assert_one_cancel(&mut rx, request.header.corr).await;
}

#[tokio::test]
async fn operator_confirm_plain_thread_drop_uses_connection_runtime() {
    let (handle, mut rx) = handle();
    let owned_handle = handle.clone();
    let mut call = Box::pin(async move {
        owned_handle
            .confirm_operator("Replace identity", &owned_handle.route_handle(7, 3))
            .await
    });
    still_pending(call.as_mut()).await;
    let request = rx.recv().await.unwrap();
    fill_egress(&handle);
    std::thread::spawn(move || drop(call))
        .join()
        .expect("drop panicked on a plain thread");
    assert_eq!(pending_count(&handle), 0);
    assert_eq!(rx.recv().await.unwrap().header.corr, 999);
    assert_one_cancel(&mut rx, request.header.corr).await;
}

#[test]
fn operator_confirm_second_runtime_shutdown_uses_connection_runtime() {
    let connection_runtime = tokio::runtime::Runtime::new().unwrap();
    let (handle, mut rx) = handle_on(connection_runtime.handle().clone(), &[OPERATOR_CONFIRM_OP]);
    let polling_runtime = tokio::runtime::Runtime::new().unwrap();
    let owned_handle = handle.clone();
    polling_runtime.spawn(async move {
        owned_handle
            .confirm_operator("Replace identity", &owned_handle.route_handle(7, 3))
            .await
    });
    let request = connection_runtime.block_on(async {
        timeout(Duration::from_secs(2), rx.recv())
            .await
            .unwrap()
            .unwrap()
    });
    fill_egress(&handle);
    drop(polling_runtime);
    assert_eq!(pending_count(&handle), 0);
    connection_runtime.block_on(async {
        assert_eq!(rx.recv().await.unwrap().header.corr, 999);
        assert_one_cancel(&mut rx, request.header.corr).await;
    });
}

#[tokio::test]
async fn operator_confirm_late_reply_cannot_resolve_another_call() {
    let (handle, mut rx) = handle();
    let route = handle.route_handle(7, 3);
    let mut first = Box::pin(handle.confirm_operator("First write", &route));
    still_pending(first.as_mut()).await;
    let first_corr = rx.recv().await.unwrap().header.corr;
    drop(first);
    assert_one_cancel(&mut rx, first_corr).await;
    let mut second = Box::pin(handle.confirm_operator("Second write", &route));
    still_pending(second.as_mut()).await;
    let second_corr = rx.recv().await.unwrap().header.corr;
    assert_ne!(second_corr, first_corr);
    assert!(!handle.handle_control_reply(confirmed(first_corr)));
    still_pending(second.as_mut()).await;
    handle.handle_control_reply(confirmed(second_corr));
    assert_eq!(second.await, Ok(()));
}

#[tokio::test]
async fn operator_confirm_close_drains_pending_table_and_wakes_waiter() {
    let (handle, mut rx) = handle();
    let route = handle.route_handle(7, 3);
    let mut call = Box::pin(handle.confirm_operator("Replace identity", &route));
    still_pending(call.as_mut()).await;
    let _ = rx.recv().await.unwrap();
    handle.close_connection();
    assert_eq!(pending_count(&handle), 0);
    assert_eq!(
        timeout(Duration::from_secs(2), &mut call).await.unwrap(),
        Err(OperatorConfirmError::PresenceUnavailable)
    );
}

#[tokio::test]
async fn operator_confirm_corr_exhaustion_drains_both_tables_from_either_allocator() {
    for catalog_exhausts in [true, false] {
        let (handle, mut rx) = handle();
        let (_, _, catalog_rx) = handle.shared.begin_catalog_update().unwrap();
        let route = handle.route_handle(7, 3);
        let mut call = Box::pin(handle.confirm_operator("Replace identity", &route));
        still_pending(call.as_mut()).await;
        let _ = rx.recv().await.unwrap();
        handle.shared.lock_inner().next_corr = None;
        if catalog_exhausts {
            assert!(matches!(
                handle.shared.begin_catalog_update(),
                Err(CatalogUpdateError::ConnectionClosed)
            ));
        } else {
            assert!(matches!(
                handle.shared.begin_operator_confirm(),
                Err(OperatorConfirmError::PresenceUnavailable)
            ));
        }
        assert!(handle.is_closed());
        assert_eq!(pending_count(&handle), 0);
        assert!(handle
            .shared
            .lock_inner()
            .pending_catalog_updates
            .is_empty());
        assert_eq!(
            timeout(Duration::from_secs(2), &mut call).await.unwrap(),
            Err(OperatorConfirmError::PresenceUnavailable)
        );
        assert!(matches!(
            catalog_rx.await.unwrap(),
            Err(CatalogUpdateError::ConnectionClosed)
        ));
    }
}

#[tokio::test]
async fn operator_confirm_closed_writer_fails_without_leaking_pending_entry() {
    let (handle, rx) = handle();
    drop(rx);
    assert_eq!(
        handle
            .confirm_operator("Replace identity", &handle.route_handle(7, 3))
            .await,
        Err(OperatorConfirmError::PresenceUnavailable)
    );
    assert_eq!(pending_count(&handle), 0);
}

#[tokio::test]
async fn operator_confirm_request_bytes_carry_neither_kind_nor_operation() {
    let mut served =
        super::stand_in::serve_against_stand_in_with_ops(|_| Echo, &[OPERATOR_CONFIRM_OP]).await;
    let route = served.handle.route_handle(7, 3);
    let mut call = Box::pin(served.handle.confirm_operator("Replace identity", &route));
    still_pending(call.as_mut()).await;
    let request = timeout(Duration::from_secs(2), read_frame(&mut served.daemon))
        .await
        .unwrap()
        .unwrap()
        .unwrap();
    let body: serde_json::Value =
        serde_json::from_slice(&request.body).expect("confirm_operator body is JSON");
    assert_eq!(
        body,
        serde_json::json!({"op": "operator.confirm", "summary": "Replace identity",
            "route_channel": 7, "route_epoch": 3})
    );
    assert!(body.get("kind").is_none(), "legacy request must omit kind");
    assert!(
        body.get("operation").is_none(),
        "legacy request must omit operation"
    );
    write_frame(&mut served.daemon, &confirmed(request.header.corr))
        .await
        .unwrap();
    served.daemon.flush().await.unwrap();
    assert_eq!(
        timeout(Duration::from_secs(2), &mut call).await.unwrap(),
        Ok(())
    );
    drop(call);
    served.handle.close_connection();
    timeout(Duration::from_secs(3), served.serve)
        .await
        .unwrap()
        .unwrap()
        .unwrap();
}

#[tokio::test]
async fn confirm_operation_sends_kind_operation_plus_name() {
    let mut served =
        super::stand_in::serve_against_stand_in_with_ops(|_| Echo, &[OPERATOR_CONFIRM_OP]).await;
    let route = served.handle.route_handle(7, 3);
    let mut call = Box::pin(served.handle.confirm_operation(
        "Replace identity",
        &route,
        "pair.device",
    ));
    still_pending(call.as_mut()).await;
    let request = timeout(Duration::from_secs(2), read_frame(&mut served.daemon))
        .await
        .unwrap()
        .unwrap()
        .unwrap();
    assert_eq!(
        serde_json::from_slice::<serde_json::Value>(&request.body).unwrap(),
        serde_json::json!({"op": "operator.confirm", "summary": "Replace identity",
            "route_channel": 7, "route_epoch": 3,
            "kind": "operation", "operation": "pair.device"})
    );
    write_frame(&mut served.daemon, &confirmed(request.header.corr))
        .await
        .unwrap();
    served.daemon.flush().await.unwrap();
    assert_eq!(
        timeout(Duration::from_secs(2), &mut call).await.unwrap(),
        Ok(())
    );
    assert_eq!(pending_count(&served.handle), 0);
    drop(call);
    served.handle.close_connection();
    timeout(Duration::from_secs(3), served.serve)
        .await
        .unwrap()
        .unwrap()
        .unwrap();
}

#[tokio::test]
async fn confirm_operation_sends_unusual_names_as_is() {
    let (handle, mut rx) = handle();
    let route = handle.route_handle(7, 3);
    let mut call = Box::pin(handle.confirm_operation("Replace identity", &route, "has space"));
    still_pending(call.as_mut()).await;
    let request = rx.recv().await.expect("operation request must send");
    assert_eq!(
        serde_json::from_slice::<serde_json::Value>(&request.body).unwrap(),
        serde_json::json!({"op": "operator.confirm", "summary": "Replace identity",
            "route_channel": 7, "route_epoch": 3,
            "kind": "operation", "operation": "has space"})
    );
    assert!(handle.handle_control_reply(confirmed(request.header.corr)));
    assert_eq!(call.await, Ok(()));
    assert_eq!(pending_count(&handle), 0);
}

#[tokio::test]
async fn confirm_enrollment_sends_kind_enrollment_without_an_operation() {
    let (handle, mut rx) = handle();
    let route = handle.route_handle(7, 3);
    let mut call = Box::pin(handle.confirm_enrollment("Pair with Office Mac", &route));
    still_pending(call.as_mut()).await;
    let request = rx.recv().await.expect("enrollment request must send");
    assert_eq!(
        serde_json::from_slice::<serde_json::Value>(&request.body).unwrap(),
        serde_json::json!({"op": "operator.confirm", "summary": "Pair with Office Mac",
            "route_channel": 7, "route_epoch": 3, "kind": "enrollment"})
    );
    assert!(handle.handle_control_reply(confirmed(request.header.corr)));
    assert_eq!(call.await, Ok(()));
    assert_eq!(pending_count(&handle), 0);
}

#[tokio::test]
async fn confirm_operation_empty_name_is_refused_without_sending() {
    let (handle, mut rx) = handle();
    assert_eq!(
        handle
            .confirm_operation("Replace identity", &handle.route_handle(7, 3), "")
            .await,
        Err(OperatorConfirmError::OperationInvalid)
    );
    assert_eq!(pending_count(&handle), 0);
    assert!(rx.try_recv().is_err(), "invalid operation must not send");
    assert_eq!(
        OperatorConfirmError::OperationInvalid.to_string(),
        "operator confirmation operation is invalid"
    );
}