cf-gears-toolkit 0.15.0

Core ToolKit library
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
use std::sync::Arc;
use std::time::Duration;

use parking_lot::Mutex;
use serde_json::json;
use tokio::sync::Notify;
use toolkit_contract::runtime::config::{CredentialState, InternalTokenProvider};
use toolkit_contract::wiring::ClientTuning;

use super::{GtsDeploymentOutcome, GtsDeploymentReport, publish};
use crate::client_hub::ClientHub;
use crate::config::ConfigProvider;
use crate::discovery::{EndpointResolver, WireOutcome};
use crate::gts_publication::{
    DeclarationSource, GtsPublicationBackend, GtsPublicationDescriptor, GtsPublicationExpired,
    GtsPublicationRequest,
};

const ENDPOINT: &str = "https://registry.example:8443";
const BASE: &str = "gts.cf.test.publication.base.v1~";
const DERIVED: &str = "gts.cf.test.publication.base.v1~cf.test.publication.derived.v1~";

/// The remote registry the wire fn binds: it records the endpoint and the
/// credential it got, and admits `DERIVED` only once `BASE` is admitted.
#[derive(Default)]
struct RemoteRegistry {
    deadlines: Mutex<Vec<Option<tokio::time::Instant>>>,
    endpoint: Mutex<Option<String>>,
    token: Mutex<Option<String>>,
    tunings: Mutex<Vec<ClientTuning>>,
    admitted: Mutex<Vec<String>>,
    base_admitted: Notify,
}

static REGISTRY: std::sync::LazyLock<Mutex<Option<Arc<RemoteRegistry>>>> =
    std::sync::LazyLock::new(|| Mutex::new(None));

#[allow(
    clippy::unnecessary_wraps,
    clippy::needless_pass_by_value,
    reason = "must match the WireFn signature the gear macro emits"
)]
fn wire(
    hub: &ClientHub,
    resolver: Arc<dyn EndpointResolver>,
    tuning: ClientTuning,
) -> anyhow::Result<WireOutcome> {
    if hub.try_get_local::<RemoteRegistry>().is_some() {
        return Ok(WireOutcome::Local);
    }
    if hub.has_remote_proxy::<RemoteRegistry>() {
        return Ok(WireOutcome::Remote);
    }
    let registry = REGISTRY
        .lock()
        .clone()
        .ok_or_else(|| anyhow::anyhow!("no test registry"))?;
    registry.tunings.lock().push(tuning.clone());
    if let Some(provider) = &tuning.internal_token_provider
        && let CredentialState::Available(token) = provider.current()
    {
        use secrecy::ExposeSecret as _;
        *registry.token.lock() = Some(token.expose_secret().to_owned());
    }
    let endpoint = futures_util::FutureExt::now_or_never(resolver.resolve_endpoint("registry"))
        .and_then(Result::ok)
        .flatten();
    *registry.endpoint.lock() = endpoint;
    hub.register_remote_proxy::<RemoteRegistry>(registry);
    Ok(WireOutcome::Remote)
}

fn backend(hub: &ClientHub) -> anyhow::Result<GtsPublicationBackend> {
    let registry = hub.get::<RemoteRegistry>()?;
    Ok(GtsPublicationBackend::new(
        move |request: GtsPublicationRequest| {
            let registry = Arc::clone(&registry);
            async move {
                registry.deadlines.lock().push(request.deadline());
                for (id, document) in request.gts_manifest().documents() {
                    if document.get("refuse").is_some() {
                        anyhow::bail!("{id}: rejected");
                    }
                    if document.get("opaque_expire").is_some() {
                        // An adapter whose expiry carries no identifier.
                        return Err(anyhow::Error::new(GtsPublicationExpired));
                    }
                    if document.get("expire").is_some() {
                        // The gear's own budget, shorter than the job's deadline.
                        return Err(anyhow::anyhow!("{id}: deadline reached")
                            .context(GtsPublicationExpired));
                    }
                    if let Some(cause) = document.get("pending").and_then(serde_json::Value::as_str)
                    {
                        let detail = format!("{id}: {cause}");
                        request.report_pending(&detail);
                        if document.get("end").is_some() {
                            return Err(anyhow::anyhow!(detail).context(GtsPublicationExpired));
                        }
                        std::future::pending::<()>().await;
                    }
                    if id.id() == DERIVED {
                        loop {
                            let base_admitted = registry.base_admitted.notified();
                            if registry.admitted.lock().iter().any(|a| a == BASE) {
                                break;
                            }
                            base_admitted.await;
                        }
                    }
                    if document.get("hang").is_some() {
                        std::future::pending::<()>().await;
                    }
                    registry.admitted.lock().push(id.to_string());
                    if id.id() == BASE {
                        registry.base_admitted.notify_waiters();
                    }
                }
                Ok(())
            }
        },
    ))
}

