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