subc-client-rs 0.38.2

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
use super::*;
use crate::control_flags;
use cortexkit_test_support::ScratchDir;
use subc_transport::connection_file::{ConnectionInfo, Endpoint, LocalEndpoint, SCHEMA_VERSION};
use subc_transport::{authenticate_server, write_atomic_with_local_endpoint};
use tokio::net::TcpListener;
use tokio::time::timeout;

const BUDGET: Duration = Duration::from_secs(3);

fn socket_dir() -> ScratchDir {
    // Short labels leave room for the runner's prefix within macOS's socket path limit.
    ScratchDir::new("lt")
}

fn info(tcp: &TcpListener) -> ConnectionInfo {
    ConnectionInfo {
        schema: SCHEMA_VERSION,
        wire_version: None,
        endpoints: vec![Endpoint {
            host: "127.0.0.1".into(),
            port: tcp.local_addr().unwrap().port(),
        }],
        key: vec![0x42; 32],
        daemon_id: [0x21; 16],
        pid: std::process::id(),
        daemon_ver: "0.39.0".into(),
    }
}

#[cfg(unix)]
type LocalListener = tokio::net::UnixListener;
#[cfg(windows)]
type LocalListener = tokio::net::windows::named_pipe::NamedPipeServer;

#[cfg(unix)]
fn listen(dir: &Path, name: &str) -> (LocalEndpoint, LocalListener) {
    let path = dir.join(name);
    let listener = LocalListener::bind(&path).unwrap();
    (LocalEndpoint::Unix { path }, listener)
}

#[cfg(windows)]
fn listen(_dir: &Path, name: &str) -> (LocalEndpoint, LocalListener) {
    use std::sync::atomic::{AtomicUsize, Ordering};
    static NEXT: AtomicUsize = AtomicUsize::new(0);
    let name = format!(
        r"\\.\pipe\subc-sdk-{}-{}-{name}",
        std::process::id(),
        NEXT.fetch_add(1, Ordering::Relaxed)
    );
    let listener = tokio::net::windows::named_pipe::ServerOptions::new()
        .first_pipe_instance(true)
        .create(&name)
        .unwrap();
    (LocalEndpoint::Pipe { name }, listener)
}

async fn accept(listener: LocalListener) -> Box<dyn ConsumerStream> {
    #[cfg(unix)]
    {
        Box::new(listener.accept().await.unwrap().0)
    }
    #[cfg(windows)]
    {
        listener.connect().await.unwrap();
        Box::new(listener)
    }
}

