Skip to main content

toolkit/
discovery.rs

1//! Consumer-side discovery wiring for eventual readiness.
2//!
3//! Bridges the service [`DirectoryClient`](crate::DirectoryClient) into the
4//! contract layer's [`EndpointResolver`], and carries the
5//! [`ConsumerRegistration`]s emitted by `#[toolkit::consumes]` that the
6//! runtime's proxy-wiring phase replays at startup.
7//!
8//! Unconditional: consuming another gear over a discovered REST transport is
9//! the normal case, and `#[toolkit::consumes]` emits its registration
10//! unconditionally too. Putting this behind a feature only created a way to
11//! build a gear whose declared dependencies were silently never wired.
12
13use std::sync::Arc;
14
15use async_trait::async_trait;
16
17use cf_system_sdks::directory::{DirectoryInvalidArgument, DirectoryNotFound};
18
19use crate::DirectoryClient;
20use crate::client_hub::ClientHub;
21
22/// Re-export so the `#[toolkit::consumes]`-generated wire fn can name the
23/// resolver type as `toolkit::discovery::EndpointResolver` without the consuming
24/// gear crate needing a direct `toolkit-contract` dependency.
25pub use toolkit_contract::runtime::resolving::{EndpointResolver, ResolveError};
26
27/// Adapts the service [`DirectoryClient`] into the contract-layer
28/// [`EndpointResolver`] consumed by `DirectoryResolvingClient`.
29///
30/// Keeps `toolkit-contract` free of a dependency on the directory SDK: the
31/// adapter lives here in `toolkit`, which already owns `DirectoryClient`.
32///
33/// Successful resolutions are memoized for a short TTL ([`Self::TTL`]) so a
34/// per-call resolving client does not incur a directory round-trip on every
35/// business call (the `OoP` directory is a network hop). Only `Ok(Some(uri))` is
36/// cached; `Ok(None)` / `Err` always re-resolve. The TTL is deliberately short
37/// so endpoint churn self-heals within ~TTL.
38pub struct DirectoryEndpointResolver {
39    client: Arc<dyn DirectoryClient>,
40    cache: parking_lot::Mutex<std::collections::HashMap<String, (String, std::time::Instant)>>,
41}
42
43impl DirectoryEndpointResolver {
44    /// Memoization window for successful resolutions.
45    ///
46    /// Public because it bounds observable behaviour: a provider that moves is
47    /// followed within roughly this window, not instantly, since the cache
48    /// holds only successes and is not invalidated by a failed call.
49    pub const TTL: std::time::Duration = std::time::Duration::from_millis(1500);
50
51    /// Wrap a [`DirectoryClient`] with a short-TTL resolution cache.
52    #[must_use]
53    pub fn new(client: Arc<dyn DirectoryClient>) -> Self {
54        Self {
55            client,
56            cache: parking_lot::Mutex::new(std::collections::HashMap::new()),
57        }
58    }
59
60    fn cached(&self, gear: &str) -> Option<String> {
61        self.cache
62            .lock()
63            .get(gear)
64            .filter(|(_, at)| at.elapsed() < Self::TTL)
65            .map(|(uri, _)| uri.clone())
66    }
67
68    fn store(&self, gear: &str, uri: &str) {
69        self.cache
70            .lock()
71            .insert(gear.to_owned(), (uri.to_owned(), std::time::Instant::now()));
72    }
73}
74
75#[async_trait]
76impl EndpointResolver for DirectoryEndpointResolver {
77    async fn resolve_endpoint(&self, gear: &str) -> Result<Option<String>, ResolveError> {
78        // Fresh cache hit avoids the directory round-trip.
79        if let Some(uri) = self.cached(gear) {
80            return Ok(Some(uri));
81        }
82        // Preserve the trait's `Ok(None)` (no live instance / not ready) vs
83        // `Err` (directory backend unreachable) distinction so a real directory
84        // outage surfaces at `warn` rather than being silently treated as
85        // "provider not ready". The directory returns the typed
86        // `DirectoryNotFound` sentinel for the not-found case; anything else is
87        // a genuine backend/transport failure (relevant for the OoP gRPC
88        // directory client).
89        match self.client.resolve_rest_service(gear).await {
90            Ok(ep) => {
91                self.store(gear, &ep.uri);
92                Ok(Some(ep.uri))
93            }
94            Err(e) if e.downcast_ref::<DirectoryNotFound>().is_some() => Ok(None),
95            Err(e) if e.downcast_ref::<DirectoryInvalidArgument>().is_some() => {
96                // A malformed provider name is a permanent configuration error,
97                // not a transient outage: re-resolving can never succeed. Log
98                // it distinctly from the generic backend-failure path (at
99                // `error`, not the caller's transient `warn`) so the actionable
100                // "fix your config" message is not mistaken for a directory
101                // outage, and still return `Err` so the call fails.
102                tracing::error!(
103                    gear,
104                    error = %e,
105                    "provider name permanently rejected by the directory (invalid \
106                     argument); this is a static configuration error, not a directory \
107                     outage, and will never resolve. Check the consumed gear name"
108                );
109                Err(ResolveError::new(gear, e))
110            }
111            Err(e) => Err(ResolveError::new(gear, e)),
112        }
113    }
114}
115
116/// An [`EndpointResolver`] that never resolves any gear (`Ok(None)` for every
117/// lookup). Used by the proxy-wiring phase when no [`DirectoryClient`] is present
118/// in the [`ClientHub`]: co-located (local) consumers still short-circuit and
119/// wire successfully, while remote consumers register as *unresolved* readiness
120/// gates (so `/readyz` correctly stays 503) rather than being silently skipped.
121pub struct NullEndpointResolver;
122
123#[async_trait]
124impl EndpointResolver for NullEndpointResolver {
125    async fn resolve_endpoint(&self, _gear: &str) -> Result<Option<String>, ResolveError> {
126        Ok(None)
127    }
128}
129
130/// An [`EndpointResolver`] that always resolves to a single, fixed endpoint —
131/// the ADR-0004 static-endpoint override escape hatch for local development and
132/// integration testing. It bypasses the service directory: a consumer configured
133/// with `gears.<owner>.clients.consumes.<dep>.endpoint` wires a resolving client
134/// whose endpoint is this constant. Not for production use.
135pub struct StaticEndpointResolver {
136    endpoint: String,
137}
138
139impl StaticEndpointResolver {
140    /// Wrap a fixed base endpoint URI.
141    #[must_use]
142    pub fn new(endpoint: impl Into<String>) -> Self {
143        Self {
144            endpoint: endpoint.into(),
145        }
146    }
147}
148
149#[async_trait]
150impl EndpointResolver for StaticEndpointResolver {
151    async fn resolve_endpoint(&self, _gear: &str) -> Result<Option<String>, ResolveError> {
152        Ok(Some(self.endpoint.clone()))
153    }
154}
155
156/// Outcome of a [`ConsumerRegistration::wire`] call: whether the dependency was
157/// satisfied by a co-located compile-time impl (no directory dependency) or by
158/// a directory-resolving REST client that still needs endpoint resolution.
159///
160/// The runtime uses this to gate readiness: `Local` deps are readiness-resolved
161/// immediately (no `/readyz` gating, no probe loop), while `Remote` deps gate
162/// readiness until the directory resolves them (ADR-0007).
163#[derive(Debug, Clone, Copy, PartialEq, Eq)]
164pub enum WireOutcome {
165    /// A compile-time (in-process) impl was already registered — it won the
166    /// `hub.try_get_local` short-circuit; no remote binding was created.
167    Local,
168    /// A directory-resolving REST client was registered; its endpoint is
169    /// resolved lazily/at readiness-probe time.
170    Remote,
171}
172
173/// A consumer→provider contract wiring, registered by `#[toolkit::consumes]`
174/// via `inventory::submit!` and replayed by the runtime's proxy-wiring phase.
175///
176/// `wire` is a non-capturing `fn` (the provider gear name is inlined into the
177/// generated body). It must:
178///   1. short-circuit returning [`WireOutcome::Local`] if a compile-time (local)
179///      impl is already registered (`hub.try_get_local::<dyn Trait>().is_some()`),
180///      so in-process providers win;
181///   2. otherwise register a directory-resolving REST client under the contract
182///      trait via [`ClientHub::register_remote_proxy`] (using the supplied
183///      [`EndpointResolver`]) and return [`WireOutcome::Remote`].
184///
185/// The runtime passes the owner gear's view ([`ClientHub::for_gear`]) when
186/// `owner_gear` is a gear in this process, so each consumer gets its own proxy
187/// built from its own `clients.consumes.<dep>` settings; otherwise it passes the
188/// process-wide hub.
189///
190/// Step 1 must use `try_get_local`, not `try_get`: `try_get` also returns a
191/// process-wide proxy, and reporting that as `Local` would mark the dependency
192/// readiness-resolved — flipping `/readyz` to 200 while the provider is still
193/// absent.
194pub struct ConsumerRegistration {
195    /// Gear that declares the dependency (diagnostics).
196    pub owner_gear: &'static str,
197    /// Provider gear name the contract resolves against (diagnostics).
198    pub dep_gear: &'static str,
199    /// Wiring action: register the client into the hub; reports whether the
200    /// dependency was satisfied locally or bound to a remote client. See
201    /// [`WireFn`] for the argument roles.
202    pub wire: WireFn,
203}
204
205/// The wiring function pointer emitted by `#[toolkit::consumes]`: registers the
206/// client into the `ClientHub` from an endpoint resolver and a prepared
207/// [`ClientTuning`](toolkit_contract::wiring::ClientTuning) (the `clients.consumes`
208/// knobs plus the process's platform-plane credential source). Aliased to keep
209/// the fn-pointer type readable.
210pub type WireFn = fn(
211    &ClientHub,
212    Arc<dyn EndpointResolver>,
213    toolkit_contract::wiring::ClientTuning,
214) -> anyhow::Result<WireOutcome>;
215
216inventory::collect!(ConsumerRegistration);
217
218#[cfg(test)]
219#[cfg_attr(coverage_nightly, coverage(off))]
220mod tests {
221    use super::*;
222    use cf_system_sdks::directory::{RegisterInstanceInfo, ServiceEndpoint, ServiceInstanceInfo};
223    use std::sync::atomic::{AtomicUsize, Ordering};
224
225    /// Counts `resolve_rest_service` calls; all other methods are unused here.
226    struct CountingDirectory {
227        calls: AtomicUsize,
228    }
229
230    #[async_trait]
231    impl DirectoryClient for CountingDirectory {
232        async fn resolve_grpc_service(&self, _: &str) -> anyhow::Result<ServiceEndpoint> {
233            unimplemented!()
234        }
235        async fn resolve_rest_service(&self, gear: &str) -> anyhow::Result<ServiceEndpoint> {
236            self.calls.fetch_add(1, Ordering::SeqCst);
237            Ok(ServiceEndpoint::new(format!("http://{gear}.local")))
238        }
239        async fn get_openapi_spec(&self, _: &str) -> anyhow::Result<String> {
240            unimplemented!()
241        }
242        async fn list_instances(&self, _: &str) -> anyhow::Result<Vec<ServiceInstanceInfo>> {
243            unimplemented!()
244        }
245        async fn list_all_instances(&self) -> anyhow::Result<Vec<ServiceInstanceInfo>> {
246            unimplemented!()
247        }
248        async fn register_instance(&self, _: RegisterInstanceInfo) -> anyhow::Result<()> {
249            unimplemented!()
250        }
251        async fn deregister_instance(&self, _: &str, _: &str) -> anyhow::Result<()> {
252            unimplemented!()
253        }
254        async fn send_heartbeat(&self, _: &str, _: &str) -> anyhow::Result<()> {
255            unimplemented!()
256        }
257    }
258
259    #[tokio::test]
260    async fn memoizes_successful_resolution_within_ttl() {
261        let dir = Arc::new(CountingDirectory {
262            calls: AtomicUsize::new(0),
263        });
264        let resolver = DirectoryEndpointResolver::new(dir.clone());
265
266        for _ in 0..3 {
267            let ep = resolver.resolve_endpoint("billing").await.unwrap();
268            assert_eq!(ep.as_deref(), Some("http://billing.local"));
269        }
270
271        assert_eq!(
272            dir.calls.load(Ordering::SeqCst),
273            1,
274            "successful resolution must be memoized within the TTL (one directory lookup)"
275        );
276    }
277
278    #[tokio::test]
279    async fn static_resolver_always_returns_fixed_endpoint() {
280        let resolver = StaticEndpointResolver::new("http://localhost:8081");
281        assert_eq!(
282            resolver
283                .resolve_endpoint("anything")
284                .await
285                .unwrap()
286                .as_deref(),
287            Some("http://localhost:8081")
288        );
289        assert_eq!(
290            resolver.resolve_endpoint("other").await.unwrap().as_deref(),
291            Some("http://localhost:8081")
292        );
293    }
294
295    #[tokio::test]
296    async fn null_resolver_never_resolves() {
297        assert_eq!(
298            NullEndpointResolver
299                .resolve_endpoint("billing")
300                .await
301                .unwrap(),
302            None
303        );
304    }
305
306    /// Answers every lookup with a caller-chosen failure, so the resolver's
307    /// two error branches can be told apart.
308    struct FailingDirectory {
309        make_error: fn(&str) -> anyhow::Error,
310    }
311
312    #[async_trait]
313    impl DirectoryClient for FailingDirectory {
314        async fn resolve_grpc_service(&self, _: &str) -> anyhow::Result<ServiceEndpoint> {
315            unimplemented!()
316        }
317        async fn resolve_rest_service(&self, gear: &str) -> anyhow::Result<ServiceEndpoint> {
318            Err((self.make_error)(gear))
319        }
320        async fn get_openapi_spec(&self, _: &str) -> anyhow::Result<String> {
321            unimplemented!()
322        }
323        async fn list_instances(&self, _: &str) -> anyhow::Result<Vec<ServiceInstanceInfo>> {
324            unimplemented!()
325        }
326        async fn list_all_instances(&self) -> anyhow::Result<Vec<ServiceInstanceInfo>> {
327            unimplemented!()
328        }
329        async fn register_instance(&self, _: RegisterInstanceInfo) -> anyhow::Result<()> {
330            unimplemented!()
331        }
332        async fn deregister_instance(&self, _: &str, _: &str) -> anyhow::Result<()> {
333            unimplemented!()
334        }
335        async fn send_heartbeat(&self, _: &str, _: &str) -> anyhow::Result<()> {
336            unimplemented!()
337        }
338    }
339
340    #[tokio::test]
341    async fn not_found_sentinel_resolves_to_ok_none() {
342        // "The provider has not registered yet" is a routine startup condition,
343        // not a failure: it must come back as `Ok(None)` so the readiness probe
344        // logs it at `debug` and the resolving client reports `Unresolved`
345        // rather than warning on every call.
346        let dir = Arc::new(FailingDirectory {
347            make_error: |gear| DirectoryNotFound::new(format!("gear {gear}")).into(),
348        });
349        let resolver = DirectoryEndpointResolver::new(dir);
350
351        assert_eq!(resolver.resolve_endpoint("billing").await.unwrap(), None);
352    }
353
354    #[tokio::test]
355    async fn backend_failure_resolves_to_err() {
356        // Anything that is not the sentinel is a genuine directory outage and
357        // must stay an error, so a stuck 503 has a diagnostic trail.
358        let dir = Arc::new(FailingDirectory {
359            make_error: |_| anyhow::anyhow!("connection refused"),
360        });
361        let resolver = DirectoryEndpointResolver::new(dir);
362
363        assert!(resolver.resolve_endpoint("billing").await.is_err());
364    }
365
366    #[tokio::test]
367    #[tracing_test::traced_test]
368    async fn invalid_argument_resolves_to_err_and_logs_config_error() {
369        // A malformed provider name is a permanent configuration error, handled
370        // by the dedicated arm. Unlike the not-found sentinel (`Ok(None)`), it
371        // must stay an `Err` so the call fails rather than being treated as a
372        // provider that is merely not ready yet. It must also be logged
373        // distinctly at `error` (a static configuration error) so it is not
374        // folded into the generic backend-failure path, which emits no log of
375        // its own at the resolver.
376        let dir = Arc::new(FailingDirectory {
377            make_error: |gear| DirectoryInvalidArgument::new(format!("bad name {gear}")).into(),
378        });
379        let resolver = DirectoryEndpointResolver::new(dir);
380
381        assert!(resolver.resolve_endpoint("Bad Name").await.is_err());
382
383        logs_assert(|lines: &[&str]| {
384            match lines
385                .iter()
386                .find(|line| line.contains("permanently rejected by the directory"))
387            {
388                Some(line) if line.contains("ERROR") => Ok(()),
389                Some(_) => Err("invalid-argument arm logged at the wrong level".to_owned()),
390                None => {
391                    Err("invalid-argument arm must emit a distinct config-error log".to_owned())
392                }
393            }
394        });
395    }
396
397    /// Mirrors the body `#[toolkit::consumes]` generates, so the wiring
398    /// contract is exercised without going through `inventory` (which is
399    /// link-time global and cannot hold two registrations built by a test).
400    fn generated_wire_body<C>(hub: &ClientHub, proxy: Arc<C>) -> anyhow::Result<WireOutcome>
401    where
402        C: ?Sized + Send + Sync + 'static,
403    {
404        if hub.try_get_local::<C>().is_some() {
405            return Ok(WireOutcome::Local);
406        }
407        if hub.has_remote_proxy::<C>() {
408            if let Some(owner) = hub.owner() {
409                anyhow::bail!("gear `{owner}` declares #[toolkit::consumes] more than once");
410            }
411            return Ok(WireOutcome::Remote);
412        }
413        hub.register_remote_proxy::<C>(proxy);
414        Ok(WireOutcome::Remote)
415    }
416
417    trait Payments: Send + Sync {}
418    struct PaymentsProxy;
419    impl Payments for PaymentsProxy {}
420    struct PaymentsLocal;
421    impl Payments for PaymentsLocal {}
422
423    #[test]
424    fn two_consumers_of_one_contract_get_their_own_proxies() {
425        // Two gears in one process consuming the same contract from the same
426        // provider. Each must get its own proxy (built from its own wiring
427        // settings), and neither may short-circuit to `Local`, which would mark
428        // the dependency readiness-resolved with no provider up.
429        let hub = ClientHub::new();
430        let a = hub.for_gear("a");
431        let b = hub.for_gear("b");
432
433        let first = generated_wire_body::<dyn Payments>(&a, Arc::new(PaymentsProxy)).unwrap();
434        let second = generated_wire_body::<dyn Payments>(&b, Arc::new(PaymentsProxy)).unwrap();
435
436        assert_eq!(first, WireOutcome::Remote);
437        assert_eq!(
438            second,
439            WireOutcome::Remote,
440            "the second consumer must still gate readiness, not short-circuit to Local"
441        );
442        assert!(!Arc::ptr_eq(
443            &a.get::<dyn Payments>().unwrap(),
444            &b.get::<dyn Payments>().unwrap()
445        ));
446    }
447
448    #[test]
449    fn a_gear_consuming_one_contract_twice_is_an_error() {
450        let hub = ClientHub::new();
451        let a = hub.for_gear("a");
452
453        generated_wire_body::<dyn Payments>(&a, Arc::new(PaymentsProxy)).unwrap();
454        let err = generated_wire_body::<dyn Payments>(&a, Arc::new(PaymentsProxy)).unwrap_err();
455
456        assert!(err.to_string().contains("more than once"), "{err}");
457    }
458
459    #[test]
460    fn the_process_wide_hub_reuses_its_proxy() {
461        // Registrations whose owner is not a gear here (cluster-sdk's) wire into
462        // the plain hub and share one proxy.
463        let hub = ClientHub::new();
464
465        let first = generated_wire_body::<dyn Payments>(&hub, Arc::new(PaymentsProxy)).unwrap();
466        let second = generated_wire_body::<dyn Payments>(&hub, Arc::new(PaymentsProxy)).unwrap();
467
468        assert_eq!((first, second), (WireOutcome::Remote, WireOutcome::Remote));
469    }
470
471    #[test]
472    fn a_genuine_local_impl_still_wins() {
473        // The short-circuit must keep working for its actual purpose: a
474        // co-located provider registered during init means no HTTP hop and no
475        // readiness gate.
476        let hub = ClientHub::new();
477        hub.register::<dyn Payments>(Arc::new(PaymentsLocal));
478
479        let outcome = generated_wire_body::<dyn Payments>(&hub, Arc::new(PaymentsProxy)).unwrap();
480
481        assert_eq!(outcome, WireOutcome::Local);
482    }
483
484    #[tokio::test]
485    async fn local_directory_client_not_found_reaches_the_resolver_as_ok_none() {
486        // End-to-end over the real in-process client rather than a stub: this
487        // is the pairing that was broken (the client returned a bare `anyhow`,
488        // so the resolver could never produce `Ok(None)`).
489        let dir = Arc::new(crate::directory::LocalDirectoryClient::new(Arc::new(
490            crate::runtime::GearManager::new(),
491        )));
492        let resolver = DirectoryEndpointResolver::new(dir);
493
494        assert_eq!(
495            resolver.resolve_endpoint("never-registered").await.unwrap(),
496            None
497        );
498    }
499}