1use std::collections::{BTreeMap, HashMap};
36use std::panic::AssertUnwindSafe;
37use std::sync::Arc;
38use std::sync::atomic::{AtomicUsize, Ordering};
39use std::time::Duration;
40
41use axum::{
42 Json, Router,
43 extract::{DefaultBodyLimit, MatchedPath, Request, State},
44 http::{HeaderMap, HeaderValue, Method, StatusCode, header::RETRY_AFTER},
45 middleware::{Next, from_fn, from_fn_with_state},
46 response::{IntoResponse, Response},
47 routing::get,
48};
49use futures_util::FutureExt as _;
50use serde::{Deserialize, Serialize};
51use tokio_util::sync::CancellationToken;
52use tower::ServiceExt as _;
53use tower_http::limit::RequestBodyLimitLayer;
54use url::Url;
55
56use cf_system_sdks::directory::{DirectoryClient, RegisterInstanceInfo, ServiceEndpoint};
57use toolkit_canonical_errors::{CanonicalError, resource_error};
58use toolkit_http_middleware::{RouteAuthPolicy, TenantPlane, layer_route_auth_with};
59use toolkit_security::{DynBearerAuthenticator, DynInternalAuthenticator};
60use toolkit_trace_context::{TRACEPARENT, parse_trace_id};
61
62use super::presence_manager::{PresenceManager, ReportedStateSource};
63use super::readiness::ReadinessState;
64use crate::api::canonical_error_middleware;
65use crate::api::operation_builder::{OperationSpec, RouteTimeout};
66
67const DRAIN_RETRY_AFTER_SECONDS: u64 = 5;
69
70const STARTING_RETRY_AFTER_SECONDS: u64 = 1;
73
74#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
80#[serde(try_from = "RawOopRequestLimits")]
81pub struct OopRequestLimits {
82 body_limit_bytes: usize,
83 #[serde(with = "toolkit_utils::humantime_serde")]
84 request_timeout: Duration,
85}
86
87#[derive(Deserialize)]
88#[serde(deny_unknown_fields)]
89struct RawOopRequestLimits {
90 body_limit_bytes: usize,
91 #[serde(with = "toolkit_utils::humantime_serde")]
92 request_timeout: Duration,
93}
94
95impl TryFrom<RawOopRequestLimits> for OopRequestLimits {
96 type Error = OopRequestLimitsError;
97
98 fn try_from(raw: RawOopRequestLimits) -> Result<Self, Self::Error> {
99 Self::new(raw.body_limit_bytes, raw.request_timeout)
100 }
101}
102
103#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
105pub enum OopRequestLimitsError {
106 #[error("body_limit_bytes must be positive")]
108 BodyLimitZero,
109 #[error("request_timeout must be positive")]
111 RequestTimeoutZero,
112}
113
114impl OopRequestLimits {
115 pub fn new(
122 body_limit_bytes: usize,
123 request_timeout: Duration,
124 ) -> Result<Self, OopRequestLimitsError> {
125 if body_limit_bytes == 0 {
126 return Err(OopRequestLimitsError::BodyLimitZero);
127 }
128 if request_timeout.is_zero() {
129 return Err(OopRequestLimitsError::RequestTimeoutZero);
130 }
131 Ok(Self {
132 body_limit_bytes,
133 request_timeout,
134 })
135 }
136
137 #[must_use]
139 pub const fn body_limit_bytes(&self) -> usize {
140 self.body_limit_bytes
141 }
142
143 #[must_use]
146 pub const fn request_timeout(&self) -> Duration {
147 self.request_timeout
148 }
149}
150
151#[non_exhaustive]
166pub struct OopServeOptions {
167 pub gear_name: String,
169 pub instance_id: String,
171 pub version: Option<String>,
173 pub advertise_uri: String,
177 pub listen_addr: std::net::SocketAddr,
179 pub probe_bind_addr: Option<std::net::SocketAddr>,
182 pub drain_timeout: Duration,
184 pub heartbeat_interval: Duration,
188 pub healthcheck_timeout: Duration,
192 pub request_limits: Option<OopRequestLimits>,
194 pub directory: Arc<dyn DirectoryClient>,
196 pub bearer_authenticator: Option<DynBearerAuthenticator>,
199 pub internal_authenticator: Option<DynInternalAuthenticator>,
202 pub auth_disabled: bool,
206 pub labels: BTreeMap<String, String>,
209}
210
211impl OopServeOptions {
212 #[must_use]
218 pub fn new(
219 gear_name: String,
220 instance_id: String,
221 advertise_uri: String,
222 listen_addr: std::net::SocketAddr,
223 directory: Arc<dyn DirectoryClient>,
224 ) -> Self {
225 Self {
226 gear_name,
227 instance_id,
228 version: None,
229 advertise_uri,
230 listen_addr,
231 probe_bind_addr: None,
232 drain_timeout: Duration::from_secs(30),
233 heartbeat_interval: Duration::from_secs(5),
234 healthcheck_timeout: Duration::from_millis(500),
235 request_limits: None,
236 directory,
237 bearer_authenticator: None,
238 internal_authenticator: None,
239 auth_disabled: false,
240 labels: BTreeMap::new(),
241 }
242 }
243
244 #[must_use]
246 pub fn with_auth_disabled(mut self, auth_disabled: bool) -> Self {
247 self.auth_disabled = auth_disabled;
248 self
249 }
250
251 #[must_use]
254 pub fn tenant_plane(&self) -> TenantPlane {
255 match (&self.bearer_authenticator, self.auth_disabled) {
256 (Some(bearer), _) => TenantPlane::Authenticator(bearer.clone()),
257 (None, true) => TenantPlane::Disabled,
258 (None, false) => TenantPlane::Absent,
259 }
260 }
261
262 #[must_use]
264 pub fn with_version(mut self, version: Option<String>) -> Self {
265 self.version = version;
266 self
267 }
268
269 #[must_use]
271 pub fn with_probe_bind_addr(mut self, addr: Option<std::net::SocketAddr>) -> Self {
272 self.probe_bind_addr = addr;
273 self
274 }
275
276 #[must_use]
278 pub fn with_drain_timeout(mut self, timeout: Duration) -> Self {
279 self.drain_timeout = timeout;
280 self
281 }
282
283 #[must_use]
285 pub fn with_heartbeat_interval(mut self, interval: Duration) -> Self {
286 self.heartbeat_interval = interval;
287 self
288 }
289
290 #[must_use]
292 pub fn with_healthcheck_timeout(mut self, timeout: Duration) -> Self {
293 self.healthcheck_timeout = timeout;
294 self
295 }
296
297 #[must_use]
299 pub fn with_request_limits(mut self, limits: OopRequestLimits) -> Self {
300 self.request_limits = Some(limits);
301 self
302 }
303
304 #[must_use]
306 pub fn with_bearer_authenticator(mut self, auth: Option<DynBearerAuthenticator>) -> Self {
307 self.bearer_authenticator = auth;
308 self
309 }
310
311 #[must_use]
313 pub fn with_internal_authenticator(mut self, auth: Option<DynInternalAuthenticator>) -> Self {
314 self.internal_authenticator = auth;
315 self
316 }
317
318 #[must_use]
320 pub fn with_labels(mut self, labels: BTreeMap<String, String>) -> Self {
321 self.labels = labels;
322 self
323 }
324}
325
326impl std::fmt::Debug for OopServeOptions {
327 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
328 f.debug_struct("OopServeOptions")
329 .field("gear_name", &self.gear_name)
330 .field("instance_id", &self.instance_id)
331 .field("version", &self.version)
332 .field("advertise_uri", &self.advertise_uri)
333 .field("listen_addr", &self.listen_addr)
334 .field("probe_bind_addr", &self.probe_bind_addr)
335 .field("drain_timeout", &self.drain_timeout)
336 .field("heartbeat_interval", &self.heartbeat_interval)
337 .field("healthcheck_timeout", &self.healthcheck_timeout)
338 .field("request_limits", &self.request_limits)
339 .field("bearer_authenticator", &self.bearer_authenticator.is_some())
340 .field(
341 "internal_authenticator",
342 &self.internal_authenticator.is_some(),
343 )
344 .field("labels", &self.labels)
345 .finish_non_exhaustive()
346 }
347}
348
349#[derive(Clone, Default)]
360struct LateRoutes {
361 inner: Arc<arc_swap::ArcSwapOption<LateRoutesInner>>,
362}
363
364struct LateRoutesInner {
365 gear: Router,
367 openapi: Arc<str>,
369}
370
371impl LateRoutes {
372 fn publish(&self, gear: Router, openapi: Arc<str>) {
374 self.inner
375 .store(Some(Arc::new(LateRoutesInner { gear, openapi })));
376 }
377
378 fn gear(&self) -> Option<Router> {
380 self.inner.load_full().map(|i| i.gear.clone())
381 }
382
383 fn openapi(&self) -> Option<Arc<str>> {
385 self.inner.load_full().map(|i| Arc::clone(&i.openapi))
386 }
387}
388
389fn starting_response() -> Response {
391 (
392 StatusCode::SERVICE_UNAVAILABLE,
393 [(RETRY_AFTER, STARTING_RETRY_AFTER_SECONDS.to_string())],
394 "starting",
395 )
396 .into_response()
397}
398
399#[derive(Clone)]
401struct ProbeState {
402 readiness: Arc<ReadinessState>,
403 late: LateRoutes,
404}
405
406fn build_outer_router(readiness: Arc<ReadinessState>, late: LateRoutes) -> Router {
410 let fallback_late = late.clone();
411 build_probe_router(readiness, late).fallback_service(tower::util::service_fn(
412 move |req: Request| {
413 let late = fallback_late.clone();
414 async move {
415 match late.gear() {
416 Some(router) => Ok::<_, std::convert::Infallible>(
418 router.oneshot(req).await.unwrap_or_else(|e| match e {}),
419 ),
420 None => Ok::<_, std::convert::Infallible>(starting_response()),
421 }
422 }
423 },
424 ))
425}
426
427fn build_probe_router(readiness: Arc<ReadinessState>, late: LateRoutes) -> Router {
433 let state = ProbeState { readiness, late };
434
435 Router::new()
436 .route("/healthz", get(healthz))
437 .route("/readyz", get(readyz))
438 .route("/health", get(health))
439 .route("/.well-known/openapi.json", get(openapi))
440 .route("/openapi.json", get(openapi))
441 .with_state(state)
442}
443
444async fn healthz() -> &'static str {
446 "ok"
447}
448
449async fn readyz(State(state): State<ProbeState>) -> Response {
452 let report = state.readiness.evaluate().await;
453 let status = if report.ready {
454 StatusCode::OK
455 } else {
456 StatusCode::SERVICE_UNAVAILABLE
457 };
458 (status, Json(report)).into_response()
459}
460
461async fn health(State(state): State<ProbeState>) -> impl IntoResponse {
464 let report = state.readiness.health_report().await;
465 let status = if report.is_ready() {
466 StatusCode::OK
467 } else {
468 StatusCode::SERVICE_UNAVAILABLE
469 };
470 (status, Json(report))
471}
472
473async fn openapi(State(state): State<ProbeState>) -> Response {
476 match state.late.openapi() {
477 Some(spec) => (
478 StatusCode::OK,
479 [(axum::http::header::CONTENT_TYPE, "application/json")],
480 spec.to_string(),
481 )
482 .into_response(),
483 None => starting_response(),
484 }
485}
486
487#[derive(Clone)]
493struct DrainGuard {
494 readiness: Arc<ReadinessState>,
495 in_flight: Arc<AtomicUsize>,
496}
497
498impl DrainGuard {
499 fn new(readiness: Arc<ReadinessState>) -> Self {
500 Self {
501 readiness,
502 in_flight: Arc::new(AtomicUsize::new(0)),
503 }
504 }
505
506 fn in_flight(&self) -> usize {
508 self.in_flight.load(Ordering::SeqCst)
509 }
510
511 fn begin_drain(&self) {
514 self.readiness.set_draining(true);
515 }
516}
517
518struct InFlightGuard(Arc<AtomicUsize>);
521
522impl InFlightGuard {
523 fn new(counter: Arc<AtomicUsize>) -> Self {
524 counter.fetch_add(1, Ordering::SeqCst);
525 Self(counter)
526 }
527}
528
529impl Drop for InFlightGuard {
530 fn drop(&mut self) {
531 self.0.fetch_sub(1, Ordering::SeqCst);
532 }
533}
534
535async fn drain_guard_middleware(
538 State(guard): State<DrainGuard>,
539 request: axum::extract::Request,
540 next: Next,
541) -> Response {
542 if guard.readiness.is_draining() {
543 return (
544 StatusCode::SERVICE_UNAVAILABLE,
545 [(RETRY_AFTER, DRAIN_RETRY_AFTER_SECONDS.to_string())],
546 "draining",
547 )
548 .into_response();
549 }
550
551 let _in_flight = InFlightGuard::new(guard.in_flight.clone());
557 let outcome = AssertUnwindSafe(next.run(request)).catch_unwind().await;
558
559 match outcome {
560 Ok(response) => response,
561 Err(panic) => {
562 let detail = panic_message(panic.as_ref());
563 tracing::error!(panic = %detail, "OoP gear handler panicked");
564 CanonicalError::internal(format!("gear handler panicked: {detail}"))
567 .create()
568 .into_response()
569 }
570 }
571}
572
573fn panic_message(panic: &(dyn std::any::Any + Send)) -> String {
575 panic
576 .downcast_ref::<&str>()
577 .map(|s| (*s).to_owned())
578 .or_else(|| panic.downcast_ref::<String>().cloned())
579 .unwrap_or_else(|| "unknown panic".to_owned())
580}
581
582async fn bootstrap_plane_gate(
590 State(policy): State<Arc<RouteAuthPolicy>>,
591 request: Request,
592 next: Next,
593) -> Response {
594 let auth = request
595 .extensions()
596 .get::<axum::extract::MatchedPath>()
597 .and_then(|path| policy.resolve(request.method(), path.as_str()));
598 match auth {
599 Some(toolkit_security::RouteAuth::Platform | toolkit_security::RouteAuth::Anonymous) => {
600 next.run(request).await
601 }
602 _ => CanonicalError::service_unavailable()
603 .with_retry_after_seconds(STARTING_RETRY_AFTER_SECONDS)
604 .with_detail("tenant-plane routes are served once the application group has started")
605 .create()
606 .into_response(),
607 }
608}
609
610type RouteTimeouts = HashMap<Method, HashMap<String, RouteTimeout>>;
611
612#[derive(Debug, Default)]
614pub(super) struct OopRoutePolicy {
615 auth: RouteAuthPolicy,
616 timeouts: RouteTimeouts,
617}
618
619impl OopRoutePolicy {
620 pub(super) fn from_specs<S>(specs: impl IntoIterator<Item = S>) -> Self
621 where
622 S: std::ops::Deref<Target = OperationSpec>,
623 {
624 let mut policy = Self::default();
625 for spec in specs {
626 policy
627 .auth
628 .insert(spec.method.clone(), spec.path.clone(), spec.auth);
629 if spec.request_timeout != RouteTimeout::Inherit {
630 policy
631 .timeouts
632 .entry(spec.method.clone())
633 .or_default()
634 .insert(spec.path.clone(), spec.request_timeout);
635 }
636 }
637 policy
638 }
639}
640
641fn layer_gear_router(
643 gear_router: Router,
644 policy: OopRoutePolicy,
645 tenant_plane: TenantPlane,
646 drain_guard: DrainGuard,
647 options: &OopServeOptions,
648) -> Router {
649 let gear = layer_route_auth_with(
655 gear_router,
656 policy.auth,
657 tenant_plane,
658 options.internal_authenticator.clone(),
659 );
660 layer_serving(gear, drain_guard, options, policy.timeouts)
661}
662
663fn layer_serving(
665 gear: Router,
666 drain_guard: DrainGuard,
667 options: &OopServeOptions,
668 timeouts: RouteTimeouts,
669) -> Router {
670 let drain = from_fn_with_state(drain_guard, drain_guard_middleware);
671 let gear = match options.request_limits {
672 Some(limits) => {
673 let body_limit = limits.body_limit_bytes();
674 let deadlines = Arc::new(RequestDeadlines {
675 default: limits.request_timeout(),
676 timeouts,
677 });
678 gear.layer(DefaultBodyLimit::max(body_limit))
680 .layer(RequestBodyLimitLayer::new(body_limit))
681 .layer(drain)
682 .layer(from_fn_with_state(deadlines, RequestDeadlines::apply))
683 }
684 None => gear.layer(drain),
685 };
686
687 gear.layer(from_fn(canonical_error_middleware))
689 .layer(from_fn(trace_context_middleware))
690}
691
692#[resource_error(gts_id!("cf.core.http.request.v1~"))]
693struct RequestDeadlineError;
694
695struct RequestDeadlines {
696 default: Duration,
697 timeouts: RouteTimeouts,
698}
699
700impl RequestDeadlines {
701 fn resolve(&self, request: &Request) -> Option<Duration> {
702 let declared = request
703 .extensions()
704 .get::<MatchedPath>()
705 .and_then(|path| self.timeouts.get(request.method())?.get(path.as_str()));
706 match declared {
707 Some(RouteTimeout::Custom(timeout)) => Some(*timeout),
708 Some(RouteTimeout::Disabled) => None,
709 Some(RouteTimeout::Inherit) | None => Some(self.default),
710 }
711 }
712
713 async fn apply(State(deadlines): State<Arc<Self>>, request: Request, next: Next) -> Response {
714 let Some(timeout) = deadlines.resolve(&request) else {
715 return next.run(request).await;
716 };
717 match tokio::time::timeout(timeout, next.run(request)).await {
719 Ok(response) => response,
720 Err(_) => RequestDeadlineError::deadline_exceeded(format!(
721 "Request exceeded {timeout:?} timeout"
722 ))
723 .create()
724 .into_response(),
725 }
726 }
727}
728
729tokio::task_local! {
730 static INBOUND_TRACEPARENT: Option<HeaderValue>;
731}
732
733pub fn inject_inbound_traceparent(headers: &mut HeaderMap) {
736 if !headers.contains_key(TRACEPARENT)
737 && let Ok(Some(parent)) = INBOUND_TRACEPARENT.try_with(Clone::clone)
738 {
739 headers.insert(TRACEPARENT, parent);
740 }
741}
742
743async fn trace_context_middleware(req: Request, next: Next) -> Response {
746 use tracing::Instrument as _;
747 use tracing::field::Empty;
748
749 let mut parents = req.headers().get_all(TRACEPARENT).iter();
750 let inbound = parents
751 .next()
752 .filter(|value| {
753 parents.next().is_none()
754 && value.len() == 55
755 && value.to_str().ok().and_then(parse_trace_id).is_some()
756 })
757 .cloned();
758 let request_id = toolkit_trace_context::extract_request_id(req.headers());
759
760 let span = tracing::info_span!(
761 "http_request",
762 method = %req.method(),
763 uri = %req.uri().path(),
764 request_id = %request_id.as_deref().unwrap_or("n/a"),
765 trace_id = Empty,
766 parent.trace_id = Empty,
767 );
768
769 toolkit_trace_context::set_parent_from_headers(&span, req.headers());
770
771 let request =
772 toolkit_trace_context::with_request_id(request_id, next.run(req).instrument(span));
773 INBOUND_TRACEPARENT.scope(inbound, request).await
774}
775
776async fn serve_loop(
796 listener: tokio::net::TcpListener,
797 router: Router,
798 drain_guard: DrainGuard,
799 sidecar: Option<(tokio::net::TcpListener, Router)>,
800 drain_timeout: Duration,
801 cancel: CancellationToken,
802) -> anyhow::Result<()> {
803 let sidecar = match sidecar {
805 Some((probe_listener, probe_router)) => {
806 let shutdown = {
807 let cancel = cancel.clone();
808 async move { cancel.cancelled().await }
809 };
810 Some(tokio::spawn(async move {
811 if let Err(e) = axum::serve(probe_listener, probe_router)
812 .with_graceful_shutdown(shutdown)
813 .await
814 {
815 tracing::warn!(error = %e, "OoP probe sidecar server error");
816 }
817 }))
818 }
819 None => None,
820 };
821
822 let shutdown = {
824 let cancel = cancel.clone();
825 let guard = drain_guard.clone();
826 async move {
827 cancel.cancelled().await;
828 guard.begin_drain();
830 tracing::info!("OoP HTTP server draining (graceful shutdown)");
831 drain_in_flight(&guard, drain_timeout).await;
833 }
834 };
835
836 let result = axum::serve(
837 listener,
838 router.into_make_service_with_connect_info::<std::net::SocketAddr>(),
839 )
840 .with_graceful_shutdown(shutdown)
841 .await
842 .map_err(anyhow::Error::from);
843
844 if let Some(handle) = sidecar {
845 handle.abort();
846 if let Err(e) = handle.await
847 && !e.is_cancelled()
848 {
849 tracing::warn!(error = %e, "OoP probe sidecar task join error");
850 }
851 }
852
853 result
854}
855
856pub(super) struct OopHttpServer {
871 readiness: Arc<ReadinessState>,
872 late: LateRoutes,
873 drain_guard: DrainGuard,
874 options: OopServeOptions,
875 cancel: CancellationToken,
876 registration_task: Option<tokio::task::JoinHandle<()>>,
877 presence_openapi: Option<Arc<str>>,
880 presence_updates: Option<tokio::sync::watch::Sender<RegisterInstanceInfo>>,
881 provider_writers: Vec<(String, tokio::task::JoinHandle<()>)>,
885 presence: Arc<PresenceManager>,
890 presence_cancel: CancellationToken,
896 presence_run: Option<tokio::task::JoinHandle<()>>,
897 serve: Option<tokio::task::JoinHandle<anyhow::Result<()>>>,
899}
900
901impl Drop for OopHttpServer {
905 fn drop(&mut self) {
906 if let Some(task) = self.registration_task.take() {
907 task.abort();
908 }
909 for (_, task) in self.provider_writers.drain(..) {
910 task.abort();
911 }
912 self.presence_cancel.cancel();
914 if let Some(task) = self.presence_run.take() {
915 task.abort();
916 }
917 if let Some(serve) = self.serve.take() {
918 serve.abort();
919 }
920 }
921}
922
923impl OopHttpServer {
924 pub(super) async fn start(
930 readiness: Arc<ReadinessState>,
931 options: OopServeOptions,
932 cancel: CancellationToken,
933 ) -> anyhow::Result<Self> {
934 let late = LateRoutes::default();
935 let drain_guard = DrainGuard::new(Arc::clone(&readiness));
936 let mut options = options;
937
938 let listener = tokio::net::TcpListener::bind(options.listen_addr).await?;
939 let bound = listener.local_addr()?;
940 let configured_port = options.listen_addr.port();
941 if bound.port() != configured_port {
942 if let Some(rewritten) =
943 rewrite_advertise_uri_port(&options.advertise_uri, bound.port(), configured_port)
944 {
945 tracing::info!(
946 old = %options.advertise_uri,
947 new = %rewritten,
948 "advertise_uri rewritten to use actually bound port"
949 );
950 options.advertise_uri = rewritten;
951 } else {
952 tracing::info!(
953 advertise_uri = %options.advertise_uri,
954 bound_port = bound.port(),
955 configured_port,
956 "bound port differs from configured; leaving advertise_uri unchanged"
957 );
958 }
959 }
960 options.listen_addr = bound;
961 tracing::info!(
962 addr = %options.listen_addr,
963 "OoP HTTP server bound (probes live; gear routes attach after start)"
964 );
965
966 let outer = build_outer_router(Arc::clone(&readiness), late.clone());
967
968 let sidecar = if let Some(addr) = options.probe_bind_addr {
969 let probe_listener = tokio::net::TcpListener::bind(addr).await?;
970 let bound_probe = probe_listener.local_addr()?;
971 options.probe_bind_addr = Some(bound_probe);
972 tracing::info!(addr = %bound_probe, "OoP probe sidecar bound");
973 Some((
974 probe_listener,
975 build_probe_router(Arc::clone(&readiness), late.clone()),
976 ))
977 } else {
978 None
979 };
980
981 let serve = tokio::spawn(serve_loop(
982 listener,
983 outer,
984 drain_guard.clone(),
985 sidecar,
986 options.drain_timeout,
987 cancel.clone(),
988 ));
989
990 let presence_cancel = CancellationToken::new();
999 let presence = PresenceManager::new(
1000 Arc::clone(&options.directory),
1001 ReportedStateSource::Readiness(Arc::clone(&readiness)),
1002 options.heartbeat_interval,
1003 );
1004 let presence_run = tokio::spawn(Arc::clone(&presence).run(presence_cancel.clone()));
1009 {
1013 let drain_pm = Arc::clone(&presence);
1014 let drain_readiness = Arc::clone(&readiness);
1015 let root = cancel.clone();
1016 let stop = presence_cancel.clone();
1017 tokio::spawn(async move {
1018 tokio::select! {
1019 () = root.cancelled() => {
1020 drain_readiness.set_draining(true);
1026 drain_pm.begin_drain();
1027 }
1028 () = stop.cancelled() => {}
1029 }
1030 });
1031 }
1032
1033 Ok(Self {
1034 readiness,
1035 late,
1036 drain_guard,
1037 options,
1038 cancel,
1039 registration_task: None,
1040 presence_openapi: None,
1041 presence_updates: None,
1042 provider_writers: Vec::new(),
1043 presence,
1044 presence_cancel,
1045 presence_run: Some(presence_run),
1046 serve: Some(serve),
1047 })
1048 }
1049
1050 pub(super) fn options(&self) -> &OopServeOptions {
1052 &self.options
1053 }
1054
1055 pub(super) fn resolve_bearer_authenticator(&mut self, hub: &crate::ClientHub) {
1065 if self.options.bearer_authenticator.is_some() {
1066 return;
1067 }
1068 if let Ok(auth) = hub.get::<DynBearerAuthenticator>() {
1069 self.options.bearer_authenticator = Some((*auth).clone());
1070 tracing::info!(
1071 gear = %self.options.gear_name,
1072 "tenant-plane authenticator installed (security_context_middleware enabled)"
1073 );
1074 } else {
1075 tracing::info!(
1076 gear = %self.options.gear_name,
1077 "no tenant-plane authenticator registered in ClientHub"
1078 );
1079 }
1080 }
1081
1082 pub(super) fn check_route_auth(&self, route_auth: &RouteAuthPolicy) -> anyhow::Result<()> {
1093 if !matches!(self.options.tenant_plane(), TenantPlane::Absent) {
1094 return Ok(());
1095 }
1096 let gear = &self.options.gear_name;
1097 let tenant = route_auth.tenant_routes();
1098 if !tenant.is_empty() {
1099 anyhow::bail!(
1100 "gear '{gear}' serves tenant operations but no tenant authenticator is \
1101 available (link authn-resolver, or set oop_http.auth_disabled for \
1102 development): {tenant:?}"
1103 );
1104 }
1105 tracing::warn!(
1106 gear = %gear,
1107 reason = "TENANT_AUTH_NOT_CONFIGURED",
1108 "no tenant authenticator on this listener: a route not declared through \
1109 OperationBuilder is refused with 401 (link authn-resolver, or set \
1110 oop_http.auth_disabled for development)"
1111 );
1112 Ok(())
1113 }
1114
1115 pub(super) fn publish_bootstrap_routes(
1119 &mut self,
1120 gear_router: Router,
1121 openapi_json: String,
1122 policy: OopRoutePolicy,
1123 ) {
1124 let authenticated = layer_route_auth_with(
1127 gear_router,
1128 policy.auth.clone(),
1129 TenantPlane::Absent,
1130 self.options.internal_authenticator.clone(),
1131 );
1132 let gated = authenticated.layer(from_fn_with_state(
1133 Arc::new(policy.auth),
1134 bootstrap_plane_gate,
1135 ));
1136 let layered = layer_serving(
1137 gated,
1138 self.drain_guard.clone(),
1139 &self.options,
1140 policy.timeouts,
1141 );
1142 self.late.publish(layered, Arc::from(openapi_json));
1143 tracing::info!(
1144 gear = %self.options.gear_name,
1145 "OoP system routes attached (platform plane only)"
1146 );
1147 }
1148
1149 pub(super) fn attach(
1160 &mut self,
1161 gear_router: Router,
1162 openapi_json: String,
1163 policy: OopRoutePolicy,
1164 ) -> anyhow::Result<()> {
1165 self.check_route_auth(&policy.auth)?;
1168 let layered = layer_gear_router(
1169 gear_router,
1170 policy,
1171 self.options.tenant_plane(),
1172 self.drain_guard.clone(),
1173 &self.options,
1174 );
1175 self.late.publish(layered, Arc::from(openapi_json));
1176 self.readiness.mark_startup_complete();
1177 tracing::info!(gear = %self.options.gear_name, "OoP gear routes attached (now serving)");
1178 Ok(())
1179 }
1180
1181 pub(super) fn presence_manager(&self) -> Arc<PresenceManager> {
1186 Arc::clone(&self.presence)
1187 }
1188
1189 pub(super) fn start_presence(&mut self) {
1195 let openapi = self.late.openapi();
1196 if let Some(updates) = &self.presence_updates {
1197 if self.presence_openapi != openapi {
1198 updates.send_replace(self.registration_info(openapi.as_ref()));
1199 self.presence_openapi = openapi;
1200 }
1201 return;
1202 }
1203 let registration_info = self.registration_info(openapi.as_ref());
1204 self.presence_openapi = openapi;
1205 let (updates, presence_rx) = tokio::sync::watch::channel(registration_info);
1206 self.presence_updates = Some(updates);
1207 let manager = self.presence_manager();
1208 let cancel = self.cancel.clone();
1209 self.registration_task = Some(tokio::spawn(async move {
1210 super::oop_registration::presence_loop_with_updates(manager, presence_rx, cancel).await;
1211 }));
1212 }
1213
1214 fn registration_info(&self, openapi: Option<&Arc<str>>) -> RegisterInstanceInfo {
1216 let mut registration_info = RegisterInstanceInfo::new(
1217 self.options.gear_name.clone(),
1218 self.options.instance_id.clone(),
1219 )
1220 .with_rest_endpoint(ServiceEndpoint::new(self.options.advertise_uri.clone()))
1221 .with_labels(self.options.labels.clone());
1222 if let Some(openapi) = openapi {
1223 registration_info = registration_info
1227 .with_openapi_spec_hash(crate::directory::openapi_spec_hash(openapi.as_bytes()));
1228 }
1229 if let Some(version) = self.options.version.clone() {
1230 registration_info = registration_info.with_version(version);
1231 }
1232 registration_info
1233 }
1234
1235 pub(super) fn start_provider_presence(&mut self, gear: String) {
1239 if gear == self.options.gear_name
1240 || self.provider_writers.iter().any(|(name, _)| *name == gear)
1241 {
1242 return;
1243 }
1244 let mut info = RegisterInstanceInfo::new(gear.clone(), self.options.instance_id.clone())
1245 .with_rest_endpoint(ServiceEndpoint::new(self.options.advertise_uri.clone()))
1246 .with_labels(self.options.labels.clone());
1247 if let Some(version) = self.options.version.clone() {
1248 info = info.with_version(version);
1249 }
1250 let manager = self.presence_manager();
1251 let cancel = self.cancel.clone();
1252 let task = tokio::spawn(async move {
1253 super::oop_registration::presence_loop(manager, info, cancel).await;
1254 });
1255 self.provider_writers.push((gear, task));
1256 }
1257
1258 pub(super) async fn join(mut self) -> anyhow::Result<()> {
1265 let Some(serve) = self.serve.as_mut() else {
1267 anyhow::bail!("OoP serve task already joined");
1268 };
1269 let serve_result = match serve.await {
1270 Ok(r) => r,
1271 Err(e) => Err(anyhow::anyhow!("OoP serve task join error: {e}")),
1272 };
1273 self.serve = None;
1274
1275 if let Some(task) = self.registration_task.take() {
1282 task.abort();
1283 }
1284 for (_, task) in std::mem::take(&mut self.provider_writers) {
1285 task.abort();
1286 }
1287 self.presence_cancel.cancel();
1288 if let Some(task) = self.presence_run.take()
1289 && let Err(e) = task.await
1290 {
1291 tracing::warn!(error = %e, "presence manager renewal task join error");
1292 }
1293 self.presence.deregister_all().await;
1294 tracing::info!(gear = %self.options.gear_name, "deregistered from DirectoryService");
1295
1296 serve_result
1297 }
1298}
1299
1300fn rewrite_advertise_uri_port(
1305 advertise_uri: &str,
1306 bound_port: u16,
1307 configured_port: u16,
1308) -> Option<String> {
1309 let mut url = Url::parse(advertise_uri).ok()?;
1310 if url.port_or_known_default() != Some(configured_port) {
1311 return None;
1312 }
1313 url.set_port(Some(bound_port)).ok()?;
1314 Some(url.to_string())
1315}
1316
1317async fn drain_in_flight(guard: &DrainGuard, timeout: Duration) {
1319 let deadline = tokio::time::Instant::now() + timeout;
1320 loop {
1321 let in_flight = guard.in_flight();
1322 if in_flight == 0 {
1323 tracing::info!("OoP drain complete: no in-flight requests");
1324 return;
1325 }
1326 if tokio::time::Instant::now() >= deadline {
1327 tracing::warn!(
1328 in_flight,
1329 timeout_secs = timeout.as_secs(),
1330 "OoP drain timed out with in-flight requests remaining"
1331 );
1332 return;
1333 }
1334 tokio::time::sleep(Duration::from_millis(50)).await;
1335 }
1336}
1337
1338#[cfg(test)]
1339#[cfg_attr(coverage_nightly, coverage(off))]
1340#[path = "oop_serve_tests.rs"]
1341mod tests;