async fn server(mut stream: Box<dyn ConsumerStream>, info: ConnectionInfo) {
    authenticate_server(
        &mut stream,
        &info.key,
        &info.daemon_id,
        &info.daemon_ver,
        BUDGET,
    )
    .await
    .unwrap();
    let request = read_frame(&mut stream).await.unwrap().unwrap();
    assert_eq!(request.header.channel, 0);
    assert_eq!(request.body, br#"{"op":"catalog.list"}"#);
    let reply = Frame::build(
        FrameType::Response,
        control_flags(),
        0,
        0,
        request.header.corr,
        br#"{"op":"catalog.list","generation":1,"modules":[],"subc_ops":[]}"#.to_vec(),
    )
    .unwrap();
    write_frame(&mut stream, &reply).await.unwrap();
    stream.flush().await.unwrap();
}

fn spawn_local(listener: LocalListener, info: ConnectionInfo) -> JoinHandle<()> {
    tokio::spawn(async move { server(accept(listener).await, info).await })
}

async fn assert_no_tcp(tcp: &TcpListener) {
    assert!(
        timeout(Duration::from_millis(20), tcp.accept())
            .await
            .is_err(),
        "local mode attempted TCP"
    );
}

fn local_opts() -> ConsumerOptions {
    ConsumerOptions {
        reconnect_backoff: RetryBackoff {
            max_attempts: 2,
            base: Duration::from_millis(1),
            ..RetryBackoff::default()
        },
        ..ConsumerOptions::default()
    }
}

fn identity_query() -> ActivityQueryRequest {
    serde_json::from_value(serde_json::json!({"op": "activity.query", "limit": 1})).unwrap()
}

async fn run_identity_round(
    client: &SubcConsumer,
    target: &RouteTarget,
    identity: &BindIdentity,
    explicit: &ConsumerIdentity,
) {
    for consumer_identity in [None, Some(explicit.clone())] {
        let handle = client
            .open_route(
                target.clone(),
                identity.clone(),
                CallOptions {
                    consumer_identity: consumer_identity.clone(),
                    timeout: BUDGET,
                    ..CallOptions::default()
                },
            )
            .await
            .unwrap();
        client
            .close_route(
                target.clone(),
                identity.clone(),
                CloseRouteOptions {
                    consumer_identity,
                    ..CloseRouteOptions::default()
                },
            )
            .await;
        assert!(
            client.shared.route_state(handle).is_err(),
            "close must find the same identity-keyed route"
        );
    }
    let error = client.query_activity(identity_query()).await.unwrap_err();
    assert_eq!(error.code(), Some("test_complete"));
    let mut subscription = client.subscribe_activity(None).await.unwrap();
    assert!(subscription.next().await.is_err());
}

fn spawn_identity_server(
    listener: LocalListener,
    info: ConnectionInfo,
    identities: Vec<Option<ConsumerIdentity>>,
    activity_identity: Option<ConsumerIdentity>,
) -> JoinHandle<()> {
    tokio::spawn(async move {
        identity_server(accept(listener).await, info, identities, activity_identity).await
    })
}

fn spawn_tcp_identity_server(
    tcp: TcpListener,
    info: ConnectionInfo,
    identities: Vec<Option<ConsumerIdentity>>,
    activity_identity: Option<ConsumerIdentity>,
) -> JoinHandle<()> {
    tokio::spawn(async move {
        let stream: Box<dyn ConsumerStream> = Box::new(tcp.accept().await.unwrap().0);
        identity_server(stream, info, identities, activity_identity).await
    })
}

async fn identity_server(
    mut stream: Box<dyn ConsumerStream>,
    info: ConnectionInfo,
    identities: Vec<Option<ConsumerIdentity>>,
    activity_identity: Option<ConsumerIdentity>,
) {
    {
        authenticate_server(
            &mut stream,
            &info.key,
            &info.daemon_id,
            &info.daemon_ver,
            BUDGET,
        )
        .await
        .unwrap();
        for (index, identity) in identities.into_iter().enumerate() {
            let request = read_frame(&mut stream).await.unwrap().unwrap();
            let body: serde_json::Value = serde_json::from_slice(&request.body).unwrap();
            assert_eq!(body["op"], "route.open");
            assert_eq!(
                body.get("consumer_identity"),
                identity
                    .as_ref()
                    .map(serde_json::to_value)
                    .transpose()
                    .unwrap()
                    .as_ref()
            );
            let channel = 7 + index as u16;
            let reply = Frame::build(
                FrameType::Response,
                control_flags(),
                0,
                0,
                request.header.corr,
                serde_json::to_vec(&ClientControlResponse::RouteOpen {
                    request_window: None,
                    watch_window: None,
                    route_channel: channel,
                    route_epoch: 1,
                })
                .unwrap(),
            )
            .unwrap();
            write_frame(&mut stream, &reply).await.unwrap();
            stream.flush().await.unwrap();
            // Closing is a one-way GOODBYE, not a JSON identity-bearing request.
            // Seeing it proves close_route used the same identity-keyed route.
            let goodbye = read_frame(&mut stream).await.unwrap().unwrap();
            assert_eq!(goodbye.header.ty, FrameType::Goodbye);
            assert_eq!(goodbye.header.channel, channel);
            assert!(goodbye.body.is_empty());
        }
        for op in ["activity.query", "activity.subscribe"] {
            let request = read_frame(&mut stream).await.unwrap().unwrap();
            let body: serde_json::Value = serde_json::from_slice(&request.body).unwrap();
            assert_eq!(body["op"], op);
            assert_eq!(
                body.get("consumer_identity"),
                activity_identity
                    .as_ref()
                    .map(serde_json::to_value)
                    .transpose()
                    .unwrap()
                    .as_ref()
            );
            let reply = Frame::build(
                FrameType::Error,
                control_flags(),
                0,
                0,
                request.header.corr,
                serde_json::to_vec(&ErrorBody::new("test_complete", "identity captured")).unwrap(),
            )
            .unwrap();
            write_frame(&mut stream, &reply).await.unwrap();
            stream.flush().await.unwrap();
        }
    }
}

#[tokio::test]
async fn operator_app_omits_environment_identity_and_honours_explicit() {
    const CHILD: &str = "SUBC_OPERATOR_IDENTITY_CHILD";
    let inherited = ConsumerIdentity {
        module_id: "untrusted-launcher".into(),
        launch_nonce: "untrusted-environment-nonce".into(),
    };
    if std::env::var_os(CHILD).is_none() {
        let output = std::process::Command::new(std::env::current_exe().unwrap())
            .args([
                "--exact",
                "consumer::local_transport_tests::operator_app_omits_environment_identity_and_honours_explicit",
                "--nocapture",
            ])
            .env(CHILD, "1")
            .env("SUBC_MODULE_ID", &inherited.module_id)
            .env("SUBC_LAUNCH_NONCE", &inherited.launch_nonce)
            .env_remove("SUBC_LAUNCH_NONCE_FD")
            .env_remove("SUBC_LAUNCH_NONCE_HANDLE")
            .output()
            .unwrap();
        assert!(output.status.success(), "{output:?}");
        assert!(String::from_utf8_lossy(&output.stdout).contains("1 passed"));
        return;
    }

    timeout(Duration::from_secs(20), async {
        let dir = socket_dir();
        let tcp = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let info = info(&tcp);
        let file = dir.join("connection.json");
        let explicit = ConsumerIdentity {
            module_id: "explicit-caller".into(),
            launch_nonce: "explicit-nonce".into(),
        };
        let target = RouteTarget::ToolProvider {
            module_id: "provider".into(),
        };
        let identity = BindIdentity::new("test", "operator");

        let (endpoint, listener) = listen(&dir, "operator");
        write_atomic_with_local_endpoint(&file, &info, Some(&endpoint)).unwrap();
        let task = spawn_identity_server(
            listener,
            info.clone(),
            vec![None, Some(explicit.clone())],
            None,
        );
        // Inject only the candidate paths so the real constructor's policy and
        // local connection setup run without touching the installed daemon.
        let client = SubcConsumer::connect_operator_app_resolving(
            local_opts(),
            ConsumerTransport::Local,
            || Ok(vec![file.clone()]),
        )
        .await
        .unwrap();

        run_identity_round(&client, &target, &identity, &explicit).await;
        timeout(BUDGET, task).await.unwrap().unwrap();
        let (endpoint, listener) = listen(&dir, "reconnected");
        write_atomic_with_local_endpoint(&file, &info, Some(&endpoint)).unwrap();
        let next = spawn_identity_server(
            listener,
            info.clone(),
            vec![None, Some(explicit.clone())],
            None,
        );
        // The next call must reconnect using the new file endpoint,
        // retaining the operator-app identity policy.
        run_identity_round(&client, &target, &identity, &explicit).await;
        timeout(BUDGET, next).await.unwrap().unwrap();
        client.close().await;

        // Legacy constructors still use the identity supplied through the launch environment.
        let (endpoint, listener) = listen(&dir, "legacy");
        write_atomic_with_local_endpoint(&file, &info, Some(&endpoint)).unwrap();
        let task = spawn_identity_server(
            listener,
            info,
            vec![Some(inherited.clone())],
            Some(inherited),
        );
        let legacy = SubcConsumer::connect_local(&file, local_opts())
            .await
            .unwrap();
        legacy
            .open_route(target.clone(), identity.clone(), CallOptions::default())
            .await
            .unwrap();
        legacy
            .close_route(target, identity, CloseRouteOptions::default())
            .await;
        assert_eq!(
            legacy
                .query_activity(identity_query())
                .await
                .unwrap_err()
                .code(),
            Some("test_complete")
        );
        let mut subscription = legacy.subscribe_activity(None).await.unwrap();
        assert!(subscription.next().await.is_err());
        timeout(BUDGET, task).await.unwrap().unwrap();
        legacy.close().await;
        assert_no_tcp(&tcp).await;
    })
    .await
    .expect("identity exercise must finish");
}

#[tokio::test]
async fn operator_app_plain_dials_tcp_and_omits_environment_identity() {
    const CHILD: &str = "SUBC_OPERATOR_PLAIN_CHILD";
    if std::env::var_os(CHILD).is_none() {
        // Run in a child with a module ID and launch nonce in its environment,
        // so the test catches their use as implicit route or activity identity.
        let output = std::process::Command::new(std::env::current_exe().unwrap())
            .args([
                "--exact",
                "consumer::local_transport_tests::operator_app_plain_dials_tcp_and_omits_environment_identity",
                "--nocapture",
            ])
            .env(CHILD, "1")
            .env("SUBC_MODULE_ID", "untrusted-launcher")
            .env("SUBC_LAUNCH_NONCE", "untrusted-environment-nonce")
            .env_remove("SUBC_LAUNCH_NONCE_FD")
            .env_remove("SUBC_LAUNCH_NONCE_HANDLE")
            .output()
            .unwrap();
        assert!(output.status.success(), "{output:?}");
        assert!(String::from_utf8_lossy(&output.stdout).contains("1 passed"));
        return;
    }

    timeout(Duration::from_secs(20), async {
        let dir = socket_dir();
        let file = dir.join("connection.json");
        let explicit = ConsumerIdentity {
            module_id: "explicit-caller".into(),
            launch_nonce: "explicit-nonce".into(),
        };
        let target = RouteTarget::ToolProvider {
            module_id: "provider".into(),
        };
        let identity = BindIdentity::new("test", "operator");

        // The file also names a local endpoint; the plain connection must not use it.
        let tcp = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let first = info(&tcp);
        let (endpoint, local) = listen(&dir, "plain");
        write_atomic_with_local_endpoint(&file, &first, Some(&endpoint)).unwrap();
        let task = spawn_tcp_identity_server(tcp, first, vec![None, Some(explicit.clone())], None);
        let client = SubcConsumer::connect_operator_app_resolving(
            local_opts(),
            ConsumerTransport::Tcp,
            || Ok(vec![file.clone()]),
        )
        .await
        .unwrap();
        run_identity_round(&client, &target, &identity, &explicit).await;
        timeout(BUDGET, task).await.unwrap().unwrap();

        // Simulate a daemon restart by replacing the TCP listener and rewriting
        // the connection file. The next round must reconnect over TCP and keep
        // the identity policy.
        let tcp = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let restarted = info(&tcp);
        write_atomic_with_local_endpoint(&file, &restarted, Some(&endpoint)).unwrap();
        let next =
            spawn_tcp_identity_server(tcp, restarted, vec![None, Some(explicit.clone())], None);
        run_identity_round(&client, &target, &identity, &explicit).await;
        timeout(BUDGET, next).await.unwrap().unwrap();
        client.close().await;
        assert!(
            timeout(Duration::from_millis(20), accept(local))
                .await
                .is_err(),
            "the plain connection dialed the local endpoint"
        );
    })
    .await
    .expect("plain-connection exercise must finish");
}

#[tokio::test]
async fn default_transport_is_tcp_with_unchanged_frames() {
    let dir = socket_dir();
    let tcp = TcpListener::bind("127.0.0.1:0").await.unwrap();
    let info = info(&tcp);
    let (endpoint, local) = listen(&dir, "local");
    let file = dir.join("connection.json");
    write_atomic_with_local_endpoint(&file, &info, Some(&endpoint)).unwrap();
    let task =
        tokio::spawn(async move { server(Box::new(tcp.accept().await.unwrap().0), info).await });
    let client = SubcConsumer::connect(&file, ConsumerOptions::default())
        .await
        .unwrap();
    assert!(client.catalog_list().await.unwrap().modules.is_empty());
    client.close().await;
    timeout(BUDGET, task).await.unwrap().unwrap();
    assert!(
        timeout(Duration::from_millis(20), accept(local))
            .await
            .is_err(),
        "default dialed local endpoint"
    );
}

#[cfg(unix)]
#[tokio::test]
async fn operator_app_connects_with_only_home_rung() {
    let dir = socket_dir();
    let candidates =
        crate::operator_app::macos_candidates(&dir.join("home"), &dir.join("temp"), "501");
    let home = dir.join("home/.local/share/cortexkit/run/subc-connection.json");
    let temp = dir.join("temp/subc-501.connection.json");
    let tcp = TcpListener::bind("127.0.0.1:0").await.unwrap();
    let info = info(&tcp);
    let (endpoint, listener) = listen(&dir, "h.sock");
    write_atomic_with_local_endpoint(&home, &info, Some(&endpoint)).unwrap();
    assert!(!temp.exists());
    let task = spawn_local(listener, info.clone());
    let client = SubcConsumer::connect_operator_app_resolving(
        local_opts(),
        ConsumerTransport::Local,
        || Ok(candidates.clone()),
    )
    .await
    .unwrap();
    assert!(client.catalog_list().await.unwrap().modules.is_empty());
    timeout(BUDGET, task).await.unwrap().unwrap();

    // A restart can move between the production home and temporary rungs.
    // Reconnect must choose again instead of pinning the initial home file.
    std::fs::remove_file(&home).unwrap();
    let (endpoint, listener) = listen(&dir, "t.sock");
    write_atomic_with_local_endpoint(&temp, &info, Some(&endpoint)).unwrap();
    let task = spawn_local(listener, info);
    assert!(client.catalog_list().await.unwrap().modules.is_empty());
    timeout(BUDGET, task).await.unwrap().unwrap();
    client.close().await;
    assert_no_tcp(&tcp).await;
}

#[cfg(unix)]
#[tokio::test]
async fn operator_app_does_not_fall_through_owner_checked_home_file() {
    for malformed in [true, false] {
        let dir = socket_dir();
        let candidates =
            crate::operator_app::macos_candidates(&dir.join("home"), &dir.join("temp"), "501");
        let tcp = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let info = info(&tcp);
        let (endpoint, listener) = listen(&dir, "not-selected");
        write_atomic_with_local_endpoint(&candidates[1], &info, Some(&endpoint)).unwrap();
        write_atomic_with_local_endpoint(&candidates[0], &info, None).unwrap();
        if malformed {
            std::fs::write(&candidates[0], b"not json").unwrap();
        }
        let error = SubcConsumer::connect_operator_app_resolving(
            local_opts(),
            ConsumerTransport::Local,
            || Ok(candidates.clone()),
        )
        .await
        .err()
        .unwrap();
        if malformed {
            assert!(
                matches!(error, ConsumerError::ConnectionFile { path, source: ConnectionFileError::JsonRead { .. } } if path == candidates[0])
            );
        } else {
            assert!(matches!(error, ConsumerError::NoEndpoint { path } if path == candidates[0]));
        }
        assert!(
            timeout(Duration::from_millis(20), accept(listener))
                .await
                .is_err(),
            "fell through to the temporary rung"
        );
        assert_no_tcp(&tcp).await;
    }
}

#[tokio::test]
async fn local_transport_handshake_frames_and_reconnect_use_current_endpoint() {
    let dir = socket_dir();
    let tcp = TcpListener::bind("127.0.0.1:0").await.unwrap();
    let info = info(&tcp);
    let file = dir.join("connection.json");
    let (first, listener) = listen(&dir, "first");
    write_atomic_with_local_endpoint(&file, &info, Some(&first)).unwrap();
    let task = spawn_local(listener, info.clone());
    let client = SubcConsumer::connect_local(&file, local_opts())
        .await
        .unwrap();
    assert!(client.catalog_list().await.unwrap().modules.is_empty());
    timeout(BUDGET, task).await.unwrap().unwrap();

    let (next, listener) = listen(&dir, "next");
    write_atomic_with_local_endpoint(&file, &info, Some(&next)).unwrap();
    let task = spawn_local(listener, info);
    assert!(client.catalog_list().await.unwrap().modules.is_empty());
    client.close().await;
    timeout(BUDGET, task).await.unwrap().unwrap();
    assert_no_tcp(&tcp).await;
}

#[tokio::test]
async fn local_transport_each_reconnect_attempt_rereads_file() {
    let dir = socket_dir();
    let tcp = TcpListener::bind("127.0.0.1:0").await.unwrap();
    let info = info(&tcp);
    let file = dir.join("connection.json");
    let (stale, stale_listener) = listen(&dir, "stale");
    let (current, current_listener) = listen(&dir, "current");
    write_atomic_with_local_endpoint(&file, &info, Some(&stale)).unwrap();
    let task = spawn_local(current_listener, info.clone());
    let rotate_file = file.clone();
    let stale_task = tokio::spawn(async move {
        let mut stream = accept(stale_listener).await;
        // Rotate the endpoint after the first attempt reads the old file but
        // before authentication fails, as during a daemon restart race.
        write_atomic_with_local_endpoint(&rotate_file, &info, Some(&current)).unwrap();
        assert!(authenticate_server(
            &mut stream,
            &[0x99; 32],
            &info.daemon_id,
            &info.daemon_ver,
            BUDGET
        )
        .await
        .is_err());
    });
    let shared = Arc::new(Shared::with_transport(
        file,
        local_opts(),
        ConsumerTransport::Local,
    ));
    shared.lock_inner().reconnect = ReconnectState::Inline { generation: 1 };
    shared.reconnect_with_retry(1).await.unwrap();
    shared.lock_inner().reconnect = ReconnectState::Idle;
    let client = SubcConsumer { shared };
    assert!(client.catalog_list().await.unwrap().modules.is_empty());
    client.close().await;
    timeout(BUDGET, task).await.unwrap().unwrap();
    timeout(BUDGET, stale_task).await.unwrap().unwrap();
    assert_no_tcp(&tcp).await;
}

#[tokio::test]
async fn local_transport_absence_and_connect_error_survive_initial_and_reconnect() {
    for absent in [true, false] {
        let dir = socket_dir();
        let tcp = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let info = info(&tcp);
        let file = dir.join("connection.json");
        let (endpoint, listener) = listen(&dir, "unreachable");
        drop(listener);
        let endpoint = (!absent).then_some(endpoint);
        write_atomic_with_local_endpoint(&file, &info, endpoint.as_ref()).unwrap();
        let absent_message = format!(
            "subc connection file '{}' has no endpoint for the requested transport",
            file.display()
        );
        let check_error = |error: ConsumerError| {
            if absent {
                assert_eq!(error.to_string(), absent_message);
                assert!(matches!(error, ConsumerError::NoEndpoint { .. }));
            } else {
                match error {
                    ConsumerError::Connect {
                        endpoint: label,
                        source,
                        ..
                    } => {
                        assert!(label.contains("unreachable"));
                        assert!(matches!(
                            source.kind(),
                            io::ErrorKind::NotFound | io::ErrorKind::ConnectionRefused
                        ));
                    }
                    error => panic!("lost local connect error: {error}"),
                }
            }
        };
        check_error(
            SubcConsumer::connect_local(&file, local_opts())
                .await
                .err()
                .unwrap(),
        );

        let (working, listener) = listen(&dir, "working");
        write_atomic_with_local_endpoint(&file, &info, Some(&working)).unwrap();
        let task = spawn_local(listener, info.clone());
        let client = SubcConsumer::connect_local(&file, local_opts())
            .await
            .unwrap();
        client.catalog_list().await.unwrap();
        client.close().await;
        timeout(BUDGET, task).await.unwrap().unwrap();
        write_atomic_with_local_endpoint(&file, &info, endpoint.as_ref()).unwrap();
        let shared = Arc::new(Shared::with_transport(
            file,
            local_opts(),
            ConsumerTransport::Local,
        ));
        shared.lock_inner().reconnect = ReconnectState::Inline { generation: 1 };
        check_error(shared.reconnect_with_retry(1).await.err().unwrap());
        shared.close_sync("test finished");
        assert_no_tcp(&tcp).await;
    }
}