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
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
//! GTS publication capability.
//!
//! A gear declares its publication in its gear attribute:
//!
//! ```ignore
//! #[toolkit::gear(
//!     name = "my-gear",
//!     gts_publication(
//!         crates = [crate, my_gear_sdk],
//!         publisher = types_registry_sdk::publication,
//!         entities = Self::configured_entities, // optional
//!     ),
//! )]
//! pub struct MyGear { /* ... */ }
//! ```
//!
//! Each crate in `crates` invokes `toolkit_gts::declare_gts_inventory!()`. The
//! macro generates the [`GtsPublicationDescriptor`], the
//! [`GtsPublicationCapability`] and the registry-client wiring of the
//! publisher adapter. The gear writes no task, retry loop or readiness code.
//!
//! The runtime builds every manifest from the configuration before any gear
//! runs, then — once the system group (the registry among it) started and
//! the application migrations ran — publishes them all concurrently
//! ([`publish_all`]) and waits until each one is admitted. No application
//! `init` runs before that barrier. A gear reads its admitted manifest in
//! `init` ([`GearCtx::gts_publication_manifest`]): a plugin binds its scoped
//! clients to the instances it lists. A pending publication of one gear does
//! not delay another publication; it delays every application `init`.
//!
//! [`GearCtx::gts_publication_manifest`]: crate::context::GearCtx::gts_publication_manifest
//!
//! # Publisher adapter
//!
//! The `publisher` path names a module with this interface:
//!
//! ```ignore
//! pub type Registry = dyn SomeRegistryApi;          // client-hub key
//! pub const PROVIDER: &str = "provider-gear";       // directory name
//! pub use some::ResolvingClient;                    // ::new(resolver, PROVIDER, tuning)
//! pub struct Publication<'a> { /* ... */ }
//! impl<'a> Publication<'a> {
//!     pub fn from_manifest(
//!         registry: &'a Registry,
//!         publisher_name: &str,
//!         publisher_version: &str,
//!         documents: &[(gts::GtsId, serde_json::Value)],
//!     ) -> Result<Self, impl std::error::Error + Send + Sync + 'static>;
//!     pub fn deadline(self, deadline: Option<tokio::time::Instant>) -> Self;
//!     pub fn timeout(self, timeout: Option<std::time::Duration>) -> Self;
//!     pub fn retry_backoff(self, initial: std::time::Duration, max: std::time::Duration) -> Self;
//!     pub fn batch_size(self, batch_size: std::num::NonZeroUsize) -> Self;
//!     // Returns a builder with the same `publish`.
//!     pub fn on_pending(self, on_pending: impl FnMut(&impl std::fmt::Display) + Send) -> _;
//!     pub async fn publish(self, cancel: &CancellationToken)
//!         -> Result<impl Sized, PublishError>;
//! }
//! // Whether `publish` failed because its budget ran out, not on a refusal.
//! pub fn expired(error: &PublishError) -> bool;
//! // PublishError: std::error::Error + Send + Sync + 'static
//! ```
//!
//! `from_manifest` rejects invalid input before any request; the GTS ids arrive parsed. `publish` returns `Ok` only
//! after every document is admitted; the runtime discards its value. It retries retryable
//! conditions within its budget, reporting each pending pass to `on_pending`, and returns
//! an error for expiry, a terminal refusal or cancellation; `expired` tells the first
//! apart, which the runtime reports as [`GtsPublicationError::Expired`]. Its future is `Send`.
//! Toolkit does not depend on the adapter's crate, so the policy crosses the boundary
//! as plain `std` values: the runtime always calls `timeout`, `retry_backoff` and
//! `batch_size` with the gear's [`GtsPublicationOptions`], already validated.
//!
//! The budget starts with `publish`. A caller's absolute deadline (a deployment job's)
//! replaces the adapter's default budget, and may exceed it; a configured `timeout`
//! caps either, and never extends the caller's deadline, which is never renewed.
//!
//! # Configuration
//!
//! `gears.<gear>.config.gts_publication` sets the policy of one publishing gear
//! ([`GtsPublicationOptions`]); the typed gear configuration does not see it. The
//! registry client itself — its URL, HTTP timeout and HTTP retries — stays in
//! `gears.<gear>.clients.consumes.<provider>`. Each consuming gear has its own
//! client view, remote registry proxy and tuning. A publisher that also explicitly
//! consumes the registry contract reuses that gear's client. Publication policy
//! remains per gear for both local and remote registries.

