1#![forbid(unsafe_code)]
43#![deny(missing_docs)]
44
45use http::Request;
46use http::Response;
47use pin_project_lite::pin_project;
48use rlg::log::Log;
49use rlg::log_format::LogFormat;
50use rlg::log_level::LogLevel;
51use std::future::Future;
52use std::pin::Pin;
53use std::task::{Context, Poll};
54use std::time::Instant;
55use tower_layer::Layer;
56use tower_service::Service;
57
58#[derive(Debug, Clone)]
63pub struct RlgLayer {
64 config: Config,
65}
66
67#[derive(Debug, Clone)]
68struct Config {
69 level: LogLevel,
70 format: LogFormat,
71 component: &'static str,
72 trace_header: Option<&'static str>,
73}
74
75impl Default for Config {
76 fn default() -> Self {
77 Self {
78 level: LogLevel::INFO,
79 format: LogFormat::Logfmt,
80 component: "rlg-tower",
81 trace_header: None,
82 }
83 }
84}
85
86impl Default for RlgLayer {
87 fn default() -> Self {
88 Self::new()
89 }
90}
91
92impl RlgLayer {
93 #[must_use]
97 pub fn new() -> Self {
98 Self {
99 config: Config::default(),
100 }
101 }
102
103 #[must_use]
105 pub const fn level(mut self, level: LogLevel) -> Self {
106 self.config.level = level;
107 self
108 }
109
110 #[must_use]
112 pub const fn format(mut self, format: LogFormat) -> Self {
113 self.config.format = format;
114 self
115 }
116
117 #[must_use]
121 pub const fn component(mut self, component: &'static str) -> Self {
122 self.config.component = component;
123 self
124 }
125
126 #[must_use]
130 pub const fn header(mut self, name: &'static str) -> Self {
131 self.config.trace_header = Some(name);
132 self
133 }
134}
135
136impl<S> Layer<S> for RlgLayer {
137 type Service = RlgService<S>;
138
139 fn layer(&self, inner: S) -> Self::Service {
140 RlgService {
141 inner,
142 config: self.config.clone(),
143 }
144 }
145}
146
147#[derive(Debug, Clone)]
149pub struct RlgService<S> {
150 inner: S,
151 config: Config,
152}
153
154impl<S, ReqBody, ResBody> Service<Request<ReqBody>> for RlgService<S>
155where
156 S: Service<Request<ReqBody>, Response = Response<ResBody>>,
157{
158 type Response = S::Response;
159 type Error = S::Error;
160 type Future = RlgFuture<S::Future>;
161
162 fn poll_ready(
163 &mut self,
164 cx: &mut Context<'_>,
165 ) -> Poll<Result<(), Self::Error>> {
166 self.inner.poll_ready(cx)
167 }
168
169 fn call(&mut self, req: Request<ReqBody>) -> Self::Future {
170 let method = req.method().clone();
171 let path = req.uri().path().to_string();
172 let trace_id = self
173 .config
174 .trace_header
175 .and_then(|name| req.headers().get(name))
176 .and_then(|v| v.to_str().ok())
177 .map(str::to_string);
178 let cfg = self.config.clone();
179 let start = Instant::now();
180 let fut = self.inner.call(req);
181 RlgFuture {
182 inner: fut,
183 method,
184 path,
185 trace_id,
186 cfg,
187 start,
188 }
189 }
190}
191
192pin_project! {
193 #[derive(Debug)]
195 pub struct RlgFuture<F> {
196 #[pin]
197 inner: F,
198 method: http::Method,
199 path: String,
200 trace_id: Option<String>,
201 cfg: Config,
202 start: Instant,
203 }
204}
205
206impl<F, ResBody, E> Future for RlgFuture<F>
207where
208 F: Future<Output = Result<Response<ResBody>, E>>,
209{
210 type Output = Result<Response<ResBody>, E>;
211
212 fn poll(
213 self: Pin<&mut Self>,
214 cx: &mut Context<'_>,
215 ) -> Poll<Self::Output> {
216 let this = self.project();
217 match this.inner.poll(cx) {
218 Poll::Pending => Poll::Pending,
219 Poll::Ready(Ok(response)) => {
220 emit(
221 this.cfg,
222 this.method,
223 this.path,
224 this.trace_id.as_deref(),
225 Some(response.status().as_u16()),
226 this.start.elapsed().as_millis() as u64,
227 );
228 Poll::Ready(Ok(response))
229 }
230 Poll::Ready(Err(err)) => {
231 emit(
232 this.cfg,
233 this.method,
234 this.path,
235 this.trace_id.as_deref(),
236 None,
237 this.start.elapsed().as_millis() as u64,
238 );
239 Poll::Ready(Err(err))
240 }
241 }
242 }
243}
244
245fn emit(
246 cfg: &Config,
247 method: &http::Method,
248 path: &str,
249 trace_id: Option<&str>,
250 status: Option<u16>,
251 latency_ms: u64,
252) {
253 let status_str =
254 status.map_or_else(|| "ERR".to_string(), |s| s.to_string());
255 let description = format!("{method} {path} -> {status_str}");
256 let mut log = Log::build(cfg.level, &description)
257 .component(cfg.component)
258 .format(cfg.format)
259 .with("http.method", method.as_str())
260 .with("http.path", path)
261 .with("http.latency_ms", latency_ms);
262 if let Some(s) = status {
263 log = log.with("http.status", s);
264 }
265 if let Some(t) = trace_id {
266 log = log.with("trace_id", t);
267 }
268 log.fire();
269}
270
271#[cfg(test)]
272mod tests {
273 use super::*;
274
275 #[test]
276 fn defaults_are_sensible() {
277 let cfg = Config::default();
278 assert_eq!(cfg.level, LogLevel::INFO);
279 assert_eq!(cfg.format, LogFormat::Logfmt);
280 assert_eq!(cfg.component, "rlg-tower");
281 assert!(cfg.trace_header.is_none());
282 }
283
284 #[test]
285 fn fluent_setters_chain() {
286 let layer = RlgLayer::new()
287 .level(LogLevel::WARN)
288 .format(LogFormat::JSON)
289 .component("api")
290 .header("traceparent");
291 assert_eq!(layer.config.level, LogLevel::WARN);
292 assert_eq!(layer.config.format, LogFormat::JSON);
293 assert_eq!(layer.config.component, "api");
294 assert_eq!(layer.config.trace_header, Some("traceparent"));
295 }
296
297 #[test]
298 fn default_constructor_matches_new() {
299 let a = RlgLayer::default();
300 let b = RlgLayer::new();
301 assert_eq!(a.config.level, b.config.level);
302 assert_eq!(a.config.format, b.config.format);
303 }
304
305 #[test]
306 fn layer_is_clone() {
307 let l1 = RlgLayer::new().component("svc");
308 let l2 = l1.clone();
309 assert_eq!(l1.config.component, l2.config.component);
310 }
311}