Skip to main content

toolkit/runtime/
oop_serve.rs

1//! Out-of-process (`OoP`) HTTP server: probes, two-plane auth, and graceful
2//! drain (`cpt-cf-component-oop-bootstrap`).
3//!
4//! This module owns the edge of an `OoP` gear's HTTP surface:
5//!
6//! - **Framework probes** — `/healthz` (liveness), `/readyz` (readiness, gated
7//!   on dependency resolution + custom checks), `/health` (diagnostics, full
8//!   healthcheck report), and `/.well-known/openapi.json` (the canonical
9//!   discovery path; `cpt-cf-binding-constraint-openapi-well-known`).
10//! - **Two-plane auth** — platform-plane ([`internal_auth_middleware`]) runs
11//!   *before* tenant-plane ([`security_context_middleware`]) per
12//!   `cpt-cf-adr-two-plane-auth`,
13//!   but only when the corresponding authenticator is injected. Because both
14//!   authenticator traits use return-position `impl Trait` (not `dyn`-safe),
15//!   callers inject the object-safe [`DynBearerAuthenticator`] /
16//!   [`DynInternalAuthenticator`] adapters.
17//! - **Graceful drain** — a drain guard rejects new gear-route requests with
18//!   `503 + Retry-After` once draining begins, while in-flight requests finish.
19//! - **Framework middleware** — a canonical-error layer normalizes gear/auth
20//!   error responses into `problem+json` (`trace_id` / `instance` filled),
21//!   matching the in-process (`api-gateway`) path. The drain guard also catches
22//!   panics so a panic can neither drop the client connection nor leak the
23//!   in-flight counter (which would otherwise stall graceful drain).
24//! - **Request/trace context** — the outermost `trace_context_middleware`
25//!   continues the inbound W3C `traceparent` and scopes the inbound
26//!   `x-request-id` (`toolkit_trace_context::with_request_id`), so the gear's
27//!   span carries the edge id and outbound `toolkit-http` calls forward it.
28//!
29//! The server is driven by [`OopHttpServer`], invoked from the `HostRuntime`
30//! `OoP` path: it binds and serves the probes **before** the gear's `start()`
31//! phase (so `/healthz` is up during a slow startup), then swaps in the composed
32//! gear routes. Self-registration and dependency resolution live in
33//! [`super::oop_registration`].
34
35use std::collections::{BTreeMap, HashMap};
36use std::panic::AssertUnwindSafe;
37use std::sync::Arc;
38use std::sync::atomic::{AtomicUsize, Ordering};
39use std::time::Duration;
40
41use axum::{
42    Json, Router,
43    extract::{DefaultBodyLimit, MatchedPath, Request, State},
44    http::{HeaderMap, HeaderValue, Method, StatusCode, header::RETRY_AFTER},
45    middleware::{Next, from_fn, from_fn_with_state},
46    response::{IntoResponse, Response},
47    routing::get,
48};
49use futures_util::FutureExt as _;
50use serde::{Deserialize, Serialize};
51use tokio_util::sync::CancellationToken;
52use tower::ServiceExt as _;
53use tower_http::limit::RequestBodyLimitLayer;
54use url::Url;
55
56use cf_system_sdks::directory::{DirectoryClient, RegisterInstanceInfo, ServiceEndpoint};
57use toolkit_canonical_errors::{CanonicalError, resource_error};
58use toolkit_http_middleware::{RouteAuthPolicy, TenantPlane, layer_route_auth_with};
59use toolkit_security::{DynBearerAuthenticator, DynInternalAuthenticator};
60use toolkit_trace_context::{TRACEPARENT, parse_trace_id};
61
62use super::presence_manager::{PresenceManager, ReportedStateSource};
63use super::readiness::ReadinessState;
64use crate::api::canonical_error_middleware;
65use crate::api::operation_builder::{OperationSpec, RouteTimeout};
66
67/// `Retry-After` (seconds) advertised while the gear is draining.
68const DRAIN_RETRY_AFTER_SECONDS: u64 = 5;
69
70/// `Retry-After` (seconds) advertised for gear routes before the gear has
71/// finished starting (probes are already live; routes come up shortly).
72const STARTING_RETRY_AFTER_SECONDS: u64 = 1;
73
74// ---------------------------------------------------------------------------
75// Serve options
76// ---------------------------------------------------------------------------
77
78/// Request body and response deadline policy for published `OoP` gear routes.
79#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
80#[serde(try_from = "RawOopRequestLimits")]
81pub struct OopRequestLimits {
82    body_limit_bytes: usize,
83    #[serde(with = "toolkit_utils::humantime_serde")]
84    request_timeout: Duration,
85}
86
87#[derive(Deserialize)]
88#[serde(deny_unknown_fields)]
89struct RawOopRequestLimits {
90    body_limit_bytes: usize,
91    #[serde(with = "toolkit_utils::humantime_serde")]
92    request_timeout: Duration,
93}
94
95impl TryFrom<RawOopRequestLimits> for OopRequestLimits {
96    type Error = OopRequestLimitsError;
97
98    fn try_from(raw: RawOopRequestLimits) -> Result<Self, Self::Error> {
99        Self::new(raw.body_limit_bytes, raw.request_timeout)
100    }
101}
102
103/// An invalid request limit.
104#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
105pub enum OopRequestLimitsError {
106    /// The body byte limit is zero.
107    #[error("body_limit_bytes must be positive")]
108    BodyLimitZero,
109    /// The response deadline is zero.
110    #[error("request_timeout must be positive")]
111    RequestTimeoutZero,
112}
113
114impl OopRequestLimits {
115    /// Create a policy with positive body bytes and a positive response deadline.
116    ///
117    /// # Errors
118    ///
119    /// Returns [`OopRequestLimitsError::BodyLimitZero`] for a zero byte limit or
120    /// [`OopRequestLimitsError::RequestTimeoutZero`] for a zero timeout.
121    pub fn new(
122        body_limit_bytes: usize,
123        request_timeout: Duration,
124    ) -> Result<Self, OopRequestLimitsError> {
125        if body_limit_bytes == 0 {
126            return Err(OopRequestLimitsError::BodyLimitZero);
127        }
128        if request_timeout.is_zero() {
129            return Err(OopRequestLimitsError::RequestTimeoutZero);
130        }
131        Ok(Self {
132            body_limit_bytes,
133            request_timeout,
134        })
135    }
136
137    /// Maximum number of request body bytes.
138    #[must_use]
139    pub const fn body_limit_bytes(&self) -> usize {
140        self.body_limit_bytes
141    }
142
143    /// Default time to produce a response. A registered operation may replace or
144    /// disable this deadline. Response streams continue independently.
145    #[must_use]
146    pub const fn request_timeout(&self) -> Duration {
147        self.request_timeout
148    }
149}
150
151/// Configuration and collaborators for the `OoP` HTTP runtime, assembled by the
152/// bootstrap layer and consumed by `HostRuntime`'s `OoP` serving path.
153///
154/// `#[non_exhaustive]` so new fields (like `labels`) stay additive. Construct via
155/// [`OopServeOptions::new`] + the `with_*` builders rather than a struct literal,
156/// exactly as [`RunOptions`](super::RunOptions) is built: the five arguments to
157/// `new` are the fields with no meaningful default, and everything else defaults
158/// to the same values the bootstrap config layer uses. (A `Default` impl is still
159/// not provided — the `directory` collaborator is a required dependency.)
160///
161/// The builders are what keep [`run_oop_serving`](super::run_oop_serving)
162/// callable: it is `pub` and takes this type by value, so an out-of-crate caller
163/// — an integration test driving the real serve path, for instance — needs some
164/// way to build one.
165#[non_exhaustive]
166pub struct OopServeOptions {
167    /// Logical gear name (used for registration + `OpenAPI` title).
168    pub gear_name: String,
169    /// Process instance id (used for registration/deregistration).
170    pub instance_id: String,
171    /// Optional gear version (used for registration + `OpenAPI` version).
172    pub version: Option<String>,
173    /// Base URL other services use to reach this instance's REST endpoint
174    /// (e.g. `http://billing.default.svc.cluster.local:8080`). Registered with
175    /// `DirectoryService` as the instance's `rest_endpoint`.
176    pub advertise_uri: String,
177    /// Address the main HTTP server binds to (gear routes + probes).
178    pub listen_addr: std::net::SocketAddr,
179    /// Optional separate address for probe endpoints (sidecar port). When set,
180    /// probes are served here *and* on the main listener.
181    pub probe_bind_addr: Option<std::net::SocketAddr>,
182    /// Maximum time to wait for in-flight requests to drain on shutdown.
183    pub drain_timeout: Duration,
184    /// Fallback heartbeat interval, used only when the directory grants no lease
185    /// TTL (an older directory). Otherwise the [`PresenceManager`] renews at
186    /// `lease_ttl / 3`. Clamped to a 1s minimum so it can't hot-loop.
187    pub heartbeat_interval: Duration,
188    /// Per-check timeout for readiness healthchecks (`/readyz`). A gear's
189    /// [`Healthcheck`](crate::healthcheck::Healthcheck) that exceeds this is
190    /// reported `Unhealthy`. Mirrors the `api-gateway` `healthcheck_timeout_ms`.
191    pub healthcheck_timeout: Duration,
192    /// Optional body and response deadline policy for published gear routes.
193    pub request_limits: Option<OopRequestLimits>,
194    /// Directory client used for self-registration and dependency resolution.
195    pub directory: Arc<dyn DirectoryClient>,
196    /// Tenant-plane authenticator; when `Some`, `security_context_middleware`
197    /// is installed on gear routes.
198    pub bearer_authenticator: Option<DynBearerAuthenticator>,
199    /// Platform-plane authenticator; when `Some`, `internal_auth_middleware` is
200    /// installed on gear routes (runs before the tenant plane).
201    pub internal_authenticator: Option<DynInternalAuthenticator>,
202    /// Development only (`oop_http.auth_disabled`): without a tenant authenticator,
203    /// non-platform routes run with the default tenant `SecurityContext` instead of
204    /// being refused. Platform routes still require a validated platform caller.
205    pub auth_disabled: bool,
206    /// Stable addressing labels (k8s `matchLabels` style) advertised with this
207    /// instance's directory registration for label-based selection.
208    pub labels: BTreeMap<String, String>,
209}
210
211impl OopServeOptions {
212    /// Create `OopServeOptions` with the fields that have no meaningful default;
213    /// every optional field defaults to the bootstrap config layer's own default
214    /// (`drain_timeout` 30s, `heartbeat_interval` 5s, `healthcheck_timeout`
215    /// 500ms). Add optional request limits, probe sidecar, authenticators, and labels
216    /// with the `with_*` builders.
217    #[must_use]
218    pub fn new(
219        gear_name: String,
220        instance_id: String,
221        advertise_uri: String,
222        listen_addr: std::net::SocketAddr,
223        directory: Arc<dyn DirectoryClient>,
224    ) -> Self {
225        Self {
226            gear_name,
227            instance_id,
228            version: None,
229            advertise_uri,
230            listen_addr,
231            probe_bind_addr: None,
232            drain_timeout: Duration::from_secs(30),
233            heartbeat_interval: Duration::from_secs(5),
234            healthcheck_timeout: Duration::from_millis(500),
235            request_limits: None,
236            directory,
237            bearer_authenticator: None,
238            internal_authenticator: None,
239            auth_disabled: false,
240            labels: BTreeMap::new(),
241        }
242    }
243
244    /// Development only: see [`Self::auth_disabled`].
245    #[must_use]
246    pub fn with_auth_disabled(mut self, auth_disabled: bool) -> Self {
247        self.auth_disabled = auth_disabled;
248        self
249    }
250
251    /// The listener's tenant plane: the bearer authenticator when one is installed, else
252    /// [`TenantPlane::Disabled`] under `auth_disabled`, else [`TenantPlane::Absent`].
253    #[must_use]
254    pub fn tenant_plane(&self) -> TenantPlane {
255        match (&self.bearer_authenticator, self.auth_disabled) {
256            (Some(bearer), _) => TenantPlane::Authenticator(bearer.clone()),
257            (None, true) => TenantPlane::Disabled,
258            (None, false) => TenantPlane::Absent,
259        }
260    }
261
262    /// Set the gear version (used for registration + `OpenAPI` version).
263    #[must_use]
264    pub fn with_version(mut self, version: Option<String>) -> Self {
265        self.version = version;
266        self
267    }
268
269    /// Serve probes on a separate sidecar port *in addition to* the main listener.
270    #[must_use]
271    pub fn with_probe_bind_addr(mut self, addr: Option<std::net::SocketAddr>) -> Self {
272        self.probe_bind_addr = addr;
273        self
274    }
275
276    /// Override how long in-flight requests may drain on shutdown.
277    #[must_use]
278    pub fn with_drain_timeout(mut self, timeout: Duration) -> Self {
279        self.drain_timeout = timeout;
280        self
281    }
282
283    /// Override the `DirectoryService` heartbeat interval.
284    #[must_use]
285    pub fn with_heartbeat_interval(mut self, interval: Duration) -> Self {
286        self.heartbeat_interval = interval;
287        self
288    }
289
290    /// Override the per-check readiness healthcheck timeout.
291    #[must_use]
292    pub fn with_healthcheck_timeout(mut self, timeout: Duration) -> Self {
293        self.healthcheck_timeout = timeout;
294        self
295    }
296
297    /// Apply request limits to published gear routes.
298    #[must_use]
299    pub fn with_request_limits(mut self, limits: OopRequestLimits) -> Self {
300        self.request_limits = Some(limits);
301        self
302    }
303
304    /// Install the tenant-plane authenticator (`security_context_middleware`).
305    #[must_use]
306    pub fn with_bearer_authenticator(mut self, auth: Option<DynBearerAuthenticator>) -> Self {
307        self.bearer_authenticator = auth;
308        self
309    }
310
311    /// Install the platform-plane authenticator (`internal_auth_middleware`).
312    #[must_use]
313    pub fn with_internal_authenticator(mut self, auth: Option<DynInternalAuthenticator>) -> Self {
314        self.internal_authenticator = auth;
315        self
316    }
317
318    /// Advertise stable addressing labels for label-based selection.
319    #[must_use]
320    pub fn with_labels(mut self, labels: BTreeMap<String, String>) -> Self {
321        self.labels = labels;
322        self
323    }
324}
325
326impl std::fmt::Debug for OopServeOptions {
327    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
328        f.debug_struct("OopServeOptions")
329            .field("gear_name", &self.gear_name)
330            .field("instance_id", &self.instance_id)
331            .field("version", &self.version)
332            .field("advertise_uri", &self.advertise_uri)
333            .field("listen_addr", &self.listen_addr)
334            .field("probe_bind_addr", &self.probe_bind_addr)
335            .field("drain_timeout", &self.drain_timeout)
336            .field("heartbeat_interval", &self.heartbeat_interval)
337            .field("healthcheck_timeout", &self.healthcheck_timeout)
338            .field("request_limits", &self.request_limits)
339            .field("bearer_authenticator", &self.bearer_authenticator.is_some())
340            .field(
341                "internal_authenticator",
342                &self.internal_authenticator.is_some(),
343            )
344            .field("labels", &self.labels)
345            .finish_non_exhaustive()
346    }
347}
348
349// ---------------------------------------------------------------------------
350// Probe router
351// ---------------------------------------------------------------------------
352
353/// Composed gear routes + `OpenAPI` document, published *after* the gear's
354/// `start()` phase completes.
355///
356/// Held behind an [`arc_swap::ArcSwapOption`] so the probe listener can bind and
357/// serve `/healthz` immediately (while a slow `start()` runs), then have the gear
358/// routes swapped in atomically — no port rebind, so liveness never blips.
359#[derive(Clone, Default)]
360struct LateRoutes {
361    inner: Arc<arc_swap::ArcSwapOption<LateRoutesInner>>,
362}
363
364struct LateRoutesInner {
365    /// Fully-layered gear router (auth planes + drain guard + canonical errors).
366    gear: Router,
367    /// Serialized `OpenAPI` document served at the well-known path.
368    openapi: Arc<str>,
369}
370
371impl LateRoutes {
372    /// Publish the composed gear routes; subsequent requests are served by them.
373    fn publish(&self, gear: Router, openapi: Arc<str>) {
374        self.inner
375            .store(Some(Arc::new(LateRoutesInner { gear, openapi })));
376    }
377
378    /// The current gear router, if the gear has finished starting.
379    fn gear(&self) -> Option<Router> {
380        self.inner.load_full().map(|i| i.gear.clone())
381    }
382
383    /// The current `OpenAPI` document, if published.
384    fn openapi(&self) -> Option<Arc<str>> {
385        self.inner.load_full().map(|i| Arc::clone(&i.openapi))
386    }
387}
388
389/// `503 + Retry-After` returned for gear routes before the gear has started.
390fn starting_response() -> Response {
391    (
392        StatusCode::SERVICE_UNAVAILABLE,
393        [(RETRY_AFTER, STARTING_RETRY_AFTER_SECONDS.to_string())],
394        "starting",
395    )
396        .into_response()
397}
398
399/// Shared state for the probe endpoints.
400#[derive(Clone)]
401struct ProbeState {
402    readiness: Arc<ReadinessState>,
403    late: LateRoutes,
404}
405
406/// Build the outer router bound at startup: framework probes plus a gear-route
407/// fallback that is `503 starting` until [`LateRoutes::publish`] swaps in the
408/// composed gear router. Probes are live as soon as the listener binds.
409fn build_outer_router(readiness: Arc<ReadinessState>, late: LateRoutes) -> Router {
410    let fallback_late = late.clone();
411    build_probe_router(readiness, late).fallback_service(tower::util::service_fn(
412        move |req: Request| {
413            let late = fallback_late.clone();
414            async move {
415                match late.gear() {
416                    // `Router`'s service error is `Infallible`, hence `match e {}`.
417                    Some(router) => Ok::<_, std::convert::Infallible>(
418                        router.oneshot(req).await.unwrap_or_else(|e| match e {}),
419                    ),
420                    None => Ok::<_, std::convert::Infallible>(starting_response()),
421                }
422            }
423        },
424    ))
425}
426
427/// Build the framework probe router: `/healthz`, `/readyz`, `/health`, and the
428/// well-known `OpenAPI` discovery path.
429///
430/// These routes carry no tenant JWT and are never subject to the drain guard or
431/// the auth middlewares (they must respond during startup and drain).
432fn build_probe_router(readiness: Arc<ReadinessState>, late: LateRoutes) -> Router {
433    let state = ProbeState { readiness, late };
434
435    Router::new()
436        .route("/healthz", get(healthz))
437        .route("/readyz", get(readyz))
438        .route("/health", get(health))
439        .route("/.well-known/openapi.json", get(openapi))
440        .route("/openapi.json", get(openapi))
441        .with_state(state)
442}
443
444/// Liveness: always `200` with plain body `ok` once the server is listening.
445async fn healthz() -> &'static str {
446    "ok"
447}
448
449/// Readiness: `200` when ready, `503` with the unresolved-deps / failing-checks
450/// body otherwise. `Degraded` checks keep the response `200`.
451async fn readyz(State(state): State<ProbeState>) -> Response {
452    let report = state.readiness.evaluate().await;
453    let status = if report.ready {
454        StatusCode::OK
455    } else {
456        StatusCode::SERVICE_UNAVAILABLE
457    };
458    (status, Json(report)).into_response()
459}
460
461/// Health: returns the full `HealthcheckReport` (`status` + per-component
462/// detail). `200` for `Healthy`/`Degraded`, `503` for `Unhealthy`.
463async fn health(State(state): State<ProbeState>) -> impl IntoResponse {
464    let report = state.readiness.health_report().await;
465    let status = if report.is_ready() {
466        StatusCode::OK
467    } else {
468        StatusCode::SERVICE_UNAVAILABLE
469    };
470    (status, Json(report))
471}
472
473/// Serve the gear's generated `OpenAPI` document once published (after
474/// `start()`); `503 starting` beforehand.
475async fn openapi(State(state): State<ProbeState>) -> Response {
476    match state.late.openapi() {
477        Some(spec) => (
478            StatusCode::OK,
479            [(axum::http::header::CONTENT_TYPE, "application/json")],
480            spec.to_string(),
481        )
482            .into_response(),
483        None => starting_response(),
484    }
485}
486
487// ---------------------------------------------------------------------------
488// Drain guard
489// ---------------------------------------------------------------------------
490
491/// Tracks in-flight gear-route requests and enforces the drain state.
492#[derive(Clone)]
493struct DrainGuard {
494    readiness: Arc<ReadinessState>,
495    in_flight: Arc<AtomicUsize>,
496}
497
498impl DrainGuard {
499    fn new(readiness: Arc<ReadinessState>) -> Self {
500        Self {
501            readiness,
502            in_flight: Arc::new(AtomicUsize::new(0)),
503        }
504    }
505
506    /// Current number of in-flight gear-route requests.
507    fn in_flight(&self) -> usize {
508        self.in_flight.load(Ordering::SeqCst)
509    }
510
511    /// Begin draining: flip readiness to `503` so upstreams stop routing new
512    /// traffic and the guard starts rejecting new requests (drain step 1/2).
513    fn begin_drain(&self) {
514        self.readiness.set_draining(true);
515    }
516}
517
518/// RAII guard that increments the in-flight request counter on creation and
519/// decrements it on drop, so cancellation or panic cannot leak a count.
520struct InFlightGuard(Arc<AtomicUsize>);
521
522impl InFlightGuard {
523    fn new(counter: Arc<AtomicUsize>) -> Self {
524        counter.fetch_add(1, Ordering::SeqCst);
525        Self(counter)
526    }
527}
528
529impl Drop for InFlightGuard {
530    fn drop(&mut self) {
531        self.0.fetch_sub(1, Ordering::SeqCst);
532    }
533}
534
535/// Middleware: reject new requests with `503 + Retry-After` while draining;
536/// otherwise track the request as in-flight until it completes.
537async fn drain_guard_middleware(
538    State(guard): State<DrainGuard>,
539    request: axum::extract::Request,
540    next: Next,
541) -> Response {
542    if guard.readiness.is_draining() {
543        return (
544            StatusCode::SERVICE_UNAVAILABLE,
545            [(RETRY_AFTER, DRAIN_RETRY_AFTER_SECONDS.to_string())],
546            "draining",
547        )
548            .into_response();
549    }
550
551    // The in-flight counter is tracked by an RAII guard so it is decremented
552    // whether the handler completes normally, panics, or the future is cancelled.
553    // Panics are caught and converted to a canonical 500 (enriched by the outer
554    // canonical-error layer) instead of dropping the connection — the OoP
555    // equivalent of `tower_http`'s `CatchPanicLayer`.
556    let _in_flight = InFlightGuard::new(guard.in_flight.clone());
557    let outcome = AssertUnwindSafe(next.run(request)).catch_unwind().await;
558
559    match outcome {
560        Ok(response) => response,
561        Err(panic) => {
562            let detail = panic_message(panic.as_ref());
563            tracing::error!(panic = %detail, "OoP gear handler panicked");
564            // `detail` is a server-side diagnostic only; `CanonicalError::internal`
565            // keeps it off the wire (`#[serde(skip)]`) per the error contract.
566            CanonicalError::internal(format!("gear handler panicked: {detail}"))
567                .create()
568                .into_response()
569        }
570    }
571}
572
573/// Extract a human-readable message from a caught panic payload.
574fn panic_message(panic: &(dyn std::any::Any + Send)) -> String {
575    panic
576        .downcast_ref::<&str>()
577        .map(|s| (*s).to_owned())
578        .or_else(|| panic.downcast_ref::<String>().cloned())
579        .unwrap_or_else(|| "unknown panic".to_owned())
580}
581
582// ---------------------------------------------------------------------------
583// Router assembly
584// ---------------------------------------------------------------------------
585
586/// Before the application group started, serve only platform-plane and
587/// anonymous routes: a tenant-plane route (and an unknown path) replies `503`
588/// rather than run without a tenant authenticator.
589async fn bootstrap_plane_gate(
590    State(policy): State<Arc<RouteAuthPolicy>>,
591    request: Request,
592    next: Next,
593) -> Response {
594    let auth = request
595        .extensions()
596        .get::<axum::extract::MatchedPath>()
597        .and_then(|path| policy.resolve(request.method(), path.as_str()));
598    match auth {
599        Some(toolkit_security::RouteAuth::Platform | toolkit_security::RouteAuth::Anonymous) => {
600            next.run(request).await
601        }
602        _ => CanonicalError::service_unavailable()
603            .with_retry_after_seconds(STARTING_RETRY_AFTER_SECONDS)
604            .with_detail("tenant-plane routes are served once the application group has started")
605            .create()
606            .into_response(),
607    }
608}
609
610type RouteTimeouts = HashMap<Method, HashMap<String, RouteTimeout>>;
611
612/// Operation policies for one publication of the gear router.
613#[derive(Debug, Default)]
614pub(super) struct OopRoutePolicy {
615    auth: RouteAuthPolicy,
616    timeouts: RouteTimeouts,
617}
618
619impl OopRoutePolicy {
620    pub(super) fn from_specs<S>(specs: impl IntoIterator<Item = S>) -> Self
621    where
622        S: std::ops::Deref<Target = OperationSpec>,
623    {
624        let mut policy = Self::default();
625        for spec in specs {
626            policy
627                .auth
628                .insert(spec.method.clone(), spec.path.clone(), spec.auth);
629            if spec.request_timeout != RouteTimeout::Inherit {
630                policy
631                    .timeouts
632                    .entry(spec.method.clone())
633                    .or_default()
634                    .insert(spec.path.clone(), spec.request_timeout);
635            }
636        }
637        policy
638    }
639}
640
641/// Probes stay on [`build_outer_router`] so they remain available during startup and drain.
642fn layer_gear_router(
643    gear_router: Router,
644    policy: OopRoutePolicy,
645    tenant_plane: TenantPlane,
646    drain_guard: DrainGuard,
647    options: &OopServeOptions,
648) -> Router {
649    // Policy, both auth planes and the platform gate, in the order
650    // `cpt-cf-adr-two-plane-auth` requires. Both planes fail closed: platform routes
651    // without an internal authenticator, tenant and unlisted routes without a bearer
652    // authenticator (unless `auth_disabled`). `check_route_auth` refuses to start
653    // before that can happen for a declared tenant operation.
654    let gear = layer_route_auth_with(
655        gear_router,
656        policy.auth,
657        tenant_plane,
658        options.internal_authenticator.clone(),
659    );
660    layer_serving(gear, drain_guard, options, policy.timeouts)
661}
662
663/// Assemble the gear ingress layers shared by early and final route publication.
664fn layer_serving(
665    gear: Router,
666    drain_guard: DrainGuard,
667    options: &OopServeOptions,
668    timeouts: RouteTimeouts,
669) -> Router {
670    let drain = from_fn_with_state(drain_guard, drain_guard_middleware);
671    let gear = match options.request_limits {
672        Some(limits) => {
673            let body_limit = limits.body_limit_bytes();
674            let deadlines = Arc::new(RequestDeadlines {
675                default: limits.request_timeout(),
676                timeouts,
677            });
678            // Both layers use the same cap so opting in can raise Axum's extractor default.
679            gear.layer(DefaultBodyLimit::max(body_limit))
680                .layer(RequestBodyLimitLayer::new(body_limit))
681                .layer(drain)
682                .layer(from_fn_with_state(deadlines, RequestDeadlines::apply))
683        }
684        None => gear.layer(drain),
685    };
686
687    // Canonical errors use the outer request span to fill the wire trace ID.
688    gear.layer(from_fn(canonical_error_middleware))
689        .layer(from_fn(trace_context_middleware))
690}
691
692#[resource_error(gts_id!("cf.core.http.request.v1~"))]
693struct RequestDeadlineError;
694
695struct RequestDeadlines {
696    default: Duration,
697    timeouts: RouteTimeouts,
698}
699
700impl RequestDeadlines {
701    fn resolve(&self, request: &Request) -> Option<Duration> {
702        let declared = request
703            .extensions()
704            .get::<MatchedPath>()
705            .and_then(|path| self.timeouts.get(request.method())?.get(path.as_str()));
706        match declared {
707            Some(RouteTimeout::Custom(timeout)) => Some(*timeout),
708            Some(RouteTimeout::Disabled) => None,
709            Some(RouteTimeout::Inherit) | None => Some(self.default),
710        }
711    }
712
713    async fn apply(State(deadlines): State<Arc<Self>>, request: Request, next: Next) -> Response {
714        let Some(timeout) = deadlines.resolve(&request) else {
715            return next.run(request).await;
716        };
717        // Expiry drops the request future and releases its drain guard.
718        match tokio::time::timeout(timeout, next.run(request)).await {
719            Ok(response) => response,
720            Err(_) => RequestDeadlineError::deadline_exceeded(format!(
721                "Request exceeded {timeout:?} timeout"
722            ))
723            .create()
724            .into_response(),
725        }
726    }
727}
728
729tokio::task_local! {
730    static INBOUND_TRACEPARENT: Option<HeaderValue>;
731}
732
733/// Forward the current `OoP` request's single valid inbound `traceparent`
734/// when the outbound headers lack a parent from the active span or caller.
735pub fn inject_inbound_traceparent(headers: &mut HeaderMap) {
736    if !headers.contains_key(TRACEPARENT)
737        && let Ok(Some(parent)) = INBOUND_TRACEPARENT.try_with(Clone::clone)
738    {
739        headers.insert(TRACEPARENT, parent);
740    }
741}
742
743/// Scope the caller's correlation headers to the gear request. Its span
744/// records the wire trace ID even when no tracing provider is installed.
745async fn trace_context_middleware(req: Request, next: Next) -> Response {
746    use tracing::Instrument as _;
747    use tracing::field::Empty;
748
749    let mut parents = req.headers().get_all(TRACEPARENT).iter();
750    let inbound = parents
751        .next()
752        .filter(|value| {
753            parents.next().is_none()
754                && value.len() == 55
755                && value.to_str().ok().and_then(parse_trace_id).is_some()
756        })
757        .cloned();
758    let request_id = toolkit_trace_context::extract_request_id(req.headers());
759
760    let span = tracing::info_span!(
761        "http_request",
762        method = %req.method(),
763        uri = %req.uri().path(),
764        request_id = %request_id.as_deref().unwrap_or("n/a"),
765        trace_id = Empty,
766        parent.trace_id = Empty,
767    );
768
769    toolkit_trace_context::set_parent_from_headers(&span, req.headers());
770
771    let request =
772        toolkit_trace_context::with_request_id(request_id, next.run(req).instrument(span));
773    INBOUND_TRACEPARENT.scope(inbound, request).await
774}
775
776// ---------------------------------------------------------------------------
777// Serve
778// ---------------------------------------------------------------------------
779
780/// Serve the pre-bound `OoP` listener(s) until `cancel` fires, then drain.
781///
782/// Binding happens earlier in [`OopHttpServer::start`] so `/healthz` is up
783/// before the gear's (possibly slow) `start()` phase; this loop only drives the
784/// accept + graceful-shutdown machinery:
785/// 1. Serve with graceful shutdown wired to `cancel`.
786/// 2. On `cancel`: flip readiness to draining (via the caller-owned
787///    `ReadinessState`), wait up to `drain_timeout` for in-flight to reach zero,
788///    then let `axum` close the listener.
789///
790/// The `DirectoryService` deregistration is orchestrated by [`OopHttpServer::join`]
791/// so the full drain sequence (`cpt-cf-component-oop-bootstrap`) is honored.
792///
793/// # Errors
794/// Returns an error if the server task fails.
795async fn serve_loop(
796    listener: tokio::net::TcpListener,
797    router: Router,
798    drain_guard: DrainGuard,
799    sidecar: Option<(tokio::net::TcpListener, Router)>,
800    drain_timeout: Duration,
801    cancel: CancellationToken,
802) -> anyhow::Result<()> {
803    // Optional sidecar probe listener (bound by the caller).
804    let sidecar = match sidecar {
805        Some((probe_listener, probe_router)) => {
806            let shutdown = {
807                let cancel = cancel.clone();
808                async move { cancel.cancelled().await }
809            };
810            Some(tokio::spawn(async move {
811                if let Err(e) = axum::serve(probe_listener, probe_router)
812                    .with_graceful_shutdown(shutdown)
813                    .await
814                {
815                    tracing::warn!(error = %e, "OoP probe sidecar server error");
816                }
817            }))
818        }
819        None => None,
820    };
821
822    // Main server: graceful shutdown waits for cancellation, then drains.
823    let shutdown = {
824        let cancel = cancel.clone();
825        let guard = drain_guard.clone();
826        async move {
827            cancel.cancelled().await;
828            // Drain step 1/2: flip readiness to 503 and start rejecting new work.
829            guard.begin_drain();
830            tracing::info!("OoP HTTP server draining (graceful shutdown)");
831            // Drain step 3: wait for in-flight requests to complete.
832            drain_in_flight(&guard, drain_timeout).await;
833        }
834    };
835
836    let result = axum::serve(
837        listener,
838        router.into_make_service_with_connect_info::<std::net::SocketAddr>(),
839    )
840    .with_graceful_shutdown(shutdown)
841    .await
842    .map_err(anyhow::Error::from);
843
844    if let Some(handle) = sidecar {
845        handle.abort();
846        if let Err(e) = handle.await
847            && !e.is_cancelled()
848        {
849            tracing::warn!(error = %e, "OoP probe sidecar task join error");
850        }
851    }
852
853    result
854}
855
856/// Owns an `OoP` gear's HTTP surface across the startup boundary.
857///
858/// [`start`](Self::start) binds the listener and serves the framework probes
859/// **immediately** — `/healthz` → `200`, `/readyz` → `starting`/`503`, and gear
860/// routes → `503 starting` — so the kubelet's liveness probe passes while the
861/// gear's (possibly slow) `start()` phase runs. Once the gear router is composed,
862/// [`attach`](Self::attach) swaps it in atomically (no port rebind) and starts
863/// background directory presence + dependency resolution. [`join`](Self::join)
864/// waits for the graceful drain on shutdown, then deregisters from
865/// `DirectoryService` (drain step 4, `cpt-cf-component-oop-bootstrap`).
866///
867/// Steps 5–7 of the drain order (reverse-dependency wait, stopping runtime
868/// services, process exit) are the caller's / operator's responsibility;
869/// the presence task stops when `cancel` fires.
870pub(super) struct OopHttpServer {
871    readiness: Arc<ReadinessState>,
872    late: LateRoutes,
873    drain_guard: DrainGuard,
874    options: OopServeOptions,
875    cancel: CancellationToken,
876    registration_task: Option<tokio::task::JoinHandle<()>>,
877    /// The `OpenAPI` document `registration_task` registers, and the channel
878    /// replacing its registration info.
879    presence_openapi: Option<Arc<str>>,
880    presence_updates: Option<tokio::sync::watch::Sender<RegisterInstanceInfo>>,
881    /// Writer tasks for co-hosted provider gears other than
882    /// `options.gear_name`; each registers its record through the presence
883    /// manager, which renews and (on [`join`](Self::join)) deregisters it.
884    provider_writers: Vec<(String, tokio::task::JoinHandle<()>)>,
885    /// Per-process presence manager: owns lease renewal, the
886    /// `Draining` drain signal and deregistration for every record the writer
887    /// tasks register. Created eagerly in [`start`](Self::start) and published in
888    /// the `ClientHub` by the caller, so co-hosted registrars renew through it.
889    presence: Arc<PresenceManager>,
890    /// Drives the manager's renewal loop. **Independent of the root `cancel`**
891    /// so the manager keeps renewing — and reporting `Draining` — for the whole
892    /// drain window. [`join`](Self::join) stops it *just before* the final
893    /// deregistration (drain step 4) so an in-flight renewal cannot re-register
894    /// a record after it is removed; `Drop` aborts it.
895    presence_cancel: CancellationToken,
896    presence_run: Option<tokio::task::JoinHandle<()>>,
897    /// Taken by [`join`](Self::join); aborted by `Drop` otherwise.
898    serve: Option<tokio::task::JoinHandle<anyhow::Result<()>>>,
899}
900
901/// Dropped without [`join`](OopHttpServer::join) — the lifecycle future was
902/// dropped — the server closes its listeners and presence instead of
903/// outliving the runtime.
904impl Drop for OopHttpServer {
905    fn drop(&mut self) {
906        if let Some(task) = self.registration_task.take() {
907            task.abort();
908        }
909        for (_, task) in self.provider_writers.drain(..) {
910            task.abort();
911        }
912        // Stop the manager's renewal loop (its own token, not the root's).
913        self.presence_cancel.cancel();
914        if let Some(task) = self.presence_run.take() {
915            task.abort();
916        }
917        if let Some(serve) = self.serve.take() {
918            serve.abort();
919        }
920    }
921}
922
923impl OopHttpServer {
924    /// Bind the listener(s) and start serving probes immediately; gear routes
925    /// reply `503 starting` until [`attach`](Self::attach) publishes them.
926    ///
927    /// # Errors
928    /// Returns an error if the main (or sidecar) listener cannot be bound.
929    pub(super) async fn start(
930        readiness: Arc<ReadinessState>,
931        options: OopServeOptions,
932        cancel: CancellationToken,
933    ) -> anyhow::Result<Self> {
934        let late = LateRoutes::default();
935        let drain_guard = DrainGuard::new(Arc::clone(&readiness));
936        let mut options = options;
937
938        let listener = tokio::net::TcpListener::bind(options.listen_addr).await?;
939        let bound = listener.local_addr()?;
940        let configured_port = options.listen_addr.port();
941        if bound.port() != configured_port {
942            if let Some(rewritten) =
943                rewrite_advertise_uri_port(&options.advertise_uri, bound.port(), configured_port)
944            {
945                tracing::info!(
946                    old = %options.advertise_uri,
947                    new = %rewritten,
948                    "advertise_uri rewritten to use actually bound port"
949                );
950                options.advertise_uri = rewritten;
951            } else {
952                tracing::info!(
953                    advertise_uri = %options.advertise_uri,
954                    bound_port = bound.port(),
955                    configured_port,
956                    "bound port differs from configured; leaving advertise_uri unchanged"
957                );
958            }
959        }
960        options.listen_addr = bound;
961        tracing::info!(
962            addr = %options.listen_addr,
963            "OoP HTTP server bound (probes live; gear routes attach after start)"
964        );
965
966        let outer = build_outer_router(Arc::clone(&readiness), late.clone());
967
968        let sidecar = if let Some(addr) = options.probe_bind_addr {
969            let probe_listener = tokio::net::TcpListener::bind(addr).await?;
970            let bound_probe = probe_listener.local_addr()?;
971            options.probe_bind_addr = Some(bound_probe);
972            tracing::info!(addr = %bound_probe, "OoP probe sidecar bound");
973            Some((
974                probe_listener,
975                build_probe_router(Arc::clone(&readiness), late.clone()),
976            ))
977        } else {
978            None
979        };
980
981        let serve = tokio::spawn(serve_loop(
982            listener,
983            outer,
984            drain_guard.clone(),
985            sidecar,
986            options.drain_timeout,
987            cancel.clone(),
988        ));
989
990        // The per-process presence manager is created eagerly, not on the first
991        // `start_presence`: co-hosted registrars (grpc-hub, event-broker) register
992        // during the startup phases — before any root gear's routes attach — and
993        // must resolve the same manager so their records are renewed too. The
994        // caller publishes it in the `ClientHub` (see
995        // `HostRuntime::run_oop_serving`). Its reported state comes from the gear's
996        // *full* readiness (startup, deps, healthchecks, drain — ADR-0005), so a
997        // gear failing its readiness check advertises `Starting`, not `Serving`.
998        let presence_cancel = CancellationToken::new();
999        let presence = PresenceManager::new(
1000            Arc::clone(&options.directory),
1001            ReportedStateSource::Readiness(Arc::clone(&readiness)),
1002            options.heartbeat_interval,
1003        );
1004        // The renewal loop runs on `presence_cancel` (independent of the root
1005        // `cancel`) so it keeps renewing and reporting `Draining` through the
1006        // whole drain window; `join` stops it just before the final deregister,
1007        // `Drop` aborts it.
1008        let presence_run = tokio::spawn(Arc::clone(&presence).run(presence_cancel.clone()));
1009        // Push an immediate `Draining` heartbeat the moment shutdown begins,
1010        // rather than waiting for the next renewal tick. Also exits on
1011        // `presence_cancel` so it never outlives the manager.
1012        {
1013            let drain_pm = Arc::clone(&presence);
1014            let drain_readiness = Arc::clone(&readiness);
1015            let root = cancel.clone();
1016            let stop = presence_cancel.clone();
1017            tokio::spawn(async move {
1018                tokio::select! {
1019                    () = root.cancelled() => {
1020                        // Flip readiness to `Draining` *before* waking the
1021                        // manager so the immediate renewal reports `Draining`,
1022                        // not a stale `Serving`. The serve loop also flips it on
1023                        // cancel; doing it here too (idempotent) removes the race
1024                        // where this wake wins first.
1025                        drain_readiness.set_draining(true);
1026                        drain_pm.begin_drain();
1027                    }
1028                    () = stop.cancelled() => {}
1029                }
1030            });
1031        }
1032
1033        Ok(Self {
1034            readiness,
1035            late,
1036            drain_guard,
1037            options,
1038            cancel,
1039            registration_task: None,
1040            presence_openapi: None,
1041            presence_updates: None,
1042            provider_writers: Vec::new(),
1043            presence,
1044            presence_cancel,
1045            presence_run: Some(presence_run),
1046            serve: Some(serve),
1047        })
1048    }
1049
1050    /// The serve options (used by the caller to compose the `OpenAPI` document).
1051    pub(super) fn options(&self) -> &OopServeOptions {
1052        &self.options
1053    }
1054
1055    /// Resolve the tenant-plane authenticator from the populated `ClientHub`.
1056    ///
1057    /// Called by the `OoP` serving path after the gear lifecycle's `start`
1058    /// phase and before [`attach`](Self::attach) layers the middleware. When an
1059    /// in-process authn stack (e.g. the `authn-resolver` gear) is linked into
1060    /// the binary it registers a [`DynBearerAuthenticator`] bridge during
1061    /// `init`; picking it up here installs `security_context_middleware` on the
1062    /// gear routes. A no-op if an authenticator was already supplied directly or
1063    /// none is registered in the hub.
1064    pub(super) fn resolve_bearer_authenticator(&mut self, hub: &crate::ClientHub) {
1065        if self.options.bearer_authenticator.is_some() {
1066            return;
1067        }
1068        if let Ok(auth) = hub.get::<DynBearerAuthenticator>() {
1069            self.options.bearer_authenticator = Some((*auth).clone());
1070            tracing::info!(
1071                gear = %self.options.gear_name,
1072                "tenant-plane authenticator installed (security_context_middleware enabled)"
1073            );
1074        } else {
1075            tracing::info!(
1076                gear = %self.options.gear_name,
1077                "no tenant-plane authenticator registered in ClientHub"
1078            );
1079        }
1080    }
1081
1082    /// Refuse to serve tenant operations without a bearer authenticator (unless
1083    /// `auth_disabled`): a startup error names the cause instead of a listener that
1084    /// refuses every tenant request. Without one, a route the policy does not list is
1085    /// refused too, which only a warning can flag: the router cannot list its routes.
1086    /// Platform operations without an internal authenticator only warn (when layered):
1087    /// the platform gate already refuses each request, and a linked gear's platform route
1088    /// nobody calls must not stop the process.
1089    ///
1090    /// # Errors
1091    /// When tenant operations are declared and no tenant authenticator is available.
1092    pub(super) fn check_route_auth(&self, route_auth: &RouteAuthPolicy) -> anyhow::Result<()> {
1093        if !matches!(self.options.tenant_plane(), TenantPlane::Absent) {
1094            return Ok(());
1095        }
1096        let gear = &self.options.gear_name;
1097        let tenant = route_auth.tenant_routes();
1098        if !tenant.is_empty() {
1099            anyhow::bail!(
1100                "gear '{gear}' serves tenant operations but no tenant authenticator is \
1101                 available (link authn-resolver, or set oop_http.auth_disabled for \
1102                 development): {tenant:?}"
1103            );
1104        }
1105        tracing::warn!(
1106            gear = %gear,
1107            reason = "TENANT_AUTH_NOT_CONFIGURED",
1108            "no tenant authenticator on this listener: a route not declared through \
1109             OperationBuilder is refused with 401 (link authn-resolver, or set \
1110             oop_http.auth_disabled for development)"
1111        );
1112        Ok(())
1113    }
1114
1115    /// Serve system platform-plane and anonymous routes before application startup;
1116    /// tenant routes and unknown paths return `503` until tenant auth is installed.
1117    /// Does not mark startup complete or advertise; see [`start_presence`](Self::start_presence).
1118    pub(super) fn publish_bootstrap_routes(
1119        &mut self,
1120        gear_router: Router,
1121        openapi_json: String,
1122        policy: OopRoutePolicy,
1123    ) {
1124        // The outer gate blocks tenant calls. Keep anonymous contexts anonymous,
1125        // even with `auth_disabled`; install tenant auth with the final routes.
1126        let authenticated = layer_route_auth_with(
1127            gear_router,
1128            policy.auth.clone(),
1129            TenantPlane::Absent,
1130            self.options.internal_authenticator.clone(),
1131        );
1132        let gated = authenticated.layer(from_fn_with_state(
1133            Arc::new(policy.auth),
1134            bootstrap_plane_gate,
1135        ));
1136        let layered = layer_serving(
1137            gated,
1138            self.drain_guard.clone(),
1139            &self.options,
1140            policy.timeouts,
1141        );
1142        self.late.publish(layered, Arc::from(openapi_json));
1143        tracing::info!(
1144            gear = %self.options.gear_name,
1145            "OoP system routes attached (platform plane only)"
1146        );
1147    }
1148
1149    /// Atomically publish the composed gear routes with their listener policy and
1150    /// `OpenAPI` document on the bound listener, replacing the bootstrap
1151    /// routes, and mark startup complete.
1152    ///
1153    /// Dependency resolution runs in the proxy-wiring phase before serving;
1154    /// directory presence is started separately by
1155    /// [`start_presence`](Self::start_presence).
1156    ///
1157    /// # Errors
1158    /// When the route policy fails [`Self::check_route_auth`]; nothing is published.
1159    pub(super) fn attach(
1160        &mut self,
1161        gear_router: Router,
1162        openapi_json: String,
1163        policy: OopRoutePolicy,
1164    ) -> anyhow::Result<()> {
1165        // A declared operation whose plane has no validator would refuse every request;
1166        // stop here, before serving, and say why.
1167        self.check_route_auth(&policy.auth)?;
1168        let layered = layer_gear_router(
1169            gear_router,
1170            policy,
1171            self.options.tenant_plane(),
1172            self.drain_guard.clone(),
1173            &self.options,
1174        );
1175        self.late.publish(layered, Arc::from(openapi_json));
1176        self.readiness.mark_startup_complete();
1177        tracing::info!(gear = %self.options.gear_name, "OoP gear routes attached (now serving)");
1178        Ok(())
1179    }
1180
1181    /// The per-process presence manager (created in [`start`](Self::start)).
1182    ///
1183    /// Published in the `ClientHub` by the caller so co-hosted registrars renew
1184    /// through the same manager.
1185    pub(super) fn presence_manager(&self) -> Arc<PresenceManager> {
1186        Arc::clone(&self.presence)
1187    }
1188
1189    /// Register directory presence with the current `OpenAPI` document; the
1190    /// presence manager then owns the record's lease renewal, the `Draining`
1191    /// drain signal and deregistration. Later calls register a changed document
1192    /// without interrupting renewal, so gateway discovery sees the newly served
1193    /// routes. An unchanged document is a no-op.
1194    pub(super) fn start_presence(&mut self) {
1195        let openapi = self.late.openapi();
1196        if let Some(updates) = &self.presence_updates {
1197            if self.presence_openapi != openapi {
1198                updates.send_replace(self.registration_info(openapi.as_ref()));
1199                self.presence_openapi = openapi;
1200            }
1201            return;
1202        }
1203        let registration_info = self.registration_info(openapi.as_ref());
1204        self.presence_openapi = openapi;
1205        let (updates, presence_rx) = tokio::sync::watch::channel(registration_info);
1206        self.presence_updates = Some(updates);
1207        let manager = self.presence_manager();
1208        let cancel = self.cancel.clone();
1209        self.registration_task = Some(tokio::spawn(async move {
1210            super::oop_registration::presence_loop_with_updates(manager, presence_rx, cancel).await;
1211        }));
1212    }
1213
1214    /// The advertised gear's registration, with `openapi`.
1215    fn registration_info(&self, openapi: Option<&Arc<str>>) -> RegisterInstanceInfo {
1216        let mut registration_info = RegisterInstanceInfo::new(
1217            self.options.gear_name.clone(),
1218            self.options.instance_id.clone(),
1219        )
1220        .with_rest_endpoint(ServiceEndpoint::new(self.options.advertise_uri.clone()))
1221        .with_labels(self.options.labels.clone());
1222        if let Some(openapi) = openapi {
1223            // The directory stores only the hash; the edge fetches the document
1224            // from this worker's `/.well-known/openapi.json` and verifies it
1225            // against the hash (ADR-0011). Send the hash, not the ~1 MiB body.
1226            registration_info = registration_info
1227                .with_openapi_spec_hash(crate::directory::openapi_spec_hash(openapi.as_bytes()));
1228        }
1229        if let Some(version) = self.options.version.clone() {
1230            registration_info = registration_info.with_version(version);
1231        }
1232        registration_info
1233    }
1234
1235    /// Advertise a co-hosted provider at this listener's URL and instance id,
1236    /// even while the root starts. The record registers (with backoff) and is
1237    /// then renewed and deregistered by the shared presence manager.
1238    pub(super) fn start_provider_presence(&mut self, gear: String) {
1239        if gear == self.options.gear_name
1240            || self.provider_writers.iter().any(|(name, _)| *name == gear)
1241        {
1242            return;
1243        }
1244        let mut info = RegisterInstanceInfo::new(gear.clone(), self.options.instance_id.clone())
1245            .with_rest_endpoint(ServiceEndpoint::new(self.options.advertise_uri.clone()))
1246            .with_labels(self.options.labels.clone());
1247        if let Some(version) = self.options.version.clone() {
1248            info = info.with_version(version);
1249        }
1250        let manager = self.presence_manager();
1251        let cancel = self.cancel.clone();
1252        let task = tokio::spawn(async move {
1253            super::oop_registration::presence_loop(manager, info, cancel).await;
1254        });
1255        self.provider_writers.push((gear, task));
1256    }
1257
1258    /// Wait for the server to drain on shutdown, then deregister from
1259    /// `DirectoryService` (drain step 4 — after in-flight requests finish so
1260    /// consumers don't see stale "ready" state).
1261    ///
1262    /// # Errors
1263    /// Propagates a serve error; deregistration failures are logged only.
1264    pub(super) async fn join(mut self) -> anyhow::Result<()> {
1265        // Awaited in place: if this future is dropped, `Drop` still aborts it.
1266        let Some(serve) = self.serve.as_mut() else {
1267            anyhow::bail!("OoP serve task already joined");
1268        };
1269        let serve_result = match serve.await {
1270            Ok(r) => r,
1271            Err(e) => Err(anyhow::anyhow!("OoP serve task join error: {e}")),
1272        };
1273        self.serve = None;
1274
1275        // The writer tasks stop; through the drain window above the presence
1276        // manager kept renewing and reporting `Draining`. Stop and join the
1277        // renewal loop *before* deregistering (drain step 4) so a renewal pass
1278        // in flight cannot re-register a record after `deregister_all` removes
1279        // it. The drain window has already elapsed (the serve task above drained
1280        // in-flight requests), so stopping renewal here does not cut it short.
1281        if let Some(task) = self.registration_task.take() {
1282            task.abort();
1283        }
1284        for (_, task) in std::mem::take(&mut self.provider_writers) {
1285            task.abort();
1286        }
1287        self.presence_cancel.cancel();
1288        if let Some(task) = self.presence_run.take()
1289            && let Err(e) = task.await
1290        {
1291            tracing::warn!(error = %e, "presence manager renewal task join error");
1292        }
1293        self.presence.deregister_all().await;
1294        tracing::info!(gear = %self.options.gear_name, "deregistered from DirectoryService");
1295
1296        serve_result
1297    }
1298}
1299
1300/// Rewrite `advertise_uri` to use the actually bound port, but only if the
1301/// URI currently uses the `configured_port` (i.e. the port the caller asked
1302/// the server to bind to). This preserves user-provided load-balancer URLs
1303/// that intentionally advertise a different port from the local socket.
1304fn rewrite_advertise_uri_port(
1305    advertise_uri: &str,
1306    bound_port: u16,
1307    configured_port: u16,
1308) -> Option<String> {
1309    let mut url = Url::parse(advertise_uri).ok()?;
1310    if url.port_or_known_default() != Some(configured_port) {
1311        return None;
1312    }
1313    url.set_port(Some(bound_port)).ok()?;
1314    Some(url.to_string())
1315}
1316
1317/// Wait up to `timeout` for the in-flight counter to reach zero.
1318async fn drain_in_flight(guard: &DrainGuard, timeout: Duration) {
1319    let deadline = tokio::time::Instant::now() + timeout;
1320    loop {
1321        let in_flight = guard.in_flight();
1322        if in_flight == 0 {
1323            tracing::info!("OoP drain complete: no in-flight requests");
1324            return;
1325        }
1326        if tokio::time::Instant::now() >= deadline {
1327            tracing::warn!(
1328                in_flight,
1329                timeout_secs = timeout.as_secs(),
1330                "OoP drain timed out with in-flight requests remaining"
1331            );
1332            return;
1333        }
1334        tokio::time::sleep(Duration::from_millis(50)).await;
1335    }
1336}
1337
1338#[cfg(test)]
1339#[cfg_attr(coverage_nightly, coverage(off))]
1340#[path = "oop_serve_tests.rs"]
1341mod tests;