toolkit/runtime/presence_manager.rs
1//! Per-process lease renewal for every directory record the process registered
2//! (`cpt-cf-adr-directory-persistence-and-replication`, `cpt-cf-component-oop-bootstrap`).
3//!
4//! Under the lease model a registration is only kept observable while its lease
5//! is renewed. Several registrars in one process write directory records — the
6//! `OoP` presence loop, grpc-hub's gRPC registrar, [`RestAdvertiser`], and
7//! event-broker's role registration. The [`PresenceManager`] is the single
8//! per-process owner of renewal for *all* of those records: whoever registers a
9//! record hands it to the manager, which then renews it on one timer,
10//! re-registers it if the directory forgets it, and serializes its own writes
11//! so recovery and a concurrent registration cannot reach the directory out of
12//! order (DESIGN's "one writer per instance record").
13//!
14//! The state each record reports (`Starting` / `Serving` / `Draining`) comes
15//! from the process readiness signal (see [`ReportedStateSource`]: full
16//! readiness in the `OoP` serve path, the dependency/drain checker in-process),
17//! so readiness and drain are reflected in the directory without each registrar
18//! tracking them itself.
19
20use std::collections::HashMap;
21use std::sync::Arc;
22use std::time::Duration;
23
24use tokio::sync::Notify;
25use tokio_util::sync::CancellationToken;
26
27use cf_system_sdks::directory::{
28 DirectoryClient, DirectoryNotFound, RegisterInstanceInfo, ReportedState,
29};
30
31use crate::runtime::readiness::{DependencyChecker, ReadinessLifecycle, ReadinessState};
32
33/// Where a [`PresenceManager`] reads the state to report for this process,
34/// evaluated at each renewal: `Starting` while not ready, `Serving`
35/// once ready, `Draining` while shutting down.
36///
37/// Using the *readiness* signal — not dependency resolution alone — keeps a gear
38/// that is failing its readiness check from advertising itself as `Serving`.
39/// There are exactly two process topologies, so this is a closed set rather than
40/// an open trait.
41pub enum ReportedStateSource {
42 /// The `OoP` serve path's full readiness: startup completion, dependency
43 /// resolution, healthchecks and drain (ADR-0005). `Ready`/`Degraded` are
44 /// serving; anything else (including an `Unhealthy` healthcheck) is not.
45 Readiness(Arc<ReadinessState>),
46 /// The in-process host's dependency/drain signal — it has no aggregate
47 /// readiness object, so this is the best available source.
48 Dependencies(Arc<DependencyChecker>),
49}
50
51impl ReportedStateSource {
52 /// The state to report right now.
53 pub async fn reported_state(&self) -> ReportedState {
54 match self {
55 Self::Readiness(readiness) => match readiness.evaluate().await.state {
56 ReadinessLifecycle::Draining => ReportedState::Draining,
57 ReadinessLifecycle::Ready | ReadinessLifecycle::Degraded => ReportedState::Serving,
58 ReadinessLifecycle::Starting => ReportedState::Starting,
59 },
60 Self::Dependencies(deps) => {
61 if deps.is_draining() {
62 ReportedState::Draining
63 } else if deps.all_resolved() {
64 ReportedState::Serving
65 } else {
66 ReportedState::Starting
67 }
68 }
69 }
70 }
71}
72
73/// Lower bound on the renewal cadence, so a tiny or zero lease TTL cannot turn
74/// the renewal loop into a hot loop.
75const MIN_RENEWAL_INTERVAL: Duration = Duration::from_secs(1);
76
77/// Union `incoming` with a half already tracked for the same record, mirroring
78/// the directory's half-preserving merge (`GearInstance::with_metadata_of`): a
79/// present half in `incoming` replaces the stored one, an absent half keeps it.
80/// Keeps the renewal snapshot complete when grpc-hub and the REST advertiser
81/// register different halves of one `(gear, instance_id)`.
82fn merge_registration(
83 stored: &RegisterInstanceInfo,
84 mut incoming: RegisterInstanceInfo,
85) -> RegisterInstanceInfo {
86 if incoming.grpc_services.is_empty() {
87 incoming.grpc_services.clone_from(&stored.grpc_services);
88 }
89 if incoming.rest_endpoint.is_none() {
90 incoming.rest_endpoint.clone_from(&stored.rest_endpoint);
91 }
92 if incoming.openapi_spec.is_none() {
93 incoming.openapi_spec.clone_from(&stored.openapi_spec);
94 }
95 if incoming.labels.is_empty() {
96 incoming.labels.clone_from(&stored.labels);
97 }
98 if incoming.version.is_none() {
99 incoming.version.clone_from(&stored.version);
100 }
101 if incoming.reported_state.is_none() {
102 incoming.reported_state = stored.reported_state;
103 }
104 incoming
105}
106
107/// Identifies a tracked record within the process.
108type RecordKey = (String, String);
109
110/// Mutable state behind the manager's lock.
111#[derive(Default)]
112struct Inner {
113 /// Every `(gear, instance_id)` the process registered, mapped to the info
114 /// last used to register it so a `NOT_FOUND` heartbeat can re-register.
115 /// Held behind an `Arc` so recovery can grab the record handle under the
116 /// lock and deep-copy the (up to ~1 MiB `OpenAPI`) info outside it.
117 records: HashMap<RecordKey, Arc<RegisterInstanceInfo>>,
118 /// Lease TTL the directory last granted, if any. `None` means fall back to
119 /// the configured heartbeat interval (an old directory that returns no TTL).
120 lease_ttl: Option<Duration>,
121 /// Set once [`deregister_all`](PresenceManager::deregister_all) has run.
122 /// A `register` after shutdown is rejected rather than silently re-tracked,
123 /// so it cannot resurrect a record the manager has already drained.
124 closed: bool,
125}
126
127/// Owns lease renewal for every directory record registered by this process.
128///
129/// Create one per process, register each record through
130/// [`register`](Self::register), and drive renewal with [`run`](Self::run).
131/// During shutdown call [`begin_drain`](Self::begin_drain) (after readiness has
132/// flipped to draining) to push an immediate `Draining` heartbeat, then
133/// [`deregister_all`](Self::deregister_all) once in-flight requests have
134/// drained.
135pub struct PresenceManager {
136 directory: Arc<dyn DirectoryClient>,
137 /// Source of the reported state: the process readiness signal,
138 /// evaluated at each renewal.
139 readiness: ReportedStateSource,
140 /// Heartbeat interval used when the directory returns no lease TTL.
141 fallback_interval: Duration,
142 inner: parking_lot::Mutex<Inner>,
143 /// Serializes this manager's directory *writes* (`register` and
144 /// `reregister_after_not_found`). Both read the record and send it to the
145 /// directory across an await; without serialization a recovery
146 /// re-registration and a concurrent registration of the same record can
147 /// reach the directory in the opposite order to the cache, leaving the
148 /// directory holding stale metadata. Held across the `register_with_lease`
149 /// await, so it must be an async mutex. Heartbeats do not take it (they
150 /// carry no metadata half to clobber).
151 write_lock: tokio::sync::Mutex<()>,
152 /// Wakes the renewal loop for an out-of-band renewal (e.g. the immediate
153 /// `Draining` heartbeat at the start of drain).
154 wake: Notify,
155}
156
157impl PresenceManager {
158 /// Create a manager that renews through `directory`, reporting the state
159 /// from `readiness`, and heartbeating at `fallback_interval` until a
160 /// registration teaches it the directory's lease TTL.
161 #[must_use]
162 pub fn new(
163 directory: Arc<dyn DirectoryClient>,
164 readiness: ReportedStateSource,
165 fallback_interval: Duration,
166 ) -> Arc<Self> {
167 Arc::new(Self {
168 directory,
169 readiness,
170 fallback_interval,
171 inner: parking_lot::Mutex::new(Inner::default()),
172 write_lock: tokio::sync::Mutex::new(()),
173 wake: Notify::new(),
174 })
175 }
176
177 /// The renewal cadence: a third of the granted lease TTL, or the
178 /// configured fallback when the directory returned none, clamped so it can
179 /// never hot-loop.
180 fn renewal_interval(&self) -> Duration {
181 let base = self
182 .inner
183 .lock()
184 .lease_ttl
185 .map_or(self.fallback_interval, |ttl| ttl / 3);
186 base.max(MIN_RENEWAL_INTERVAL)
187 }
188
189 /// Register (or re-register) `info` and track it for renewal.
190 ///
191 /// The declared state is overwritten with the process's current reported
192 /// state so every registrar agrees on one record's liveness. The lease TTL
193 /// the directory grants is remembered to pace renewals.
194 ///
195 /// Several registrars write the same `(gear, instance_id)` — grpc-hub's
196 /// gRPC half and the REST advertiser's REST half — and the directory unions
197 /// their halves ([`GearInstance::with_metadata_of`](crate::runtime)). `info`
198 /// is merged with whatever half is already tracked so the renewal snapshot
199 /// reflects that same union; otherwise a `NOT_FOUND` re-register would drop
200 /// whichever half the last registrar did not carry.
201 ///
202 /// Serialized with recovery and shutdown through [`write_lock`](Self::write_lock);
203 /// a registration after [`deregister_all`](Self::deregister_all) is rejected
204 /// so it cannot resurrect a record the manager has already drained.
205 ///
206 /// # Errors
207 /// Propagates a registration failure (e.g. a gRPC service-name conflict);
208 /// the record is still tracked so renewal retries it. Also errors if the
209 /// manager has already been drained by `deregister_all`.
210 pub async fn register(&self, mut info: RegisterInstanceInfo) -> anyhow::Result<()> {
211 info.reported_state = Some(self.readiness.reported_state().await);
212 let key = (info.gear.clone(), info.instance_id.clone());
213 // Cover the merge *and* the directory write (see `write_lock`). Held
214 // across `register_with_lease` so a drain cannot run between tracking
215 // the record and the directory write landing.
216 let _write = self.write_lock.lock().await;
217 // Merge with any tracked half and track before the await, so a record
218 // whose first registration fails is still renewed (which re-registers
219 // it) rather than lost, and so recovery carries every registrar's half.
220 let merged = {
221 let mut inner = self.inner.lock();
222 // Reject once drained: re-tracking here would resurrect a record
223 // `deregister_all` already removed, leaving a zombie nothing renews.
224 if inner.closed {
225 anyhow::bail!("presence manager is draining; registration rejected");
226 }
227 let merged = Arc::new(match inner.records.get(&key) {
228 Some(existing) => merge_registration(existing, info),
229 None => info,
230 });
231 inner.records.insert(key, Arc::clone(&merged));
232 merged
233 };
234
235 let ack = self
236 .directory
237 .register_with_lease((*merged).clone())
238 .await?;
239 if let Some(ttl) = ack.lease_ttl {
240 let shortened = {
241 let mut inner = self.inner.lock();
242 // A newly learned (or shorter) TTL means the renewal interval
243 // just dropped. The loop may already be sleeping on the longer
244 // fallback (or a previous, longer lease), so its next renewal
245 // would land after this lease expires.
246 let shortened = inner.lease_ttl.is_none_or(|prev| ttl < prev);
247 inner.lease_ttl = Some(ttl);
248 shortened
249 };
250 if shortened {
251 // Wake the loop so it re-reads the interval and renews before
252 // the deadline it was previously scheduled for.
253 self.wake.notify_one();
254 }
255 }
256 Ok(())
257 }
258
259 /// Stop renewing a record without deregistering it, e.g. when the registrar
260 /// that owns it deregisters it itself. Prevents the renewal loop from
261 /// re-registering a record that was intentionally removed.
262 pub fn untrack(&self, gear: &str, instance_id: &str) {
263 self.inner
264 .lock()
265 .records
266 .remove(&(gear.to_owned(), instance_id.to_owned()));
267 }
268
269 /// Request an immediate renewal pass. Used at the start of drain so the
270 /// directory (and the edge) sees `Draining` without waiting for the next
271 /// tick. Readiness must already be flipped to draining before calling this.
272 pub fn begin_drain(&self) {
273 self.wake.notify_one();
274 }
275
276 /// Run the renewal loop until `cancel` fires. Each pass heartbeats every
277 /// tracked record with the current reported state; a record the directory
278 /// has forgotten (`NOT_FOUND`) is re-registered, so recovery after a
279 /// directory restart or an eviction takes one heartbeat.
280 pub async fn run(self: Arc<Self>, cancel: CancellationToken) {
281 loop {
282 let interval = self.renewal_interval();
283 tokio::select! {
284 () = cancel.cancelled() => break,
285 () = self.wake.notified() => {}
286 () = tokio::time::sleep(interval) => {}
287 }
288 self.renew_all().await;
289 }
290 tracing::debug!("presence manager renewal loop stopped");
291 }
292
293 /// Heartbeat every tracked record once, re-registering any the directory no
294 /// longer knows.
295 async fn renew_all(&self) {
296 let reported = self.readiness.reported_state().await;
297 // Snapshot the keys only; the steady-state path just heartbeats, and
298 // the cold `NOT_FOUND` path re-reads the current record (below), so the
299 // (potentially ~1 MiB) info is never cloned here.
300 let keys: Vec<RecordKey> = self.inner.lock().records.keys().cloned().collect();
301
302 for (gear, instance_id) in keys {
303 match self
304 .directory
305 .heartbeat(&gear, &instance_id, Some(reported))
306 .await
307 {
308 Ok(()) => {}
309 Err(err) if err.is::<DirectoryNotFound>() => {
310 self.reregister_after_not_found(&gear, &instance_id, reported)
311 .await;
312 }
313 Err(err) => tracing::warn!(
314 gear = %gear,
315 instance = %instance_id,
316 error = %err,
317 "heartbeat failed; will retry next pass"
318 ),
319 }
320 }
321 }
322
323 /// Re-register a record the directory answered `NOT_FOUND` for (a restart or
324 /// an eviction), so it becomes routable again.
325 ///
326 /// Re-registers the record **currently tracked**, read under `write_lock`
327 /// rather than the snapshot the renewal pass started with: a registrar may
328 /// have merged in newer metadata while the heartbeat was in flight, and
329 /// recovery must carry that forward, not roll back. `write_lock` serializes
330 /// this with [`register`](Self::register) (see its doc).
331 ///
332 /// A concurrent [`untrack`](Self::untrack) / [`deregister_all`](Self::deregister_all)
333 /// must win: if the record was removed, re-registering would resurrect one
334 /// its owner deleted on purpose. The record is read before the await (absent
335 /// ⇒ skip) and its membership re-checked after it (removed while in flight ⇒
336 /// the re-registration is undone).
337 async fn reregister_after_not_found(
338 &self,
339 gear: &str,
340 instance_id: &str,
341 reported: ReportedState,
342 ) {
343 let key = (gear.to_owned(), instance_id.to_owned());
344 let _write = self.write_lock.lock().await;
345 let Some(tracked) = self.inner.lock().records.get(&key).map(Arc::clone) else {
346 return;
347 };
348 let mut info = (*tracked).clone();
349 info.reported_state = Some(reported);
350 match self.directory.register_with_lease(info).await {
351 Ok(ack) => {
352 if !self.inner.lock().records.contains_key(&key) {
353 // Untracked while we were re-registering: undo it so the
354 // removal still wins.
355 if let Err(e) = self.directory.deregister_instance(gear, instance_id).await {
356 tracing::warn!(
357 gear = %gear,
358 instance = %instance_id,
359 error = %e,
360 "could not undo a re-registration raced by untrack"
361 );
362 }
363 return;
364 }
365 if let Some(ttl) = ack.lease_ttl {
366 self.inner.lock().lease_ttl = Some(ttl);
367 }
368 tracing::info!(
369 gear = %gear,
370 instance = %instance_id,
371 "re-registered with the directory after a NOT_FOUND heartbeat"
372 );
373 }
374 Err(e) => tracing::warn!(
375 gear = %gear,
376 instance = %instance_id,
377 error = %e,
378 "re-registration after NOT_FOUND failed; will retry next pass"
379 ),
380 }
381 }
382
383 /// Deregister every tracked record and stop tracking them. Called at the end
384 /// of drain, after in-flight requests have finished, so the manager stays the
385 /// single writer of each record it owns.
386 ///
387 /// Holds [`write_lock`](Self::write_lock) across the whole drain and marks
388 /// the manager `closed`, so a [`register`](Self::register) whose directory
389 /// write is still in flight cannot land after the deregister (the lock
390 /// serializes them), and a `register` that arrives afterwards is rejected
391 /// rather than re-tracked (the flag). Either way no record survives the drain.
392 pub async fn deregister_all(&self) {
393 let _write = self.write_lock.lock().await;
394 let records: Vec<RecordKey> = {
395 let mut inner = self.inner.lock();
396 inner.closed = true;
397 inner.records.drain().map(|(k, _)| k).collect()
398 };
399 for (gear, instance_id) in records {
400 if let Err(err) = self
401 .directory
402 .deregister_instance(&gear, &instance_id)
403 .await
404 {
405 tracing::warn!(
406 gear = %gear,
407 instance = %instance_id,
408 error = %err,
409 "deregistration during shutdown failed"
410 );
411 }
412 }
413 }
414}
415
416#[cfg(test)]
417#[cfg_attr(coverage_nightly, coverage(off))]
418#[path = "presence_manager_tests.rs"]
419mod tests;