use std::fmt;
use std::future::Future;
use std::num::NonZeroUsize;
use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;

use serde::de::DeserializeOwned;
use tokio_util::sync::CancellationToken;

use crate::client_hub::ClientHub;
use crate::config::{ConfigError, ConfigProvider, gear_config_or_default, gear_config_required};

use toolkit_gts::local::DeclarationMerge;
pub use toolkit_gts::local::DeclarationSource;

/// Effective gear configuration for `entities`, without gear state, DB or clients.
/// The same configuration must produce the same runtime and deployment manifest.
pub struct GtsPublicationInputs<'a> {
    gear: &'a str,
    config: &'a dyn ConfigProvider,
}

impl<'a> GtsPublicationInputs<'a> {
    #[must_use]
    pub fn new(gear: &'a str, config: &'a dyn ConfigProvider) -> Self {
        Self { gear, config }
    }

    /// The gear's config section, as [`GearCtx::config`].
    ///
    /// # Errors
    /// The config is missing or does not deserialize.
    pub fn config<T: DeserializeOwned>(&self) -> Result<T, ConfigError> {
        gear_config_required(self.config, self.gear)
    }

    /// The gear's config section or its default, as [`GearCtx::config_or_default`].
    ///
    /// # Errors
    /// The config does not deserialize.
    pub fn config_or_default<T: DeserializeOwned + Default>(&self) -> Result<T, ConfigError> {
        gear_config_or_default(self.config, self.gear)
    }

    /// As [`GearCtx::config_expanded_or_default`].
    ///
    /// # Errors
    /// The config does not deserialize or a variable does not expand.
    pub fn config_expanded_or_default<T>(&self) -> Result<T, ConfigError>
    where
        T: DeserializeOwned + Default + crate::var_expand::ExpandVars,
    {
        let mut cfg: T = self.config_or_default()?;
        cfg.expand_vars().map_err(|e| ConfigError::VarExpand {
            gear: self.gear.to_owned(),
            cause: e,
        })?;
        Ok(cfg)
    }
}

/// The documents one publisher intends to register, sorted by GTS id.
#[derive(Debug, Clone, PartialEq)]
pub struct GtsManifest {
    publisher_name: String,
    publisher_version: String,
    documents: Vec<(gts::GtsId, serde_json::Value)>,
}

impl GtsManifest {
    /// Merge `sources` into a manifest. An id declared twice with the same
    /// canonical content is kept once.
    ///
    /// # Errors
    /// An invalid GTS id or JSON text, or an id declared with different content.
    pub fn build(
        publisher_name: impl Into<String>,
        publisher_version: impl Into<String>,
        sources: impl IntoIterator<Item = DeclarationSource>,
    ) -> anyhow::Result<Self> {
        Ok(Self {
            publisher_name: publisher_name.into(),
            publisher_version: publisher_version.into(),
            documents: toolkit_gts::local::merge_declarations(sources)?,
        })
    }

    #[must_use]
    pub fn publisher_name(&self) -> &str {
        &self.publisher_name
    }

    #[must_use]
    pub fn publisher_version(&self) -> &str {
        &self.publisher_version
    }

    /// `(GTS id, authored document)`, sorted by id.
    #[must_use]
    pub fn documents(&self) -> &[(gts::GtsId, serde_json::Value)] {
        &self.documents
    }

    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.documents.is_empty()
    }
}

