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::readiness::ReadinessState;
60use crate::api::canonical_error_middleware;
61use crate::api::operation_builder::OperationSpec;
62
63/// `Retry-After` (seconds) advertised while the gear is draining.
64const DRAIN_RETRY_AFTER_SECONDS: u64 = 5;
65
66/// `Retry-After` (seconds) advertised for gear routes before the gear has
67/// finished starting (probes are already live; routes come up shortly).
68const STARTING_RETRY_AFTER_SECONDS: u64 = 1;
69
70// ---------------------------------------------------------------------------
71// Serve options
72// ---------------------------------------------------------------------------
73
74/// Configuration and collaborators for the `OoP` HTTP runtime, assembled by the
75/// bootstrap layer and consumed by `HostRuntime`'s `OoP` serving path.
76///
77/// `#[non_exhaustive]` so new fields (like `labels`) stay additive. Construct via
78/// [`OopServeOptions::new`] + the `with_*` builders rather than a struct literal,
79/// exactly as [`RunOptions`](super::RunOptions) is built: the five arguments to
80/// `new` are the fields with no meaningful default, and everything else defaults
81/// to the same values the bootstrap config layer uses. (A `Default` impl is still
82/// not provided — the `directory` collaborator is a required dependency.)
83///
84/// The builders are what keep [`run_oop_serving`](super::run_oop_serving)
85/// callable: it is `pub` and takes this type by value, so an out-of-crate caller
86/// — an integration test driving the real serve path, for instance — needs some
87/// way to build one.
88#[non_exhaustive]
89pub struct OopServeOptions {
90 /// Logical gear name (used for registration + `OpenAPI` title).
91 pub gear_name: String,
92 /// Process instance id (used for registration/deregistration).
93 pub instance_id: String,
94 /// Optional gear version (used for registration + `OpenAPI` version).
95 pub version: Option<String>,
96 /// Base URL other services use to reach this instance's REST endpoint
97 /// (e.g. `http://billing.default.svc.cluster.local:8080`). Registered with
98 /// `DirectoryService` as the instance's `rest_endpoint`.
99 pub advertise_uri: String,
100 /// Address the main HTTP server binds to (gear routes + probes).
101 pub listen_addr: std::net::SocketAddr,
102 /// Optional separate address for probe endpoints (sidecar port). When set,
103 /// probes are served here *and* on the main listener.
104 pub probe_bind_addr: Option<std::net::SocketAddr>,
105 /// Maximum time to wait for in-flight requests to drain on shutdown.
106 pub drain_timeout: Duration,
107 /// Interval between `DirectoryService` heartbeats. The single presence task
108 /// ([`presence_loop`](super::oop_registration)) sends a heartbeat every
109 /// interval to keep the instance `Healthy`/routable and avoid
110 /// heartbeat-timeout eviction. The presence loop clamps this to a 1s minimum.
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 /// Presence of co-hosted provider gears other than `options.gear_name`
723 /// (the system group's, published before the application group), each
724 /// deregistered on [`join`](Self::join) like the root's.
725 provider_presence: Vec<(String, tokio::task::JoinHandle<()>)>,
726 /// Taken by [`join`](Self::join); aborted by `Drop` otherwise.
727 serve: Option<tokio::task::JoinHandle<anyhow::Result<()>>>,
728}
729
730/// Dropped without [`join`](OopHttpServer::join) — the lifecycle future was
731/// dropped — the server closes its listeners and presence instead of
732/// outliving the runtime.
733impl Drop for OopHttpServer {
734 fn drop(&mut self) {
735 if let Some(task) = self.registration_task.take() {
736 task.abort();
737 }
738 for (_, task) in self.provider_presence.drain(..) {
739 task.abort();
740 }
741 if let Some(serve) = self.serve.take() {
742 serve.abort();
743 }
744 }
745}
746
747impl OopHttpServer {
748 /// Bind the listener(s) and start serving probes immediately; gear routes
749 /// reply `503 starting` until [`attach`](Self::attach) publishes them.
750 ///
751 /// # Errors
752 /// Returns an error if the main (or sidecar) listener cannot be bound.
753 pub(super) async fn start(
754 readiness: Arc<ReadinessState>,
755 options: OopServeOptions,
756 cancel: CancellationToken,
757 ) -> anyhow::Result<Self> {
758 let late = LateRoutes::default();
759 let drain_guard = DrainGuard::new(Arc::clone(&readiness));
760 let mut options = options;
761
762 let listener = tokio::net::TcpListener::bind(options.listen_addr).await?;
763 let bound = listener.local_addr()?;
764 let configured_port = options.listen_addr.port();
765 if bound.port() != configured_port {
766 if let Some(rewritten) =
767 rewrite_advertise_uri_port(&options.advertise_uri, bound.port(), configured_port)
768 {
769 tracing::info!(
770 old = %options.advertise_uri,
771 new = %rewritten,
772 "advertise_uri rewritten to use actually bound port"
773 );
774 options.advertise_uri = rewritten;
775 } else {
776 tracing::info!(
777 advertise_uri = %options.advertise_uri,
778 bound_port = bound.port(),
779 configured_port,
780 "bound port differs from configured; leaving advertise_uri unchanged"
781 );
782 }
783 }
784 options.listen_addr = bound;
785 tracing::info!(
786 addr = %options.listen_addr,
787 "OoP HTTP server bound (probes live; gear routes attach after start)"
788 );
789
790 let outer = build_outer_router(Arc::clone(&readiness), late.clone());
791
792 let sidecar = if let Some(addr) = options.probe_bind_addr {
793 let probe_listener = tokio::net::TcpListener::bind(addr).await?;
794 let bound_probe = probe_listener.local_addr()?;
795 options.probe_bind_addr = Some(bound_probe);
796 tracing::info!(addr = %bound_probe, "OoP probe sidecar bound");
797 Some((
798 probe_listener,
799 build_probe_router(Arc::clone(&readiness), late.clone()),
800 ))
801 } else {
802 None
803 };
804
805 let serve = tokio::spawn(serve_loop(
806 listener,
807 outer,
808 drain_guard.clone(),
809 sidecar,
810 options.drain_timeout,
811 cancel.clone(),
812 ));
813
814 Ok(Self {
815 readiness,
816 late,
817 drain_guard,
818 options,
819 cancel,
820 registration_task: None,
821 presence_openapi: None,
822 presence_updates: None,
823 provider_presence: Vec::new(),
824 serve: Some(serve),
825 })
826 }
827
828 /// The serve options (used by the caller to compose the `OpenAPI` document).
829 pub(super) fn options(&self) -> &OopServeOptions {
830 &self.options
831 }
832
833 /// Resolve the tenant-plane authenticator from the populated `ClientHub`.
834 ///
835 /// Called by the `OoP` serving path after the gear lifecycle's `start`
836 /// phase and before [`attach`](Self::attach) layers the middleware. When an
837 /// in-process authn stack (e.g. the `authn-resolver` gear) is linked into
838 /// the binary it registers a [`DynBearerAuthenticator`] bridge during
839 /// `init`; picking it up here installs `security_context_middleware` on the
840 /// gear routes. A no-op if an authenticator was already supplied directly or
841 /// none is registered in the hub.
842 pub(super) fn resolve_bearer_authenticator(&mut self, hub: &crate::ClientHub) {
843 if self.options.bearer_authenticator.is_some() {
844 return;
845 }
846 if let Ok(auth) = hub.get::<DynBearerAuthenticator>() {
847 self.options.bearer_authenticator = Some((*auth).clone());
848 tracing::info!(
849 gear = %self.options.gear_name,
850 "tenant-plane authenticator installed (security_context_middleware enabled)"
851 );
852 } else {
853 tracing::info!(
854 gear = %self.options.gear_name,
855 "no tenant-plane authenticator registered in ClientHub"
856 );
857 }
858 }
859
860 /// Refuse to serve tenant operations without a bearer authenticator (unless
861 /// `auth_disabled`): a startup error names the cause instead of a listener that
862 /// refuses every tenant request. Without one, a route the policy does not list is
863 /// refused too, which only a warning can flag: the router cannot list its routes.
864 /// Platform operations without an internal authenticator only warn (when layered):
865 /// the platform gate already refuses each request, and a linked gear's platform route
866 /// nobody calls must not stop the process.
867 ///
868 /// # Errors
869 /// When tenant operations are declared and no tenant authenticator is available.
870 pub(super) fn check_route_auth(&self, route_auth: &RouteAuthPolicy) -> anyhow::Result<()> {
871 if !matches!(self.options.tenant_plane(), TenantPlane::Absent) {
872 return Ok(());
873 }
874 let gear = &self.options.gear_name;
875 let tenant = route_auth.tenant_routes();
876 if !tenant.is_empty() {
877 anyhow::bail!(
878 "gear '{gear}' serves tenant operations but no tenant authenticator is \
879 available (link authn-resolver, or set oop_http.auth_disabled for \
880 development): {tenant:?}"
881 );
882 }
883 tracing::warn!(
884 gear = %gear,
885 reason = "TENANT_AUTH_NOT_CONFIGURED",
886 "no tenant authenticator on this listener: a route not declared through \
887 OperationBuilder is refused with 401 (link authn-resolver, or set \
888 oop_http.auth_disabled for development)"
889 );
890 Ok(())
891 }
892
893 /// Serve system platform-plane and anonymous routes before application startup;
894 /// tenant routes and unknown paths return `503` until tenant auth is installed.
895 /// Does not mark startup complete or advertise; see [`start_presence`](Self::start_presence).
896 pub(super) fn publish_bootstrap_routes(
897 &mut self,
898 gear_router: Router,
899 openapi_json: String,
900 route_auth: RouteAuthPolicy,
901 ) {
902 // The outer gate blocks tenant calls. Keep anonymous contexts anonymous,
903 // even with `auth_disabled`; install tenant auth with the final routes.
904 let authenticated = layer_route_auth_with(
905 gear_router,
906 route_auth.clone(),
907 TenantPlane::Absent,
908 self.options.internal_authenticator.clone(),
909 );
910 let gated = authenticated.layer(from_fn_with_state(
911 Arc::new(route_auth),
912 bootstrap_plane_gate,
913 ));
914 let layered = layer_serving(gated, self.drain_guard.clone());
915 self.late.publish(layered, Arc::from(openapi_json));
916 tracing::info!(
917 gear = %self.options.gear_name,
918 "OoP system routes attached (platform plane only)"
919 );
920 }
921
922 /// Atomically publish the composed gear routes (with auth policy) and their
923 /// `OpenAPI` document on the bound listener, replacing the bootstrap
924 /// routes, and mark startup complete.
925 ///
926 /// Dependency resolution runs in the proxy-wiring phase before serving;
927 /// directory presence is started separately by
928 /// [`start_presence`](Self::start_presence).
929 ///
930 /// # Errors
931 /// When the route policy fails [`Self::check_route_auth`]; nothing is published.
932 pub(super) fn attach(
933 &mut self,
934 gear_router: Router,
935 openapi_json: String,
936 route_auth: RouteAuthPolicy,
937 ) -> anyhow::Result<()> {
938 // A declared operation whose plane has no validator would refuse every request;
939 // stop here, before serving, and say why.
940 self.check_route_auth(&route_auth)?;
941 let layered = layer_gear_router(
942 gear_router,
943 route_auth,
944 self.options.tenant_plane(),
945 self.drain_guard.clone(),
946 &self.options,
947 );
948 self.late.publish(layered, Arc::from(openapi_json));
949 self.readiness.mark_startup_complete();
950 tracing::info!(gear = %self.options.gear_name, "OoP gear routes attached (now serving)");
951 Ok(())
952 }
953
954 /// Start directory registration, heartbeats and self-heal with the current
955 /// `OpenAPI` document. Later calls register a changed document without
956 /// interrupting heartbeats, so gateway discovery sees the newly served routes.
957 /// An unchanged document is a no-op.
958 pub(super) fn start_presence(&mut self) {
959 let openapi = self.late.openapi();
960 if let Some(updates) = &self.presence_updates {
961 if self.presence_openapi != openapi {
962 updates.send_replace(self.registration_info(openapi.as_ref()));
963 self.presence_openapi = openapi;
964 }
965 return;
966 }
967 let registration_info = self.registration_info(openapi.as_ref());
968 self.presence_openapi = openapi;
969 let (updates, presence) = tokio::sync::watch::channel(registration_info);
970 self.presence_updates = Some(updates);
971 let directory = Arc::clone(&self.options.directory);
972 let heartbeat_interval = self.options.heartbeat_interval;
973 let cancel = self.cancel.clone();
974 self.registration_task = Some(tokio::spawn(async move {
975 super::oop_registration::presence_loop_with_updates(
976 directory,
977 presence,
978 heartbeat_interval,
979 cancel,
980 )
981 .await;
982 }));
983 }
984
985 /// The advertised gear's registration, with `openapi`.
986 fn registration_info(&self, openapi: Option<&Arc<str>>) -> RegisterInstanceInfo {
987 let mut registration_info = RegisterInstanceInfo::new(
988 self.options.gear_name.clone(),
989 self.options.instance_id.clone(),
990 )
991 .with_rest_endpoint(ServiceEndpoint::new(self.options.advertise_uri.clone()))
992 .with_labels(self.options.labels.clone());
993 if let Some(openapi) = openapi {
994 registration_info = registration_info.with_openapi_spec(openapi.to_string());
995 }
996 if let Some(version) = self.options.version.clone() {
997 registration_info = registration_info.with_version(version);
998 }
999 registration_info
1000 }
1001
1002 /// Advertise a co-hosted provider at this listener's URL and instance id,
1003 /// even while the root starts. Uses normal directory retries and heartbeats.
1004 pub(super) fn start_provider_presence(&mut self, gear: String) {
1005 if gear == self.options.gear_name
1006 || self.provider_presence.iter().any(|(name, _)| *name == gear)
1007 {
1008 return;
1009 }
1010 let mut info = RegisterInstanceInfo::new(gear.clone(), self.options.instance_id.clone())
1011 .with_rest_endpoint(ServiceEndpoint::new(self.options.advertise_uri.clone()))
1012 .with_labels(self.options.labels.clone());
1013 if let Some(version) = self.options.version.clone() {
1014 info = info.with_version(version);
1015 }
1016 let directory = Arc::clone(&self.options.directory);
1017 let heartbeat_interval = self.options.heartbeat_interval;
1018 let cancel = self.cancel.clone();
1019 let task = tokio::spawn(async move {
1020 super::oop_registration::presence_loop(directory, info, heartbeat_interval, cancel)
1021 .await;
1022 });
1023 self.provider_presence.push((gear, task));
1024 }
1025
1026 /// Wait for the server to drain on shutdown, then deregister from
1027 /// `DirectoryService` (drain step 4 — after in-flight requests finish so
1028 /// consumers don't see stale "ready" state).
1029 ///
1030 /// # Errors
1031 /// Propagates a serve error; deregistration failures are logged only.
1032 pub(super) async fn join(mut self) -> anyhow::Result<()> {
1033 // Awaited in place: if this future is dropped, `Drop` still aborts it.
1034 let Some(serve) = self.serve.as_mut() else {
1035 anyhow::bail!("OoP serve task already joined");
1036 };
1037 let serve_result = match serve.await {
1038 Ok(r) => r,
1039 Err(e) => Err(anyhow::anyhow!("OoP serve task join error: {e}")),
1040 };
1041 self.serve = None;
1042
1043 if let Some(task) = self.registration_task.take() {
1044 task.abort();
1045 }
1046 for (gear, task) in std::mem::take(&mut self.provider_presence) {
1047 task.abort();
1048 if let Err(e) = self
1049 .options
1050 .directory
1051 .deregister_instance(&gear, &self.options.instance_id)
1052 .await
1053 {
1054 tracing::warn!(gear, error = %e, "deregistration from DirectoryService failed on shutdown");
1055 }
1056 }
1057 if let Err(e) = self
1058 .options
1059 .directory
1060 .deregister_instance(&self.options.gear_name, &self.options.instance_id)
1061 .await
1062 {
1063 tracing::warn!(
1064 gear = %self.options.gear_name,
1065 error = %e,
1066 "deregistration from DirectoryService failed on shutdown"
1067 );
1068 } else {
1069 tracing::info!(gear = %self.options.gear_name, "deregistered from DirectoryService");
1070 }
1071
1072 serve_result
1073 }
1074}
1075
1076/// Rewrite `advertise_uri` to use the actually bound port, but only if the
1077/// URI currently uses the `configured_port` (i.e. the port the caller asked
1078/// the server to bind to). This preserves user-provided load-balancer URLs
1079/// that intentionally advertise a different port from the local socket.
1080fn rewrite_advertise_uri_port(
1081 advertise_uri: &str,
1082 bound_port: u16,
1083 configured_port: u16,
1084) -> Option<String> {
1085 let mut url = Url::parse(advertise_uri).ok()?;
1086 if url.port_or_known_default() != Some(configured_port) {
1087 return None;
1088 }
1089 url.set_port(Some(bound_port)).ok()?;
1090 Some(url.to_string())
1091}
1092
1093/// Wait up to `timeout` for the in-flight counter to reach zero.
1094async fn drain_in_flight(guard: &DrainGuard, timeout: Duration) {
1095 let deadline = tokio::time::Instant::now() + timeout;
1096 loop {
1097 let in_flight = guard.in_flight();
1098 if in_flight == 0 {
1099 tracing::info!("OoP drain complete: no in-flight requests");
1100 return;
1101 }
1102 if tokio::time::Instant::now() >= deadline {
1103 tracing::warn!(
1104 in_flight,
1105 timeout_secs = timeout.as_secs(),
1106 "OoP drain timed out with in-flight requests remaining"
1107 );
1108 return;
1109 }
1110 tokio::time::sleep(Duration::from_millis(50)).await;
1111 }
1112}
1113
1114#[cfg(test)]
1115#[cfg_attr(coverage_nightly, coverage(off))]
1116#[path = "oop_serve_tests.rs"]
1117mod tests;