use std::collections::HashMap;
use std::convert::Infallible;
use std::sync::{Arc, Mutex};
use encore::opentelemetry::trace::{
FutureExt, SpanContext, SpanId, TraceContextExt, TraceFlags, TraceId, TraceState,
};
use encore::opentelemetry::Context;
use encore::reqctx::Field;
use encore::services;
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
use tokio::net::TcpListener;
#[derive(Debug, Clone)]
struct Received {
method: String,
path: String,
headers: HashMap<String, String>,
body: String,
}
type Log = Arc<Mutex<Vec<Received>>>;
type Answer = fn(&str) -> (u16, Vec<(&'static str, String)>);
async fn server(log: Log, answer: Answer) -> String {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!("http://{}", listener.local_addr().unwrap());
tokio::spawn(async move {
loop {
let (stream, _) = listener.accept().await.unwrap();
let log = log.clone();
tokio::spawn(async move {
let mut stream = BufReader::new(stream);
let mut line = String::new();
stream.read_line(&mut line).await.unwrap();
let mut parts = line.split_whitespace();
let method = parts.next().unwrap_or_default().to_string();
let path = parts.next().unwrap_or_default().to_string();
let mut headers = HashMap::new();
loop {
let mut line = String::new();
stream.read_line(&mut line).await.unwrap();
let line = line.trim_end();
if line.is_empty() {
break;
}
let (name, value) = line.split_once(':').unwrap();
headers.insert(name.to_ascii_lowercase(), value.trim().to_string());
}
let length = headers
.get("content-length")
.map_or(0, |l| l.parse().unwrap());
let mut body = vec![0; length];
stream.read_exact(&mut body).await.unwrap();
let (status, extra) = answer(&path);
log.lock().unwrap().push(Received {
method,
path,
headers,
body: String::from_utf8(body).unwrap(),
});
let mut response =
format!("HTTP/1.1 {status} X\r\ncontent-length: 2\r\nconnection: close\r\n");
for (name, value) in extra {
response.push_str(&format!("{name}: {value}\r\n"));
}
response.push_str("\r\nok");
stream
.get_mut()
.write_all(response.as_bytes())
.await
.unwrap();
});
}
});
url
}
const TRACEPARENT: &str = "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01";
static PLAN: Field<String> = Field::new("plan");
fn request_context() -> Context {
let sc = SpanContext::new(
TraceId::from_hex("0af7651916cd43dd8448eb211c80319c").unwrap(),
SpanId::from_hex("b7ad6b7169203331").unwrap(),
TraceFlags::SAMPLED,
true,
TraceState::from_key_value([("encore", "rc"), ("vendor", "1")]).unwrap(),
);
let cx = Context::new().with_remote_span_context(sc);
PLAN.context_in(&cx, &"pro".to_string()).unwrap()
}
fn no_field(received: &Received) {
for name in received.headers.keys() {
assert!(
!name.starts_with("x-encore-meta-ctx-"),
"{received:#?} carried {name}"
);
}
}
#[tokio::test]
async fn calls_carry_their_context_only_to_services() {
let third_log = Log::default();
let third = server(third_log.clone(), |_| (200, vec![])).await;
let svc_log = Log::default();
static THIRD: std::sync::OnceLock<String> = std::sync::OnceLock::new();
THIRD.set(third.clone()).unwrap();
let svc = server(svc_log.clone(), |path| match path {
"/billing/away" => (
307,
vec![("location", format!("{}/landed", THIRD.get().unwrap()))],
),
"/billing/here" => (303, vec![("location", "/billing/landed".to_string())]),
"/billing/moved" => (302, vec![("location", "/billing/moved-to".to_string())]),
_ => (200, vec![]),
})
.await;
let config = serde_json::json!({
"environment": {
"app_id": "test-app", "app_slug": "test-app", "env_id": "test-env",
"env_name": "test", "env_type": "development", "cloud": "local",
},
"deployment": {
"deploy_id": "test-deploy",
"hosted_services": [{"name": "users"}],
"service_discovery": {"services": {"billing": {"base_url": format!("{svc}/billing/")}}},
},
});
std::env::set_var("ENCORE_RUNTIME_CONFIG", config.to_string());
static BILLING: services::Client = services::client("billing");
assert_eq!(BILLING.base_url(), format!("{svc}/billing"));
let inbound = |b: services::RequestBuilder| {
b.header("x-encore-meta-ctx-plan", "InN0YWxlIg")
.header("x-encore-meta-ctx-stale", "x")
.header("accept", "application/json")
};
async {
inbound(BILLING.get("/invoices?limit=1"))
.send()
.await
.unwrap();
inbound(services::client("billing").get(&format!("{third}/hook")))
.send()
.await
.unwrap();
BILLING
.put("away")
.bearer_auth("t")
.body("payload")
.send()
.await
.unwrap();
BILLING.post("here").body("form").send().await.unwrap();
BILLING.put("moved").body("update").send().await.unwrap();
BILLING.post("moved").body("create").send().await.unwrap();
BILLING
.post("here")
.body(services::reqwest::Body::wrap_stream(chunks([
"str", "eamed",
])))
.send()
.await
.unwrap();
}
.with_context(request_context())
.await;
let svc_got = svc_log.lock().unwrap().clone();
let third_got = third_log.lock().unwrap().clone();
let invoices = &svc_got[0];
assert_eq!(invoices.path, "/billing/invoices?limit=1");
assert_eq!(invoices.headers["x-encore-meta-ctx-plan"], "InBybyI");
assert!(!invoices.headers.contains_key("x-encore-meta-ctx-stale"));
assert_eq!(invoices.headers["traceparent"], TRACEPARENT);
assert_eq!(invoices.headers["tracestate"], "encore=rc,vendor=1");
assert_eq!(invoices.headers["accept"], "application/json");
let hook = &third_got[0];
assert_eq!(hook.path, "/hook");
no_field(hook);
assert!(!hook.headers.contains_key("traceparent"));
assert_eq!(hook.headers["accept"], "application/json");
let landed = &third_got[1];
assert_eq!(
(landed.method.as_str(), landed.path.as_str()),
("PUT", "/landed")
);
assert_eq!(landed.body, "payload");
assert!(!landed.headers.contains_key("authorization"));
no_field(landed);
let within = svc_got
.iter()
.find(|r| r.path == "/billing/landed")
.unwrap();
assert_eq!(within.method, "GET");
assert_eq!(within.body, "");
assert_eq!(within.headers["x-encore-meta-ctx-plan"], "InBybyI");
let moved: Vec<(&str, &str)> = svc_got
.iter()
.filter(|r| r.path == "/billing/moved-to")
.map(|r| (r.method.as_str(), r.body.as_str()))
.collect();
assert_eq!(moved, [("PUT", "update"), ("GET", "")]);
let landed: Vec<&str> = svc_got
.iter()
.filter(|r| r.path == "/billing/landed")
.map(|r| r.method.as_str())
.collect();
assert_eq!(landed, ["GET", "GET"]);
let own = "00-11111111111111111111111111111111-2222222222222222-01";
BILLING
.get("x")
.header("traceparent", own)
.send()
.with_context(request_context())
.await
.unwrap();
assert_eq!(
svc_log.lock().unwrap().last().unwrap().headers["traceparent"],
own
);
let sent = {
let _cx = request_context().attach();
tokio::spawn(BILLING.get("spawned").send())
};
sent.await.unwrap().unwrap();
let spawned = svc_log.lock().unwrap().last().unwrap().clone();
assert_eq!(spawned.path, "/billing/spawned");
assert_eq!(spawned.headers["x-encore-meta-ctx-plan"], "InBybyI");
BILLING
.get("x")
.header("tracestate", "encore=r,stale=1")
.send()
.with_context(request_context())
.await
.unwrap();
assert_eq!(
svc_log.lock().unwrap().last().unwrap().headers["tracestate"],
"encore=rc,vendor=1"
);
use tower_layer::Layer;
use tower_service::Service;
let seen = Arc::new(Mutex::new(Vec::new()));
let mut client = services::PropagateLayer.layer(tower_fn(seen.clone()));
let _cx = request_context().attach();
for uri in [
format!("{svc}/billing/x"),
format!("{third}/y"),
"/pkg.Svc/M".into(),
] {
let request = http::Request::builder()
.uri(uri)
.header("x-encore-meta-ctx-stale", "x")
.body(())
.unwrap();
client.call(request).await.unwrap();
}
let seen = seen.lock().unwrap();
assert_eq!(seen[0].get("x-encore-meta-ctx-plan").unwrap(), "InBybyI");
assert_eq!(seen[0].get("traceparent").unwrap(), TRACEPARENT);
for headers in &seen[1..] {
assert!(headers
.keys()
.all(|n| !n.as_str().starts_with("x-encore-meta-ctx-")));
assert!(headers.get("traceparent").is_none());
}
}
fn tower_fn(
seen: Arc<Mutex<Vec<http::HeaderMap>>>,
) -> impl tower_service::Service<
http::Request<()>,
Response = (),
Error = Infallible,
Future = std::future::Ready<Result<(), Infallible>>,
> {
struct Record(Arc<Mutex<Vec<http::HeaderMap>>>);
impl tower_service::Service<http::Request<()>> for Record {
type Response = ();
type Error = Infallible;
type Future = std::future::Ready<Result<(), Infallible>>;
fn poll_ready(
&mut self,
_: &mut std::task::Context<'_>,
) -> std::task::Poll<Result<(), Infallible>> {
std::task::Poll::Ready(Ok(()))
}
fn call(&mut self, request: http::Request<()>) -> Self::Future {
self.0.lock().unwrap().push(request.headers().clone());
std::future::ready(Ok(()))
}
}
Record(seen)
}
fn chunks(
chunks: [&'static str; 2],
) -> impl futures_core::Stream<Item = Result<&'static str, Infallible>> + Send + 'static {
struct Chunks(std::array::IntoIter<&'static str, 2>);
impl futures_core::Stream for Chunks {
type Item = Result<&'static str, Infallible>;
fn poll_next(
mut self: std::pin::Pin<&mut Self>,
_: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<Self::Item>> {
std::task::Poll::Ready(self.0.next().map(Ok))
}
}
Chunks(chunks.into_iter())
}