1use crate::clock::{Clock, SystemClock};
2use crate::config::{AppConfig, is_local_development_environment};
3use crate::db::DbPool;
4use crate::events::EventPublisher;
5use crate::execution_logs::{ExecutionLogProvider, PostgresExecutionLogProvider};
6use crate::health::HealthRegistry;
7use crate::ids::{IdGenerator, UuidGenerator};
8use crate::runtime_config::{RuntimeConfigProvider, StaticRuntimeConfigProvider};
9use crate::shutdown::Shutdown;
10use crate::telemetry_query::{NoopTelemetrySpanProvider, TelemetrySpanProvider};
11use serde::{Deserialize, Serialize};
12use std::fmt::Debug;
13use std::sync::Arc;
14
15#[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize, Serialize)]
16pub struct CorrelationId(pub String);
17
18impl CorrelationId {
19 pub fn new(value: impl Into<String>) -> Self {
20 Self(value.into())
21 }
22}
23
24#[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize, Serialize)]
25pub struct RequestId(pub String);
26
27impl RequestId {
28 pub fn new(value: impl Into<String>) -> Self {
29 Self(value.into())
30 }
31}
32
33#[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize, Serialize)]
34pub struct TenantId(pub String);
35
36#[derive(Debug, Clone, Default, Deserialize, Serialize)]
37pub struct TraceContext {
38 pub trace_id: Option<String>,
39 pub span_id: Option<String>,
40 pub baggage: Vec<(String, String)>,
41}
42
43#[derive(Debug, Clone, Deserialize, Serialize)]
44#[serde(tag = "kind", rename_all = "snake_case")]
45pub enum ActorContext {
46 Anonymous,
47 User {
48 user_id: String,
49 scopes: Vec<String>,
50 },
51 Service {
52 service_id: String,
53 scopes: Vec<String>,
54 },
55 System,
56}
57
58impl Default for ActorContext {
59 fn default() -> Self {
60 Self::Anonymous
61 }
62}
63
64#[derive(Debug, Clone, Default)]
65pub struct ActorResolutionRequest {
66 pub authorization: Option<String>,
67 pub cookie: Option<String>,
68}
69
70#[async_trait::async_trait]
71pub trait ActorResolver: Debug + Send + Sync {
72 async fn resolve_actor(&self, request: ActorResolutionRequest) -> ActorContext;
73}
74
75#[derive(Debug, Clone)]
76pub struct DevActorResolver {
77 environment: String,
78}
79
80impl DevActorResolver {
81 #[must_use]
82 pub fn new(environment: impl Into<String>) -> Self {
83 Self {
84 environment: environment.into(),
85 }
86 }
87}
88
89#[async_trait::async_trait]
90impl ActorResolver for DevActorResolver {
91 async fn resolve_actor(&self, request: ActorResolutionRequest) -> ActorContext {
92 let _ = request.cookie;
93 request
94 .authorization
95 .and_then(|value| parse_dev_bearer_actor(&value, &self.environment))
96 .unwrap_or_default()
97 }
98}
99
100fn parse_dev_bearer_actor(value: &str, environment: &str) -> Option<ActorContext> {
101 if !is_local_development_environment(environment) {
102 return None;
103 }
104
105 let token = value.strip_prefix("Bearer ")?;
106
107 if let Some(user_id) = token.strip_prefix("dev-user:") {
108 return Some(ActorContext::User {
109 user_id: user_id.to_owned(),
110 scopes: Vec::new(),
111 });
112 }
113
114 if let Some(service_token) = token.strip_prefix("dev-service:") {
115 let (service_id, scopes) = parse_dev_actor_scopes(service_token);
116 return Some(ActorContext::Service { service_id, scopes });
117 }
118
119 None
120}
121
122fn parse_dev_actor_scopes(value: &str) -> (String, Vec<String>) {
123 let Some((id, raw_scopes)) = value.split_once(':') else {
124 return (value.to_owned(), Vec::new());
125 };
126 let scopes = raw_scopes
127 .split(',')
128 .filter(|scope| !scope.is_empty())
129 .map(ToOwned::to_owned)
130 .collect();
131 (id.to_owned(), scopes)
132}
133
134#[derive(Debug, Clone, Deserialize, Serialize)]
135pub struct RequestContext {
136 pub request_id: RequestId,
137 pub correlation_id: CorrelationId,
138 pub trace: TraceContext,
139 pub actor: ActorContext,
140 pub tenant_id: Option<TenantId>,
141 pub causation_id: Option<String>,
142}
143
144impl RequestContext {
145 pub fn new(request_id: RequestId, correlation_id: CorrelationId) -> Self {
146 Self {
147 request_id,
148 correlation_id,
149 trace: TraceContext::default(),
150 actor: ActorContext::Anonymous,
151 tenant_id: None,
152 causation_id: None,
153 }
154 }
155}
156
157#[derive(Clone)]
158pub struct AppContext {
159 pub config: Arc<AppConfig>,
160 pub db: DbPool,
161 pub redis: Option<crate::RedisConnection>,
162 pub actor_resolver: Arc<dyn ActorResolver>,
163 pub clock: Arc<dyn Clock>,
164 pub ids: Arc<dyn IdGenerator>,
165 pub events: Arc<dyn EventPublisher>,
166 pub telemetry_spans: Arc<dyn TelemetrySpanProvider>,
167 pub execution_logs: Arc<dyn ExecutionLogProvider>,
168 pub runtime_config: Arc<dyn RuntimeConfigProvider>,
169 pub health: HealthRegistry,
170 pub shutdown: Shutdown,
171}
172
173impl Debug for AppContext {
174 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
175 formatter
176 .debug_struct("AppContext")
177 .field("config", &self.config)
178 .field("db", &"<pool>")
179 .field("redis", &self.redis.as_ref().map(|_| "<connection>"))
180 .field("actor_resolver", &self.actor_resolver)
181 .field("telemetry_spans", &self.telemetry_spans)
182 .field("execution_logs", &self.execution_logs)
183 .field("runtime_config", &self.runtime_config)
184 .field("health", &self.health)
185 .field("shutdown", &self.shutdown)
186 .finish_non_exhaustive()
187 }
188}
189
190impl AppContext {
191 pub fn new(config: AppConfig, db: DbPool, events: Arc<dyn EventPublisher>) -> Self {
192 let execution_logs = Arc::new(PostgresExecutionLogProvider::new(db.clone()));
193 let actor_resolver = Arc::new(DevActorResolver::new(config.service.environment.clone()));
194 Self {
195 config: Arc::new(config),
196 db,
197 redis: None,
198 actor_resolver,
199 clock: Arc::new(SystemClock),
200 ids: Arc::new(UuidGenerator),
201 events,
202 telemetry_spans: Arc::new(NoopTelemetrySpanProvider),
203 execution_logs,
204 runtime_config: Arc::new(StaticRuntimeConfigProvider::empty()),
205 health: HealthRegistry::default(),
206 shutdown: Shutdown::new(),
207 }
208 }
209
210 pub fn with_actor_resolver(mut self, actor_resolver: Arc<dyn ActorResolver>) -> Self {
211 self.actor_resolver = actor_resolver;
212 self
213 }
214
215 pub fn with_redis(mut self, redis: Option<crate::RedisConnection>) -> Self {
216 self.redis = redis;
217 self
218 }
219
220 pub fn with_telemetry_span_provider(
221 mut self,
222 telemetry_spans: Arc<dyn TelemetrySpanProvider>,
223 ) -> Self {
224 self.telemetry_spans = telemetry_spans;
225 self
226 }
227
228 pub fn with_execution_log_provider(
229 mut self,
230 execution_logs: Arc<dyn ExecutionLogProvider>,
231 ) -> Self {
232 self.execution_logs = execution_logs;
233 self
234 }
235
236 pub fn with_runtime_config_provider(
237 mut self,
238 runtime_config: Arc<dyn RuntimeConfigProvider>,
239 ) -> Self {
240 self.runtime_config = runtime_config;
241 self
242 }
243}