Skip to main content

toolkit/
context.rs

1use serde::de::DeserializeOwned;
2use std::sync::Arc;
3use tokio_util::sync::CancellationToken;
4use toolkit_contract::runtime::config::InternalTokenProvider;
5use uuid::Uuid;
6
7// Import configuration types from the config gear
8use crate::{
9    config::{ConfigError, ConfigProvider, gear_config_or_default},
10    gear_config_required,
11};
12
13/// Database manager type, available with the `db` feature.
14#[cfg(feature = "db")]
15pub(crate) type DbManager = toolkit_db::DbManager;
16/// Database provider type, available with the `db` feature.
17#[cfg(feature = "db")]
18pub(crate) type DbProvider = toolkit_db::DBProvider<toolkit_db::DbError>;
19
20#[derive(Clone)]
21#[must_use]
22pub struct GearCtx {
23    gear_name: Arc<str>,
24    instance_id: Uuid,
25    config_provider: Arc<dyn ConfigProvider>,
26    client_hub: Arc<crate::client_hub::ClientHub>,
27    cancellation_token: CancellationToken,
28    internal_token_provider: Option<InternalTokenProvider>,
29    /// This gear's admitted GTS manifest; see [`GearCtx::gts_publication_manifest`].
30    gts_publication_manifest: Option<Arc<crate::gts_publication::GtsManifest>>,
31    #[cfg(feature = "db")]
32    db: Option<DbProvider>,
33}
34
35/// Builder for creating gear-scoped contexts with resolved database handles.
36///
37/// Use [`GearContextBuilder::with_db_manager`] (feature `db`) to attach a
38/// `DbManager` so `for_gear` can resolve a per-gear `DbHandle`.
39#[must_use]
40pub struct GearContextBuilder {
41    instance_id: Uuid,
42    config_provider: Arc<dyn ConfigProvider>,
43    client_hub: Arc<crate::client_hub::ClientHub>,
44    root_token: CancellationToken,
45    internal_token_provider: Option<InternalTokenProvider>,
46    /// Admitted manifests by gear, filled once the application group's
47    /// publication is admitted and before any application `init`.
48    gts_publication_manifests: GtsAdmittedManifests,
49    #[cfg(feature = "db")]
50    db_manager: Option<Arc<DbManager>>, // internal only, never exposed to gears
51}
52
53impl GearContextBuilder {
54    pub fn new(
55        instance_id: Uuid,
56        config_provider: Arc<dyn ConfigProvider>,
57        client_hub: Arc<crate::client_hub::ClientHub>,
58        root_token: CancellationToken,
59    ) -> Self {
60        Self {
61            instance_id,
62            config_provider,
63            client_hub,
64            root_token,
65            internal_token_provider: None,
66            gts_publication_manifests: GtsAdmittedManifests::default(),
67            #[cfg(feature = "db")]
68            db_manager: None,
69        }
70    }
71
72    /// Set the process-wide platform-plane credential source applied to every
73    /// built [`GearCtx`]. See [`GearCtx::internal_token_provider`].
74    pub fn with_internal_token_provider(mut self, provider: Option<InternalTokenProvider>) -> Self {
75        self.internal_token_provider = provider;
76        self
77    }
78
79    /// The store the runtime fills with each gear's admitted manifest; every
80    /// context built afterwards reads its gear's manifest from it.
81    #[must_use]
82    pub(crate) fn gts_admitted_manifests(&self) -> GtsAdmittedManifests {
83        self.gts_publication_manifests.clone()
84    }
85
86    /// Attach a `DbManager` used by [`for_gear`](Self::for_gear) to resolve
87    /// per-gear database handles.
88    #[cfg(feature = "db")]
89    pub fn with_db_manager(mut self, db_manager: Arc<DbManager>) -> Self {
90        self.db_manager = Some(db_manager);
91        self
92    }
93
94    /// Returns the process-level instance ID.
95    #[must_use]
96    pub fn instance_id(&self) -> Uuid {
97        self.instance_id
98    }
99
100    /// The process-wide platform-plane credential source, if any. Used by the
101    /// runtime proxy-wiring phase to thread the credential into
102    /// directory-resolving (`#[toolkit::consumes]`) clients.
103    #[must_use]
104    pub(crate) fn internal_token_provider(&self) -> Option<&InternalTokenProvider> {
105        self.internal_token_provider.as_ref()
106    }
107
108    /// Build the context of a gear's `pre_init`: like [`for_gear`](Self::for_gear),
109    /// but with no database handle and no admitted GTS manifest, since the
110    /// gear's group is neither migrated nor published yet.
111    pub(crate) fn for_gear_before_migrations(&self, gear_name: &str) -> GearCtx {
112        GearCtx::new(
113            Arc::<str>::from(gear_name),
114            self.instance_id,
115            self.config_provider.clone(),
116            self.client_hub.clone(),
117            self.root_token.child_token(),
118        )
119        .with_internal_token_provider(self.internal_token_provider.clone())
120    }
121
122    /// Build a gear-scoped context, resolving the `DbHandle` for the given
123    /// gear when the `db` feature is enabled.
124    ///
125    /// Kept `async` in both configurations so callers don't need cfg branches
126    /// around `.await`; under `not(feature = "db")` the future is ready on
127    /// first poll.
128    ///
129    /// # Errors
130    /// Returns an error if database resolution fails.
131    #[cfg_attr(not(feature = "db"), allow(clippy::unused_async))]
132    pub async fn for_gear(&self, gear_name: &str) -> anyhow::Result<GearCtx> {
133        let ctx = GearCtx::new(
134            Arc::<str>::from(gear_name),
135            self.instance_id,
136            self.config_provider.clone(),
137            self.client_hub.clone(),
138            self.root_token.child_token(),
139        )
140        .with_internal_token_provider(self.internal_token_provider.clone());
141        let ctx = match self.gts_publication_manifests.get(gear_name) {
142            Some(manifest) => ctx.with_gts_publication_manifest(manifest),
143            None => ctx,
144        };
145        #[cfg(feature = "db")]
146        let ctx = if let Some(mgr) = &self.db_manager
147            && let Some(handle) = mgr.get(gear_name).await?
148        {
149            ctx.with_db(toolkit_db::DBProvider::new(handle))
150        } else {
151            ctx
152        };
153        Ok(ctx)
154    }
155}
156
157/// Each gear's admitted GTS manifest, by gear name. Written once by the
158/// runtime when the application group's publication is admitted; the
159/// manifests are never rebuilt from the configuration afterwards.
160#[derive(Clone, Default)]
161pub(crate) struct GtsAdmittedManifests(
162    Arc<
163        parking_lot::RwLock<
164            std::collections::HashMap<String, Arc<crate::gts_publication::GtsManifest>>,
165        >,
166    >,
167);
168
169impl GtsAdmittedManifests {
170    /// Record `manifest` as admitted for its publisher gear.
171    pub(crate) fn insert(&self, manifest: Arc<crate::gts_publication::GtsManifest>) {
172        self.0
173            .write()
174            .insert(manifest.publisher_name().to_owned(), manifest);
175    }
176
177    /// The admitted manifest of `gear`, if any.
178    #[must_use]
179    fn get(&self, gear: &str) -> Option<Arc<crate::gts_publication::GtsManifest>> {
180        self.0.read().get(gear).cloned()
181    }
182}
183
184impl GearCtx {
185    /// Create a new gear-scoped context with all required fields.
186    ///
187    /// Attach a database entrypoint with [`with_db`](Self::with_db) (feature `db`).
188    pub fn new(
189        gear_name: impl Into<Arc<str>>,
190        instance_id: Uuid,
191        config_provider: Arc<dyn ConfigProvider>,
192        client_hub: Arc<crate::client_hub::ClientHub>,
193        cancellation_token: CancellationToken,
194    ) -> Self {
195        let gear_name: Arc<str> = gear_name.into();
196        let client_hub = if client_hub.owner() == Some(&*gear_name) {
197            client_hub
198        } else {
199            client_hub.for_gear(Arc::clone(&gear_name))
200        };
201        Self {
202            client_hub,
203            gear_name,
204            instance_id,
205            config_provider,
206            cancellation_token,
207            internal_token_provider: None,
208            gts_publication_manifest: None,
209            #[cfg(feature = "db")]
210            db: None,
211        }
212    }
213
214    /// Attach the process-wide platform-plane credential source.
215    ///
216    /// **Wiring-only** (`#[doc(hidden)]`): set by [`GearContextBuilder::for_gear`]
217    /// from the bootstrap-selected `InternalCredential`, not part of the public
218    /// gear-facing API. See [`GearCtx::internal_token_provider`] for why the
219    /// credential is kept off the gear API.
220    #[doc(hidden)]
221    pub fn with_internal_token_provider(mut self, provider: Option<InternalTokenProvider>) -> Self {
222        self.internal_token_provider = provider;
223        self
224    }
225
226    /// The process-wide platform-plane credential source, if any.
227    ///
228    /// **Wiring-only.** This is `#[doc(hidden)]` and intended solely for the
229    /// `#[toolkit::provides]`-generated wiring, which moves it onto a generated
230    /// client's [`ClientConfig`](toolkit_contract::runtime::config::ClientConfig)
231    /// so platform-plane methods attach `X-ToolKit-Internal-Token`. It is **not**
232    /// part of the public gear-facing API: the two-plane design injects the
233    /// platform credential *below* the contract layer, and gear/plugin code must
234    /// not read it — `InternalTokenProvider::current()` yields the rotating
235    /// process credential that grants access to every system service, so exposing
236    /// it to arbitrary co-hosted (incl. third-party) gears would let them forge
237    /// platform-plane requests (`cpt-cf-adr-two-plane-auth`).
238    ///
239    /// `None` (Profile 1 / in-process) means platform-plane calls attach no
240    /// credential.
241    #[doc(hidden)]
242    #[must_use]
243    pub fn internal_token_provider(&self) -> Option<InternalTokenProvider> {
244        self.internal_token_provider.clone()
245    }
246
247    /// Attach this gear's admitted GTS manifest: the runtime's, after the barrier.
248    pub(crate) fn with_gts_publication_manifest(
249        mut self,
250        manifest: Arc<crate::gts_publication::GtsManifest>,
251    ) -> Self {
252        self.gts_publication_manifest = Some(manifest);
253        self
254    }
255
256    /// Attach an admitted-manifest fixture in downstream gear tests.
257    ///
258    /// Requires the `test-support` feature, enabled through a dev-dependency.
259    /// This bypasses publication; tests of admission must exercise the runtime
260    /// or publish through `PreparedGtsPublication` before using this helper.
261    #[cfg(feature = "test-support")]
262    pub fn with_gts_publication_manifest_for_test(
263        self,
264        manifest: Arc<crate::gts_publication::GtsManifest>,
265    ) -> Self {
266        self.with_gts_publication_manifest(manifest)
267    }
268
269    /// The documents of this gear's `gts_publication(...)`, admitted before `init`.
270    /// Plugins bind scoped clients to its instances. This is the published manifest,
271    /// never rebuilt from configuration.
272    ///
273    /// # Errors
274    /// No `gts_publication(...)` declaration, or no admitted manifest in this context
275    /// (e.g. during `pre_init` or outside the runtime).
276    pub fn gts_publication_manifest(
277        &self,
278    ) -> anyhow::Result<Arc<crate::gts_publication::GtsManifest>> {
279        self.gts_publication_manifest.clone().ok_or_else(|| {
280            anyhow::anyhow!(
281                "gear '{}' has no admitted GTS manifest: it declares no `gts_publication(...)`, or the \
282                 runtime did not publish it",
283                self.gear_name
284            )
285        })
286    }
287
288    /// Attach the per-gear database entrypoint.
289    #[cfg(feature = "db")]
290    pub fn with_db(mut self, db: DbProvider) -> Self {
291        self.db = Some(db);
292        self
293    }
294
295    // ---- public read-only API for gears ----
296
297    #[inline]
298    #[must_use]
299    pub fn gear_name(&self) -> &str {
300        &self.gear_name
301    }
302
303    /// Returns the process-level instance ID.
304    ///
305    /// This is a unique identifier for this process instance, shared by all gears
306    /// in the same process. It is generated once at bootstrap.
307    #[inline]
308    #[must_use]
309    pub fn instance_id(&self) -> Uuid {
310        self.instance_id
311    }
312
313    #[inline]
314    #[must_use]
315    pub fn config_provider(&self) -> &dyn ConfigProvider {
316        &*self.config_provider
317    }
318
319    /// Get this gear's view of the `ClientHub` for dependency resolution.
320    ///
321    /// Local registrations are shared by all gears; remote proxies wired by
322    /// this gear's `#[toolkit::consumes]` are its own (see
323    /// [`ClientHub::for_gear`](crate::client_hub::ClientHub::for_gear)).
324    #[inline]
325    #[must_use]
326    pub fn client_hub(&self) -> Arc<crate::client_hub::ClientHub> {
327        self.client_hub.clone()
328    }
329
330    #[inline]
331    #[must_use]
332    pub fn cancellation_token(&self) -> &CancellationToken {
333        &self.cancellation_token
334    }
335
336    /// Get a gear-scoped DB entrypoint for secure database operations.
337    ///
338    /// Returns `None` if no database is configured for this gear.
339    ///
340    /// # Security
341    ///
342    /// The returned `DBProvider<toolkit_db::DbError>`:
343    /// - Is cheap to clone (shares an internal `Db`)
344    /// - Provides `conn()` for non-transactional access (fails inside tx via guard)
345    /// - Provides `transaction(..)` for transactional operations
346    ///
347    /// # Example
348    ///
349    /// ```ignore
350    /// let db = ctx.db().ok_or_else(|| anyhow!("no db"))?;
351    /// let conn = db.conn()?;
352    /// let user = svc.get_user(&conn, &scope, id).await?;
353    /// ```
354    #[must_use]
355    #[cfg(feature = "db")]
356    pub fn db(&self) -> Option<toolkit_db::DBProvider<toolkit_db::DbError>> {
357        self.db.clone()
358    }
359
360    /// Get a database handle, returning an error if not configured.
361    ///
362    /// This is a convenience method that combines `db()` with an error for
363    /// gears that require database access.
364    ///
365    /// # Errors
366    ///
367    /// Returns an error if the database is not configured for this gear.
368    ///
369    /// # Example
370    ///
371    /// ```ignore
372    /// let db = ctx.db_required()?;
373    /// let conn = db.conn()?;
374    /// let user = svc.get_user(&conn, &scope, id).await?;
375    /// ```
376    #[cfg(feature = "db")]
377    pub fn db_required(&self) -> anyhow::Result<toolkit_db::DBProvider<toolkit_db::DbError>> {
378        self.db().ok_or_else(|| {
379            anyhow::anyhow!("Database is not configured for gear '{}'", self.gear_name)
380        })
381    }
382
383    /// Deserialize the gear's config section into `T`.
384    ///
385    /// This reads the `gears.<name>.config` object for the current gear and
386    /// deserializes it into the requested type.
387    ///
388    /// # Errors
389    /// Returns `ConfigError` if the gear config is missing or deserialization fails.
390    pub fn config<T: DeserializeOwned>(&self) -> Result<T, ConfigError> {
391        gear_config_required(self.config_provider.as_ref(), &self.gear_name)
392    }
393
394    /// Deserialize the gear's config section into T, or use defaults if missing.
395    ///
396    /// This method uses lenient configuration loading: if the gear is not present in config,
397    /// has no config section, or the gear entry is not an object, it returns `T::default()`.
398    /// This allows gears to exist without configuration sections in the main config file.
399    ///
400    /// It extracts the 'config' field from: `gears.<name> = { database: ..., config: ... }`
401    ///
402    /// # Example
403    ///
404    /// ```rust,ignore
405    /// #[derive(serde::Deserialize, Default)]
406    /// struct MyConfig {
407    ///     api_key: String,
408    ///     timeout_ms: u64,
409    /// }
410    ///
411    /// let config: MyConfig = ctx.config_or_default()?;
412    /// ```
413    ///
414    /// # Errors
415    /// Returns `ConfigError` if deserialization fails.
416    pub fn config_or_default<T: DeserializeOwned + Default>(&self) -> Result<T, ConfigError> {
417        gear_config_or_default(self.config_provider.as_ref(), &self.gear_name)
418    }
419
420    /// Like [`config()`](Self::config), but additionally expands `${VAR}` placeholders
421    /// in fields marked with `#[expand_vars]`.
422    ///
423    /// # Errors
424    /// Returns `ConfigError` if the gear config is missing, deserialization fails,
425    /// or environment variable expansion fails.
426    pub fn config_expanded<T>(&self) -> Result<T, ConfigError>
427    where
428        T: DeserializeOwned + crate::var_expand::ExpandVars,
429    {
430        let mut cfg: T = self.config()?;
431        cfg.expand_vars().map_err(|e| ConfigError::VarExpand {
432            gear: self.gear_name.to_string(),
433            cause: e,
434        })?;
435        Ok(cfg)
436    }
437
438    /// Like [`config_or_default()`](Self::config_or_default), but additionally expands `${VAR}`
439    /// placeholders
440    /// in fields marked with `#[expand_vars]` (requires `#[derive(ExpandVars)]` on the config
441    /// struct).
442    ///
443    /// Gears that do not need environment variable expansion should use
444    /// [`config_or_default()`](Self::config_or_default).
445    ///
446    /// # Example
447    ///
448    /// ```rust,ignore
449    /// #[derive(serde::Deserialize, Default, ExpandVars)]
450    /// struct MyConfig {
451    ///     #[expand_vars]
452    ///     api_key: String,
453    ///     timeout_ms: u64,
454    /// }
455    ///
456    /// let config: MyConfig = ctx.config_expanded_or_default()?;
457    /// ```
458    ///
459    /// # Errors
460    /// Returns `ConfigError` if deserialization fails or if environment variable expansion fails.
461    pub fn config_expanded_or_default<T>(&self) -> Result<T, ConfigError>
462    where
463        T: DeserializeOwned + Default + crate::var_expand::ExpandVars,
464    {
465        let mut cfg: T = self.config_or_default()?;
466        cfg.expand_vars().map_err(|e| ConfigError::VarExpand {
467            gear: self.gear_name.to_string(),
468            cause: e,
469        })?;
470        Ok(cfg)
471    }
472
473    /// Get the raw JSON value of the gear's config section.
474    /// Returns the 'config' field from: gears.<name> = { database: ..., config: ... }
475    #[must_use]
476    pub fn raw_config(&self) -> &serde_json::Value {
477        use std::sync::LazyLock;
478
479        static EMPTY: LazyLock<serde_json::Value> =
480            LazyLock::new(|| serde_json::Value::Object(serde_json::Map::new()));
481
482        if let Some(gear_raw) = self.config_provider.get_gear_config(&self.gear_name) {
483            // Try new structure first: gears.<name> = { database: ..., config: ... }
484            if let Some(obj) = gear_raw.as_object()
485                && let Some(config_section) = obj.get("config")
486            {
487                return config_section;
488            }
489        }
490        &EMPTY
491    }
492
493    /// Create a derivative context with the same references but no DB handle.
494    /// Useful for gears that don't require database access.
495    pub fn without_db(&self) -> GearCtx {
496        GearCtx {
497            gear_name: self.gear_name.clone(),
498            instance_id: self.instance_id,
499            config_provider: self.config_provider.clone(),
500            client_hub: self.client_hub.clone(),
501            cancellation_token: self.cancellation_token.clone(),
502            internal_token_provider: self.internal_token_provider.clone(),
503            gts_publication_manifest: self.gts_publication_manifest.clone(),
504            #[cfg(feature = "db")]
505            db: None,
506        }
507    }
508}
509
510#[cfg(test)]
511#[cfg_attr(coverage_nightly, coverage(off))]
512mod tests {
513    use super::*;
514    use serde::Deserialize;
515    use serde_json::json;
516    use std::collections::HashMap;
517
518    #[derive(Debug, PartialEq, Deserialize, Default)]
519    struct TestConfig {
520        #[serde(default)]
521        api_key: String,
522        #[serde(default)]
523        timeout_ms: u64,
524        #[serde(default)]
525        enabled: bool,
526    }
527
528    struct MockConfigProvider {
529        gears: HashMap<String, serde_json::Value>,
530    }
531
532    impl MockConfigProvider {
533        fn new() -> Self {
534            let mut gears = HashMap::new();
535
536            // Valid gear config
537            gears.insert(
538                "test_gear".to_owned(),
539                json!({
540                    "database": {
541                        "url": "postgres://localhost/test"
542                    },
543                    "config": {
544                        "api_key": "secret123",
545                        "timeout_ms": 5000,
546                        "enabled": true
547                    }
548                }),
549            );
550
551            Self { gears }
552        }
553    }
554
555    impl ConfigProvider for MockConfigProvider {
556        fn get_gear_config(&self, gear_name: &str) -> Option<&serde_json::Value> {
557            self.gears.get(gear_name)
558        }
559    }
560
561    #[test]
562    fn test_gear_ctx_config_with_valid_config() {
563        let provider = Arc::new(MockConfigProvider::new());
564        let ctx = GearCtx::new(
565            "test_gear",
566            Uuid::new_v4(),
567            provider,
568            Arc::new(crate::client_hub::ClientHub::default()),
569            CancellationToken::new(),
570        );
571
572        let result: Result<TestConfig, ConfigError> = ctx.config();
573        assert!(result.is_ok());
574
575        let config = result.unwrap();
576        assert_eq!(config.api_key, "secret123");
577        assert_eq!(config.timeout_ms, 5000);
578        assert!(config.enabled);
579    }
580
581    #[test]
582    fn test_gear_ctx_config_returns_error_for_missing_gear() {
583        let provider = Arc::new(MockConfigProvider::new());
584        let ctx = GearCtx::new(
585            "nonexistent_gear",
586            Uuid::new_v4(),
587            provider,
588            Arc::new(crate::client_hub::ClientHub::default()),
589            CancellationToken::new(),
590        );
591
592        let result: Result<TestConfig, ConfigError> = ctx.config();
593        assert!(matches!(
594            result,
595            Err(ConfigError::GearNotFound { ref gear }) if gear == "nonexistent_gear"
596        ));
597    }
598
599    #[test]
600    fn test_gear_ctx_config_or_default_returns_default_for_missing_gear() {
601        let provider = Arc::new(MockConfigProvider::new());
602        let ctx = GearCtx::new(
603            "nonexistent_gear",
604            Uuid::new_v4(),
605            provider,
606            Arc::new(crate::client_hub::ClientHub::default()),
607            CancellationToken::new(),
608        );
609
610        let result: Result<TestConfig, ConfigError> = ctx.config_or_default();
611        assert!(result.is_ok());
612
613        let config = result.unwrap();
614        assert_eq!(config, TestConfig::default());
615    }
616
617    /// The `pre_init` context carries neither the database handle nor the
618    /// admitted GTS manifest that the later contexts of the same gear carry.
619    #[tokio::test]
620    async fn the_context_before_migrations_has_no_database_and_no_admitted_manifest() {
621        let builder = GearContextBuilder::new(
622            Uuid::new_v4(),
623            Arc::new(MockConfigProvider::new()),
624            Arc::new(crate::client_hub::ClientHub::default()),
625            CancellationToken::new(),
626        );
627        #[cfg(feature = "db")]
628        let (builder, _dir) = {
629            let dir = tempfile::TempDir::new().unwrap();
630            let dsn = format!("sqlite://{}", dir.path().join("gear.db").display());
631            let figment = figment::Figment::new().merge(figment::providers::Serialized::defaults(
632                json!({ "gears": { "test_gear": { "database": { "dsn": dsn } } } }),
633            ));
634            let manager = DbManager::from_figment(figment, dir.path().to_path_buf()).unwrap();
635            (builder.with_db_manager(Arc::new(manager)), dir)
636        };
637        builder.gts_admitted_manifests().insert(Arc::new(
638            crate::gts_publication::GtsManifest::build("test_gear", "1.0.0", Vec::new()).unwrap(),
639        ));
640
641        let later = builder.for_gear("test_gear").await.unwrap();
642        assert!(later.gts_publication_manifest().is_ok());
643        #[cfg(feature = "db")]
644        assert!(later.db().is_some());
645
646        let early = builder.for_gear_before_migrations("test_gear");
647        assert!(early.gts_publication_manifest().is_err());
648        #[cfg(feature = "db")]
649        assert!(early.db().is_none());
650        assert_eq!(early.gear_name(), "test_gear");
651    }
652
653    #[tokio::test]
654    async fn internal_token_provider_flows_from_builder_to_ctx() {
655        use std::sync::atomic::{AtomicBool, Ordering};
656
657        // The builder's provider must be threaded onto every `GearCtx` it
658        // builds, and `GearCtx::internal_token_provider()` must return the SAME
659        // provider (proven by observing the closure fire on `.current()`).
660        let invoked = Arc::new(AtomicBool::new(false));
661        let invoked_in_closure = Arc::clone(&invoked);
662        let provider = InternalTokenProvider::new(move || {
663            invoked_in_closure.store(true, Ordering::SeqCst);
664            toolkit_contract::runtime::config::CredentialState::NotConfigured
665        });
666
667        let builder = GearContextBuilder::new(
668            Uuid::new_v4(),
669            Arc::new(MockConfigProvider::new()),
670            Arc::new(crate::client_hub::ClientHub::default()),
671            CancellationToken::new(),
672        )
673        .with_internal_token_provider(Some(provider));
674
675        let ctx = builder.for_gear("test_gear").await.unwrap();
676        let threaded = ctx.internal_token_provider();
677        assert!(threaded.is_some(), "provider must be threaded onto GearCtx");
678
679        // Invoking it runs the original closure — confirming identity, not a
680        // freshly-defaulted provider. The configured closure yields no token.
681        assert!(matches!(
682            threaded.unwrap().current(),
683            toolkit_contract::runtime::config::CredentialState::NotConfigured
684        ));
685        assert!(
686            invoked.load(Ordering::SeqCst),
687            "the threaded provider must be the one configured on the builder"
688        );
689
690        // A builder without a provider yields a context with none (Profile 1).
691        let bare = GearContextBuilder::new(
692            Uuid::new_v4(),
693            Arc::new(MockConfigProvider::new()),
694            Arc::new(crate::client_hub::ClientHub::default()),
695            CancellationToken::new(),
696        )
697        .for_gear("test_gear")
698        .await
699        .unwrap();
700        assert!(bare.internal_token_provider().is_none());
701    }
702
703    #[test]
704    fn test_gear_ctx_instance_id() {
705        let provider = Arc::new(MockConfigProvider::new());
706        let instance_id = Uuid::new_v4();
707        let ctx = GearCtx::new(
708            "test_gear",
709            instance_id,
710            provider,
711            Arc::new(crate::client_hub::ClientHub::default()),
712            CancellationToken::new(),
713        );
714
715        assert_eq!(ctx.instance_id(), instance_id);
716    }
717
718    /// Issue #5686: a gear's context reads its own consumer proxy, not another
719    /// gear's. Built the way the runtime builds it, through the builder.
720    #[tokio::test]
721    async fn a_gear_ctx_reads_its_own_proxy() {
722        trait PingApi: Send + Sync {}
723        struct Ping;
724        impl PingApi for Ping {}
725
726        let hub = Arc::new(crate::client_hub::ClientHub::default());
727        let builder = GearContextBuilder::new(
728            Uuid::new_v4(),
729            Arc::new(MockConfigProvider::new()),
730            Arc::clone(&hub),
731            CancellationToken::new(),
732        );
733        let proxy: Arc<dyn PingApi> = Arc::new(Ping);
734        hub.for_gear("a")
735            .register_remote_proxy::<dyn PingApi>(Arc::clone(&proxy));
736
737        let a = builder.for_gear("a").await.unwrap();
738        let b = builder.for_gear("b").await.unwrap();
739
740        assert_eq!(a.client_hub().owner(), Some("a"));
741        assert!(Arc::ptr_eq(
742            &a.client_hub().get::<dyn PingApi>().unwrap(),
743            &proxy
744        ));
745        assert!(b.client_hub().try_get::<dyn PingApi>().is_none());
746    }
747
748    // --- config_expanded tests ---
749
750    #[derive(Debug, PartialEq, Deserialize, Default, toolkit_macros::ExpandVars)]
751    struct ExpandableConfig {
752        #[expand_vars]
753        #[serde(default)]
754        api_key: String,
755        #[expand_vars]
756        #[serde(default)]
757        endpoint: Option<String>,
758        #[serde(default)]
759        retries: u32,
760    }
761
762    fn make_ctx(gear_name: &str, config_json: serde_json::Value) -> GearCtx {
763        let mut gears = HashMap::new();
764        gears.insert(gear_name.to_owned(), config_json);
765        let provider = Arc::new(MockConfigProvider { gears });
766        GearCtx::new(
767            gear_name,
768            Uuid::new_v4(),
769            provider,
770            Arc::new(crate::client_hub::ClientHub::default()),
771            CancellationToken::new(),
772        )
773    }
774
775    #[test]
776    fn config_expanded_resolves_env_vars() {
777        let ctx = make_ctx(
778            "expand_mod",
779            json!({
780                "config": {
781                    "api_key": "${TOOLKIT_TEST_KEY}",
782                    "endpoint": "https://${TOOLKIT_TEST_HOST}/api",
783                    "retries": 3
784                }
785            }),
786        );
787
788        temp_env::with_vars(
789            [
790                ("TOOLKIT_TEST_KEY", Some("secret-42")),
791                ("TOOLKIT_TEST_HOST", Some("example.com")),
792            ],
793            || {
794                let cfg: ExpandableConfig = ctx.config_expanded().unwrap();
795                assert_eq!(cfg.api_key, "secret-42");
796                assert_eq!(cfg.endpoint.as_deref(), Some("https://example.com/api"));
797                assert_eq!(cfg.retries, 3);
798            },
799        );
800    }
801
802    #[test]
803    fn config_expanded_returns_error_on_missing_var() {
804        let ctx = make_ctx(
805            "expand_mod",
806            json!({
807                "config": {
808                    "api_key": "${TOOLKIT_TEST_MISSING_VAR_XYZ}"
809                }
810            }),
811        );
812
813        temp_env::with_vars([("TOOLKIT_TEST_MISSING_VAR_XYZ", None::<&str>)], || {
814            let err = ctx.config_expanded::<ExpandableConfig>().unwrap_err();
815            assert!(
816                matches!(err, ConfigError::VarExpand { ref gear, .. } if gear == "expand_mod"),
817                "expected EnvExpand error, got: {err:?}"
818            );
819        });
820    }
821
822    #[test]
823    fn config_expanded_skips_none_option_fields() {
824        let ctx = make_ctx(
825            "expand_mod",
826            json!({
827                "config": {
828                    "api_key": "literal-key",
829                    "retries": 5
830                }
831            }),
832        );
833
834        let cfg: ExpandableConfig = ctx.config_expanded().unwrap();
835        assert_eq!(cfg.api_key, "literal-key");
836        assert_eq!(cfg.endpoint, None);
837        assert_eq!(cfg.retries, 5);
838    }
839
840    #[test]
841    fn config_expanded_returns_error_when_missing() {
842        let ctx = make_ctx("missing_mod", json!({}));
843        let err = ctx.config_expanded::<ExpandableConfig>().unwrap_err();
844        assert!(matches!(
845            err,
846            ConfigError::MissingConfigSection { ref gear } if gear == "missing_mod"
847        ));
848    }
849
850    #[test]
851    fn config_expanded_or_default_falls_back_to_default_when_missing() {
852        let ctx = make_ctx("missing_mod", json!({}));
853        let cfg: ExpandableConfig = ctx.config_expanded_or_default().unwrap();
854        assert_eq!(cfg, ExpandableConfig::default());
855    }
856
857    // --- nested struct expansion ---
858
859    #[derive(Debug, PartialEq, Deserialize, Default, toolkit_macros::ExpandVars)]
860    struct NestedProvider {
861        #[expand_vars]
862        #[serde(default)]
863        host: String,
864        #[expand_vars]
865        #[serde(default)]
866        token: Option<String>,
867        #[expand_vars]
868        #[serde(default)]
869        auth_config: Option<HashMap<String, String>>,
870        #[serde(default)]
871        port: u16,
872    }
873
874    #[derive(Debug, PartialEq, Deserialize, Default, toolkit_macros::ExpandVars)]
875    struct NestedConfig {
876        #[expand_vars]
877        #[serde(default)]
878        name: String,
879        #[expand_vars]
880        #[serde(default)]
881        providers: HashMap<String, NestedProvider>,
882        #[expand_vars]
883        #[serde(default)]
884        tags: Vec<String>,
885    }
886
887    #[test]
888    fn config_expanded_resolves_nested_structs() {
889        let ctx = make_ctx(
890            "nested_mod",
891            json!({
892                "config": {
893                    "name": "${TOOLKIT_NESTED_NAME}",
894                    "providers": {
895                        "primary": {
896                            "host": "${TOOLKIT_NESTED_HOST}",
897                            "token": "${TOOLKIT_NESTED_TOKEN}",
898                            "auth_config": {
899                                "header": "X-Api-Key",
900                                "secret_ref": "${TOOLKIT_NESTED_SECRET}"
901                            },
902                            "port": 443
903                        }
904                    },
905                    "tags": ["${TOOLKIT_NESTED_TAG}", "literal"]
906                }
907            }),
908        );
909
910        temp_env::with_vars(
911            [
912                ("TOOLKIT_NESTED_NAME", Some("my-service")),
913                ("TOOLKIT_NESTED_HOST", Some("api.example.com")),
914                ("TOOLKIT_NESTED_TOKEN", Some("sk-secret")),
915                ("TOOLKIT_NESTED_SECRET", Some("key-12345")),
916                ("TOOLKIT_NESTED_TAG", Some("production")),
917            ],
918            || {
919                let cfg: NestedConfig = ctx.config_expanded().unwrap();
920                assert_eq!(cfg.name, "my-service");
921                assert_eq!(cfg.tags, vec!["production", "literal"]);
922
923                let primary = cfg.providers.get("primary").expect("primary provider");
924                assert_eq!(primary.host, "api.example.com");
925                assert_eq!(primary.token.as_deref(), Some("sk-secret"));
926                assert_eq!(primary.port, 443);
927
928                let auth = primary.auth_config.as_ref().expect("auth_config present");
929                assert_eq!(auth.get("header").map(String::as_str), Some("X-Api-Key"));
930                assert_eq!(
931                    auth.get("secret_ref").map(String::as_str),
932                    Some("key-12345")
933                );
934            },
935        );
936    }
937
938    #[test]
939    fn config_expanded_nested_missing_var_returns_error() {
940        let ctx = make_ctx(
941            "nested_mod",
942            json!({
943                "config": {
944                    "name": "ok",
945                    "providers": {
946                        "bad": { "host": "${TOOLKIT_NESTED_GONE}", "port": 80 }
947                    }
948                }
949            }),
950        );
951
952        temp_env::with_vars([("TOOLKIT_NESTED_GONE", None::<&str>)], || {
953            let err = ctx.config_expanded::<NestedConfig>().unwrap_err();
954            assert!(
955                matches!(err, ConfigError::VarExpand { ref gear, .. } if gear == "nested_mod"),
956                "expected EnvExpand, got: {err:?}"
957            );
958        });
959    }
960}