/// Require one publisher per GTS id across this process or deployment job,
/// even for identical content.
///
/// # Errors
/// Lists every conflicting id with its publishers.
pub fn check_ownership<'a>(
    manifests: impl IntoIterator<Item = &'a GtsManifest>,
) -> anyhow::Result<()> {
    let mut owners: std::collections::BTreeMap<&str, Vec<&str>> = std::collections::BTreeMap::new();
    for manifest in manifests {
        for (id, _) in manifest.documents() {
            owners
                .entry(id.id())
                .or_default()
                .push(manifest.publisher_name());
        }
    }
    let conflicts: Vec<String> = owners
        .into_iter()
        .filter(|(_, publishers)| publishers.len() > 1)
        .map(|(id, mut publishers)| {
            publishers.sort_unstable();
            format!("{id} is published by {}", publishers.join(" and "))
        })
        .collect();
    if conflicts.is_empty() {
        Ok(())
    } else {
        anyhow::bail!(
            "GTS ids with more than one publisher:\n- {}",
            conflicts.join("\n- ")
        )
    }
}

/// Per-publisher policy at `gears.<gear>.config.gts_publication`.
///
/// ```yaml
/// gears:
///   account-management:
///     config:
///       gts_publication:
///         timeout: "120s"          # optional cap, see below
///         retry_backoff: "1s"      # default 1s
///         retry_backoff_max: "30s" # default 30s
///         batch_size: 100          # default 100
/// ```
///
/// Read once with the manifest and forwarded unchanged to the adapter. Hidden
/// from typed gear config ([`crate::config::GTS_PUBLICATION_CONFIG_KEY`]) and
/// excluded from [`GtsManifest`], so policy changes do not affect ownership.
/// Applies per publication, with local or shared remote clients alike; client
/// URL, HTTP timeout and HTTP retries remain in `clients.consumes`.
///
/// `timeout` caps the budget from `publish` and never extends a caller's deadline.
/// At most [`MAX_PUBLICATION_BUDGET`] (10 minutes), the same bound as a deployment
/// deadline, on every OS.
/// Without it, startup uses the adapter's default (120 s for the registry SDK);
/// a deployment deadline replaces that default, even when longer.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct GtsPublicationOptions {
    timeout: Option<Duration>,
    retry_backoff: Duration,
    retry_backoff_max: Duration,
    batch_size: NonZeroUsize,
}

impl Default for GtsPublicationOptions {
    fn default() -> Self {
        Self {
            timeout: None,
            retry_backoff: Duration::from_secs(1),
            retry_backoff_max: Duration::from_secs(30),
            batch_size: NonZeroUsize::new(100).unwrap_or(NonZeroUsize::MIN),
        }
    }
}

/// The longest budget any publication path accepts: `gts_publication.timeout`, a
/// deployment job's deadline (`publish-gts --timeout`) and programmatic callers of
/// [`deployment::publish`], and an absolute deadline given to [`GtsPublicationBackend::publish`]
/// (how far ahead it lies). One bound, so a mistyped value cannot hold startup or a
/// deployment step for an impractically long time.
pub const MAX_PUBLICATION_BUDGET: Duration = Duration::from_mins(10);

/// Reject a publication budget above [`MAX_PUBLICATION_BUDGET`]: an error naming `what`,
/// never a silent clamp. Exactly the maximum is accepted.
///
/// # Errors
/// `budget` exceeds [`MAX_PUBLICATION_BUDGET`].
pub(crate) fn check_publication_budget(what: &str, budget: Duration) -> anyhow::Result<()> {
    anyhow::ensure!(
        budget <= MAX_PUBLICATION_BUDGET,
        "{what}: {budget:?} is too large to be a publication budget (at most {MAX_PUBLICATION_BUDGET:?})"
    );
    Ok(())
}