fn derived() -> Vec<DeclarationSource> {
    vec![DeclarationSource::new(
        "t",
        vec![(DERIVED.to_owned(), "{}".to_owned())],
    )]
}

fn base() -> Vec<DeclarationSource> {
    vec![DeclarationSource::new(
        "t",
        vec![(BASE.to_owned(), "{}".to_owned())],
    )]
}

fn refused() -> Vec<DeclarationSource> {
    vec![DeclarationSource::new(
        "t",
        vec![(
            "gts.cf.test.publication.refused.v1~".to_owned(),
            json!({"refuse": true}).to_string(),
        )],
    )]
}

fn expiring() -> Vec<DeclarationSource> {
    vec![DeclarationSource::new(
        "t",
        vec![(
            "gts.cf.test.publication.expiring.v1~".to_owned(),
            json!({"expire": true}).to_string(),
        )],
    )]
}

const OPAQUE: &str = "gts.cf.test.publication.opaque.v1~";
const OPAQUE_PEER: &str = "gts.cf.test.publication.opaque_peer.v1~";

fn opaque_expiring() -> Vec<DeclarationSource> {
    vec![DeclarationSource::new(
        "t",
        vec![
            (
                OPAQUE.to_owned(),
                json!({"opaque_expire": true}).to_string(),
            ),
            (OPAQUE_PEER.to_owned(), "{}".to_owned()),
        ],
    )]
}

fn hanging() -> Vec<DeclarationSource> {
    vec![DeclarationSource::new(
        "t",
        vec![(
            "gts.cf.test.publication.hanging.v1~".to_owned(),
            json!({"hang": true}).to_string(),
        )],
    )]
}

macro_rules! descriptor {
    ($name:ident, $gear:literal, $docs:path) => {
        static $name: GtsPublicationDescriptor = GtsPublicationDescriptor {
            gear: $gear,
            publisher_version: "1.0.0",
            declarations: $docs,
            entities: None,
            backend,
            provider: "registry",
            wire,
        };
    };
}

descriptor!(DERIVED_PUB, "derived-publisher", derived);
descriptor!(BASE_PUB, "base-publisher", base);
descriptor!(REFUSED_PUB, "refused-publisher", refused);
descriptor!(HANGING_PUB, "hanging-publisher", hanging);
descriptor!(EXPIRING_PUB, "expiring-publisher", expiring);
descriptor!(OPAQUE_PUB, "opaque-publisher", opaque_expiring);

struct NoConfig;

impl ConfigProvider for NoConfig {
    fn get_gear_config(&self, _gear: &str) -> Option<&serde_json::Value> {
        None
    }
}

struct PublicationConfig(serde_json::Value);

impl ConfigProvider for PublicationConfig {
    fn get_gear_config(&self, gear: &str) -> Option<&serde_json::Value> {
        self.0.get(gear)
    }
}

fn partially_admitted_expiry() -> Vec<DeclarationSource> {
    vec![DeclarationSource::new(
        "t",
        vec![
            (BASE.to_owned(), "{}".to_owned()),
            (
                DERIVED.to_owned(),
                json!({"pending": "dependency_not_found", "end": true}).to_string(),
            ),
        ],
    )]
}

fn partially_admitted_pending() -> Vec<DeclarationSource> {
    vec![DeclarationSource::new(
        "t",
        vec![
            (BASE.to_owned(), "{}".to_owned()),
            (
                DERIVED.to_owned(),
                json!({"pending": "dependency_not_found"}).to_string(),
            ),
        ],
    )]
}

descriptor!(PARTIAL_EXPIRY, "partial-expiry", partially_admitted_expiry);
descriptor!(
    PARTIAL_PENDING,
    "partial-pending",
    partially_admitted_pending
);

