cf-gears-toolkit 0.12.1

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
use std::future::Future;
use std::sync::Arc;

use parking_lot::RwLock;
use tokio::sync::Mutex;

use crate::client_hub::{ClientHub, ClientScope};
use crate::gts::PluginV1;

/// A resettable, allocation-friendly selector for GTS plugin instance IDs.
///
/// Uses a single-flight pattern to ensure that the resolve function is called
/// at most once even under concurrent callers. The selected instance ID is
/// cached as `Arc<str>` to avoid allocations on the happy path.
pub struct GtsPluginSelector {
    /// Cached selected instance ID (sync lock for fast access and sync reset).
    cached: RwLock<Option<Arc<str>>>,
    /// Mutex to ensure single-flight resolution.
    resolve_lock: Mutex<()>,
}

impl Default for GtsPluginSelector {
    fn default() -> Self {
        Self::new()
    }
}

impl GtsPluginSelector {
    #[must_use]
    pub fn new() -> Self {
        Self {
            cached: RwLock::new(None),
            resolve_lock: Mutex::new(()),
        }
    }

    /// Create a selector with `value` already cached, skipping resolution entirely.
    ///
    /// Useful in tests to pre-warm the selector with a known instance ID or
    /// an empty-string sentinel (meaning "no plugin configured").
    #[must_use]
    pub fn pre_cached(value: String) -> Self {
        Self {
            cached: RwLock::new(Some(Arc::from(value))),
            resolve_lock: Mutex::new(()),
        }
    }

    /// Returns the cached instance ID, or resolves it using the provided function.
    ///
    /// Uses a single-flight pattern: even under concurrent callers, the resolve
    /// function is called at most once. Returns `Arc<str>` to avoid allocations
    /// on the happy path.
    /// # Errors
    ///
    /// Returns `Err(E)` if the provided `resolve` future fails.
    pub async fn get_or_init<F, Fut, E>(&self, resolve: F) -> Result<Arc<str>, E>
    where
        F: FnOnce() -> Fut,
        Fut: Future<Output = Result<String, E>>,
    {
        // Fast path: check if already cached (sync lock, no await)
        {
            let guard = self.cached.read();
            if let Some(ref id) = *guard {
                return Ok(Arc::clone(id));
            }
        }

        // Slow path: acquire resolve lock for single-flight
        let _resolve_guard = self.resolve_lock.lock().await;

        // Re-check after acquiring resolve lock (another caller may have resolved)
        {
            let guard = self.cached.read();
            if let Some(ref id) = *guard {
                return Ok(Arc::clone(id));
            }
        }

        // Resolve and cache
        let id_string = resolve().await?;
        let id: Arc<str> = id_string.into();

        {
            let mut guard = self.cached.write();
            *guard = Some(Arc::clone(&id));
        }

        Ok(id)
    }

    /// Clears the cached selected instance ID.
    ///
    /// Returns `true` if there was a cached value, `false` otherwise.
    pub async fn reset(&self) -> bool {
        let _resolve_guard = self.resolve_lock.lock().await;
        let mut guard = self.cached.write();
        guard.take().is_some()
    }
}

/// Error returned by [`choose_plugin_instance`].
#[derive(Debug, thiserror::Error)]
pub enum ChoosePluginError {
    /// Failed to deserialize a plugin instance's content.
    #[error("invalid plugin instance content for '{gts_id}': {reason}")]
    InvalidPluginInstance {
        /// GTS ID of the malformed instance.
        gts_id: String,
        /// Human-readable reason.
        reason: String,
    },

    /// No plugin instance matched the requested vendor.
    #[error("no plugin instances found for type '{type_id}', vendor '{vendor}'")]
    PluginNotFound {
        /// GTS Type Identifier of the plugin type being resolved.
        type_id: String,
        /// The vendor that was requested.
        vendor: String,
    },
}