/// Parse a publication budget given as text, such as `30s`, `2m` or `10m`: the format of
/// `gts_publication.timeout`. `what` names the setting in errors (for example `--timeout`).
///
/// # Errors
/// Not a humantime duration, zero, or above [`MAX_PUBLICATION_BUDGET`] (never clamped).
pub fn parse_publication_budget(what: &str, text: &str) -> anyhow::Result<Duration> {
    let budget = positive_duration(what, &serde_json::Value::String(text.to_owned()))?;
    check_publication_budget(what, budget)?;
    Ok(budget)
}

impl GtsPublicationOptions {
    const FIELDS: &str = "timeout, retry_backoff, retry_backoff_max, batch_size";

    /// The policy of `gear` in `config`; the default without a `gts_publication` section.
    ///
    /// # Errors
    /// Naming the gear and the config path: a section that is not a mapping (`null`
    /// included), an unknown field, a value of the wrong type, a zero duration or batch
    /// size, a `retry_backoff_max` below `retry_backoff` (defaults included), or a
    /// `timeout` above [`MAX_PUBLICATION_BUDGET`] (10 minutes).
    pub fn from_config(gear: &str, config: &dyn ConfigProvider) -> anyhow::Result<Self> {
        let path = format!(
            "gears.{gear}.config.{}",
            crate::config::GTS_PUBLICATION_CONFIG_KEY
        );
        let Some(section) = config
            .get_gear_config(gear)
            .and_then(|gear| gear.get("config"))
            .and_then(|config| config.get(crate::config::GTS_PUBLICATION_CONFIG_KEY))
        else {
            return Ok(Self::default());
        };
        let serde_json::Value::Object(fields) = section else {
            anyhow::bail!(
                "{path}: expected a mapping of {}, got {section}",
                Self::FIELDS
            );
        };
        let mut options = Self::default();
        for (key, value) in fields {
            let field = format!("{path}.{key}");
            match key.as_str() {
                "timeout" => options.timeout = Some(positive_duration(&field, value)?),
                "retry_backoff" => options.retry_backoff = positive_duration(&field, value)?,
                "retry_backoff_max" => {
                    options.retry_backoff_max = positive_duration(&field, value)?;
                }
                "batch_size" => {
                    options.batch_size = value
                        .as_u64()
                        .and_then(|n| usize::try_from(n).ok())
                        .and_then(NonZeroUsize::new)
                        .ok_or_else(|| {
                            anyhow::anyhow!("{field}: expected a positive integer, got {value}")
                        })?;
                }
                _ => anyhow::bail!("{field}: unknown field; expected one of {}", Self::FIELDS),
            }
        }
        if options.retry_backoff_max < options.retry_backoff {
            anyhow::bail!(
                "{path}: retry_backoff_max ({:?}) is less than retry_backoff ({:?})",
                options.retry_backoff_max,
                options.retry_backoff
            );
        }
        if let Some(timeout) = options.timeout {
            check_publication_budget(&format!("{path}.timeout"), timeout)?;
        }
        Ok(options)
    }

    /// The per-gear cap of the publication, from the start of `publish`.
    #[must_use]
    pub fn timeout(&self) -> Option<Duration> {
        self.timeout
    }

    /// The first pause between two passes.
    #[must_use]
    pub fn retry_backoff(&self) -> Duration {
        self.retry_backoff
    }

    /// The longest pause between two passes.
    #[must_use]
    pub fn retry_backoff_max(&self) -> Duration {
        self.retry_backoff_max
    }

    /// Documents per registry submission.
    #[must_use]
    pub fn batch_size(&self) -> NonZeroUsize {
        self.batch_size
    }
}

/// A non-zero humantime duration such as `"30s"`.
fn positive_duration(field: &str, value: &serde_json::Value) -> anyhow::Result<Duration> {
    let duration = toolkit_utils::humantime_serde::deserialize(value)
        .map_err(|e| anyhow::anyhow!("{field}: {e}, such as \"30s\""))?;
    if duration.is_zero() {
        anyhow::bail!("{field}: must be greater than zero");
    }
    Ok(duration)
}

