use crate::util::build_response_with_headers;
use bytes::Bytes;
use http_body_util::Full;
use hyper::{Response, StatusCode};
use std::cell::RefCell;
#[derive(Debug, thiserror::Error)]
#[error("backend unavailable: {feature}: {detail}")]
pub struct BackendUnavailable {
pub feature: &'static str,
pub detail: String,
}
tokio::task_local! {
static ANNOTATIONS: RefCell<Vec<(&'static str, String)>>;
}
pub fn annotate(key: &'static str, value: String) {
let _ = ANNOTATIONS.try_with(|a| a.borrow_mut().push((key, value)));
}
pub async fn with_annotation_scope<F: Future>(fut: F) -> (F::Output, Annotations) {
ANNOTATIONS
.scope(RefCell::new(Vec::new()), async move {
let out = fut.await;
let collected = ANNOTATIONS.with(|a| a.borrow_mut().drain(..).collect());
(out, collected)
})
.await
}
pub(crate) type Annotations = Vec<(&'static str, String)>;
#[must_use = "dropping this discards the annotations collected off-task, which is the exact \
failure issue #987 fixed -- pass them to `replay_annotations`"]
pub(crate) fn with_sync_annotation_scope<T>(f: impl FnOnce() -> T) -> (T, Annotations) {
ANNOTATIONS.sync_scope(RefCell::new(Vec::new()), || {
let out = f();
let collected = ANNOTATIONS.with(|a| a.borrow_mut().drain(..).collect());
(out, collected)
})
}
pub(crate) fn replay_annotations(collected: Annotations) {
for (key, value) in collected {
annotate(key, value);
}
}
pub(crate) fn spawn_blocking_annotated<T: Send + 'static>(
f: impl FnOnce() -> T + Send + 'static,
) -> tokio::task::JoinHandle<(T, Annotations)> {
let now = crate::imposter::clock::request_override();
let rng = crate::imposter::rng::current();
let clock = crate::imposter::clock::current_imposter_clock();
tokio::task::spawn_blocking(move || {
with_sync_annotation_scope(|| {
crate::imposter::rng::carry_request_rng(rng, || {
crate::imposter::clock::carry_imposter_clock(clock, || {
crate::imposter::clock::carry_request_override(now, f)
})
})
})
})
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ResponsePhase {
DataPlane,
Admin,
}
pub trait ResponseDecorator: Send + Sync {
fn decorate(
&self,
phase: ResponsePhase,
req_port: Option<u16>,
annotations: &[(&'static str, String)],
headers: &mut hyper::HeaderMap,
);
}
pub fn backend_error_response(err: &anyhow::Error) -> Response<Full<Bytes>> {
let (status, body) = match err.downcast_ref::<BackendUnavailable>() {
Some(b) => (
StatusCode::SERVICE_UNAVAILABLE,
serde_json::json!({
"errors": [{
"code": StatusCode::SERVICE_UNAVAILABLE.as_str(),
"type": crate::response::ErrorKind::BackendUnavailable.slug(),
"message": format!("{}: {}", b.feature, b.detail),
"feature": b.feature,
"detail": b.detail,
}],
}),
),
None => (
StatusCode::INTERNAL_SERVER_ERROR,
serde_json::json!({
"errors": [{
"code": StatusCode::INTERNAL_SERVER_ERROR.as_str(),
"type": crate::response::ErrorKind::InternalError.slug(),
"message": format!("{err:#}"),
}],
}),
),
};
tracing::warn!("backend error surfaced as {}: {err:#}", status.as_u16());
build_response_with_headers(
status,
[("content-type", "application/json")],
body.to_string(),
)
}
#[cfg(test)]
mod tests {
use super::*;
use http_body_util::BodyExt;
#[tokio::test]
async fn annotations_collected_inside_scope_across_awaits() {
let ((), notes) = with_annotation_scope(async {
annotate("first", "1".to_string());
tokio::task::yield_now().await;
annotate("second", "2".to_string());
})
.await;
assert_eq!(
notes,
vec![("first", "1".to_string()), ("second", "2".to_string()),]
);
}
#[test]
fn annotate_outside_scope_is_noop() {
annotate("orphan", "x".to_string());
}
#[tokio::test]
async fn sync_scope_collects_off_thread_and_replay_lands_in_order() {
let ((), notes) = with_annotation_scope(async {
annotate("before", "1".to_string());
let collected = std::thread::spawn(|| {
let ((), notes) = with_sync_annotation_scope(|| {
annotate("off-a", "2".to_string());
annotate("off-b", "3".to_string());
});
notes
})
.join()
.expect("probe thread");
replay_annotations(collected);
annotate("after", "4".to_string());
})
.await;
assert_eq!(
notes,
vec![
("before", "1".to_string()),
("off-a", "2".to_string()),
("off-b", "3".to_string()),
("after", "4".to_string()),
]
);
}
#[test]
fn sync_scope_returns_the_value_and_an_empty_vec_when_nothing_annotates() {
let (value, notes) = with_sync_annotation_scope(|| 7_i64);
assert_eq!(value, 7);
assert!(notes.is_empty());
}
#[tokio::test]
async fn a_sync_scope_starts_empty_even_inside_an_outer_scope() {
let ((), notes) = with_annotation_scope(async {
annotate("outer", "1".to_string());
let ((), inner) = with_sync_annotation_scope(|| {
annotate("inner", "2".to_string());
});
assert_eq!(
inner,
vec![("inner", "2".to_string())],
"the sync scope must not see the outer scope's entries"
);
replay_annotations(inner);
})
.await;
assert_eq!(
notes,
vec![("outer", "1".to_string()), ("inner", "2".to_string())]
);
}
#[test]
fn replay_outside_a_scope_is_a_noop() {
replay_annotations(vec![("orphan", "x".to_string())]);
}
#[tokio::test]
async fn scopes_start_empty_and_do_not_leak() {
annotate("orphan", "x".to_string());
let ((), notes) = with_annotation_scope(async {}).await;
assert!(
notes.is_empty(),
"a fresh scope must not see outside writes"
);
}
#[tokio::test]
async fn backend_unavailable_maps_to_structured_503() {
let err = anyhow::Error::new(BackendUnavailable {
feature: "flowState",
detail: "store connection refused".to_string(),
});
let resp = backend_error_response(&err);
assert_eq!(resp.status(), hyper::StatusCode::SERVICE_UNAVAILABLE);
let bytes = resp.into_body().collect().await.expect("body").to_bytes();
let json: serde_json::Value = serde_json::from_slice(&bytes).expect("json body");
assert!(
json.get("error").is_none()
&& json.get("feature").is_none()
&& json.get("detail").is_none(),
"top-level legacy keys were removed in 0.18.0 (#801), got: {json}"
);
assert_eq!(
json["errors"][0]["code"], "503",
"code is the status string, not a slug"
);
assert_eq!(
json["errors"][0]["type"], "backend unavailable",
"a dedicated slug — generic `unavailable` would not distinguish a backend outage \
from any other 503, which is the whole reason this door exists"
);
assert_eq!(
json["errors"][0]["message"], "flowState: store connection refused",
"message is the `feature: detail` join the docs show verbatim"
);
assert_eq!(json["errors"][0]["feature"], "flowState");
assert_eq!(json["errors"][0]["detail"], "store connection refused");
}
#[tokio::test]
async fn other_errors_map_to_500() {
let resp = backend_error_response(&anyhow::anyhow!("boom"));
assert_eq!(resp.status(), hyper::StatusCode::INTERNAL_SERVER_ERROR);
let bytes = resp.into_body().collect().await.expect("body").to_bytes();
let json: serde_json::Value = serde_json::from_slice(&bytes).expect("json body");
assert!(
json.get("error").is_none() && json.get("detail").is_none(),
"top-level legacy keys were removed in 0.18.0 (#801), got: {json}"
);
assert_eq!(json["errors"][0]["code"], "500");
assert_eq!(json["errors"][0]["type"], "internal error");
assert!(
json["errors"][0]["message"]
.as_str()
.is_some_and(|m| !m.is_empty()),
"message must carry the context chain, got: {json}"
);
assert!(
json["errors"][0]["feature"].is_null() && json["errors"][0]["detail"].is_null(),
"the non-backend branch has neither `feature` nor `detail` inside the envelope, \
got: {json}"
);
}
#[tokio::test]
async fn downcast_works_through_context_chain() {
use anyhow::Context;
let err = Err::<(), _>(anyhow::Error::new(BackendUnavailable {
feature: "flowState",
detail: "down".to_string(),
}))
.context("while reading scenario state")
.expect_err("err");
let resp = backend_error_response(&err);
assert_eq!(resp.status(), hyper::StatusCode::SERVICE_UNAVAILABLE);
}
}