#[tokio::test]
async fn deployment_preserves_each_publishers_consumer_wiring() {
    let _serial = SERIAL.lock().await;
    let registry = Arc::new(RemoteRegistry::default());
    *REGISTRY.lock() = Some(Arc::clone(&registry));
    let config = PublicationConfig(json!({
        "base-publisher": {"clients": {"consumes": {"registry": {
            "endpoint": "https://pod-registry.example",
            "timeout": "2s", "require_tls": true,
            "retry": {"max_attempts": 2}
        }}}},
        "derived-publisher": {"clients": {"consumes": {"registry": {
            "timeout": "7s", "require_tls": false,
            "retry": {"max_attempts": 5}
        }}}}
    }));
    let report = publish(
        &[&BASE_PUB, &DERIVED_PUB],
        &config,
        ENDPOINT,
        &tuning(),
        Duration::from_secs(10),
        &tokio_util::sync::CancellationToken::new(),
    )
    .await
    .unwrap();
    assert!(report.succeeded(), "{report}");
    let observed = registry.tunings.lock().clone();
    assert_eq!(observed.len(), 2);
    for (settings, (timeout, tls, attempts)) in observed.iter().zip([(2, true, 2), (7, false, 5)]) {
        assert_eq!(settings.timeout, Some(Duration::from_secs(timeout)));
        assert_eq!(settings.require_tls, Some(tls));
        assert_eq!(
            settings.retry.as_ref().and_then(|r| r.max_attempts),
            Some(attempts)
        );
        assert!(settings.internal_token_provider.is_some());
    }
    assert_eq!(registry.endpoint.lock().as_deref(), Some(ENDPOINT));
}

#[tokio::test]
async fn deployment_rejects_invalid_consumer_wiring_before_publication() {
    let _serial = SERIAL.lock().await;
    let registry = Arc::new(RemoteRegistry::default());
    *REGISTRY.lock() = Some(Arc::clone(&registry));
    let config = PublicationConfig(json!({
        "base-publisher": {"clients": {"consumes": {"registry": {
            "require_tls": "not-a-boolean"
        }}}}
    }));
    let result = publish(
        &[&BASE_PUB],
        &config,
        ENDPOINT,
        &tuning(),
        Duration::from_secs(10),
        &tokio_util::sync::CancellationToken::new(),
    )
    .await;
    assert!(
        result.is_err(),
        "a pod-invalid policy must fail the job: {result:?}"
    );
    assert!(registry.admitted.lock().is_empty());
}

#[tokio::test]
async fn deployment_rejects_plaintext_before_wiring_any_publishers_credential() {
    let _serial = SERIAL.lock().await;
    let registry = Arc::new(RemoteRegistry::default());
    *REGISTRY.lock() = Some(Arc::clone(&registry));
    // The second publisher requires TLS: even the first must not receive the
    // job's credential before all transport policies have been checked.
    let config = PublicationConfig(json!({
        "derived-publisher": {"clients": {"consumes": {"registry": {
            "require_tls": true
        }}}}
    }));
    let error = publish(
        &[&BASE_PUB, &DERIVED_PUB],
        &config,
        "http://registry.example:8080",
        &tuning(),
        Duration::from_secs(10),
        &tokio_util::sync::CancellationToken::new(),
    )
    .await
    .unwrap_err();
    assert!(error.to_string().contains("requires TLS"), "{error:#}");
    assert!(registry.token.lock().is_none());
    assert!(registry.tunings.lock().is_empty());
    assert!(registry.admitted.lock().is_empty());
}

#[tokio::test]
async fn gear_client_defaults_do_not_drop_the_jobs_tls_requirement() {
    let _serial = SERIAL.lock().await;
    let registry = Arc::new(RemoteRegistry::default());
    *REGISTRY.lock() = Some(Arc::clone(&registry));
    // `defaults` alone makes the gear's wiring apply; it says nothing about
    // TLS and must not clear the job's requirement.
    let config = PublicationConfig(json!({
        "base-publisher": {"clients": {"defaults": {"timeout": "2s"}}}
    }));
    let error = publish(
        &[&BASE_PUB],
        &config,
        "http://registry.example:8080",
        &tls_job(),
        Duration::from_secs(10),
        &tokio_util::sync::CancellationToken::new(),
    )
    .await
    .unwrap_err();
    assert!(error.to_string().contains("requires TLS"), "{error:#}");
    assert!(registry.token.lock().is_none());
    assert!(registry.tunings.lock().is_empty());
}