/// What a [`GtsPublicationBackend`] receives for one publication.
pub struct GtsPublicationRequest {
    manifest: Arc<GtsManifest>,
    cancel: CancellationToken,
    progress: Arc<dyn Fn(&str) + Send + Sync>,
    deadline: Option<tokio::time::Instant>,
    options: GtsPublicationOptions,
}

impl GtsPublicationRequest {
    #[must_use]
    pub fn new(
        manifest: Arc<GtsManifest>,
        cancel: CancellationToken,
        progress: Arc<dyn Fn(&str) + Send + Sync>,
    ) -> Self {
        Self {
            manifest,
            cancel,
            progress,
            deadline: None,
            options: GtsPublicationOptions::default(),
        }
    }

    /// The same request with the caller's absolute deadline.
    #[must_use]
    pub fn with_deadline(mut self, deadline: Option<tokio::time::Instant>) -> Self {
        self.deadline = deadline;
        self
    }

    /// The same request with the publishing gear's policy.
    #[must_use]
    pub fn with_options(mut self, options: GtsPublicationOptions) -> Self {
        self.options = options;
        self
    }

    #[must_use]
    pub fn gts_manifest(&self) -> &GtsManifest {
        &self.manifest
    }

    #[must_use]
    pub fn cancel(&self) -> &CancellationToken {
        &self.cancel
    }

    /// The caller's absolute publication deadline, when supplied (e.g. a deployment job).
    #[must_use]
    pub fn deadline(&self) -> Option<tokio::time::Instant> {
        self.deadline
    }

    /// The publishing gear's policy, for the adapter's builder.
    #[must_use]
    pub fn options(&self) -> GtsPublicationOptions {
        self.options
    }

    /// Record why the publication is not complete yet.
    pub fn report_pending(&self, detail: &str) {
        (self.progress)(detail);
    }
}

type GtsPublishFuture = Pin<Box<dyn Future<Output = anyhow::Result<()>> + Send>>;

/// Executes publications: the boundary between the executor and a publisher
/// adapter. The stateless backend calls the adapter directly; a durable
/// backend can wrap the same adapter.
#[derive(Clone)]
pub struct GtsPublicationBackend(
    Arc<dyn Fn(GtsPublicationRequest) -> GtsPublishFuture + Send + Sync>,
);

impl GtsPublicationBackend {
    pub fn new<F, Fut>(publish: F) -> Self
    where
        F: Fn(GtsPublicationRequest) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = anyhow::Result<()>> + Send + 'static,
    {
        Self(Arc::new(move |request| Box::pin(publish(request))))
    }

    /// Publish within the budget. `Err` is expiry, a terminal refusal or cancellation.
    ///
    /// # Errors
    /// See above; also a request whose absolute deadline lies more than
    /// [`MAX_PUBLICATION_BUDGET`] ahead, rejected before the adapter runs.
    pub async fn publish(&self, request: GtsPublicationRequest) -> anyhow::Result<()> {
        // Every caller-supplied absolute deadline, from any path, is held to the same
        // maximum as `timeout`: rejected here, before the adapter runs, never clamped.
        if let Some(deadline) = request.deadline() {
            check_publication_budget(
                "the publication deadline",
                deadline.saturating_duration_since(tokio::time::Instant::now()),
            )?;
        }
        (self.0)(request).await
    }
}

impl fmt::Debug for GtsPublicationBackend {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("GtsPublicationBackend")
    }
}

