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    /// The documents of this gear's `gts_publication(...)`, admitted before `init`.
257    /// Plugins bind scoped clients to its instances. This is the published manifest,
258    /// never rebuilt from configuration.
259    ///
260    /// # Errors
261    /// No `gts_publication(...)` declaration, or no admitted manifest in this context
262    /// (e.g. during `pre_init` or outside the runtime).
263    pub fn gts_publication_manifest(
264        &self,
265    ) -> anyhow::Result<Arc<crate::gts_publication::GtsManifest>> {
266        self.gts_publication_manifest.clone().ok_or_else(|| {
267            anyhow::anyhow!(
268                "gear '{}' has no admitted GTS manifest: it declares no `gts_publication(...)`, or the \
269                 runtime did not publish it",
270                self.gear_name
271            )
272        })
273    }
274
275    /// Attach the per-gear database entrypoint.
276    #[cfg(feature = "db")]
277    pub fn with_db(mut self, db: DbProvider) -> Self {
278        self.db = Some(db);
279        self
280    }
281
282    // ---- public read-only API for gears ----
283
284    #[inline]
285    #[must_use]
286    pub fn gear_name(&self) -> &str {
287        &self.gear_name
288    }
289
290    /// Returns the process-level instance ID.
291    ///
292    /// This is a unique identifier for this process instance, shared by all gears
293    /// in the same process. It is generated once at bootstrap.
294    #[inline]
295    #[must_use]
296    pub fn instance_id(&self) -> Uuid {
297        self.instance_id
298    }
299
300    #[inline]
301    #[must_use]
302    pub fn config_provider(&self) -> &dyn ConfigProvider {
303        &*self.config_provider
304    }
305
306    /// Get this gear's view of the `ClientHub` for dependency resolution.
307    ///
308    /// Local registrations are shared by all gears; remote proxies wired by
309    /// this gear's `#[toolkit::consumes]` are its own (see
310    /// [`ClientHub::for_gear`](crate::client_hub::ClientHub::for_gear)).
311    #[inline]
312    #[must_use]
313    pub fn client_hub(&self) -> Arc<crate::client_hub::ClientHub> {
314        self.client_hub.clone()
315    }
316
317    #[inline]
318    #[must_use]
319    pub fn cancellation_token(&self) -> &CancellationToken {
320        &self.cancellation_token
321    }
322
323    /// Get a gear-scoped DB entrypoint for secure database operations.
324    ///
325    /// Returns `None` if no database is configured for this gear.
326    ///
327    /// # Security
328    ///
329    /// The returned `DBProvider<toolkit_db::DbError>`:
330    /// - Is cheap to clone (shares an internal `Db`)
331    /// - Provides `conn()` for non-transactional access (fails inside tx via guard)
332    /// - Provides `transaction(..)` for transactional operations
333    ///
334    /// # Example
335    ///
336    /// ```ignore
337    /// let db = ctx.db().ok_or_else(|| anyhow!("no db"))?;
338    /// let conn = db.conn()?;
339    /// let user = svc.get_user(&conn, &scope, id).await?;
340    /// ```
341    #[must_use]
342    #[cfg(feature = "db")]
343    pub fn db(&self) -> Option<toolkit_db::DBProvider<toolkit_db::DbError>> {
344        self.db.clone()
345    }
346
347    /// Get a database handle, returning an error if not configured.
348    ///
349    /// This is a convenience method that combines `db()` with an error for
350    /// gears that require database access.
351    ///
352    /// # Errors
353    ///
354    /// Returns an error if the database is not configured for this gear.
355    ///
356    /// # Example
357    ///
358    /// ```ignore
359    /// let db = ctx.db_required()?;
360    /// let conn = db.conn()?;
361    /// let user = svc.get_user(&conn, &scope, id).await?;
362    /// ```
363    #[cfg(feature = "db")]
364    pub fn db_required(&self) -> anyhow::Result<toolkit_db::DBProvider<toolkit_db::DbError>> {
365        self.db().ok_or_else(|| {
366            anyhow::anyhow!("Database is not configured for gear '{}'", self.gear_name)
367        })
368    }
369
370    /// Deserialize the gear's config section into `T`.
371    ///
372    /// This reads the `gears.<name>.config` object for the current gear and
373    /// deserializes it into the requested type.
374    ///
375    /// # Errors
376    /// Returns `ConfigError` if the gear config is missing or deserialization fails.
377    pub fn config<T: DeserializeOwned>(&self) -> Result<T, ConfigError> {
378        gear_config_required(self.config_provider.as_ref(), &self.gear_name)
379    }
380
381    /// Deserialize the gear's config section into T, or use defaults if missing.
382    ///
383    /// This method uses lenient configuration loading: if the gear is not present in config,
384    /// has no config section, or the gear entry is not an object, it returns `T::default()`.
385    /// This allows gears to exist without configuration sections in the main config file.
386    ///
387    /// It extracts the 'config' field from: `gears.<name> = { database: ..., config: ... }`
388    ///
389    /// # Example
390    ///
391    /// ```rust,ignore
392    /// #[derive(serde::Deserialize, Default)]
393    /// struct MyConfig {
394    ///     api_key: String,
395    ///     timeout_ms: u64,
396    /// }
397    ///
398    /// let config: MyConfig = ctx.config_or_default()?;
399    /// ```
400    ///
401    /// # Errors
402    /// Returns `ConfigError` if deserialization fails.
403    pub fn config_or_default<T: DeserializeOwned + Default>(&self) -> Result<T, ConfigError> {
404        gear_config_or_default(self.config_provider.as_ref(), &self.gear_name)
405    }
406
407    /// Like [`config()`](Self::config), but additionally expands `${VAR}` placeholders
408    /// in fields marked with `#[expand_vars]`.
409    ///
410    /// # Errors
411    /// Returns `ConfigError` if the gear config is missing, deserialization fails,
412    /// or environment variable expansion fails.
413    pub fn config_expanded<T>(&self) -> Result<T, ConfigError>
414    where
415        T: DeserializeOwned + crate::var_expand::ExpandVars,
416    {
417        let mut cfg: T = self.config()?;
418        cfg.expand_vars().map_err(|e| ConfigError::VarExpand {
419            gear: self.gear_name.to_string(),
420            cause: e,
421        })?;
422        Ok(cfg)
423    }
424
425    /// Like [`config_or_default()`](Self::config_or_default), but additionally expands `${VAR}`
426    /// placeholders
427    /// in fields marked with `#[expand_vars]` (requires `#[derive(ExpandVars)]` on the config
428    /// struct).
429    ///
430    /// Gears that do not need environment variable expansion should use
431    /// [`config_or_default()`](Self::config_or_default).
432    ///
433    /// # Example
434    ///
435    /// ```rust,ignore
436    /// #[derive(serde::Deserialize, Default, ExpandVars)]
437    /// struct MyConfig {
438    ///     #[expand_vars]
439    ///     api_key: String,
440    ///     timeout_ms: u64,
441    /// }
442    ///
443    /// let config: MyConfig = ctx.config_expanded_or_default()?;
444    /// ```
445    ///
446    /// # Errors
447    /// Returns `ConfigError` if deserialization fails or if environment variable expansion fails.
448    pub fn config_expanded_or_default<T>(&self) -> Result<T, ConfigError>
449    where
450        T: DeserializeOwned + Default + crate::var_expand::ExpandVars,
451    {
452        let mut cfg: T = self.config_or_default()?;
453        cfg.expand_vars().map_err(|e| ConfigError::VarExpand {
454            gear: self.gear_name.to_string(),
455            cause: e,
456        })?;
457        Ok(cfg)
458    }
459
460    /// Get the raw JSON value of the gear's config section.
461    /// Returns the 'config' field from: gears.<name> = { database: ..., config: ... }
462    #[must_use]
463    pub fn raw_config(&self) -> &serde_json::Value {
464        use std::sync::LazyLock;
465
466        static EMPTY: LazyLock<serde_json::Value> =
467            LazyLock::new(|| serde_json::Value::Object(serde_json::Map::new()));
468
469        if let Some(gear_raw) = self.config_provider.get_gear_config(&self.gear_name) {
470            // Try new structure first: gears.<name> = { database: ..., config: ... }
471            if let Some(obj) = gear_raw.as_object()
472                && let Some(config_section) = obj.get("config")
473            {
474                return config_section;
475            }
476        }
477        &EMPTY
478    }
479
480    /// Create a derivative context with the same references but no DB handle.
481    /// Useful for gears that don't require database access.
482    pub fn without_db(&self) -> GearCtx {
483        GearCtx {
484            gear_name: self.gear_name.clone(),
485            instance_id: self.instance_id,
486            config_provider: self.config_provider.clone(),
487            client_hub: self.client_hub.clone(),
488            cancellation_token: self.cancellation_token.clone(),
489            internal_token_provider: self.internal_token_provider.clone(),
490            gts_publication_manifest: self.gts_publication_manifest.clone(),
491            #[cfg(feature = "db")]
492            db: None,
493        }
494    }
495}
496
497#[cfg(test)]
498#[cfg_attr(coverage_nightly, coverage(off))]
499mod tests {
500    use super::*;
501    use serde::Deserialize;
502    use serde_json::json;
503    use std::collections::HashMap;
504
505    #[derive(Debug, PartialEq, Deserialize, Default)]
506    struct TestConfig {
507        #[serde(default)]
508        api_key: String,
509        #[serde(default)]
510        timeout_ms: u64,
511        #[serde(default)]
512        enabled: bool,
513    }
514
515    struct MockConfigProvider {
516        gears: HashMap<String, serde_json::Value>,
517    }
518
519    impl MockConfigProvider {
520        fn new() -> Self {
521            let mut gears = HashMap::new();
522
523            // Valid gear config
524            gears.insert(
525                "test_gear".to_owned(),
526                json!({
527                    "database": {
528                        "url": "postgres://localhost/test"
529                    },
530                    "config": {
531                        "api_key": "secret123",
532                        "timeout_ms": 5000,
533                        "enabled": true
534                    }
535                }),
536            );
537
538            Self { gears }
539        }
540    }
541
542    impl ConfigProvider for MockConfigProvider {
543        fn get_gear_config(&self, gear_name: &str) -> Option<&serde_json::Value> {
544            self.gears.get(gear_name)
545        }
546    }
547
548    #[test]
549    fn test_gear_ctx_config_with_valid_config() {
550        let provider = Arc::new(MockConfigProvider::new());
551        let ctx = GearCtx::new(
552            "test_gear",
553            Uuid::new_v4(),
554            provider,
555            Arc::new(crate::client_hub::ClientHub::default()),
556            CancellationToken::new(),
557        );
558
559        let result: Result<TestConfig, ConfigError> = ctx.config();
560        assert!(result.is_ok());
561
562        let config = result.unwrap();
563        assert_eq!(config.api_key, "secret123");
564        assert_eq!(config.timeout_ms, 5000);
565        assert!(config.enabled);
566    }
567
568    #[test]
569    fn test_gear_ctx_config_returns_error_for_missing_gear() {
570        let provider = Arc::new(MockConfigProvider::new());
571        let ctx = GearCtx::new(
572            "nonexistent_gear",
573            Uuid::new_v4(),
574            provider,
575            Arc::new(crate::client_hub::ClientHub::default()),
576            CancellationToken::new(),
577        );
578
579        let result: Result<TestConfig, ConfigError> = ctx.config();
580        assert!(matches!(
581            result,
582            Err(ConfigError::GearNotFound { ref gear }) if gear == "nonexistent_gear"
583        ));
584    }
585
586    #[test]
587    fn test_gear_ctx_config_or_default_returns_default_for_missing_gear() {
588        let provider = Arc::new(MockConfigProvider::new());
589        let ctx = GearCtx::new(
590            "nonexistent_gear",
591            Uuid::new_v4(),
592            provider,
593            Arc::new(crate::client_hub::ClientHub::default()),
594            CancellationToken::new(),
595        );
596
597        let result: Result<TestConfig, ConfigError> = ctx.config_or_default();
598        assert!(result.is_ok());
599
600        let config = result.unwrap();
601        assert_eq!(config, TestConfig::default());
602    }
603
604    /// The `pre_init` context carries neither the database handle nor the
605    /// admitted GTS manifest that the later contexts of the same gear carry.
606    #[tokio::test]
607    async fn the_context_before_migrations_has_no_database_and_no_admitted_manifest() {
608        let builder = GearContextBuilder::new(
609            Uuid::new_v4(),
610            Arc::new(MockConfigProvider::new()),
611            Arc::new(crate::client_hub::ClientHub::default()),
612            CancellationToken::new(),
613        );
614        #[cfg(feature = "db")]
615        let (builder, _dir) = {
616            let dir = tempfile::TempDir::new().unwrap();
617            let dsn = format!("sqlite://{}", dir.path().join("gear.db").display());
618            let figment = figment::Figment::new().merge(figment::providers::Serialized::defaults(
619                json!({ "gears": { "test_gear": { "database": { "dsn": dsn } } } }),
620            ));
621            let manager = DbManager::from_figment(figment, dir.path().to_path_buf()).unwrap();
622            (builder.with_db_manager(Arc::new(manager)), dir)
623        };
624        builder.gts_admitted_manifests().insert(Arc::new(
625            crate::gts_publication::GtsManifest::build("test_gear", "1.0.0", Vec::new()).unwrap(),
626        ));
627
628        let later = builder.for_gear("test_gear").await.unwrap();
629        assert!(later.gts_publication_manifest().is_ok());
630        #[cfg(feature = "db")]
631        assert!(later.db().is_some());
632
633        let early = builder.for_gear_before_migrations("test_gear");
634        assert!(early.gts_publication_manifest().is_err());
635        #[cfg(feature = "db")]
636        assert!(early.db().is_none());
637        assert_eq!(early.gear_name(), "test_gear");
638    }
639
640    #[tokio::test]
641    async fn internal_token_provider_flows_from_builder_to_ctx() {
642        use std::sync::atomic::{AtomicBool, Ordering};
643
644        // The builder's provider must be threaded onto every `GearCtx` it
645        // builds, and `GearCtx::internal_token_provider()` must return the SAME
646        // provider (proven by observing the closure fire on `.current()`).
647        let invoked = Arc::new(AtomicBool::new(false));
648        let invoked_in_closure = Arc::clone(&invoked);
649        let provider = InternalTokenProvider::new(move || {
650            invoked_in_closure.store(true, Ordering::SeqCst);
651            toolkit_contract::runtime::config::CredentialState::NotConfigured
652        });
653
654        let builder = GearContextBuilder::new(
655            Uuid::new_v4(),
656            Arc::new(MockConfigProvider::new()),
657            Arc::new(crate::client_hub::ClientHub::default()),
658            CancellationToken::new(),
659        )
660        .with_internal_token_provider(Some(provider));
661
662        let ctx = builder.for_gear("test_gear").await.unwrap();
663        let threaded = ctx.internal_token_provider();
664        assert!(threaded.is_some(), "provider must be threaded onto GearCtx");
665
666        // Invoking it runs the original closure — confirming identity, not a
667        // freshly-defaulted provider. The configured closure yields no token.
668        assert!(matches!(
669            threaded.unwrap().current(),
670            toolkit_contract::runtime::config::CredentialState::NotConfigured
671        ));
672        assert!(
673            invoked.load(Ordering::SeqCst),
674            "the threaded provider must be the one configured on the builder"
675        );
676
677        // A builder without a provider yields a context with none (Profile 1).
678        let bare = GearContextBuilder::new(
679            Uuid::new_v4(),
680            Arc::new(MockConfigProvider::new()),
681            Arc::new(crate::client_hub::ClientHub::default()),
682            CancellationToken::new(),
683        )
684        .for_gear("test_gear")
685        .await
686        .unwrap();
687        assert!(bare.internal_token_provider().is_none());
688    }
689
690    #[test]
691    fn test_gear_ctx_instance_id() {
692        let provider = Arc::new(MockConfigProvider::new());
693        let instance_id = Uuid::new_v4();
694        let ctx = GearCtx::new(
695            "test_gear",
696            instance_id,
697            provider,
698            Arc::new(crate::client_hub::ClientHub::default()),
699            CancellationToken::new(),
700        );
701
702        assert_eq!(ctx.instance_id(), instance_id);
703    }
704
705    /// Issue #5686: a gear's context reads its own consumer proxy, not another
706    /// gear's. Built the way the runtime builds it, through the builder.
707    #[tokio::test]
708    async fn a_gear_ctx_reads_its_own_proxy() {
709        trait PingApi: Send + Sync {}
710        struct Ping;
711        impl PingApi for Ping {}
712
713        let hub = Arc::new(crate::client_hub::ClientHub::default());
714        let builder = GearContextBuilder::new(
715            Uuid::new_v4(),
716            Arc::new(MockConfigProvider::new()),
717            Arc::clone(&hub),
718            CancellationToken::new(),
719        );
720        let proxy: Arc<dyn PingApi> = Arc::new(Ping);
721        hub.for_gear("a")
722            .register_remote_proxy::<dyn PingApi>(Arc::clone(&proxy));
723
724        let a = builder.for_gear("a").await.unwrap();
725        let b = builder.for_gear("b").await.unwrap();
726
727        assert_eq!(a.client_hub().owner(), Some("a"));
728        assert!(Arc::ptr_eq(
729            &a.client_hub().get::<dyn PingApi>().unwrap(),
730            &proxy
731        ));
732        assert!(b.client_hub().try_get::<dyn PingApi>().is_none());
733    }
734
735    // --- config_expanded tests ---
736
737    #[derive(Debug, PartialEq, Deserialize, Default, toolkit_macros::ExpandVars)]
738    struct ExpandableConfig {
739        #[expand_vars]
740        #[serde(default)]
741        api_key: String,
742        #[expand_vars]
743        #[serde(default)]
744        endpoint: Option<String>,
745        #[serde(default)]
746        retries: u32,
747    }
748
749    fn make_ctx(gear_name: &str, config_json: serde_json::Value) -> GearCtx {
750        let mut gears = HashMap::new();
751        gears.insert(gear_name.to_owned(), config_json);
752        let provider = Arc::new(MockConfigProvider { gears });
753        GearCtx::new(
754            gear_name,
755            Uuid::new_v4(),
756            provider,
757            Arc::new(crate::client_hub::ClientHub::default()),
758            CancellationToken::new(),
759        )
760    }
761
762    #[test]
763    fn config_expanded_resolves_env_vars() {
764        let ctx = make_ctx(
765            "expand_mod",
766            json!({
767                "config": {
768                    "api_key": "${TOOLKIT_TEST_KEY}",
769                    "endpoint": "https://${TOOLKIT_TEST_HOST}/api",
770                    "retries": 3
771                }
772            }),
773        );
774
775        temp_env::with_vars(
776            [
777                ("TOOLKIT_TEST_KEY", Some("secret-42")),
778                ("TOOLKIT_TEST_HOST", Some("example.com")),
779            ],
780            || {
781                let cfg: ExpandableConfig = ctx.config_expanded().unwrap();
782                assert_eq!(cfg.api_key, "secret-42");
783                assert_eq!(cfg.endpoint.as_deref(), Some("https://example.com/api"));
784                assert_eq!(cfg.retries, 3);
785            },
786        );
787    }
788
789    #[test]
790    fn config_expanded_returns_error_on_missing_var() {
791        let ctx = make_ctx(
792            "expand_mod",
793            json!({
794                "config": {
795                    "api_key": "${TOOLKIT_TEST_MISSING_VAR_XYZ}"
796                }
797            }),
798        );
799
800        temp_env::with_vars([("TOOLKIT_TEST_MISSING_VAR_XYZ", None::<&str>)], || {
801            let err = ctx.config_expanded::<ExpandableConfig>().unwrap_err();
802            assert!(
803                matches!(err, ConfigError::VarExpand { ref gear, .. } if gear == "expand_mod"),
804                "expected EnvExpand error, got: {err:?}"
805            );
806        });
807    }
808
809    #[test]
810    fn config_expanded_skips_none_option_fields() {
811        let ctx = make_ctx(
812            "expand_mod",
813            json!({
814                "config": {
815                    "api_key": "literal-key",
816                    "retries": 5
817                }
818            }),
819        );
820
821        let cfg: ExpandableConfig = ctx.config_expanded().unwrap();
822        assert_eq!(cfg.api_key, "literal-key");
823        assert_eq!(cfg.endpoint, None);
824        assert_eq!(cfg.retries, 5);
825    }
826
827    #[test]
828    fn config_expanded_returns_error_when_missing() {
829        let ctx = make_ctx("missing_mod", json!({}));
830        let err = ctx.config_expanded::<ExpandableConfig>().unwrap_err();
831        assert!(matches!(
832            err,
833            ConfigError::MissingConfigSection { ref gear } if gear == "missing_mod"
834        ));
835    }
836
837    #[test]
838    fn config_expanded_or_default_falls_back_to_default_when_missing() {
839        let ctx = make_ctx("missing_mod", json!({}));
840        let cfg: ExpandableConfig = ctx.config_expanded_or_default().unwrap();
841        assert_eq!(cfg, ExpandableConfig::default());
842    }
843
844    // --- nested struct expansion ---
845
846    #[derive(Debug, PartialEq, Deserialize, Default, toolkit_macros::ExpandVars)]
847    struct NestedProvider {
848        #[expand_vars]
849        #[serde(default)]
850        host: String,
851        #[expand_vars]
852        #[serde(default)]
853        token: Option<String>,
854        #[expand_vars]
855        #[serde(default)]
856        auth_config: Option<HashMap<String, String>>,
857        #[serde(default)]
858        port: u16,
859    }
860
861    #[derive(Debug, PartialEq, Deserialize, Default, toolkit_macros::ExpandVars)]
862    struct NestedConfig {
863        #[expand_vars]
864        #[serde(default)]
865        name: String,
866        #[expand_vars]
867        #[serde(default)]
868        providers: HashMap<String, NestedProvider>,
869        #[expand_vars]
870        #[serde(default)]
871        tags: Vec<String>,
872    }
873
874    #[test]
875    fn config_expanded_resolves_nested_structs() {
876        let ctx = make_ctx(
877            "nested_mod",
878            json!({
879                "config": {
880                    "name": "${TOOLKIT_NESTED_NAME}",
881                    "providers": {
882                        "primary": {
883                            "host": "${TOOLKIT_NESTED_HOST}",
884                            "token": "${TOOLKIT_NESTED_TOKEN}",
885                            "auth_config": {
886                                "header": "X-Api-Key",
887                                "secret_ref": "${TOOLKIT_NESTED_SECRET}"
888                            },
889                            "port": 443
890                        }
891                    },
892                    "tags": ["${TOOLKIT_NESTED_TAG}", "literal"]
893                }
894            }),
895        );
896
897        temp_env::with_vars(
898            [
899                ("TOOLKIT_NESTED_NAME", Some("my-service")),
900                ("TOOLKIT_NESTED_HOST", Some("api.example.com")),
901                ("TOOLKIT_NESTED_TOKEN", Some("sk-secret")),
902                ("TOOLKIT_NESTED_SECRET", Some("key-12345")),
903                ("TOOLKIT_NESTED_TAG", Some("production")),
904            ],
905            || {
906                let cfg: NestedConfig = ctx.config_expanded().unwrap();
907                assert_eq!(cfg.name, "my-service");
908                assert_eq!(cfg.tags, vec!["production", "literal"]);
909
910                let primary = cfg.providers.get("primary").expect("primary provider");
911                assert_eq!(primary.host, "api.example.com");
912                assert_eq!(primary.token.as_deref(), Some("sk-secret"));
913                assert_eq!(primary.port, 443);
914
915                let auth = primary.auth_config.as_ref().expect("auth_config present");
916                assert_eq!(auth.get("header").map(String::as_str), Some("X-Api-Key"));
917                assert_eq!(
918                    auth.get("secret_ref").map(String::as_str),
919                    Some("key-12345")
920                );
921            },
922        );
923    }
924
925    #[test]
926    fn config_expanded_nested_missing_var_returns_error() {
927        let ctx = make_ctx(
928            "nested_mod",
929            json!({
930                "config": {
931                    "name": "ok",
932                    "providers": {
933                        "bad": { "host": "${TOOLKIT_NESTED_GONE}", "port": 80 }
934                    }
935                }
936            }),
937        );
938
939        temp_env::with_vars([("TOOLKIT_NESTED_GONE", None::<&str>)], || {
940            let err = ctx.config_expanded::<NestedConfig>().unwrap_err();
941            assert!(
942                matches!(err, ConfigError::VarExpand { ref gear, .. } if gear == "nested_mod"),
943                "expected EnvExpand, got: {err:?}"
944            );
945        });
946    }
947}