#[tokio::test]
async fn a_publishers_wiring_cannot_turn_off_the_jobs_tls_requirement() {
    let _serial = SERIAL.lock().await;
    let registry = Arc::new(RemoteRegistry::default());
    *REGISTRY.lock() = Some(Arc::clone(&registry));
    let config = PublicationConfig(json!({
        "base-publisher": {"clients": {"consumes": {"registry": {
            "timeout": "2s", "require_tls": false
        }}}}
    }));
    let report = publish(
        &[&BASE_PUB],
        &config,
        ENDPOINT,
        &tls_job(),
        Duration::from_secs(10),
        &tokio_util::sync::CancellationToken::new(),
    )
    .await
    .unwrap();
    assert!(report.succeeded(), "{report}");
    let observed = registry.tunings.lock().clone();
    assert_eq!(observed.len(), 1);
    assert_eq!(observed[0].require_tls, Some(true));
    assert_eq!(observed[0].timeout, Some(Duration::from_secs(2)));
}

fn assert_pending_diagnostic(report: &GtsDeploymentReport) {
    let message = report.to_string();
    assert!(message.contains("dependency_not_found"), "{message}");
    assert!(message.contains(DERIVED), "{message}");
    // BASE is a prefix of DERIVED; inspect a separate list entry rather than
    // rejecting the shared prefix in the pending derived identifier.
    assert!(!message.contains(&format!("{BASE},")), "{message}");
}

#[tokio::test]
async fn deployment_expiry_preserves_the_pending_ids_and_cause() {
    let _serial = SERIAL.lock().await;
    let (report, registry) = run(&[&PARTIAL_EXPIRY], Duration::from_secs(10)).await;
    let report = report.unwrap();
    assert!(!report.succeeded());
    assert_eq!(*registry.admitted.lock(), [BASE]);
    assert_pending_diagnostic(&report);
}

#[tokio::test(start_paused = true)]
async fn deployment_deadline_preserves_the_last_pending_diagnostic() {
    let _serial = SERIAL.lock().await;
    let (report, registry) = run(&[&PARTIAL_PENDING], Duration::from_secs(10)).await;
    let report = report.unwrap();
    assert!(!report.succeeded());
    assert_eq!(*registry.admitted.lock(), [BASE]);
    assert_pending_diagnostic(&report);
}

#[tokio::test(start_paused = true)]
async fn deployment_cancellation_preserves_the_last_pending_diagnostic() {
    let _serial = SERIAL.lock().await;
    let registry = Arc::new(RemoteRegistry::default());
    *REGISTRY.lock() = Some(Arc::clone(&registry));
    let cancel = tokio_util::sync::CancellationToken::new();
    let canceller = async {
        tokio::time::sleep(Duration::from_secs(1)).await;
        cancel.cancel();
    };
    let descriptors = [&PARTIAL_PENDING];
    let tuning = tuning();
    let (report, ()) = tokio::join!(
        publish(
            &descriptors,
            &NoConfig,
            ENDPOINT,
            &tuning,
            Duration::from_secs(30),
            &cancel,
        ),
        canceller
    );
    let report = report.unwrap();
    assert!(!report.succeeded());
    assert_eq!(*registry.admitted.lock(), [BASE]);
    assert_pending_diagnostic(&report);
}

/// A job that requires TLS for every publisher.
fn tls_job() -> ClientTuning {
    let mut job = tuning();
    job.require_tls = Some(true);
    job
}

fn tuning() -> ClientTuning {
    ClientTuning::default().with_internal_token_provider(Some(InternalTokenProvider::from_token(
        secrecy::SecretString::from("platform-token".to_owned()),
    )))
}

/// The tests share the static registry slot.
static SERIAL: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());