/// An `entities` function: config-only documents as `(GTS id, document)`. It parses
/// each id once, where it builds it; the manifest keeps the parsed id.
pub type GtsEntitiesFn =
    fn(&GtsPublicationInputs<'_>) -> anyhow::Result<Vec<(gts::GtsId, serde_json::Value)>>;

/// Static description of a gear's publication, generated by
/// `#[toolkit::gear(gts_publication(...))]`. The runtime uses it before `init`, and a
/// deployment job without the gear instance: neither calls `init`.
pub struct GtsPublicationDescriptor {
    /// The gear name, which is also the publisher name.
    pub gear: &'static str,
    /// The publisher version: the version of the gear's crate.
    pub publisher_version: &'static str,
    /// The crate-local collectors of the `crates` list.
    pub declarations: fn() -> Vec<DeclarationSource>,
    /// The optional config-only `entities` function.
    pub entities: Option<GtsEntitiesFn>,
    /// Binds the adapter to the registry client in `hub`.
    pub backend: fn(&ClientHub) -> anyhow::Result<GtsPublicationBackend>,
    /// The registry provider's directory name.
    pub provider: &'static str,
    /// Registers the adapter's registry client in a hub, as proxy wiring does;
    /// a deployment job calls it with its explicit registry endpoint.
    pub wire: crate::discovery::WireFn,
}

impl GtsPublicationDescriptor {
    /// The manifest for the effective configuration `config`.
    ///
    /// # Errors
    /// Entity generation, collection, parsing or declaration merging fails.
    pub fn build_gts_manifest(&self, config: &dyn ConfigProvider) -> anyhow::Result<GtsManifest> {
        let mut merge = DeclarationMerge::default();
        let declarations = std::panic::catch_unwind(self.declarations).map_err(|payload| {
            let detail = payload
                .downcast_ref::<String>()
                .map(String::as_str)
                .or_else(|| payload.downcast_ref::<&str>().copied())
                .unwrap_or("collector panicked without a text diagnostic");
            anyhow::anyhow!("{}: GTS declarations: {detail}", self.gear)
        })?;
        for source in declarations {
            merge.add_source(source);
        }
        if let Some(entities) = self.entities {
            let inputs = GtsPublicationInputs::new(self.gear, config);
            merge.add_documents("entities", entities(&inputs)?);
        }
        Ok(GtsManifest {
            publisher_name: self.gear.to_owned(),
            publisher_version: self.publisher_version.to_owned(),
            documents: merge.finish()?,
        })
    }
}

impl fmt::Debug for GtsPublicationDescriptor {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("GtsPublicationDescriptor")
            .field("gear", &self.gear)
            .field("publisher_version", &self.publisher_version)
            .finish_non_exhaustive()
    }
}

/// Every linked publication, for a deployment job.
pub struct GtsPublicationRegistration(pub &'static GtsPublicationDescriptor);

inventory::collect!(GtsPublicationRegistration);

/// Every publication descriptor linked into this binary, sorted by gear.
#[must_use]
pub fn linked_descriptors() -> Vec<&'static GtsPublicationDescriptor> {
    let mut out: Vec<_> = inventory::iter::<GtsPublicationRegistration>
        .into_iter()
        .map(|r| r.0)
        .collect();
    out.sort_by_key(|d| d.gear);
    out
}

/// The runtime side of a gear's publication, generated by
/// `#[toolkit::gear(gts_publication(...))]`.
pub trait GtsPublicationCapability: Send + Sync {
    fn descriptor(&self) -> &'static GtsPublicationDescriptor;
}

/// The context a publisher adapter puts on a [`GtsPublicationBackend`] error when
/// the publication's budget ran out before admission, rather than on a refusal:
/// [`PreparedGtsPublication::publish`] reports it as [`GtsPublicationError::Expired`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[error("the GTS publication budget ran out before admission")]
pub struct GtsPublicationExpired;