/// Selects the best plugin instance for the given vendor.
///
/// Accepts an iterator of `(gts_id, content)` pairs — typically
/// produced from `types_registry_sdk::GtsEntity`:
///
/// ```ignore
/// choose_plugin_instance::<MyPluginSpecV1>(
///     &self.vendor,
///     instances.iter().map(|e| (e.gts_id.as_str(), &e.content)),
/// )
/// ```
///
/// Deserializes each entry as `PluginV1<P>`, filters by
/// `vendor`, and returns the `gts_id` of the instance with the
/// **lowest** priority value.
///
/// # Type Parameters
///
/// - `P` — The plugin-specific properties struct (e.g.
///   `AuthNResolverPluginSpecV1`). Must be `DeserializeOwned`.
///
/// # Errors
///
/// - [`ChoosePluginError::InvalidPluginInstance`] if deserialization fails
///   or the `content.id` doesn't match `gts_id`.
/// - [`ChoosePluginError::PluginNotFound`] if no instance matches the vendor.
pub fn choose_plugin_instance<'a, P>(
    vendor: &str,
    instances: impl IntoIterator<Item = (&'a str, &'a serde_json::Value)>,
) -> Result<String, ChoosePluginError>
where
    P: for<'de> gts::GtsDeserialize<'de> + gts::GtsSchema,
{
    let mut best: Option<(&str, i16)> = None;
    let mut count: usize = 0;

    for (gts_id, content_val) in instances {
        count += 1;
        let content: PluginV1<P> = serde_json::from_value(content_val.clone()).map_err(|e| {
            tracing::error!(
                gts_id = %gts_id,
                error = %e,
                "Failed to deserialize plugin instance content"
            );
            ChoosePluginError::InvalidPluginInstance {
                gts_id: gts_id.to_owned(),
                reason: e.to_string(),
            }
        })?;

        if content.id != gts_id {
            return Err(ChoosePluginError::InvalidPluginInstance {
                gts_id: gts_id.to_owned(),
                reason: format!(
                    "content.id mismatch: expected {:?}, got {:?}",
                    gts_id, content.id
                ),
            });
        }

        if content.vendor != vendor {
            continue;
        }

        match &best {
            None => best = Some((gts_id, content.priority)),
            Some((_, cur_priority)) => {
                if content.priority < *cur_priority {
                    best = Some((gts_id, content.priority));
                }
            }
        }
    }

    tracing::debug!(vendor, instance_count = count, "choose_plugin_instance");

    best.map(|(gts_id, _)| gts_id.to_owned())
        .ok_or_else(|| ChoosePluginError::PluginNotFound {
            type_id: P::TYPE_ID.to_owned(),
            vendor: vendor.to_owned(),
        })
}

/// Whether `gts_id` names an instance of spec `P` or of a type derived from it:
/// an ID under `P`'s type ID (which ends at a segment boundary, `~`) that is not
/// itself a type schema (a schema ID ends with `~`).
fn is_instance_of<P: gts::GtsSchema>(gts_id: &str) -> bool {
    P::TYPE_ID.ends_with('~')
        && !gts_id.ends_with('~')
        && gts_id
            .strip_prefix(P::TYPE_ID)
            .is_some_and(|rest| !rest.is_empty())
}

/// Bind `client` as the scoped `C` client of every instance of spec `P` in
/// `documents`: a plugin's `init` binds its client to the instances of its
/// admitted manifest ([`GearCtx::gts_publication_manifest`]).
///
/// [`GearCtx::gts_publication_manifest`]: crate::context::GearCtx::gts_publication_manifest
///
/// `documents` are the manifest's `(gts::GtsId, document)` pairs, or any pairs with
/// an id that is a string.
///
/// # Errors
/// `documents` holds no instance of `P`.
pub fn bind_plugin_instances<'a, P, C>(
    hub: &ClientHub,
    documents: impl IntoIterator<Item = &'a (impl AsRef<str> + 'a, serde_json::Value)>,
    client: &Arc<C>,
) -> anyhow::Result<()>
where
    P: gts::GtsSchema,
    C: ?Sized + Send + Sync + 'static,
{
    let mut bound = 0usize;
    for (id, _) in documents {
        let id = id.as_ref();
        if is_instance_of::<P>(id) {
            hub.register_scoped::<C>(ClientScope::gts_id(id), Arc::clone(client));
            tracing::info!(gts_id = %id, "plugin instance admitted and bound");
            bound += 1;
        }
    }
    anyhow::ensure!(bound > 0, "no instance of {} to bind", P::TYPE_ID);
    Ok(())
}

