use std::collections::HashSet;
use std::future::Future;
use std::marker::PhantomData;
use std::sync::Mutex;
use encore_sdk_core::reqctx::{self as core_reqctx, FieldConfig, Values};
use serde::de::DeserializeOwned;
use serde::Serialize;
use crate::opentelemetry::trace::{FutureExt, WithContext};
use crate::opentelemetry::Context;
pub use encore_sdk_core::reqctx::SizeError;
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
#[error("reqctx: field {field:?}: cannot encode {type_name} as JSON: {error}")]
Encode {
field: &'static str,
type_name: &'static str,
error: serde_json::Error,
},
#[error("reqctx: field {field:?}: the value {size}")]
Size {
field: &'static str,
size: SizeError,
},
}
pub struct Field<T> {
name: &'static str,
config: Option<FieldConfig>,
_value: PhantomData<fn() -> T>,
}
impl<T> Field<T> {
pub const fn new(name: &'static str) -> Self {
Self {
name,
config: Some(FieldConfig {
pubsub: false,
trace: false,
}),
_value: PhantomData,
}
}
pub const fn named(name: &'static str) -> Self {
Self {
name,
config: None,
_value: PhantomData,
}
}
pub const fn pubsub(mut self) -> Self {
if let Some(config) = &mut self.config {
config.pubsub = true;
}
self
}
pub const fn trace(mut self) -> Self {
if let Some(config) = &mut self.config {
config.trace = true;
}
self
}
pub const fn tag(self, _key: &'static str, _value: &'static str) -> Self {
self
}
pub const fn name(&self) -> &'static str {
self.name
}
fn config(&self) -> FieldConfig {
crate::runtime::configured()
.and_then(|rt| rt.reqctx_fields().get(self.name))
.or(self.config)
.unwrap_or_default()
}
}
impl<T> std::fmt::Debug for Field<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("Field").field(&self.name).finish()
}
}
impl<T: Serialize + DeserializeOwned> Field<T> {
pub fn get(&self) -> Option<T> {
Context::map_current(|cx| self.get_in(cx))
}
pub fn get_in(&self, cx: &Context) -> Option<T> {
let values = Values::of(cx);
let value = values.get(self.name)?;
match decode(value) {
Ok(v) => Some(v),
Err(why) => {
log_undecodable(self.name, std::any::type_name::<T>(), &why);
None
}
}
}
pub fn context(&self, value: &T) -> Result<Context, Error> {
Context::map_current(|cx| self.context_in(cx, value))
}
pub fn context_in(&self, cx: &Context, value: &T) -> Result<Context, Error> {
let json = serde_json::to_vec(value).map_err(|error| Error::Encode {
field: self.name,
type_name: std::any::type_name::<T>(),
error,
})?;
let values = Values::of(cx)
.with(self.name, core_reqctx::encode(&json), self.config())
.map_err(|size| Error::Size {
field: self.name,
size,
})?;
Ok(values.in_context(cx))
}
pub fn without(&self) -> Context {
Context::map_current(|cx| self.without_in(cx))
}
pub fn without_in(&self, cx: &Context) -> Context {
let values = Values::of(cx);
if values.get(self.name).is_none() {
return cx.clone();
}
values.without(self.name).in_context(cx)
}
pub fn scope<F: Future>(&self, value: &T, fut: F) -> Result<WithContext<F>, Error> {
Ok(fut.with_context(self.context(value)?))
}
}
pub fn extract(cx: &Context, headers: &http::HeaderMap) -> Context {
Values::from_headers(headers).in_context(cx)
}
pub fn inject(cx: &Context, headers: &mut http::HeaderMap) {
Values::of(cx).to_headers(headers);
}
fn decode<T: DeserializeOwned>(value: &str) -> Result<T, String> {
let json = core_reqctx::decode(value).map_err(|e| e.to_string())?;
serde_json::from_slice(&json).map_err(|e| {
let what = match e.classify() {
serde_json::error::Category::Data => "it is JSON of another shape",
_ => "it is not valid JSON",
};
format!(
"{what}: the error is at line {} column {}",
e.line(),
e.column()
)
})
}
static LOGGED: Mutex<Option<HashSet<(&'static str, &'static str)>>> = Mutex::new(None);
fn log_undecodable(name: &'static str, ty: &'static str, why: &str) {
let mut logged = LOGGED.lock().unwrap_or_else(|e| e.into_inner());
if !logged.get_or_insert_with(HashSet::new).insert((name, ty)) {
return;
}
drop(logged);
tracing::warn!(
field = name,
value_type = ty,
"cannot decode Request Context field {name:?} as {ty}, treating it as unset: {why}"
);
}
#[cfg(test)]
mod tests {
use super::*;
use serde::Deserialize;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
struct User {
id: String,
admin: bool,
}
static USER: Field<User> = Field::new("test-user");
static BY_NAME: Field<User> = Field::named("test-user");
static TENANT: Field<String> = Field::new("test-tenant").pubsub().trace();
static COUNT: Field<u32> = Field::named("test-user");
fn alice() -> User {
User {
id: "alice".into(),
admin: false,
}
}
#[test]
fn a_field_reads_what_was_set_in_its_context() {
assert_eq!(USER.get(), None);
let cx = USER.context(&alice()).unwrap();
assert_eq!(USER.get_in(&cx), Some(alice()));
assert_eq!(BY_NAME.get_in(&cx), Some(alice()));
assert_eq!(USER.get_in(&USER.without_in(&cx)), None);
let _guard = cx.attach();
assert_eq!(USER.get(), Some(alice()));
assert_eq!(USER.get_in(&USER.without()), None);
}
#[test]
fn a_scope_carries_the_field_across_awaits() {
let rt = tokio::runtime::Builder::new_current_thread()
.build()
.unwrap();
let seen = rt.block_on(async {
let fut = async {
tokio::task::yield_now().await;
USER.get()
};
USER.scope(&alice(), fut).unwrap().await
});
assert_eq!(seen, Some(alice()));
assert_eq!(USER.get(), None);
let cleared = rt.block_on(async {
let cx = USER.context(&alice()).unwrap();
async { async { USER.get() }.with_context(USER.without()).await }
.with_context(cx)
.await
});
assert_eq!(cleared, None);
}
#[test]
fn a_value_of_another_shape_reads_as_unset() {
let cx = USER.context(&alice()).unwrap();
assert_eq!(COUNT.get_in(&cx), None);
assert!(
decode::<u32>(&core_reqctx::encode(b"{\"id\":\"secret-id\"}"))
.unwrap_err()
.contains("another shape")
);
let why = decode::<User>(&core_reqctx::encode(b"{\"id\":\"secret")).unwrap_err();
assert!(why.starts_with("it is not valid JSON"), "{why}");
assert!(!why.contains("secret"), "{why}");
assert_eq!(
decode::<u32>("!").unwrap_err(),
"it is not base64url without padding"
);
}
#[test]
fn limits_fail_where_the_value_is_set() {
let err = TENANT.context(&"a".repeat(1100)).unwrap_err();
assert!(
matches!(
err,
Error::Size {
field: "test-tenant",
size: SizeError::MessageValue(_)
}
),
"{err:?}"
);
let msg = err.to_string();
assert!(
msg.contains("reqctx: field \"test-tenant\": the value encodes to")
&& msg.contains("carried on Pub/Sub messages"),
"{msg}"
);
let err = USER
.context(&User {
id: "a".repeat(5000),
admin: true,
})
.unwrap_err();
assert!(
matches!(
err,
Error::Size {
size: SizeError::Value(_),
..
}
),
"{err:?}"
);
assert!(err.to_string().contains("more than the 4096"), "{err}");
}
#[test]
fn headers_carry_the_fields() {
let cx = TENANT.context(&"acme".to_string()).unwrap();
let mut headers = http::HeaderMap::new();
headers.insert("x-encore-meta-ctx-stale", "e30".parse().unwrap());
inject(&cx, &mut headers);
assert!(headers.get("x-encore-meta-ctx-stale").is_none());
let received = extract(&Context::new(), &headers);
assert_eq!(TENANT.get_in(&received), Some("acme".to_string()));
}
}