/// Why a publication did not complete.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum GtsPublicationError {
    /// The manifest could not be built from the configuration.
    #[error("{gear}: GTS manifest: {source:#}")]
    GtsManifest {
        gear: &'static str,
        source: anyhow::Error,
    },
    /// `gears.<gear>.config.gts_publication` is invalid.
    #[error("{gear}: GTS publication options: {source:#}")]
    Options {
        gear: &'static str,
        source: anyhow::Error,
    },
    /// The publisher adapter could not bind its registry client.
    #[error("{gear}: GTS publisher: {source:#}")]
    Backend {
        gear: &'static str,
        source: anyhow::Error,
    },
    /// The registry refused the publication.
    #[error("{gear}: GTS publication refused: {source:#}")]
    Refused {
        gear: &'static str,
        source: anyhow::Error,
    },
    /// Not admitted before the publication's budget ran out: the configured
    /// `timeout`, the adapter's default budget or the caller's deadline. Some
    /// documents may already be admitted.
    #[error("{gear}: GTS publication not admitted in time: {source:#}")]
    Expired {
        gear: &'static str,
        source: anyhow::Error,
    },
    /// Cancelled before admission.
    #[error("{gear}: GTS publication cancelled")]
    Cancelled { gear: &'static str },
}

/// A gear's publication, ready to run: the manifest and bound backend.
/// Every publication is prepared before any runs, so a manifest or wiring
/// error fails before the first registry write.
pub struct PreparedGtsPublication {
    gear: &'static str,
    manifest: Arc<GtsManifest>,
    /// `None` for an empty manifest: nothing to send.
    backend: Option<GtsPublicationBackend>,
    deadline: Option<tokio::time::Instant>,
    /// Read with the manifest; never re-read from the configuration.
    options: GtsPublicationOptions,
}

impl PreparedGtsPublication {
    /// Build the manifest and read the policy from `config`, and bind the backend
    /// from `hub`.
    ///
    /// # Errors
    /// [`GtsPublicationError::GtsManifest`], [`GtsPublicationError::Options`] or
    /// [`GtsPublicationError::Backend`].
    pub fn prepare(
        descriptor: &'static GtsPublicationDescriptor,
        config: &dyn ConfigProvider,
        hub: &ClientHub,
    ) -> Result<Self, GtsPublicationError> {
        let gear = descriptor.gear;
        let manifest = descriptor
            .build_gts_manifest(config)
            .map_err(|source| GtsPublicationError::GtsManifest { gear, source })?;
        let options = GtsPublicationOptions::from_config(gear, config)
            .map_err(|source| GtsPublicationError::Options { gear, source })?;
        Self::bind(descriptor, Arc::new(manifest), options, hub)
    }

    /// Bind the backend of an already built `manifest` and its already read
    /// `options` from `hub`. An empty manifest needs no backend, so no registry.
    ///
    /// # Errors
    /// [`GtsPublicationError::Backend`].
    pub fn bind(
        descriptor: &'static GtsPublicationDescriptor,
        manifest: Arc<GtsManifest>,
        options: GtsPublicationOptions,
        hub: &ClientHub,
    ) -> Result<Self, GtsPublicationError> {
        let gear = descriptor.gear;
        let backend = if manifest.is_empty() {
            None
        } else {
            Some(
                (descriptor.backend)(hub)
                    .map_err(|source| GtsPublicationError::Backend { gear, source })?,
            )
        };
        Ok(Self {
            gear,
            manifest,
            backend,
            deadline: None,
            options,
        })
    }

    /// Use the caller's absolute deadline instead of the adapter's default publication
    /// budget. A configured `timeout` still caps it; nothing extends it.
    #[must_use]
    pub fn with_deadline(mut self, deadline: tokio::time::Instant) -> Self {
        self.deadline = Some(deadline);
        self
    }

