Skip to main content

toolkit_contract/runtime/
resolving.rs

1//! Directory-resolving transport, shared by REST and gRPC.
2//!
3//! [`DirectoryResolvingClient`] is a thin, self-healing wrapper around a
4//! generated `<Trait>RestClient` or `<Trait>GrpcClient`. Instead of binding to
5//! a single static base URL at construction time, it resolves the provider's
6//! endpoint from the service directory on every call and builds a client per
7//! endpoint, reusing it while that endpoint keeps coming back.
8//!
9//! This is what makes the consumer side tolerant of *eventual readiness* and
10//! runtime churn:
11//! - **Not ready yet** — the provider hasn't registered → resolution yields
12//!   `None` → calls fail with [`TransportError::Unresolved`] (a transient
13//!   error that maps to `service_unavailable`), never a panic.
14//! - **Provider moved / pod replaced** — the directory returns a new endpoint
15//!   → the wrapper builds a client for it on the next call.
16//! - **Several instances** — the directory rotates between them; each keeps
17//!   its client (and its HTTP/2 connection and circuit breaker) instead of
18//!   being rebuilt on every rotation.
19//! - **Endpoint failing** — an attempt the circuit breaker classifies as a
20//!   backend failure drops the resolver's cached answer (at most once per
21//!   second per endpoint), so the next call asks the directory again rather
22//!   than waiting out the cache TTL. The breaker for that endpoint opens if
23//!   the failures go on.
24//! - **Provider vanished** — all instances evicted → resolution yields `None`
25//!   again → `Unresolved`; the wrapper recovers automatically once a live
26//!   instance reappears.
27//!
28//! The `Arc<dyn Trait>` registered in the `ClientHub` is the long-lived
29//! resolving wrapper, so the hub entry is wired once and never replaced; all
30//! churn handling lives inside this transport.
31
32use std::sync::{Arc, RwLock};
33use std::time::Duration;
34
35use async_trait::async_trait;
36use tokio::time::Instant;
37use tracing::{debug, warn};
38
39use crate::runtime::breaker::EndpointFailureHook;
40use crate::runtime::config::ClientConfig;
41use crate::runtime::transport_error::TransportError;
42use crate::wiring::ClientTuning;
43
44/// Endpoints whose clients are kept at once. Covers the instances a directory
45/// round-robins between; the least recently built one goes first.
46const MAX_ENDPOINTS: usize = 16;
47
48/// An endpoint failure invalidates the resolver's answer at most this often,
49/// so a dead endpoint under load does not turn every call into a directory
50/// round-trip.
51const INVALIDATE_DEBOUNCE: Duration = Duration::from_secs(1);
52
53/// Directory-lookup failure (the directory backend itself could not answer —
54/// e.g. the gRPC directory is unreachable), as opposed to a successful lookup
55/// that found no live instance (`Ok(None)`). Keeping the two distinct lets
56/// callers and observability tell a not-ready provider apart from a directory
57/// outage.
58#[derive(Debug, thiserror::Error)]
59#[error("directory lookup for gear `{gear}` failed: {source}")]
60pub struct ResolveError {
61    /// Gear name (or gRPC service name) whose lookup failed.
62    pub gear: String,
63    /// Underlying directory transport/backend error.
64    #[source]
65    pub source: Box<dyn std::error::Error + Send + Sync + 'static>,
66}
67
68impl ResolveError {
69    /// Build a [`ResolveError`] from any boxable source error.
70    pub fn new<E>(gear: impl Into<String>, source: E) -> Self
71    where
72        E: Into<Box<dyn std::error::Error + Send + Sync + 'static>>,
73    {
74        Self {
75            gear: gear.into(),
76            source: source.into(),
77        }
78    }
79}
80
81/// What a resolving client looks up.
82#[derive(Debug, Clone, PartialEq, Eq, Hash)]
83#[non_exhaustive]
84pub enum ResolveTarget {
85    /// The REST endpoint of a gear.
86    Rest {
87        /// Providing gear.
88        gear: String,
89    },
90    /// A gRPC service. The directory keys gRPC by service name
91    /// (`package.Service`), which carries the contract's major version.
92    Grpc {
93        /// Providing gear, for logs, errors and readiness.
94        gear: String,
95        /// Fully qualified gRPC service name.
96        service: String,
97    },
98}
99
100impl ResolveTarget {
101    /// REST endpoint of `gear`.
102    pub fn rest(gear: impl Into<String>) -> Self {
103        Self::Rest { gear: gear.into() }
104    }
105
106    /// gRPC `service` provided by `gear`.
107    pub fn grpc(gear: impl Into<String>, service: impl Into<String>) -> Self {
108        Self::Grpc {
109            gear: gear.into(),
110            service: service.into(),
111        }
112    }
113
114    /// The providing gear.
115    #[must_use]
116    pub fn gear(&self) -> &str {
117        match self {
118            Self::Rest { gear } | Self::Grpc { gear, .. } => gear,
119        }
120    }
121}
122
123/// Resolves a logical gear name or gRPC service name to a live base endpoint
124/// URI.
125///
126/// Kept as a minimal trait here so `toolkit-contract` does not depend on the
127/// service-directory SDK. The host layer (`toolkit`) provides an adapter over
128/// its `DirectoryClient`; tests can implement it directly.
129///
130/// Return contract:
131/// - `Ok(Some(uri))` — a live instance was resolved.
132/// - `Ok(None)` — the lookup succeeded but no live instance is registered
133///   (provider not ready yet, or every instance evicted).
134/// - `Err(ResolveError)` — the directory backend itself failed to answer.
135///
136/// Both `Ok(None)` and `Err(..)` surface to the caller as a retryable
137/// [`TransportError::Unresolved`]; the distinction exists for logging/metrics.
138///
139/// [`DirectoryResolvingClient`] calls this **on every request** so provider
140/// churn is observed immediately. Implementations whose lookup is expensive
141/// (e.g. an out-of-process gRPC directory) SHOULD memoize internally (short
142/// TTL) rather than performing a network round-trip per call, and drop the
143/// memoized answer in [`invalidate`](Self::invalidate).
144#[async_trait]
145pub trait EndpointResolver: Send + Sync {
146    /// Resolve `gear` to a base endpoint URI (e.g. `http://billing:8080`).
147    ///
148    /// # Errors
149    /// Returns [`ResolveError`] only when the directory backend could not be
150    /// queried; a successful query with no live instance is `Ok(None)`.
151    async fn resolve_endpoint(&self, gear: &str) -> Result<Option<String>, ResolveError>;
152
153    /// Resolve a gRPC `service` (`package.Service`) to the base URI of a
154    /// channel serving it. The default resolves nothing, so a resolver that
155    /// predates gRPC consumers keeps them unresolved rather than misrouted.
156    ///
157    /// # Errors
158    /// As [`resolve_endpoint`](Self::resolve_endpoint).
159    async fn resolve_grpc_endpoint(&self, _service: &str) -> Result<Option<String>, ResolveError> {
160        Ok(None)
161    }
162
163    /// Resolve `target` through the method for its transport.
164    ///
165    /// # Errors
166    /// As [`resolve_endpoint`](Self::resolve_endpoint).
167    async fn resolve_target(&self, target: &ResolveTarget) -> Result<Option<String>, ResolveError> {
168        match target {
169            ResolveTarget::Rest { gear } => self.resolve_endpoint(gear).await,
170            ResolveTarget::Grpc { service, .. } => self.resolve_grpc_endpoint(service).await,
171        }
172    }
173
174    /// Forget any memoized answer for `target`: its endpoint just failed. The
175    /// default does nothing (a resolver that does not memoize).
176    fn invalidate(&self, _target: &ResolveTarget) {}
177}
178
179type ClientBuilder<C> = dyn Fn(ClientConfig) -> Result<C, TransportError> + Send + Sync;
180
181/// Self-healing transport that resolves its endpoint from the directory.
182///
183/// Generic over the concrete generated client `C` (e.g. `PaymentApiRestClient`
184/// or `PaymentApiGrpcClient`). The generated `<Trait>RestResolvingClient` /
185/// `<Trait>GrpcResolvingClient` wraps one of these and delegates each trait
186/// method through [`DirectoryResolvingClient::resolved`].
187pub struct DirectoryResolvingClient<C> {
188    resolver: Arc<dyn EndpointResolver>,
189    target: ResolveTarget,
190    tuning: ClientTuning,
191    build: Box<ClientBuilder<C>>,
192    /// Clients by endpoint, most recently built first.
193    cache: RwLock<Vec<(String, Arc<C>)>>,
194    /// Serializes the build step. Without this, N callers that concurrently
195    /// observe the same absent cache entry (first call, or immediately after
196    /// an endpoint change) would each construct a redundant client — only the
197    /// guard is held, never across an `.await` (the directory lookup has
198    /// already completed by the time this lock is taken; `build` itself is
199    /// synchronous).
200    build_lock: std::sync::Mutex<()>,
201}
202
203impl<C: Send + Sync + 'static> DirectoryResolvingClient<C> {
204    /// Construct a client resolving the REST endpoint of `from_gear`.
205    ///
206    /// - `resolver` — resolves the provider gear name to a live endpoint.
207    /// - `from_gear` — the logical provider gear name to resolve.
208    /// - `tuning` — timeout/retry/reconnect/circuit-breaker settings applied to
209    ///   each built client.
210    /// - `build` — constructs the concrete client `C` from a [`ClientConfig`]
211    ///   (the generated `C::new(config)`, mapping its error into
212    ///   [`TransportError`]).
213    pub fn new(
214        resolver: Arc<dyn EndpointResolver>,
215        from_gear: impl Into<String>,
216        tuning: ClientTuning,
217        build: impl Fn(ClientConfig) -> Result<C, TransportError> + Send + Sync + 'static,
218    ) -> Self {
219        Self::for_target(resolver, ResolveTarget::rest(from_gear), tuning, build)
220    }
221
222    /// Construct a client resolving `target`. See [`Self::new`].
223    pub fn for_target(
224        resolver: Arc<dyn EndpointResolver>,
225        target: ResolveTarget,
226        tuning: ClientTuning,
227        build: impl Fn(ClientConfig) -> Result<C, TransportError> + Send + Sync + 'static,
228    ) -> Self {
229        Self {
230            resolver,
231            target,
232            tuning,
233            build: Box::new(build),
234            cache: RwLock::new(Vec::new()),
235            build_lock: std::sync::Mutex::new(()),
236        }
237    }
238
239    /// The logical provider gear name this client resolves against.
240    #[must_use]
241    pub fn from_gear(&self) -> &str {
242        self.target.gear()
243    }
244
245    /// What this client resolves.
246    #[must_use]
247    pub fn target(&self) -> &ResolveTarget {
248        &self.target
249    }
250
251    /// Resolve (or reuse) the underlying client for the current endpoint.
252    ///
253    /// Re-resolves the directory on every call so a moved or vanished provider
254    /// is observed immediately; the built client is cached per endpoint.
255    /// Returns [`TransportError::Unresolved`] when no live instance is
256    /// registered.
257    ///
258    /// # Errors
259    /// - [`TransportError::Unresolved`] if the directory has no live endpoint.
260    /// - Whatever `build` returns if constructing the client fails.
261    pub async fn resolved(&self) -> Result<Arc<C>, TransportError> {
262        let gear = self.target.gear();
263        let uri = match self.resolver.resolve_target(&self.target).await {
264            Ok(Some(uri)) => uri,
265            Ok(None) => {
266                debug!(gear, target = ?self.target, "no live instance registered; provider not ready");
267                self.clear();
268                return Err(TransportError::unresolved(gear));
269            }
270            Err(err) => {
271                warn!(gear, target = ?self.target, error = %err, "directory lookup failed");
272                self.clear();
273                return Err(TransportError::unresolved(gear));
274            }
275        };
276
277        // Fast path: a client for this endpoint already exists.
278        if let Some(client) = self.cached_for(&uri) {
279            return Ok(client);
280        }
281
282        // First call for this endpoint: build and cache. Single-flight via
283        // `build_lock` so a thundering herd of concurrent callers that all
284        // missed the fast path above builds the client ONCE, not N times.
285        let _build_guard = self
286            .build_lock
287            .lock()
288            .unwrap_or_else(std::sync::PoisonError::into_inner);
289        // Re-check under the lock: another caller may have just finished
290        // building for this exact endpoint while we were waiting for it.
291        if let Some(client) = self.cached_for(&uri) {
292            return Ok(client);
293        }
294        debug!(gear, endpoint = %uri, "building client for resolved endpoint");
295        let cfg = self.config_for(&uri);
296        let client = Arc::new((self.build)(cfg)?);
297        if let Ok(mut w) = self.cache.write() {
298            w.insert(0, (uri, Arc::clone(&client)));
299            w.truncate(MAX_ENDPOINTS);
300        }
301        Ok(client)
302    }
303
304    /// The config for a client of `uri`: the tuning, a circuit breaker of its
305    /// own, and the hook that makes an endpoint failure re-resolve.
306    fn config_for(&self, uri: &str) -> ClientConfig {
307        let name = format!("{}@{uri}", self.target.gear());
308        let breaker = self.tuning.circuit_breaker_for(&name);
309        let invalidator = Invalidator {
310            resolver: Arc::clone(&self.resolver),
311            target: self.target.clone(),
312            last: parking_lot::Mutex::new(None),
313        };
314        self.tuning
315            .apply_to(uri)
316            .with_circuit_breaker(breaker)
317            .with_on_endpoint_failure(EndpointFailureHook::new(move || invalidator.fire()))
318    }
319
320    /// Returns the cached client built for `uri`, if any.
321    fn cached_for(&self, uri: &str) -> Option<Arc<C>> {
322        let r = self.cache.read().ok()?;
323        r.iter()
324            .find(|(cached, _)| cached == uri)
325            .map(|(_, client)| Arc::clone(client))
326    }
327
328    /// Drop every cached client so a now-absent or moved provider isn't
329    /// masked on the next call.
330    fn clear(&self) {
331        if let Ok(mut w) = self.cache.write() {
332            w.clear();
333        }
334    }
335}
336
337/// Drops the resolver's answer for one endpoint's target, debounced.
338struct Invalidator {
339    resolver: Arc<dyn EndpointResolver>,
340    target: ResolveTarget,
341    last: parking_lot::Mutex<Option<Instant>>,
342}
343
344impl Invalidator {
345    fn fire(&self) {
346        let now = Instant::now();
347        {
348            let mut last = self.last.lock();
349            if last.is_some_and(|t| now.saturating_duration_since(t) < INVALIDATE_DEBOUNCE) {
350                return;
351            }
352            *last = Some(now);
353        }
354        self.resolver.invalidate(&self.target);
355    }
356}
357
358#[cfg(test)]
359#[cfg_attr(coverage_nightly, coverage(off))]
360mod tests {
361    use super::*;
362    use std::sync::atomic::{AtomicUsize, Ordering};
363
364    /// One scripted resolver outcome.
365    #[derive(Clone)]
366    enum Step {
367        /// `Ok(Some(uri))`.
368        Found(String),
369        /// `Ok(None)` — looked up, nothing registered.
370        Empty,
371        /// `Err(..)` — directory backend failure.
372        Fail,
373    }
374
375    /// Resolver returning a scripted sequence of outcomes.
376    struct ScriptResolver {
377        steps: Vec<Step>,
378        idx: AtomicUsize,
379    }
380
381    impl ScriptResolver {
382        fn next(&self, key: &str) -> Result<Option<String>, ResolveError> {
383            let i = self.idx.fetch_add(1, Ordering::SeqCst);
384            match self.steps.get(i).cloned() {
385                Some(Step::Found(uri)) => Ok(Some(uri)),
386                Some(Step::Empty) | None => Ok(None),
387                Some(Step::Fail) => Err(ResolveError::new(key, "directory down")),
388            }
389        }
390    }
391
392    #[async_trait]
393    impl EndpointResolver for ScriptResolver {
394        async fn resolve_endpoint(&self, gear: &str) -> Result<Option<String>, ResolveError> {
395            self.next(gear)
396        }
397    }
398
399    /// Dummy "client" carrying the endpoint it was built against.
400    #[derive(Debug)]
401    struct DummyClient {
402        base_url: String,
403    }
404
405    /// Build a resolving client with a **per-instance** build counter (returned
406    /// alongside) so parallel tests don't race on a shared global.
407    fn resolving(steps: Vec<Step>) -> (DirectoryResolvingClient<DummyClient>, Arc<AtomicUsize>) {
408        let builds = Arc::new(AtomicUsize::new(0));
409        let builds_for_closure = Arc::clone(&builds);
410        let client = DirectoryResolvingClient::new(
411            Arc::new(ScriptResolver {
412                steps,
413                idx: AtomicUsize::new(0),
414            }),
415            "billing",
416            ClientTuning::default(),
417            move |cfg| {
418                builds_for_closure.fetch_add(1, Ordering::SeqCst);
419                Ok(DummyClient {
420                    base_url: cfg.base_url,
421                })
422            },
423        );
424        (client, builds)
425    }
426
427    #[tokio::test]
428    async fn unresolved_when_no_endpoint() {
429        let (c, _builds) = resolving(vec![Step::Empty]);
430        let err = c.resolved().await.unwrap_err();
431        assert!(matches!(err, TransportError::Unresolved { .. }));
432    }
433
434    #[tokio::test]
435    async fn directory_failure_surfaces_as_unresolved() {
436        let (c, builds) = resolving(vec![Step::Fail]);
437        let err = c.resolved().await.unwrap_err();
438        assert!(matches!(err, TransportError::Unresolved { .. }));
439        assert_eq!(
440            builds.load(Ordering::SeqCst),
441            0,
442            "must not build a client on directory failure"
443        );
444    }
445
446    #[tokio::test]
447    async fn caches_while_endpoint_stable_and_rebuilds_on_change() {
448        let (c, builds) = resolving(vec![
449            Step::Found("http://a:8080".into()),
450            Step::Found("http://a:8080".into()),
451            Step::Found("http://b:9090".into()),
452        ]);
453
454        let c1 = c.resolved().await.unwrap();
455        assert_eq!(c1.base_url, "http://a:8080");
456        let c2 = c.resolved().await.unwrap();
457        assert_eq!(c2.base_url, "http://a:8080");
458        assert_eq!(
459            builds.load(Ordering::SeqCst),
460            1,
461            "stable endpoint reuses client"
462        );
463
464        let c3 = c.resolved().await.unwrap();
465        assert_eq!(c3.base_url, "http://b:9090");
466        assert_eq!(
467            builds.load(Ordering::SeqCst),
468            2,
469            "endpoint change rebuilds client"
470        );
471    }
472
473    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
474    async fn concurrent_resolves_build_client_only_once() {
475        // Real OS-thread concurrency (not single-threaded cooperative
476        // interleaving): N callers all resolving to the same first-seen
477        // endpoint race to build. Without single-flight (`build_lock`), each
478        // one that misses the cache before any write lands would construct
479        // its own redundant client.
480        const N: usize = 16;
481        let (c, builds) = resolving(vec![Step::Found("http://a:8080".into()); N]);
482        let c = Arc::new(c);
483
484        let handles: Vec<_> = (0..N)
485            .map(|_| {
486                let c = Arc::clone(&c);
487                tokio::spawn(async move { c.resolved().await.unwrap() })
488            })
489            .collect();
490
491        for h in handles {
492            let client = h.await.unwrap();
493            assert_eq!(client.base_url, "http://a:8080");
494        }
495        assert_eq!(
496            builds.load(Ordering::SeqCst),
497            1,
498            "single-flight: exactly one build for {N} concurrent resolves to the same endpoint"
499        );
500    }
501
502    #[tokio::test]
503    async fn recovers_after_provider_vanishes_and_returns() {
504        let (c, _builds) = resolving(vec![
505            Step::Found("http://a:8080".into()),
506            Step::Empty,
507            Step::Found("http://c:7070".into()),
508        ]);
509
510        assert_eq!(c.resolved().await.unwrap().base_url, "http://a:8080");
511        // Provider vanished → Unresolved, stale cache dropped.
512        assert!(matches!(
513            c.resolved().await.unwrap_err(),
514            TransportError::Unresolved { .. }
515        ));
516        // New instance appears → resolves again, self-healed.
517        assert_eq!(c.resolved().await.unwrap().base_url, "http://c:7070");
518    }
519
520    #[tokio::test]
521    async fn rotating_between_endpoints_reuses_each_client() {
522        let (c, builds) = resolving(vec![
523            Step::Found("http://a:8080".into()),
524            Step::Found("http://b:8080".into()),
525            Step::Found("http://a:8080".into()),
526            Step::Found("http://b:8080".into()),
527        ]);
528        let first_a = c.resolved().await.unwrap();
529        c.resolved().await.unwrap();
530        let again_a = c.resolved().await.unwrap();
531        c.resolved().await.unwrap();
532
533        assert!(Arc::ptr_eq(&first_a, &again_a));
534        assert_eq!(builds.load(Ordering::SeqCst), 2, "one build per endpoint");
535    }
536
537    /// Records what the resolving client asked for, and invalidations.
538    #[derive(Default)]
539    struct Recording {
540        grpc: parking_lot::Mutex<Vec<String>>,
541        invalidated: AtomicUsize,
542    }
543
544    #[async_trait]
545    impl EndpointResolver for Recording {
546        async fn resolve_endpoint(&self, _gear: &str) -> Result<Option<String>, ResolveError> {
547            Ok(Some("http://rest:8080".into()))
548        }
549
550        async fn resolve_grpc_endpoint(
551            &self,
552            service: &str,
553        ) -> Result<Option<String>, ResolveError> {
554            self.grpc.lock().push(service.to_owned());
555            Ok(Some("http://grpc:50051".into()))
556        }
557
558        fn invalidate(&self, _target: &ResolveTarget) {
559            self.invalidated.fetch_add(1, Ordering::SeqCst);
560        }
561    }
562
563    fn capturing(
564        resolver: Arc<Recording>,
565        target: ResolveTarget,
566    ) -> DirectoryResolvingClient<ClientConfig> {
567        DirectoryResolvingClient::for_target(resolver, target, ClientTuning::default(), Ok)
568    }
569
570    #[tokio::test]
571    async fn a_grpc_target_resolves_by_service_name() {
572        let resolver = Arc::new(Recording::default());
573        let c = capturing(
574            Arc::clone(&resolver),
575            ResolveTarget::grpc("payments", "payments.v1.PaymentApi"),
576        );
577        let cfg = c.resolved().await.unwrap();
578
579        assert_eq!(cfg.base_url, "http://grpc:50051");
580        assert_eq!(*resolver.grpc.lock(), ["payments.v1.PaymentApi"]);
581        assert_eq!(c.from_gear(), "payments");
582    }
583
584    #[tokio::test]
585    async fn each_endpoint_gets_its_own_breaker_by_default() {
586        let resolver = Arc::new(Recording::default());
587        let cfg = capturing(resolver, ResolveTarget::rest("payments"))
588            .resolved()
589            .await
590            .unwrap();
591        let breaker = cfg.circuit_breaker.as_ref().expect("on by default");
592        assert!(format!("{breaker:?}").contains("payments@http://rest:8080"));
593    }
594
595    #[tokio::test]
596    async fn a_disabled_breaker_is_not_attached() {
597        let tuning = ClientTuning {
598            circuit_breaker: Some(
599                toolkit_resilience::circuit_breaker::CircuitBreakerConfig::disabled(),
600            ),
601            ..ClientTuning::default()
602        };
603        let c = DirectoryResolvingClient::for_target(
604            Arc::new(Recording::default()),
605            ResolveTarget::rest("payments"),
606            tuning,
607            Ok,
608        );
609        assert!(c.resolved().await.unwrap().circuit_breaker.is_none());
610    }
611
612    #[tokio::test(start_paused = true)]
613    async fn an_endpoint_failure_invalidates_the_resolver_debounced() {
614        let resolver = Arc::new(Recording::default());
615        let cfg = capturing(Arc::clone(&resolver), ResolveTarget::rest("payments"))
616            .resolved()
617            .await
618            .unwrap();
619        let hook = cfg.on_endpoint_failure.clone().expect("hook installed");
620
621        (hook.0)();
622        (hook.0)();
623        assert_eq!(resolver.invalidated.load(Ordering::SeqCst), 1);
624
625        tokio::time::advance(INVALIDATE_DEBOUNCE).await;
626        (hook.0)();
627        assert_eq!(resolver.invalidated.load(Ordering::SeqCst), 2);
628    }
629}