async fn run(
    descriptors: &[&'static GtsPublicationDescriptor],
    deadline: Duration,
) -> (anyhow::Result<GtsDeploymentReport>, Arc<RemoteRegistry>) {
    let registry = Arc::new(RemoteRegistry::default());
    *REGISTRY.lock() = Some(Arc::clone(&registry));
    let report = publish(
        descriptors,
        &NoConfig,
        ENDPOINT,
        &tuning(),
        deadline,
        &tokio_util::sync::CancellationToken::new(),
    )
    .await;
    (report, registry)
}

/// A derived-type publisher listed first does not delay its base-type
/// publisher: both succeed, through the explicit endpoint with the credential.
#[tokio::test]
async fn publishers_run_concurrently_against_the_explicit_registry() {
    let _serial = SERIAL.lock().await;
    let (report, registry) = run(&[&DERIVED_PUB, &BASE_PUB], Duration::from_secs(10)).await;
    let report = report.unwrap();

    assert!(report.succeeded(), "{report}");
    let admitted_seen = { registry.admitted.lock().clone() };
    assert_eq!(admitted_seen, [BASE, DERIVED]);
    let endpoint_seen = { registry.endpoint.lock().clone() };
    assert_eq!(endpoint_seen.as_deref(), Some(ENDPOINT));
    let token_seen = { registry.token.lock().clone() };
    assert_eq!(token_seen.as_deref(), Some("platform-token"));
}

/// A refusal is reported per publisher, with its GTS id; the others still run.
#[tokio::test]
async fn a_refusal_fails_the_job_and_names_the_publisher() {
    let _serial = SERIAL.lock().await;
    let (report, _) = run(&[&REFUSED_PUB, &BASE_PUB], Duration::from_secs(10)).await;
    let report = report.unwrap();

    assert!(!report.succeeded());
    assert_eq!(
        report.publishers[1],
        (
            "base-publisher",
            GtsDeploymentOutcome::Published { documents: 1 }
        )
    );
    let (gear, GtsDeploymentOutcome::Refused(message)) = &report.publishers[0] else {
        panic!("{report}");
    };
    assert_eq!(*gear, "refused-publisher");
    assert!(
        message.contains("gts.cf.test.publication.refused.v1~"),
        "{message}"
    );
}

/// The deadline ends what is still pending and names its GTS ids.
#[tokio::test(start_paused = true)]
async fn the_deadline_ends_pending_publishers() {
    let _serial = SERIAL.lock().await;
    let deadline = tokio::time::Instant::now() + Duration::from_secs(30);
    let (report, registry) = run(&[&HANGING_PUB, &BASE_PUB], Duration::from_secs(30)).await;
    let report = report.unwrap();

    let deadlines_seen = { registry.deadlines.lock().clone() };
    assert_eq!(deadlines_seen, [Some(deadline), Some(deadline)]);

    assert!(!report.succeeded());
    assert_eq!(
        report.publishers,
        [
            (
                "hanging-publisher",
                GtsDeploymentOutcome::DeadlineExceeded {
                    unconfirmed: vec!["gts.cf.test.publication.hanging.v1~".to_owned()]
                }
            ),
            (
                "base-publisher",
                GtsDeploymentOutcome::Published { documents: 1 }
            ),
        ]
    );
}

/// A publisher whose own budget runs out before the job's deadline is reported
/// as not confirmed in time, with its GTS ids, not as refused.
#[tokio::test]
async fn a_gear_budget_expiry_is_a_deadline_not_a_refusal() {
    let _serial = SERIAL.lock().await;
    let (report, _) = run(&[&EXPIRING_PUB, &BASE_PUB], Duration::from_secs(10)).await;
    let report = report.unwrap();

    assert!(!report.succeeded());
    let (gear, GtsDeploymentOutcome::DeadlineExceededWithDetails(detail)) = &report.publishers[0]
    else {
        panic!("{report}");
    };
    assert_eq!(*gear, "expiring-publisher");
    assert!(
        detail.contains("gts.cf.test.publication.expiring.v1~"),
        "{detail}"
    );
    assert!(detail.contains("deadline reached"), "{detail}");
    assert_eq!(
        report.publishers[1],
        (
            "base-publisher",
            GtsDeploymentOutcome::Published { documents: 1 }
        )
    );
}

/// An expiry whose adapter error names no identifier still reports the
/// manifest's ids, as not confirmed rather than as exactly pending.
#[tokio::test]
async fn an_opaque_budget_expiry_still_names_the_manifest_ids() {
    let _serial = SERIAL.lock().await;
    let (report, _) = run(&[&OPAQUE_PUB], Duration::from_secs(10)).await;
    let report = report.unwrap();

    let (gear, GtsDeploymentOutcome::DeadlineExceededWithDetails(detail)) = &report.publishers[0]
    else {
        panic!("{report}");
    };
    assert_eq!(*gear, "opaque-publisher");
    assert!(
        detail.contains("budget ran out before admission"),
        "{detail}"
    );
    let (_, ids) = detail
        .split_once("; not confirmed (some may be admitted): ")
        .unwrap_or_else(|| panic!("{detail}"));
    let mut ids: Vec<&str> = ids.split(", ").collect();
    ids.sort_unstable();
    assert_eq!(ids, [OPAQUE, OPAQUE_PEER], "{detail}");
}

/// The platform credential never goes to an endpoint that is not an absolute
/// http(s) URI: the job fails before any wiring.
#[tokio::test]
async fn a_relative_or_foreign_registry_endpoint_fails_before_wiring() {
    let _serial = SERIAL.lock().await;
    for endpoint in [
        "registry:8443",
        "/registry",
        "ftp://registry",
        "not a uri",
        "https://:8443",
    ] {
        let registry = Arc::new(RemoteRegistry::default());
        *REGISTRY.lock() = Some(Arc::clone(&registry));
        let err = publish(
            &[&BASE_PUB],
            &NoConfig,
            endpoint,
            &tuning(),
            Duration::from_secs(10),
            &tokio_util::sync::CancellationToken::new(),
        )
        .await
        .unwrap_err();

        assert!(
            err.to_string().contains("registry endpoint"),
            "{endpoint}: {err:#}"
        );
        let token = { registry.token.lock().clone() };
        assert_eq!(token, None, "{endpoint}: no wiring, so no credential");
    }
}

/// Two publishers of one GTS id fail the job before any request.
#[tokio::test]
async fn an_ownership_conflict_fails_before_publication() {
    let _serial = SERIAL.lock().await;
    descriptor!(BASE_AGAIN, "base-again", base);
    let (report, registry) = run(&[&BASE_PUB, &BASE_AGAIN], Duration::from_secs(10)).await;

    let err = report.unwrap_err();
    assert!(
        err.to_string().contains("base-again and base-publisher"),
        "{err:#}"
    );
    assert!(registry.admitted.lock().is_empty());
}

/// The caller's cancellation ends pending publishers as cancelled, not as past
/// the deadline.
#[tokio::test]
async fn caller_cancellation_is_not_a_deadline() {
    let _serial = SERIAL.lock().await;
    let registry = Arc::new(RemoteRegistry::default());
    *REGISTRY.lock() = Some(Arc::clone(&registry));
    let cancel = tokio_util::sync::CancellationToken::new();
    let canceller = {
        let cancel = cancel.clone();
        async move {
            tokio::time::sleep(Duration::from_millis(50)).await;
            cancel.cancel();
        }
    };
    let descriptors = [&HANGING_PUB];
    let tuning = tuning();
    let (report, ()) = tokio::join!(
        publish(
            &descriptors,
            &NoConfig,
            ENDPOINT,
            &tuning,
            Duration::from_secs(600),
            &cancel
        ),
        canceller
    );

    assert_eq!(
        report.unwrap().publishers,
        [(
            "hanging-publisher",
            GtsDeploymentOutcome::Cancelled {
                unconfirmed: vec!["gts.cf.test.publication.hanging.v1~".to_owned()]
            }
        )]
    );
}

/// Exactly the maximum deadline is accepted and reaches every publisher.
#[tokio::test(start_paused = true)]
async fn a_deadline_of_exactly_ten_minutes_is_accepted() {
    let _serial = SERIAL.lock().await;
    let (report, registry) =
        run(&[&BASE_PUB], crate::gts_publication::MAX_PUBLICATION_BUDGET).await;
    assert!(report.unwrap().succeeded());
    let deadlines_seen = { registry.deadlines.lock().len() };
    assert_eq!(deadlines_seen, 1);
}

/// A deadline above the maximum is an error before any wiring or publication:
/// not clamped, and no credential reaches a registry.
#[tokio::test(start_paused = true)]
async fn a_deadline_above_ten_minutes_is_rejected_before_publication_starts() {
    let _serial = SERIAL.lock().await;
    let over = crate::gts_publication::MAX_PUBLICATION_BUDGET + Duration::from_secs(1);
    let (report, registry) = run(&[&BASE_PUB], over).await;
    let message = format!("{:#}", report.unwrap_err());
    assert!(
        message.contains("the publication deadline")
            && message.contains("too large to be a publication budget")
            && message.contains("at most"),
        "{message}"
    );
    assert!(registry.endpoint.lock().is_none(), "nothing was wired");
    assert!(
        registry.deadlines.lock().is_empty(),
        "nothing was published"
    );
}