/// [`choose_plugin_instance`] among entries with a scoped `C` client in `hub`
/// under [`ClientScope::gts_id`]. Checks registration, not health.
///
/// Skips unregistered entries without validation, tolerating stale catalogue data.
/// Registered entries retain listing order; the first wins a priority tie.
/// Select after all plugins bind in `init` so every local candidate is visible.
///
/// Callers must pair `C` with the listing's `P` and subsequent scoped lookup;
/// types do not enforce this. Registered content must decode as `PluginV1<P>`
/// with `id == gts_id`.
///
/// # Errors
/// - [`ChoosePluginError::InvalidPluginInstance`] for missing registered content
///   (checked before decoding), or as [`choose_plugin_instance`] reports.
/// - [`ChoosePluginError::PluginNotFound`] if no registered instance matches the vendor.
pub fn choose_registered_plugin_instance<'a, P, C>(
    hub: &ClientHub,
    vendor: &str,
    instances: impl IntoIterator<Item = (&'a str, Option<&'a serde_json::Value>)>,
) -> Result<String, ChoosePluginError>
where
    P: for<'de> gts::GtsDeserialize<'de> + gts::GtsSchema,
    C: ?Sized + Send + Sync + 'static,
{
    let registered = instances
        .into_iter()
        .filter(|(gts_id, _)| {
            hub.try_get_scoped::<C>(&ClientScope::gts_id(gts_id))
                .is_some()
        })
        .map(|(gts_id, content)| {
            content.map(|content| (gts_id, content)).ok_or_else(|| {
                ChoosePluginError::InvalidPluginInstance {
                    gts_id: gts_id.to_owned(),
                    reason: "listed without content".to_owned(),
                }
            })
        })
        .collect::<Result<Vec<_>, _>>()?;
    choose_plugin_instance::<P>(vendor, registered)
}

#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
mod tests {
    use super::*;
    use std::sync::Arc;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use toolkit_gts::gts_id;

    const PLUGIN_A: &str =
        gts_id!("cf.toolkit.plugins.plugin.v1~cf.core.test.plugin.v1~vendor.a.test.plugin.v1");
    const PLUGIN_B: &str =
        gts_id!("cf.toolkit.plugins.plugin.v1~cf.core.test.plugin.v1~vendor.b.test.plugin.v1");
    const CONCURRENT_PLUGIN: &str = gts_id!(
        "cf.toolkit.plugins.plugin.v1~cf.core.test.plugin.v1~vendor.concurrent.test.plugin.v1"
    );

    #[tokio::test]
    async fn resolve_called_once_returns_same_str() {
        let selector = GtsPluginSelector::new();
        let calls = Arc::new(AtomicUsize::new(0));

        let calls_a = calls.clone();
        let id_a = selector
            .get_or_init(|| async move {
                calls_a.fetch_add(1, Ordering::SeqCst);
                Ok::<_, std::convert::Infallible>(PLUGIN_A.to_owned())
            })
            .await
            .unwrap();

        let calls_b = calls.clone();
        let id_b = selector
            .get_or_init(|| async move {
                calls_b.fetch_add(1, Ordering::SeqCst);
                Ok::<_, std::convert::Infallible>(PLUGIN_B.to_owned())
            })
            .await
            .unwrap();

        assert_eq!(id_a, id_b);
        assert_eq!(calls.load(Ordering::SeqCst), 1);
    }

