Skip to main content

cf_system_sdk_directory/
api.rs

1//! Directory API - contract for service discovery and instance resolution
2//!
3//! This gear defines the core traits and types for the directory service API.
4
5use anyhow::Result;
6use async_trait::async_trait;
7use std::collections::BTreeMap;
8
9/// Represents an endpoint where a service can be reached
10#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
11pub struct ServiceEndpoint {
12    pub uri: String,
13}
14
15impl ServiceEndpoint {
16    pub fn new(uri: impl Into<String>) -> Self {
17        Self { uri: uri.into() }
18    }
19
20    #[must_use]
21    pub fn http(host: &str, port: u16) -> Self {
22        Self {
23            uri: format!("{}://{}:{}", "http", host, port),
24        }
25    }
26
27    #[must_use]
28    pub fn https(host: &str, port: u16) -> Self {
29        Self {
30            uri: format!("https://{host}:{port}"),
31        }
32    }
33
34    pub fn uds(path: impl AsRef<std::path::Path>) -> Self {
35        Self {
36            uri: format!("unix://{}", path.as_ref().display()),
37        }
38    }
39}
40
41/// Label-equality selector over instance labels (k8s `matchLabels` style).
42///
43/// Matching is equality-AND: an instance matches iff it carries **every**
44/// `(key, value)` pair in `match_labels`. An empty selector matches every
45/// instance. This is the selector consumed by
46/// [`DirectoryClient::resolve_by_labels`].
47#[derive(Clone, Debug, Default, PartialEq, Eq)]
48pub struct LabelSelector {
49    /// Required label equalities; all must match.
50    pub match_labels: BTreeMap<String, String>,
51}
52
53impl LabelSelector {
54    /// An empty selector (matches every instance).
55    #[must_use]
56    pub fn new() -> Self {
57        Self::default()
58    }
59
60    /// Build a selector from an existing `matchLabels` map.
61    #[must_use]
62    pub fn from_match_labels(match_labels: BTreeMap<String, String>) -> Self {
63        Self { match_labels }
64    }
65
66    /// Add one required label equality, returning `self` for chaining.
67    #[must_use]
68    pub fn with(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
69        self.match_labels.insert(key.into(), value.into());
70        self
71    }
72
73    /// Whether this selector constrains nothing (matches every instance).
74    #[must_use]
75    pub fn is_empty(&self) -> bool {
76        self.match_labels.is_empty()
77    }
78
79    /// Whether `labels` satisfies every required equality in this selector.
80    #[must_use]
81    pub fn matches(&self, labels: &BTreeMap<String, String>) -> bool {
82        self.match_labels
83            .iter()
84            .all(|(k, v)| labels.get(k) == Some(v))
85    }
86}
87
88/// Serving state of a directory instance, projected from the directory's live
89/// registration/heartbeat tracking.
90///
91/// Only [`Ready`](Self::Ready) / [`Healthy`](Self::Healthy) are **serving**;
92/// [`Draining`](Self::Draining) is a graceful shutdown (callers should avoid
93/// sending new work) and [`Quarantined`](Self::Quarantined) is stale (missed
94/// heartbeats). [`Registered`](Self::Registered) is the pre-serving baseline.
95/// Exposed on [`ServiceInstanceInfo`] so [`DirectoryClient::resolve_by_labels`]
96/// callers can apply their own health policy from a single resolve.
97#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
98pub enum InstanceState {
99    /// Registered but not yet serving (no heartbeat / readiness signal).
100    #[default]
101    Registered,
102    /// Dependencies resolved and marked ready.
103    Ready,
104    /// Serving and heartbeating.
105    Healthy,
106    /// Missed its heartbeat deadline; not serving, pending eviction.
107    Quarantined,
108    /// Gracefully shutting down; upstreams should stop routing new work.
109    Draining,
110    /// State could not be determined.
111    Unknown,
112}
113
114impl InstanceState {
115    /// Whether an instance in this state should receive new traffic
116    /// (`Ready` / `Healthy`). All other states are non-serving.
117    #[must_use]
118    pub fn is_serving(self) -> bool {
119        matches!(self, InstanceState::Ready | InstanceState::Healthy)
120    }
121}
122
123/// What an instance declares about itself in `RegisterInstance` / `Heartbeat`
124/// (`cpt-cf-adr-directory-persistence-and-replication`). The directory derives
125/// the observable [`InstanceState`] from this
126/// plus the instance's lease; this is the only liveness signal an instance
127/// writes. Distinct from [`InstanceState`], which is the *observed* projection.
128#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
129pub enum ReportedState {
130    /// Not yet serving (starting up, or failing a readiness check).
131    #[default]
132    Starting,
133    /// Serving and heartbeating.
134    Serving,
135    /// Gracefully draining; upstreams should stop routing new work.
136    Draining,
137}
138
139/// Acknowledgement returned by a successful registration.
140#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
141pub struct RegisterAck {
142    /// Lease TTL the directory granted, if it returned one. A new worker
143    /// heartbeats every `lease_ttl / 3`; `None` means the directory returned no
144    /// TTL and the worker falls back to its configured heartbeat interval.
145    pub lease_ttl: Option<std::time::Duration>,
146}
147
148/// Information about a service instance
149#[derive(Debug, Clone, Default)]
150#[non_exhaustive]
151pub struct ServiceInstanceInfo {
152    /// Gear name this instance belongs to
153    pub gear: String,
154    /// Unique instance identifier
155    pub instance_id: String,
156    /// Primary endpoint for the instance
157    pub endpoint: Option<ServiceEndpoint>,
158    /// Optional version string
159    pub version: Option<String>,
160    /// REST endpoint (HTTP base URL) for this instance, or `None` if the gear
161    /// exposes no REST API. This is the address the edge reverse-proxy actually
162    /// dials for REST routing.
163    pub rest_endpoint: Option<ServiceEndpoint>,
164    /// Stable content token for the published `OpenAPI` spec, if any.
165    ///
166    /// Enumeration is deliberately spec-free: only this hash rides along, never
167    /// the full document (fetched out-of-band via
168    /// [`DirectoryClient::get_openapi_spec`]). The hash lets a consumer detect a
169    /// spec change without inlining N copies of the document.
170    pub openapi_spec_hash: Option<String>,
171    /// Published gRPC services as `(service name, endpoint)` pairs.
172    ///
173    /// Kept as an ordered list rather than a map so it round-trips a repeated
174    /// proto field without reordering; service names are unique per instance.
175    /// Carried back by `list_instances` so a subsequent `register_instance`
176    /// (which replaces the entry wholesale) can augment — rather than clobber —
177    /// the previously-registered gRPC services when adding a REST endpoint.
178    pub grpc_services: Vec<(String, ServiceEndpoint)>,
179    /// Stable addressing labels published by this instance (k8s `matchLabels`
180    /// style). Used by [`DirectoryClient::resolve_by_labels`] to select shards
181    /// or peers within a directory name.
182    pub labels: BTreeMap<String, String>,
183    /// Live serving state, so a `resolve_by_labels` caller can apply its own
184    /// health policy without a second call. Defaults to
185    /// [`InstanceState::Registered`].
186    pub state: InstanceState,
187}
188
189impl ServiceInstanceInfo {
190    /// Start a projection for `gear` / `instance_id` with no primary endpoint
191    /// and no optional metadata. Chain the `with_*` builders to populate it.
192    /// `#[non_exhaustive]` means callers must use this builder rather than a
193    /// struct literal, so future fields stay additive.
194    #[must_use]
195    pub fn new(gear: impl Into<String>, instance_id: impl Into<String>) -> Self {
196        Self {
197            gear: gear.into(),
198            instance_id: instance_id.into(),
199            ..Self::default()
200        }
201    }
202
203    /// Set the primary endpoint (`None` for an instance with no primary
204    /// endpoint).
205    #[must_use]
206    pub fn with_endpoint(mut self, endpoint: Option<ServiceEndpoint>) -> Self {
207        self.endpoint = endpoint;
208        self
209    }
210
211    /// Set the optional version string.
212    #[must_use]
213    pub fn with_version(mut self, version: Option<String>) -> Self {
214        self.version = version;
215        self
216    }
217
218    /// Set the optional REST endpoint.
219    #[must_use]
220    pub fn with_rest_endpoint(mut self, rest_endpoint: Option<ServiceEndpoint>) -> Self {
221        self.rest_endpoint = rest_endpoint;
222        self
223    }
224
225    /// Set the optional `OpenAPI` spec content token.
226    #[must_use]
227    pub fn with_openapi_spec_hash(mut self, openapi_spec_hash: Option<String>) -> Self {
228        self.openapi_spec_hash = openapi_spec_hash;
229        self
230    }
231
232    /// Set the published gRPC services.
233    #[must_use]
234    pub fn with_grpc_services(mut self, grpc_services: Vec<(String, ServiceEndpoint)>) -> Self {
235        self.grpc_services = grpc_services;
236        self
237    }
238
239    /// Set the stable addressing labels.
240    #[must_use]
241    pub fn with_labels(mut self, labels: BTreeMap<String, String>) -> Self {
242        self.labels = labels;
243        self
244    }
245
246    /// Set the live serving state.
247    #[must_use]
248    pub fn with_state(mut self, state: InstanceState) -> Self {
249        self.state = state;
250        self
251    }
252
253    /// Drop the stable addressing labels, returning `self`.
254    ///
255    /// The shared transform every [`DirectoryClient::list_all_instances`]
256    /// implementation applies so the cross-gear snapshot omits labels
257    /// identically across transports — see that method's doc for why.
258    #[must_use]
259    pub fn without_labels(mut self) -> Self {
260        self.labels.clear();
261        self
262    }
263}
264
265/// Information for registering a new gear instance
266#[derive(Debug, Clone, Default)]
267#[non_exhaustive]
268pub struct RegisterInstanceInfo {
269    /// Gear name
270    pub gear: String,
271    /// Unique instance identifier
272    pub instance_id: String,
273    /// Published gRPC services as `(service name, endpoint)` pairs (service
274    /// names are unique per instance; ordered to mirror the proto repeated
275    /// field rather than reordered into a map).
276    pub grpc_services: Vec<(String, ServiceEndpoint)>,
277    /// Optional version string
278    pub version: Option<String>,
279    /// Optional REST endpoint (HTTP base URL) exposed by the gear.
280    pub rest_endpoint: Option<ServiceEndpoint>,
281    /// Optional `OpenAPI` spec (JSON) published by the gear.
282    pub openapi_spec: Option<String>,
283    /// Stable addressing labels for this instance (k8s `matchLabels` style).
284    pub labels: BTreeMap<String, String>,
285    /// State the registrant declares about itself, or `None` when
286    /// unspecified. On a new record `None` means [`ReportedState::Starting`];
287    /// on a re-registration `None` leaves the stored state unchanged.
288    pub reported_state: Option<ReportedState>,
289}
290
291impl RegisterInstanceInfo {
292    /// Start a registration for `gear` / `instance_id` with no endpoints,
293    /// version, spec, or labels. Chain the `with_*` builders to populate it.
294    #[must_use]
295    pub fn new(gear: impl Into<String>, instance_id: impl Into<String>) -> Self {
296        Self {
297            gear: gear.into(),
298            instance_id: instance_id.into(),
299            ..Self::default()
300        }
301    }
302
303    /// Set the published gRPC services.
304    #[must_use]
305    pub fn with_grpc_services(mut self, grpc_services: Vec<(String, ServiceEndpoint)>) -> Self {
306        self.grpc_services = grpc_services;
307        self
308    }
309
310    /// Set the version string.
311    #[must_use]
312    pub fn with_version(mut self, version: impl Into<String>) -> Self {
313        self.version = Some(version.into());
314        self
315    }
316
317    /// Set the REST endpoint (HTTP base URL).
318    #[must_use]
319    pub fn with_rest_endpoint(mut self, rest_endpoint: ServiceEndpoint) -> Self {
320        self.rest_endpoint = Some(rest_endpoint);
321        self
322    }
323
324    /// Set the published `OpenAPI` spec (JSON).
325    #[must_use]
326    pub fn with_openapi_spec(mut self, openapi_spec: impl Into<String>) -> Self {
327        self.openapi_spec = Some(openapi_spec.into());
328        self
329    }
330
331    /// Set the stable addressing labels.
332    ///
333    /// Re-registration replaces the directory entry, but an **empty** label
334    /// set is treated as "preserve the stored labels", not "clear them" (see
335    /// `GearManager::with_metadata_of`, which treats an absent REST endpoint,
336    /// `OpenAPI` spec or gRPC service set the same way): the periodic self-heal
337    /// and REST augmentation re-register without labels and must not erase a
338    /// shard's identity. A non-empty set replaces the stored one. Clearing labels
339    /// outright is therefore intentionally not expressible — an instance's
340    /// labels are its static shard/peer identity for its lifetime; changing
341    /// them means restarting with new configuration.
342    #[must_use]
343    pub fn with_labels(mut self, labels: BTreeMap<String, String>) -> Self {
344        self.labels = labels;
345        self
346    }
347
348    /// Set the state the registrant declares about itself.
349    #[must_use]
350    pub fn with_reported_state(mut self, reported: ReportedState) -> Self {
351        self.reported_state = Some(reported);
352        self
353    }
354}
355
356/// A resolved gRPC service and the endpoint it is reachable at.
357#[derive(Clone, Debug, PartialEq, Eq, Hash)]
358pub struct GrpcServiceInfo {
359    /// Fully-qualified gRPC service name (e.g. `payment.v1.PaymentApi`).
360    pub service_name: String,
361    /// Endpoint the service is reachable at.
362    pub endpoint: ServiceEndpoint,
363}
364
365impl GrpcServiceInfo {
366    pub fn new(service_name: impl Into<String>, endpoint: ServiceEndpoint) -> Self {
367        Self {
368            service_name: service_name.into(),
369            endpoint,
370        }
371    }
372}
373
374/// Sentinel error wrapped via `anyhow::Error` to signal "the requested gear or
375/// service is not registered (or has no live instance)" through the
376/// [`DirectoryClient`] trait. Consumers downcast to this type to distinguish a
377/// not-ready provider (eventual readiness) from a directory-backend failure —
378/// see `toolkit::discovery::DirectoryEndpointResolver`.
379#[derive(Debug, Clone, PartialEq, Eq)]
380pub struct DirectoryNotFound {
381    /// What was being looked up — e.g. `"gear foo"` or `"service foo.Bar"`.
382    pub resource: String,
383}
384
385impl DirectoryNotFound {
386    pub fn new(resource: impl Into<String>) -> Self {
387        Self {
388            resource: resource.into(),
389        }
390    }
391}
392
393impl std::fmt::Display for DirectoryNotFound {
394    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
395        write!(f, "directory: not found: {}", self.resource)
396    }
397}
398
399impl std::error::Error for DirectoryNotFound {}
400
401/// Sentinel error wrapped via `anyhow::Error` to signal "client-supplied
402/// argument is malformed" (e.g. invalid UUID) through the [`DirectoryClient`]
403/// trait. Allows the gRPC server boundary to return `Status::invalid_argument`
404/// instead of mislabeling a client bug as an internal failure.
405#[derive(Debug, Clone, PartialEq, Eq)]
406pub struct DirectoryInvalidArgument {
407    /// Human-readable description of what was invalid.
408    pub message: String,
409}
410
411impl DirectoryInvalidArgument {
412    pub fn new(message: impl Into<String>) -> Self {
413        Self {
414            message: message.into(),
415        }
416    }
417}
418
419impl std::fmt::Display for DirectoryInvalidArgument {
420    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
421        write!(f, "directory: invalid argument: {}", self.message)
422    }
423}
424
425impl std::error::Error for DirectoryInvalidArgument {}
426
427/// Sentinel error (wrapped via `anyhow::Error`) signalling a **permanent**
428/// authorization refusal: retrying the identical request can never turn a "no"
429/// into a "yes". Carries the gRPC `PermissionDenied` code across the
430/// [`DirectoryClient`] boundary (otherwise lost when a `tonic::Status` is
431/// stringified) so the presence loop stops retrying and logs loudly instead of
432/// spinning at `warn!`. Reached when the peer is not authorized for the gear, its
433/// namespace / trust domain is not allowlisted, or a service name is *pinned* to
434/// another gear (a non-recoverable [`DirectoryServiceNameConflict`]; a recoverable
435/// one is `FailedPrecondition`).
436#[derive(Debug, Clone, PartialEq, Eq)]
437pub struct DirectoryPermissionDenied {
438    /// Human-readable description of why the call was refused.
439    pub message: String,
440}
441
442impl DirectoryPermissionDenied {
443    pub fn new(message: impl Into<String>) -> Self {
444        Self {
445            message: message.into(),
446        }
447    }
448}
449
450impl std::fmt::Display for DirectoryPermissionDenied {
451    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
452        write!(f, "directory: permission denied: {}", self.message)
453    }
454}
455
456impl std::error::Error for DirectoryPermissionDenied {}
457
458/// Sentinel error signalling "a gRPC service name in this registration is already
459/// owned by a *different* gear" (single-gear ownership is enforced atomically in
460/// `GearManager::register_instance`). The gRPC boundary logs the conflicting
461/// `service_name` / `owner` server-side and returns a static-message status whose
462/// code depends on [`recoverable`](Self::recoverable):
463///
464/// - `recoverable` → `Status::failed_precondition`: another gear merely
465///   *currently advertises* the name; it clears when that gear deregisters, so
466///   the registrant retries.
467/// - not `recoverable` → `Status::permission_denied`: the name is pinned to
468///   another gear by the ownership map; retrying can never reassign it.
469#[derive(Debug, Clone, PartialEq, Eq)]
470pub struct DirectoryServiceNameConflict {
471    /// The gRPC service name that is already owned.
472    pub service_name: String,
473    /// The gear that currently owns `service_name`.
474    pub owner: String,
475    /// Whether waiting could clear the conflict (see the type docs). `true` for
476    /// a current-advertiser conflict, `false` for a pinned-ownership conflict.
477    pub recoverable: bool,
478}
479
480impl std::fmt::Display for DirectoryServiceNameConflict {
481    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
482        write!(
483            f,
484            "directory: gRPC service name '{}' already owned by gear '{}'",
485            self.service_name, self.owner
486        )
487    }
488}
489
490impl std::error::Error for DirectoryServiceNameConflict {}
491
492/// Directory API trait for service discovery and instance management
493///
494/// This trait defines the contract for interacting with the gear directory.
495/// It can be implemented by:
496/// - A local implementation that delegates to `GearManager`
497/// - A gRPC client for out-of-process gears
498#[async_trait]
499pub trait DirectoryClient: Send + Sync {
500    /// Resolve a gRPC service by its logical name to an endpoint
501    async fn resolve_grpc_service(&self, service_name: &str) -> Result<ServiceEndpoint>;
502
503    /// Resolve a REST endpoint (HTTP base URL) for a gear by its name.
504    ///
505    /// Returns the base URL (e.g. `http://billing:8080`) that callers use to
506    /// make REST requests to the resolved gear.
507    async fn resolve_rest_service(&self, gear_name: &str) -> Result<ServiceEndpoint>;
508
509    /// Retrieve the `OpenAPI` spec (JSON) published by a gear.
510    async fn get_openapi_spec(&self, gear_name: &str) -> Result<String>;
511
512    /// List all service instances for a given gear.
513    ///
514    /// Entries are **spec-free**: only the `openapi_spec_hash` is carried, never
515    /// the full `OpenAPI` document, so a multi-instance response stays
516    /// bounded regardless of spec size. Callers fetch the document out-of-band
517    /// via [`get_openapi_spec`](Self::get_openapi_spec); the hash lets a consumer
518    /// detect a spec change without inlining N copies of the document.
519    ///
520    /// An endpoint-less instance is still returned (`endpoint`/`rest_endpoint` =
521    /// `None`, never an empty-URI sentinel): *no-endpoint, not an error*. Only
522    /// [`list_all_instances`](Self::list_all_instances), which needs a dialable
523    /// URI, drops such entries.
524    async fn list_instances(&self, gear: &str) -> Result<Vec<ServiceInstanceInfo>>;
525
526    /// Resolve instances of `gear` whose labels satisfy `selector`.
527    ///
528    /// Matching is equality-AND (k8s `matchLabels`): an instance matches iff
529    /// it carries **every** `(key, value)` pair in the selector; an empty
530    /// selector matches every instance of the name.
531    ///
532    /// The returned set is **not** health-filtered — matched instances are
533    /// returned regardless of readiness/heartbeat state, each carrying its
534    /// `instance_id`, `labels`, endpoints, and live
535    /// [`state`](ServiceInstanceInfo::state). Applying liveness policy (e.g.
536    /// keeping only [`InstanceState::is_serving`]) is the caller's
537    /// responsibility.
538    ///
539    /// Nor is it **endpoint-filtered**: a matched instance that advertises no
540    /// endpoint yet is still returned (`endpoint`/`rest_endpoint` = `None`) —
541    /// *no-endpoint, not an error* — so the caller can fall back rather than
542    /// have the match silently hidden.
543    ///
544    /// Returned entries are **spec-free** on every implementation — the full
545    /// `OpenAPI` document is omitted (only its hash is carried), so the
546    /// polled resolve payload stays bounded; the caller fetches documents via
547    /// [`get_openapi_spec`](Self::get_openapi_spec). This holds regardless of
548    /// whether the selector is empty. The default body enumerates via
549    /// [`list_instances`](Self::list_instances) and filters in-process;
550    /// transport-backed clients (e.g. the gRPC client) override it to push the
551    /// selector server-side.
552    ///
553    /// Label-based selection is effectively **out-of-process only**. Labels are
554    /// published from the `OoP` serve path's configuration (`oop_http.labels`);
555    /// the in-process registration path (grpc-hub start phase /
556    /// `run_directory_register_phase`) has no label source, so an in-process
557    /// gear carries no labels and a non-empty selector never matches it. This
558    /// matches the deployment model: shards/peers are distinct instances
559    /// (separate pods/processes), which is inherently the `OoP` topology.
560    async fn resolve_by_labels(
561        &self,
562        gear: &str,
563        selector: &LabelSelector,
564    ) -> Result<Vec<ServiceInstanceInfo>> {
565        // cancel-safe: the single await precedes any mutation; cancelling here
566        // just drops the in-flight list and leaves no partial state.
567        let instances = self.list_instances(gear).await?;
568        // Entries are spec-free by construction — `ServiceInstanceInfo` carries
569        // only the `openapi_spec_hash`, never the full OpenAPI document.
570        Ok(instances
571            .into_iter()
572            .filter(|i| selector.matches(&i.labels))
573            .collect())
574    }
575
576    /// List every service instance across all registered gears.
577    ///
578    /// Used by the edge gateway to discover which gears (and their REST
579    /// endpoints) to reverse-proxy. This is a lightweight discovery snapshot.
580    /// Like every enumeration path, it is **spec-free**: entries carry only the
581    /// `openapi_spec_hash`, never the full `OpenAPI` document, even when the
582    /// backing store holds a stored specification. The edge fetches a gear's
583    /// document once, on first discovery, via
584    /// [`get_openapi_spec`](Self::get_openapi_spec).
585    ///
586    /// The returned instances also do **not** carry `labels`: every
587    /// implementation applies [`ServiceInstanceInfo::without_labels`] so the
588    /// snapshot omits them identically regardless of transport. Labels drive
589    /// the targeted [`resolve_by_labels`](Self::resolve_by_labels) path, not
590    /// this snapshot.
591    async fn list_all_instances(&self) -> Result<Vec<ServiceInstanceInfo>>;
592
593    /// Register a new gear instance with the directory
594    async fn register_instance(&self, info: RegisterInstanceInfo) -> Result<()>;
595
596    /// Register a new gear instance and learn the lease TTL the directory
597    /// granted.
598    ///
599    /// The default delegates to [`register_instance`](Self::register_instance)
600    /// and reports no TTL, so existing implementations keep working unchanged;
601    /// the real clients (in-process and gRPC) override it to surface
602    /// `lease_ttl_ms`. Callers that need the lease to pace their heartbeats
603    /// (the presence loop) use this instead of `register_instance`.
604    async fn register_with_lease(&self, info: RegisterInstanceInfo) -> Result<RegisterAck> {
605        self.register_instance(info)
606            .await
607            .map(|()| RegisterAck::default())
608    }
609
610    /// Deregister a gear instance (for graceful shutdown)
611    async fn deregister_instance(&self, gear: &str, instance_id: &str) -> Result<()>;
612
613    /// Send a heartbeat for a gear instance to indicate it's still alive
614    async fn send_heartbeat(&self, gear: &str, instance_id: &str) -> Result<()>;
615
616    /// Send a heartbeat carrying the state the instance reports about itself:
617    /// `Serving` in steady state, `Draining` while shutting down.
618    ///
619    /// The default ignores `reported` and delegates to
620    /// [`send_heartbeat`](Self::send_heartbeat), so existing implementations
621    /// keep working; the real clients override it to carry the state (and to
622    /// map an unknown instance onto [`DirectoryNotFound`]). `None` means the
623    /// caller does not report a state, which the directory reads as `Serving`.
624    async fn heartbeat(
625        &self,
626        gear: &str,
627        instance_id: &str,
628        reported: Option<ReportedState>,
629    ) -> Result<()> {
630        let _ = reported;
631        self.send_heartbeat(gear, instance_id).await
632    }
633}
634
635#[cfg(test)]
636#[cfg_attr(coverage_nightly, coverage(off))]
637mod tests {
638    use super::*;
639
640    #[test]
641    fn test_service_endpoint_creation() {
642        let http_ep = ServiceEndpoint::http("localhost", 8080);
643        assert_eq!(http_ep.uri, concat!("http", "://localhost:8080"));
644
645        let https_endpoint = ServiceEndpoint::https("localhost", 8443);
646        assert_eq!(https_endpoint.uri, "https://localhost:8443");
647
648        let uds_ep = ServiceEndpoint::uds("/tmp/socket.sock");
649        assert!(uds_ep.uri.starts_with("unix://"));
650        assert!(uds_ep.uri.contains("socket.sock"));
651
652        let custom_ep = ServiceEndpoint::new(concat!("http", "://example.com"));
653        assert_eq!(custom_ep.uri, concat!("http", "://example.com"));
654    }
655
656    #[test]
657    fn test_register_instance_info() {
658        let info = RegisterInstanceInfo::new("test_gear", "instance1")
659            .with_grpc_services(vec![(
660                "test.Service".to_owned(),
661                ServiceEndpoint::http("127.0.0.1", 8001),
662            )])
663            .with_version("1.0.0");
664
665        assert_eq!(info.gear, "test_gear");
666        assert_eq!(info.instance_id, "instance1");
667        assert_eq!(info.grpc_services.len(), 1);
668        assert!(info.rest_endpoint.is_none());
669        assert!(info.openapi_spec.is_none());
670        assert!(info.labels.is_empty());
671    }
672
673    #[test]
674    fn test_register_instance_info_with_rest() {
675        let info = RegisterInstanceInfo {
676            gear: "billing".to_owned(),
677            instance_id: "instance1".to_owned(),
678            grpc_services: vec![],
679            version: Some("2.0.0".to_owned()),
680            labels: BTreeMap::new(),
681            rest_endpoint: Some(ServiceEndpoint::http("billing", 8080)),
682            openapi_spec: Some("{\"openapi\":\"3.1.0\"}".to_owned()),
683            reported_state: None,
684        };
685
686        assert_eq!(info.gear, "billing");
687        assert_eq!(
688            info.rest_endpoint.as_ref().unwrap().uri,
689            concat!("http", "://billing:8080")
690        );
691        assert!(info.openapi_spec.is_some());
692    }
693
694    fn labels(pairs: &[(&str, &str)]) -> BTreeMap<String, String> {
695        pairs
696            .iter()
697            .map(|(k, v)| ((*k).to_owned(), (*v).to_owned()))
698            .collect()
699    }
700
701    #[test]
702    fn label_selector_equality_and_matches() {
703        let selector = LabelSelector::new()
704            .with("shard", "7")
705            .with("role", "ingest");
706
707        // Superset of the required labels matches.
708        assert!(selector.matches(&labels(&[
709            ("shard", "7"),
710            ("role", "ingest"),
711            ("extra", "x"),
712        ])));
713        // Missing one required key fails.
714        assert!(!selector.matches(&labels(&[("shard", "7")])));
715        // Wrong value on a required key fails.
716        assert!(!selector.matches(&labels(&[("shard", "8"), ("role", "ingest")])));
717    }
718
719    #[test]
720    fn empty_label_selector_matches_everything() {
721        let selector = LabelSelector::new();
722        assert!(selector.is_empty());
723        assert!(selector.matches(&BTreeMap::new()));
724        assert!(selector.matches(&labels(&[("shard", "7")])));
725    }
726
727    struct StaticDirectory {
728        instances: Vec<ServiceInstanceInfo>,
729    }
730
731    #[async_trait]
732    impl DirectoryClient for StaticDirectory {
733        async fn resolve_grpc_service(&self, service_name: &str) -> Result<ServiceEndpoint> {
734            Err(DirectoryNotFound::new(format!("service {service_name}")).into())
735        }
736        async fn resolve_rest_service(&self, gear_name: &str) -> Result<ServiceEndpoint> {
737            Err(DirectoryNotFound::new(format!("gear {gear_name}")).into())
738        }
739        async fn get_openapi_spec(&self, gear_name: &str) -> Result<String> {
740            Err(DirectoryNotFound::new(format!("spec {gear_name}")).into())
741        }
742        async fn list_instances(&self, gear: &str) -> Result<Vec<ServiceInstanceInfo>> {
743            Ok(self
744                .instances
745                .iter()
746                .filter(|i| i.gear == gear)
747                .cloned()
748                .collect())
749        }
750        async fn list_all_instances(&self) -> Result<Vec<ServiceInstanceInfo>> {
751            Ok(self.instances.clone())
752        }
753        async fn register_instance(&self, _info: RegisterInstanceInfo) -> Result<()> {
754            Ok(())
755        }
756        async fn deregister_instance(&self, _gear: &str, _instance_id: &str) -> Result<()> {
757            Ok(())
758        }
759        async fn send_heartbeat(&self, _gear: &str, _instance_id: &str) -> Result<()> {
760            Ok(())
761        }
762    }
763
764    fn instance(id: &str, labels_pairs: &[(&str, &str)]) -> ServiceInstanceInfo {
765        ServiceInstanceInfo {
766            gear: "worker".to_owned(),
767            instance_id: id.to_owned(),
768            labels: labels(labels_pairs),
769            ..Default::default()
770        }
771    }
772
773    #[tokio::test]
774    async fn resolve_by_labels_default_filters_by_equality_and() {
775        let dir = StaticDirectory {
776            instances: vec![
777                instance("a", &[("shard", "7")]),
778                instance("b", &[("shard", "8")]),
779                instance("c", &[("shard", "7"), ("role", "ingest")]),
780            ],
781        };
782
783        let selector = LabelSelector::new().with("shard", "7");
784        let mut matched = dir
785            .resolve_by_labels("worker", &selector)
786            .await
787            .unwrap()
788            .into_iter()
789            .map(|i| i.instance_id)
790            .collect::<Vec<_>>();
791        matched.sort();
792        assert_eq!(matched, vec!["a".to_owned(), "c".to_owned()]);
793
794        // An empty selector returns every instance of the name.
795        let all = dir
796            .resolve_by_labels("worker", &LabelSelector::new())
797            .await
798            .unwrap();
799        assert_eq!(all.len(), 3);
800    }
801}