    #[must_use]
    pub fn gear(&self) -> &'static str {
        self.gear
    }

    #[must_use]
    pub fn gts_manifest(&self) -> &GtsManifest {
        &self.manifest
    }

    #[must_use]
    pub fn options(&self) -> GtsPublicationOptions {
        self.options
    }

    /// The manifest, shared.
    #[must_use]
    pub fn shared_gts_manifest(&self) -> Arc<GtsManifest> {
        Arc::clone(&self.manifest)
    }

    /// Publish until admitted, refused or expired. An empty manifest succeeds at once.
    ///
    /// # Errors
    /// [`GtsPublicationError::Refused`], [`GtsPublicationError::Expired`] or
    /// [`GtsPublicationError::Cancelled`].
    pub async fn publish(
        &self,
        cancel: &CancellationToken,
        progress: Arc<dyn Fn(&str) + Send + Sync>,
    ) -> Result<(), GtsPublicationError> {
        let gear = self.gear;
        if cancel.is_cancelled() {
            return Err(GtsPublicationError::Cancelled { gear });
        }
        let Some(backend) = &self.backend else {
            return Ok(());
        };
        let request =
            GtsPublicationRequest::new(Arc::clone(&self.manifest), cancel.clone(), progress)
                .with_deadline(self.deadline)
                .with_options(self.options);
        let result = tokio::select! {
            biased;
            () = cancel.cancelled() => return Err(GtsPublicationError::Cancelled { gear }),
            result = backend.publish(request) => result,
        };
        match result {
            Ok(()) => Ok(()),
            Err(_) if cancel.is_cancelled() => Err(GtsPublicationError::Cancelled { gear }),
            Err(source) if source.downcast_ref::<GtsPublicationExpired>().is_some() => {
                Err(GtsPublicationError::Expired { gear, source })
            }
            Err(source) => Err(GtsPublicationError::Refused { gear, source }),
        }
    }
}

/// Reports why a gear's publication is not admitted yet: `(gear, detail)`.
pub type GtsPublicationProgress = Arc<dyn Fn(&'static str, &str) + Send + Sync>;

/// Publish every prepared publication concurrently: a derived-type publisher
/// waiting for its base never delays the base publisher. Returns one result
/// per publication, in the order of `prepared`, once each one ended.
///
/// With `stop_on_refusal`, the first refusal or expiry cancels the others: the
/// batch failed and their admission no longer matters. The publications run in
/// this future, not spawned: dropping it, or cancelling `cancel`, ends them.
pub async fn publish_all(
    prepared: &[PreparedGtsPublication],
    cancel: &CancellationToken,
    progress: GtsPublicationProgress,
    stop_on_refusal: bool,
) -> Vec<(&'static str, Result<(), GtsPublicationError>)> {
    use futures_util::StreamExt as _;

    let stop = cancel.child_token();
    let mut running: futures_util::stream::FuturesUnordered<_> = prepared
        .iter()
        .enumerate()
        .map(|(index, publication)| {
            let stop = stop.clone();
            let gear = publication.gear();
            let progress = Arc::clone(&progress);
            async move {
                let report: Arc<dyn Fn(&str) + Send + Sync> =
                    Arc::new(move |detail: &str| progress(gear, detail));
                (index, publication.publish(&stop, report).await)
            }
        })
        .collect();
    let mut results: Vec<Option<Result<(), GtsPublicationError>>> =
        prepared.iter().map(|_| None).collect();
    while let Some((index, result)) = running.next().await {
        if stop_on_refusal
            && matches!(
                result,
                Err(GtsPublicationError::Refused { .. } | GtsPublicationError::Expired { .. })
            )
        {
            stop.cancel();
        }
        results[index] = Some(result);
    }
    prepared
        .iter()
        .zip(results)
        .map(|(publication, result)| {
            let gear = publication.gear();
            (
                gear,
                result.unwrap_or(Err(GtsPublicationError::Cancelled { gear })),
            )
        })
        .collect()
}

#[path = "gts_publication_deployment.rs"]
pub mod deployment;

#[cfg(test)]
#[path = "gts_publication_tests.rs"]
mod gts_publication_tests;