    #[tokio::test]
    async fn reset_triggers_reselection() {
        let selector = GtsPluginSelector::new();
        let calls = Arc::new(AtomicUsize::new(0));

        let calls_a = calls.clone();
        let id_a = selector
            .get_or_init(|| async move {
                calls_a.fetch_add(1, Ordering::SeqCst);
                Ok::<_, std::convert::Infallible>(PLUGIN_A.to_owned())
            })
            .await;
        assert_eq!(&*id_a.unwrap(), PLUGIN_A);
        assert_eq!(calls.load(Ordering::SeqCst), 1);
        assert!(selector.reset().await);

        let calls_b = calls.clone();
        let id_b = selector
            .get_or_init(|| async move {
                calls_b.fetch_add(1, Ordering::SeqCst);
                Ok::<_, std::convert::Infallible>(PLUGIN_B.to_owned())
            })
            .await;
        assert_eq!(&*id_b.unwrap(), PLUGIN_B);
        assert_eq!(calls.load(Ordering::SeqCst), 2);
    }

    #[tokio::test]
    async fn concurrent_get_or_init_resolves_once() {
        let selector = Arc::new(GtsPluginSelector::new());
        let calls = Arc::new(AtomicUsize::new(0));

        let mut handles = Vec::new();
        for _ in 0..10 {
            let selector = Arc::clone(&selector);
            let calls = Arc::clone(&calls);
            handles.push(tokio::spawn(async move {
                selector
                    .get_or_init(|| async {
                        // Small delay to increase chance of concurrent access
                        tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
                        calls.fetch_add(1, Ordering::SeqCst);
                        Ok::<_, std::convert::Infallible>(CONCURRENT_PLUGIN.to_owned())
                    })
                    .await
            }));
        }

        // Await each handle in a loop (no futures_util dependency)
        let mut results = Vec::new();
        for handle in handles {
            results.push(handle.await.unwrap().unwrap());
        }

        // All results should be the same
        for id in &results {
            assert_eq!(&**id, CONCURRENT_PLUGIN);
        }

        // Resolve should have been called exactly once
        assert_eq!(calls.load(Ordering::SeqCst), 1);
    }

    mod choose_registered {
        use super::*;
        use serde_json::{Value, json};
        use toolkit_gts::gts_type_schema;

