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