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_hash.is_none() {
93 incoming
94 .openapi_spec_hash
95 .clone_from(&stored.openapi_spec_hash);
96 }
97 if incoming.labels.is_empty() {
98 incoming.labels.clone_from(&stored.labels);
99 }
100 if incoming.version.is_none() {
101 incoming.version.clone_from(&stored.version);
102 }
103 if incoming.reported_state.is_none() {
104 incoming.reported_state = stored.reported_state;
105 }
106 incoming
107}
108
109/// Identifies a tracked record within the process.
110type RecordKey = (String, String);
111
112/// Mutable state behind the manager's lock.
113#[derive(Default)]
114struct Inner {
115 /// Every `(gear, instance_id)` the process registered, mapped to the info
116 /// last used to register it so a `NOT_FOUND` heartbeat can re-register.
117 /// Held behind an `Arc` so recovery can grab the record handle under the
118 /// lock and deep-copy the (up to ~1 MiB `OpenAPI`) info outside it.
119 records: HashMap<RecordKey, Arc<RegisterInstanceInfo>>,
120 /// Lease TTL the directory last granted, if any. `None` means fall back to
121 /// the configured heartbeat interval (an old directory that returns no TTL).
122 lease_ttl: Option<Duration>,
123 /// Set once [`deregister_all`](PresenceManager::deregister_all) has run.
124 /// A `register` after shutdown is rejected rather than silently re-tracked,
125 /// so it cannot resurrect a record the manager has already drained.
126 closed: bool,
127}
128
129/// Owns lease renewal for every directory record registered by this process.
130///
131/// Create one per process, register each record through
132/// [`register`](Self::register), and drive renewal with [`run`](Self::run).
133/// During shutdown call [`begin_drain`](Self::begin_drain) (after readiness has
134/// flipped to draining) to push an immediate `Draining` heartbeat, then
135/// [`deregister_all`](Self::deregister_all) once in-flight requests have
136/// drained.
137pub struct PresenceManager {
138 directory: Arc<dyn DirectoryClient>,
139 /// Source of the reported state: the process readiness signal,
140 /// evaluated at each renewal.
141 readiness: ReportedStateSource,
142 /// Heartbeat interval used when the directory returns no lease TTL.
143 fallback_interval: Duration,
144 inner: parking_lot::Mutex<Inner>,
145 /// Serializes this manager's directory *writes* (`register` and
146 /// `reregister_after_not_found`). Both read the record and send it to the
147 /// directory across an await; without serialization a recovery
148 /// re-registration and a concurrent registration of the same record can
149 /// reach the directory in the opposite order to the cache, leaving the
150 /// directory holding stale metadata. Held across the `register_with_lease`
151 /// await, so it must be an async mutex. Heartbeats do not take it (they
152 /// carry no metadata half to clobber).
153 write_lock: tokio::sync::Mutex<()>,
154 /// Wakes the renewal loop for an out-of-band renewal (e.g. the immediate
155 /// `Draining` heartbeat at the start of drain).
156 wake: Notify,
157}
158
159impl PresenceManager {
160 /// Create a manager that renews through `directory`, reporting the state
161 /// from `readiness`, and heartbeating at `fallback_interval` until a
162 /// registration teaches it the directory's lease TTL.
163 #[must_use]
164 pub fn new(
165 directory: Arc<dyn DirectoryClient>,
166 readiness: ReportedStateSource,
167 fallback_interval: Duration,
168 ) -> Arc<Self> {
169 Arc::new(Self {
170 directory,
171 readiness,
172 fallback_interval,
173 inner: parking_lot::Mutex::new(Inner::default()),
174 write_lock: tokio::sync::Mutex::new(()),
175 wake: Notify::new(),
176 })
177 }
178
179 /// The renewal cadence: a third of the granted lease TTL, or the
180 /// configured fallback when the directory returned none, clamped so it can
181 /// never hot-loop.
182 fn renewal_interval(&self) -> Duration {
183 let base = self
184 .inner
185 .lock()
186 .lease_ttl
187 .map_or(self.fallback_interval, |ttl| ttl / 3);
188 base.max(MIN_RENEWAL_INTERVAL)
189 }
190
191 /// Register (or re-register) `info` and track it for renewal.
192 ///
193 /// The declared state is overwritten with the process's current reported
194 /// state so every registrar agrees on one record's liveness. The lease TTL
195 /// the directory grants is remembered to pace renewals.
196 ///
197 /// Several registrars write the same `(gear, instance_id)` — grpc-hub's
198 /// gRPC half and the REST advertiser's REST half — and the directory unions
199 /// their halves ([`GearInstance::with_metadata_of`](crate::runtime)). `info`
200 /// is merged with whatever half is already tracked so the renewal snapshot
201 /// reflects that same union; otherwise a `NOT_FOUND` re-register would drop
202 /// whichever half the last registrar did not carry.
203 ///
204 /// Serialized with recovery and shutdown through [`write_lock`](Self::write_lock);
205 /// a registration after [`deregister_all`](Self::deregister_all) is rejected
206 /// so it cannot resurrect a record the manager has already drained.
207 ///
208 /// # Errors
209 /// Propagates a registration failure (e.g. a gRPC service-name conflict);
210 /// the record is still tracked so renewal retries it. Also errors if the
211 /// manager has already been drained by `deregister_all`.
212 pub async fn register(&self, mut info: RegisterInstanceInfo) -> anyhow::Result<()> {
213 info.reported_state = Some(self.readiness.reported_state().await);
214 let key = (info.gear.clone(), info.instance_id.clone());
215 // Cover the merge *and* the directory write (see `write_lock`). Held
216 // across `register_with_lease` so a drain cannot run between tracking
217 // the record and the directory write landing.
218 let _write = self.write_lock.lock().await;
219 // Merge with any tracked half and track before the await, so a record
220 // whose first registration fails is still renewed (which re-registers
221 // it) rather than lost, and so recovery carries every registrar's half.
222 let merged = {
223 let mut inner = self.inner.lock();
224 // Reject once drained: re-tracking here would resurrect a record
225 // `deregister_all` already removed, leaving a zombie nothing renews.
226 if inner.closed {
227 anyhow::bail!("presence manager is draining; registration rejected");
228 }
229 let merged = Arc::new(match inner.records.get(&key) {
230 Some(existing) => merge_registration(existing, info),
231 None => info,
232 });
233 inner.records.insert(key, Arc::clone(&merged));
234 merged
235 };
236
237 let ack = self
238 .directory
239 .register_with_lease((*merged).clone())
240 .await?;
241 if let Some(ttl) = ack.lease_ttl {
242 let shortened = {
243 let mut inner = self.inner.lock();
244 // A newly learned (or shorter) TTL means the renewal interval
245 // just dropped. The loop may already be sleeping on the longer
246 // fallback (or a previous, longer lease), so its next renewal
247 // would land after this lease expires.
248 let shortened = inner.lease_ttl.is_none_or(|prev| ttl < prev);
249 inner.lease_ttl = Some(ttl);
250 shortened
251 };
252 if shortened {
253 // Wake the loop so it re-reads the interval and renews before
254 // the deadline it was previously scheduled for.
255 self.wake.notify_one();
256 }
257 }
258 Ok(())
259 }
260
261 /// Stop renewing a record without deregistering it, e.g. when the registrar
262 /// that owns it deregisters it itself. Prevents the renewal loop from
263 /// re-registering a record that was intentionally removed.
264 pub fn untrack(&self, gear: &str, instance_id: &str) {
265 self.inner
266 .lock()
267 .records
268 .remove(&(gear.to_owned(), instance_id.to_owned()));
269 }
270
271 /// Request an immediate renewal pass. Used at the start of drain so the
272 /// directory (and the edge) sees `Draining` without waiting for the next
273 /// tick. Readiness must already be flipped to draining before calling this.
274 pub fn begin_drain(&self) {
275 self.wake.notify_one();
276 }
277
278 /// Run the renewal loop until `cancel` fires. Each pass heartbeats every
279 /// tracked record with the current reported state; a record the directory
280 /// has forgotten (`NOT_FOUND`) is re-registered, so recovery after a
281 /// directory restart or an eviction takes one heartbeat.
282 pub async fn run(self: Arc<Self>, cancel: CancellationToken) {
283 loop {
284 let interval = self.renewal_interval();
285 tokio::select! {
286 () = cancel.cancelled() => break,
287 () = self.wake.notified() => {}
288 () = tokio::time::sleep(interval) => {}
289 }
290 self.renew_all().await;
291 }
292 tracing::debug!("presence manager renewal loop stopped");
293 }
294
295 /// Heartbeat every tracked record once, re-registering any the directory no
296 /// longer knows.
297 async fn renew_all(&self) {
298 let reported = self.readiness.reported_state().await;
299 // Snapshot the keys only; the steady-state path just heartbeats, and
300 // the cold `NOT_FOUND` path re-reads the current record (below), so the
301 // (potentially ~1 MiB) info is never cloned here.
302 let keys: Vec<RecordKey> = self.inner.lock().records.keys().cloned().collect();
303
304 for (gear, instance_id) in keys {
305 match self
306 .directory
307 .heartbeat(&gear, &instance_id, Some(reported))
308 .await
309 {
310 Ok(()) => {}
311 Err(err) if err.is::<DirectoryNotFound>() => {
312 self.reregister_after_not_found(&gear, &instance_id, reported)
313 .await;
314 }
315 Err(err) => tracing::warn!(
316 gear = %gear,
317 instance = %instance_id,
318 error = %err,
319 "heartbeat failed; will retry next pass"
320 ),
321 }
322 }
323 }
324
325 /// Re-register a record the directory answered `NOT_FOUND` for (a restart or
326 /// an eviction), so it becomes routable again.
327 ///
328 /// Re-registers the record **currently tracked**, read under `write_lock`
329 /// rather than the snapshot the renewal pass started with: a registrar may
330 /// have merged in newer metadata while the heartbeat was in flight, and
331 /// recovery must carry that forward, not roll back. `write_lock` serializes
332 /// this with [`register`](Self::register) (see its doc).
333 ///
334 /// A concurrent [`untrack`](Self::untrack) / [`deregister_all`](Self::deregister_all)
335 /// must win: if the record was removed, re-registering would resurrect one
336 /// its owner deleted on purpose. The record is read before the await (absent
337 /// ⇒ skip) and its membership re-checked after it (removed while in flight ⇒
338 /// the re-registration is undone).
339 async fn reregister_after_not_found(
340 &self,
341 gear: &str,
342 instance_id: &str,
343 reported: ReportedState,
344 ) {
345 let key = (gear.to_owned(), instance_id.to_owned());
346 let _write = self.write_lock.lock().await;
347 let Some(tracked) = self.inner.lock().records.get(&key).map(Arc::clone) else {
348 return;
349 };
350 let mut info = (*tracked).clone();
351 info.reported_state = Some(reported);
352 match self.directory.register_with_lease(info).await {
353 Ok(ack) => {
354 if !self.inner.lock().records.contains_key(&key) {
355 // Untracked while we were re-registering: undo it so the
356 // removal still wins.
357 if let Err(e) = self.directory.deregister_instance(gear, instance_id).await {
358 tracing::warn!(
359 gear = %gear,
360 instance = %instance_id,
361 error = %e,
362 "could not undo a re-registration raced by untrack"
363 );
364 }
365 return;
366 }
367 if let Some(ttl) = ack.lease_ttl {
368 self.inner.lock().lease_ttl = Some(ttl);
369 }
370 tracing::info!(
371 gear = %gear,
372 instance = %instance_id,
373 "re-registered with the directory after a NOT_FOUND heartbeat"
374 );
375 }
376 Err(e) => tracing::warn!(
377 gear = %gear,
378 instance = %instance_id,
379 error = %e,
380 "re-registration after NOT_FOUND failed; will retry next pass"
381 ),
382 }
383 }
384
385 /// Deregister every tracked record and stop tracking them. Called at the end
386 /// of drain, after in-flight requests have finished, so the manager stays the
387 /// single writer of each record it owns.
388 ///
389 /// Holds [`write_lock`](Self::write_lock) across the whole drain and marks
390 /// the manager `closed`, so a [`register`](Self::register) whose directory
391 /// write is still in flight cannot land after the deregister (the lock
392 /// serializes them), and a `register` that arrives afterwards is rejected
393 /// rather than re-tracked (the flag). Either way no record survives the drain.
394 pub async fn deregister_all(&self) {
395 let _write = self.write_lock.lock().await;
396 let records: Vec<RecordKey> = {
397 let mut inner = self.inner.lock();
398 inner.closed = true;
399 inner.records.drain().map(|(k, _)| k).collect()
400 };
401 for (gear, instance_id) in records {
402 if let Err(err) = self
403 .directory
404 .deregister_instance(&gear, &instance_id)
405 .await
406 {
407 tracing::warn!(
408 gear = %gear,
409 instance = %instance_id,
410 error = %err,
411 "deregistration during shutdown failed"
412 );
413 }
414 }
415 }
416}
417
418#[cfg(test)]
419#[cfg_attr(coverage_nightly, coverage(off))]
420#[path = "presence_manager_tests.rs"]
421mod tests;