        #[derive(Default)]
        #[gts_type_schema(
            dir_path = "schemas",
            base = PluginV1,
            type_id = gts_id!("cf.toolkit.plugins.plugin.v1~cf.core.test.plugin.v1~"),
            description = "Test plugin specification",
            properties = "",
        )]
        struct TestPluginSpecV1;

        /// Another contract's spec: its instances never compete with the test spec's.
        #[derive(Default)]
        #[gts_type_schema(
            dir_path = "schemas",
            base = PluginV1,
            type_id = gts_id!("cf.toolkit.plugins.plugin.v1~cf.core.other_test.plugin.v1~"),
            description = "Other test plugin specification",
            properties = "",
        )]
        struct OtherPluginSpecV1;

        trait TestClient: Send + Sync {}
        trait OtherClient: Send + Sync {}
        struct Client;
        impl TestClient for Client {}
        impl OtherClient for Client {}

        /// A valid instance of `name`; its id and content.
        fn instance(name: &str, vendor: &str, priority: i16) -> (String, Value) {
            let (id, content) = PluginV1::<TestPluginSpecV1>::build_registration(
                &format!("vendor.x.{name}.plugin.v1"),
                vendor,
                priority,
            )
            .expect("serializes");
            (id.to_string(), content)
        }

        fn register(hub: &ClientHub, gts_id: &str) {
            hub.register_scoped::<dyn TestClient>(ClientScope::gts_id(gts_id), Arc::new(Client));
        }

        fn choose(
            hub: &ClientHub,
            listed: &[(String, Option<Value>)],
        ) -> Result<String, ChoosePluginError> {
            choose_registered_plugin_instance::<TestPluginSpecV1, dyn TestClient>(
                hub,
                "acme",
                listed
                    .iter()
                    .map(|(id, content)| (id.as_str(), content.as_ref())),
            )
        }

        #[test]
        fn unregistered_entries_are_skipped_unexamined() {
            let hub = ClientHub::new();
            let (missing, _) = instance("missing", "acme", 0);
            let (malformed, _) = instance("malformed", "acme", 0);
            let (preferred, preferred_content) = instance("preferred", "acme", -10);
            let (running, running_content) = instance("running", "acme", 5);
            let (elsewhere, elsewhere_content) = instance("elsewhere", "acme", -20);
            register(&hub, &running);
            // Registered for another client type: not a candidate for this one.
            hub.register_scoped::<dyn OtherClient>(
                ClientScope::gts_id(&elsewhere),
                Arc::new(Client),
            );

            let chosen = choose(
                &hub,
                &[
                    (missing, None),
                    (malformed, Some(json!({ "bogus": true }))),
                    (preferred, Some(preferred_content)),
                    (running.clone(), Some(running_content)),
                    (elsewhere, Some(elsewhere_content)),
                ],
            )
            .expect("chooses");
            assert_eq!(chosen, running);
        }

        #[test]
        fn the_lowest_registered_priority_of_the_vendor_wins_and_the_first_on_a_tie() {
            let hub = ClientHub::new();
            let listed: Vec<_> = [
                instance("low", "acme", 5),
                instance("other_vendor", "other", -5),
                instance("tie_first", "acme", 1),
                instance("tie_second", "acme", 1),
            ]
            .into_iter()
            .map(|(id, content)| {
                register(&hub, &id);
                (id, Some(content))
            })
            .collect();

            assert_eq!(choose(&hub, &listed).expect("chooses"), listed[2].0);
        }

        #[test]
        fn a_registered_entry_without_content_is_invalid_before_any_is_read() {
            let hub = ClientHub::new();
            let (malformed, _) = instance("malformed", "acme", 0);
            let (missing, _) = instance("missing", "acme", 0);
            register(&hub, &malformed);
            register(&hub, &missing);

            let error = choose(
                &hub,
                &[
                    (malformed, Some(json!({ "bogus": true }))),
                    (missing.clone(), None),
                ],
            )
            .expect_err("refused");
            assert!(
                matches!(&error, ChoosePluginError::InvalidPluginInstance { gts_id, reason }
                    if *gts_id == missing && reason == "listed without content"),
                "{error:?}"
            );
        }

        #[test]
        fn a_malformed_or_misnamed_registered_entry_is_invalid() {
            let hub = ClientHub::new();
            let (malformed, _) = instance("malformed", "other", 0);
            let (good, good_content) = instance("good", "acme", 0);
            let (misnamed, _) = instance("misnamed", "acme", 0);
            for id in [&malformed, &good, &misnamed] {
                register(&hub, id);
            }

            let error = choose(
                &hub,
                &[
                    (good, Some(good_content.clone())),
                    (malformed.clone(), Some(json!({ "bogus": true }))),
                ],
            )
            .expect_err("refused");
            assert!(
                matches!(&error, ChoosePluginError::InvalidPluginInstance { gts_id, .. } if *gts_id == malformed),
                "{error:?}"
            );

            let error =
                choose(&hub, &[(misnamed.clone(), Some(good_content))]).expect_err("refused");
            assert!(
                matches!(&error, ChoosePluginError::InvalidPluginInstance { gts_id, .. } if *gts_id == misnamed),
                "{error:?}"
            );
        }

        /// Two plugins of one contract and vendor, the better one bound last: the
        /// first selection after every plugin bound — all bind in their `init`,
        /// before anything is served — chooses it, and a cached choice is that one.
        #[tokio::test]
        async fn the_first_selection_after_every_binding_chooses_the_best_bound_plugin() {
            let hub = ClientHub::new();
            let (fast, fast_content) = instance("fast", "acme", 5);
            let (best, best_content) = instance("best", "acme", 1);
            register(&hub, &fast);
            register(&hub, &best);
            let selector = GtsPluginSelector::new();
            let listing = vec![
                (fast, Some(fast_content)),
                (best.clone(), Some(best_content)),
            ];

            let chosen = selector
                .get_or_init(|| async { choose(&hub, &listing) })
                .await
                .expect("chooses");

            assert_eq!(&*chosen, best);
        }

        /// A stale instance in the catalogue that no client was bound for here —
        /// a plugin removed or disabled since — is never chosen, however it ranks.
        #[test]
        fn a_stale_unbound_instance_is_never_chosen() {
            let hub = ClientHub::new();
            let (stale, stale_content) = instance("stale", "acme", -100);
            let (bound, bound_content) = instance("bound", "acme", 10);
            register(&hub, &bound);

            let chosen = choose(
                &hub,
                &[
                    (stale, Some(stale_content)),
                    (bound.clone(), Some(bound_content)),
                ],
            )
            .expect("chooses");

            assert_eq!(chosen, bound);
        }

        /// A plugin's `init` binds the client under each admitted instance of the
        /// spec, and refuses a manifest without one.
        #[test]
        fn binding_admitted_instances_binds_only_the_specs_instances() {
            let hub = ClientHub::new();
            let spec = <TestPluginSpecV1 as gts::GtsSchema>::TYPE_ID;
            let (mine, mine_content) = instance("mine", "acme", 1);
            let derived = format!("{spec}vendor.x.derived.plugin.v1~vendor.x.mine.plugin.v1");
            let derived_schema = format!("{spec}vendor.x.derived.plugin.v1~");
            let other = PluginV1::<OtherPluginSpecV1>::build_registration(
                "vendor.x.o.plugin.v1",
                "acme",
                1,
            )
            .expect("serializes");
            let manifest = [
                (mine.clone(), mine_content),
                (derived.clone(), json!({})),
                (derived_schema.clone(), json!({})),
                (spec.to_owned(), json!({})),
                (other.0.as_ref().to_owned(), other.1),
            ];
            let client: Arc<dyn TestClient> = Arc::new(Client);
            let bound = |id: &str| {
                hub.try_get_scoped::<dyn TestClient>(&ClientScope::gts_id(id))
                    .is_some()
            };

            bind_plugin_instances::<TestPluginSpecV1, dyn TestClient>(&hub, &manifest, &client)
                .expect("binds");

            assert!(
                bound(&mine) && bound(&derived),
                "the spec's instances, derived included"
            );
            assert!(
                !bound(&derived_schema) && !bound(spec),
                "type schemas are not bound"
            );
            assert!(
                !bound(other.0.as_ref()),
                "another spec's instance is not bound"
            );
            assert!(
                bind_plugin_instances::<TestPluginSpecV1, dyn TestClient>(
                    &hub,
                    &manifest[2..],
                    &client
                )
                .is_err(),
                "a manifest without an instance of the spec"
            );

            // A manifest's parsed ids bind the same instances.
            let typed_hub = ClientHub::new();
            let typed: Vec<(gts::GtsId, serde_json::Value)> = manifest
                .iter()
                .map(|(id, content)| (gts::GtsId::try_new(id).expect("valid"), content.clone()))
                .collect();
            bind_plugin_instances::<TestPluginSpecV1, _>(&typed_hub, &typed, &client)
                .expect("binds");
            let bound = |id: &str| {
                typed_hub
                    .try_get_scoped::<dyn TestClient>(&ClientScope::gts_id(id))
                    .is_some()
            };
            assert!(bound(&mine) && bound(&derived));
            assert!(!bound(&derived_schema) && !bound(spec) && !bound(other.0.as_ref()));
        }

        #[test]
        fn nothing_registered_is_not_found() {
            let (id, content) = instance("listed", "acme", 0);
            let error = choose(&ClientHub::new(), &[(id, Some(content))]).expect_err("refused");
            assert!(
                matches!(error, ChoosePluginError::PluginNotFound { .. }),
                "{error:?}"
            );
        }
    }
}