reifydb_sub_server/interceptor.rs
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2025 ReifyDB
3
4//! Request-level interceptors for pre/post query execution hooks.
5//!
6//! This module provides an async interceptor mechanism that allows consumers
7//! to hook into the request lifecycle — before and after query execution.
8//! Interceptors can reject requests (for auth, rate limiting, credit checks)
9//! or observe results (for logging, billing, usage tracking).
10//!
11//! # Example
12//!
13//! ```ignore
14//! use reifydb::server;
15//!
16//! struct MyInterceptor;
17//!
18//! impl RequestInterceptor for MyInterceptor {
19//! fn pre_execute(&self, ctx: &mut RequestContext)
20//! -> Pin<Box<dyn Future<Output = Result<(), ExecuteError>> + Send + '_>>
21//! {
22//! Box::pin(async move {
23//! if ctx.metadata.get("authorization").is_none() {
24//! return Err(ExecuteError::Rejected {
25//! code: "AUTH_REQUIRED".into(),
26//! message: "Missing API key".into(),
27//! });
28//! }
29//! Ok(())
30//! })
31//! }
32//!
33//! fn post_execute(&self, ctx: &ResponseContext)
34//! -> Pin<Box<dyn Future<Output = ()> + Send + '_>>
35//! {
36//! Box::pin(async move {
37//! tracing::info!("query executed: {:?}", ctx.metrics.total);
38//! })
39//! }
40//! }
41//!
42//! let db = server::memory()
43//! .with_request_interceptor(MyInterceptor)
44//! .build()?;
45//! ```
46
47use std::{collections::HashMap, future::Future, panic::AssertUnwindSafe, pin::Pin, sync::Arc};
48
49use futures_util::FutureExt;
50use reifydb_core::{actors::server::Operation, metric::ExecutionMetrics};
51use reifydb_type::{params::Params, value::identity::IdentityId};
52use tracing::error;
53
54use crate::execute::ExecuteError;
55
56/// The transport protocol used for the request.
57#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
58pub enum Protocol {
59 #[default]
60 Http,
61 WebSocket,
62 Grpc,
63}
64
65/// Protocol-agnostic metadata extracted from the request transport layer.
66///
67/// HTTP headers, gRPC metadata, and WS auth tokens are all normalized into
68/// a string-keyed map. Header names are lowercased for consistent lookup.
69///
70/// Note: this is a single-value map — duplicate keys are overwritten
71/// (last-write-wins). Multi-valued headers (e.g. `Set-Cookie`) only
72/// retain the last value. This is intentional for simplicity; most
73/// interceptor use cases only need single-valued lookups.
74#[derive(Debug, Clone, Default)]
75pub struct RequestMetadata {
76 headers: HashMap<String, String>,
77 protocol: Protocol,
78}
79
80impl RequestMetadata {
81 /// Create empty metadata for the given protocol.
82 pub fn new(protocol: Protocol) -> Self {
83 Self {
84 headers: HashMap::new(),
85 protocol,
86 }
87 }
88
89 /// Insert a header (key is lowercased). Duplicate keys are overwritten.
90 pub fn insert(&mut self, key: impl Into<String>, value: impl Into<String>) {
91 self.headers.insert(key.into().to_ascii_lowercase(), value.into());
92 }
93
94 /// Get a header value by name (case-insensitive).
95 pub fn get(&self, key: &str) -> Option<&str> {
96 self.headers.get(&key.to_ascii_lowercase()).map(|s| s.as_str())
97 }
98
99 /// Get the protocol.
100 pub fn protocol(&self) -> Protocol {
101 self.protocol
102 }
103
104 /// Get all headers.
105 pub fn headers(&self) -> &HashMap<String, String> {
106 &self.headers
107 }
108}
109
110/// Context available to pre-execute interceptors.
111///
112/// Fields are public and mutable so interceptors can override values
113/// (e.g., resolve API key → set identity, store key_id in metadata for post_execute).
114pub struct RequestContext {
115 /// The resolved identity. Pre-execute interceptors may replace this.
116 pub identity: IdentityId,
117 /// The operation type.
118 pub operation: Operation,
119 /// The RQL string being executed.
120 pub rql: String,
121 /// Query parameters.
122 pub params: Params,
123 /// Protocol-agnostic request metadata (headers, etc.).
124 pub metadata: RequestMetadata,
125}
126
127/// Context available to post-execute interceptors.
128pub struct ResponseContext {
129 /// The identity that executed the request (may have been mutated by pre_execute).
130 pub identity: IdentityId,
131 /// The operation type.
132 pub operation: Operation,
133 /// The RQL string that was executed.
134 pub rql: String,
135 /// Rich metrics for each statement in the request.
136 pub metrics: ExecutionMetrics,
137 /// Query parameters.
138 pub params: Params,
139 /// Protocol-agnostic request metadata.
140 pub metadata: RequestMetadata,
141 /// Execution result: Ok(frame_count) or Err with the error message.
142 pub result: Result<usize, String>,
143}
144
145/// Async trait for request-level interceptors.
146///
147/// Interceptors run in the tokio async context (before compute pool dispatch),
148/// so they can perform async I/O (database lookups, network calls, etc.).
149///
150/// Multiple interceptors are chained: `pre_execute` runs in registration order,
151/// `post_execute` runs in reverse order (like middleware stacks).
152pub trait RequestInterceptor: Send + Sync + 'static {
153 /// Called before query execution.
154 ///
155 /// Return `Ok(())` to allow the request to proceed.
156 /// Return `Err(ExecuteError)` to reject the request.
157 /// May mutate the context (e.g., set identity from API key lookup).
158 fn pre_execute<'a>(
159 &'a self,
160 ctx: &'a mut RequestContext,
161 ) -> Pin<Box<dyn Future<Output = Result<(), ExecuteError>> + Send + 'a>>;
162
163 /// Called after query execution completes (success or failure).
164 ///
165 /// This is called even if the execution failed, so interceptors can
166 /// log failures and track usage regardless of outcome.
167 fn post_execute<'a>(&'a self, ctx: &'a ResponseContext) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>>;
168}
169
170/// Ordered chain of request interceptors, cheap to clone (Arc internally).
171#[derive(Clone)]
172pub struct RequestInterceptorChain {
173 interceptors: Arc<Vec<Arc<dyn RequestInterceptor>>>,
174}
175
176impl RequestInterceptorChain {
177 pub fn new(interceptors: Vec<Arc<dyn RequestInterceptor>>) -> Self {
178 Self {
179 interceptors: Arc::new(interceptors),
180 }
181 }
182
183 pub fn empty() -> Self {
184 Self {
185 interceptors: Arc::new(Vec::new()),
186 }
187 }
188
189 pub fn is_empty(&self) -> bool {
190 self.interceptors.is_empty()
191 }
192
193 /// Run all pre_execute interceptors in order.
194 /// Stops and returns Err on first rejection.
195 pub async fn pre_execute(&self, ctx: &mut RequestContext) -> Result<(), ExecuteError> {
196 for interceptor in self.interceptors.iter() {
197 interceptor.pre_execute(ctx).await?;
198 }
199 Ok(())
200 }
201
202 /// Run all post_execute interceptors in reverse order.
203 ///
204 /// If an interceptor panics, the panic is caught and logged so that
205 /// remaining interceptors still run.
206 pub async fn post_execute(&self, ctx: &ResponseContext) {
207 for interceptor in self.interceptors.iter().rev() {
208 if let Err(panic) = AssertUnwindSafe(interceptor.post_execute(ctx)).catch_unwind().await {
209 let msg = panic
210 .downcast_ref::<&str>()
211 .copied()
212 .or_else(|| panic.downcast_ref::<String>().map(|s| s.as_str()))
213 .unwrap_or("unknown panic");
214 error!("post_execute interceptor panicked: {}", msg);
215 }
216 }
217 }
218}
219
220impl Default for RequestInterceptorChain {
221 fn default() -> Self {
222 Self::empty()
223 }
224}