laravel-rust 0.1.0

Laravel for Rust: a full-stack Rust web framework, inspired by PHP Laravel
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
use std::pin::Pin;
use std::sync::{Arc, OnceLock};
use std::task::{self, Poll};
use std::time::Instant;

use axum::body::{Body, Bytes};
use axum::extract::DefaultBodyLimit;
use axum::middleware::Next;
use axum::response::Html;
use axum::response::{IntoResponse, Response};
use http::{HeaderValue, Method, StatusCode, header};
use http_body::{Body as HttpBody, Frame, SizeHint};
use tracing::{Instrument, Span};

use super::telemetry::REQUEST_TARGET;
use crate::context::{App, Context, InContext, Internals, RequestState};
use crate::errors::{Handled, ResponseBoundary};
use crate::http::RequestId;
use crate::http::middleware::TrustProxies;
use crate::http::request::origin;
use crate::http::request_id;
use crate::session::Flash;

pub(super) struct Kernel {
    pub(super) app: Arc<App>,
    pub(super) proxies: TrustProxies,
    pub(super) health: Option<String>,
}

pub(super) fn wrap(router: axum::Router, kernel: Kernel, boundary: ResponseBoundary) -> axum::Router {
    let kernel = Arc::new(kernel);
    let app = Arc::clone(&kernel.app);

    router
        .layer(axum::middleware::from_fn(
            move |request: axum::extract::Request, next: Next| with_services(request, next, Arc::clone(&app)),
        ))
        // Enforce LimitBody and LimitUploads for framework input and Axum extractors, not Axum's default limit...
        .layer(DefaultBodyLimit::disable())
        .layer(boundary)
        .layer(axum::middleware::from_fn(
            move |request: axum::extract::Request, next: Next| handle(request, next, Arc::clone(&kernel)),
        ))
}

async fn with_services(mut request: axum::extract::Request, next: Next, app: Arc<App>) -> Response {
    match app.part::<super::Boot>().run().await {
        Ok(()) => {
            request.extensions_mut().insert(app.services.clone());
            next.run(request).await
        }
        Err(error) => error.into_response(),
    }
}

async fn handle(mut request: axum::extract::Request, next: Next, kernel: Arc<Kernel>) -> Response {
    kernel.proxies.apply(&mut request);
    trim_trailing_slashes(&mut request, &kernel.app.config).await;
    request.extensions_mut().insert(Arc::clone(&kernel.app.config));
    request.extensions_mut().insert(kernel.app.encrypter.clone());
    request.extensions_mut().insert(crate::auth::AuthCache::default());

    let started = Instant::now();
    let method = request.method().clone();
    let path = request.uri().path().to_owned();

    let id = RequestId::of(request.headers());
    request.extensions_mut().insert(id.clone());

    let origin = origin(request.headers(), request.uri());

    let is_health_check =
        (method == Method::GET || method == Method::HEAD) && kernel.health.as_deref() == Some(path.as_str());

    let is_reload_stream = kernel.app.config.app.debug && method == Method::GET && path == crate::view::reload::PATH;

    // Load balancers poll the health check, and the reload stream stays open, so neither is worth a span...
    let span = if is_health_check || is_reload_stream {
        Span::none()
    } else {
        request_span(&mut request, &id, &origin)
    };

    if let Some(RecordRoot(recorded)) = request.extensions().get::<RecordRoot>() {
        let _ = recorded.set(origin.clone());
    }

    let context = Context::new(Arc::clone(&kernel.app), Some(RequestState::new(&request, origin)));

    // Outside local development, the platform's access logs already record each request...
    let mut line = RequestLine {
        context: context.clone(),
        span: span.clone(),
        method,
        path,
        started,
        quiet: is_health_check || is_reload_stream || !kernel.app.config.app.env.is_local(),
        status: CLIENT_CLOSED_REQUEST,
    };

    let response = if is_health_check {
        Some(health(&kernel.app).instrument(span.clone()).await)
    } else if is_reload_stream {
        Some(crate::view::reload::stream(&context))
    } else {
        let cut_off = context.cutting_off();
        let handled = context.clone().scope(next.run(request)).instrument(span.clone());

        tokio::select! {
            biased;
            () = cut_off => None,
            response = handled => Some(response),
        }
    };
    let mut response = match response {
        Some(response) => response.map(|body| InContext::wrap(body, context.clone(), span.clone())),
        None => (
            StatusCode::SERVICE_UNAVAILABLE,
            [(header::CONNECTION, "close")],
            "The server stopped before the request finished.",
        )
            .into_response(),
    };

    if let Ok(value) = HeaderValue::try_from(id.as_str()) {
        response.headers_mut().entry(request_id::HEADER).or_insert(value);
    }

    let _entered = span.enter();

    if response.extensions_mut().remove::<Flash>().is_some() {
        tracing::warn!(
            target: REQUEST_TARGET,
            "data flashed with a redirect was dropped, since the route has no session; \
             flash data needs the `web` middleware group"
        );
    }

    let status = response.status().as_u16();
    span.record("http.response.status_code", i64::from(status));
    if response.status().is_server_error() {
        match response.extensions().get::<Handled>() {
            Some(handled) => super::telemetry::fail(&span, &*handled.error),
            None => super::telemetry::fail(&span, &super::telemetry::Summary::server_status(response.status())),
        }
    }

    // The server drops the body of a response that can't have one unread...
    if matches!(status, 100..=199 | 204 | 304) {
        line.status = status;
    }
    response.map(|body| Body::new(Logged { body, line, status }))
}

/// The request's span, which its handler, its log lines, and its OpenTelemetry trace run in.
fn request_span(request: &mut axum::extract::Request, id: &RequestId, origin: &str) -> Span {
    let method = request.method();
    let path = request.uri().path();
    let otel_method = super::telemetry::http_method(method.as_str());
    let span = tracing::info_span!(
        target: REQUEST_TARGET,
        "request",
        id = %id,
        method = %method,
        path = %path,
        route = tracing::field::Empty,
        otel.name = otel_method.name,
        otel.kind = "server",
        otel.status_code = tracing::field::Empty,
        http.request.method = otel_method.attribute,
        http.request.method_original = otel_method.original,
        http.route = tracing::field::Empty,
        http.response.status_code = tracing::field::Empty,
        url.path = %path,
        url.scheme = origin.split_once("://").map(|(scheme, _)| scheme),
    );
    #[cfg(feature = "opentelemetry")]
    super::telemetry::continue_trace(&span, request.headers());
    request
        .extensions_mut()
        .insert(super::telemetry::RequestSpan(span.clone()));

    span
}

/// `499`, nginx's status for a client that closed the connection before the response was sent.
const CLIENT_CLOSED_REQUEST: u16 = 499;

/// A request's summary line, written when the request ends: once its response's body has been
/// sent, or when the client disconnects first, which drops the handler or the body. Until the body
/// ends, the line records a client that left.
struct RequestLine {
    context: Context,
    span: Span,
    method: Method,
    path: String,
    started: Instant,
    quiet: bool,
    status: u16,
}

impl Drop for RequestLine {
    fn drop(&mut self) {
        let Self {
            method, path, status, ..
        } = self;
        let elapsed = self.started.elapsed();
        let duration_ms = crate::foundation::telemetry::duration_ms(elapsed);
        let elapsed = crate::console::theme::elapsed(elapsed);
        let _entered = self.span.enter();
        // In the request's context, so the line carries its values and Laravel Cloud's request ID...
        self.context.clone().sync_scope(|| {
            if self.quiet {
                tracing::debug!(target: REQUEST_TARGET, status, duration_ms, "{method} {path} {status} {elapsed}");
            } else {
                tracing::info!(target: REQUEST_TARGET, status, duration_ms, "{method} {path} {status} {elapsed}");
            }
        });
        drop(_entered);
        // End the OpenTelemetry span now so detached `task::background` work holding a parent
        // handle doesn't inflate the HTTP request span's duration.
        super::telemetry::end_now(&self.span);
    }
}

/// A response's body that writes the request's line once the body ends. A body that fails ends the
/// response on the server's side, so its line keeps the response's status.
struct Logged {
    body: Body,
    line: RequestLine,
    status: u16,
}

impl HttpBody for Logged {
    type Data = Bytes;
    type Error = axum::Error;

    fn poll_frame(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Option<Result<Frame<Bytes>, axum::Error>>> {
        let this = self.get_mut();
        let polled = Pin::new(&mut this.body).poll_frame(cx);
        if matches!(polled, Poll::Ready(None | Some(Err(_)))) {
            this.line.status = this.status;
        }
        polled
    }

    fn is_end_stream(&self) -> bool {
        self.body.is_end_stream()
    }

    fn size_hint(&self) -> SizeHint {
        self.body.size_hint()
    }
}

impl Drop for Logged {
    fn drop(&mut self) {
        // The server stops polling a body that reports its end, such as an empty one or the last
        // frame of one with a known length.
        if self.body.is_end_stream() {
            self.line.status = self.status;
        }
    }
}

#[derive(Debug, Clone, Default)]
pub(crate) struct RecordRoot(pub(crate) Arc<OnceLock<String>>);

/// Route `/users/` as `/users`, so routing and everything after it sees
/// the path without the slash. A directory in `public/` keeps its slash.
/// The file server redirects `/docs` to `/docs/` to serve its `index.html`,
/// so trimming the slash would cause a redirect loop.
async fn trim_trailing_slashes(request: &mut axum::extract::Request, config: &crate::config::Config) {
    let path = request.uri().path();
    if path.len() <= 1 || !path.ends_with('/') {
        return;
    }

    let trimmed = path.trim_end_matches('/');
    let trimmed = if trimmed.is_empty() { "/" } else { trimmed };

    let decoded = percent_encoding::percent_decode_str(path).decode_utf8_lossy();
    let in_public = config.app.public_path(decoded.trim_start_matches('/'));
    if !decoded.contains("..")
        && tokio::fs::metadata(&in_public)
            .await
            .is_ok_and(|metadata| metadata.is_dir())
    {
        return;
    }

    let path_and_query = request
        .uri()
        .query()
        .map_or_else(|| trimmed.to_owned(), |query| format!("{trimmed}?{query}"));
    let mut parts = request.uri().clone().into_parts();
    if let Ok(path_and_query) = path_and_query.parse() {
        parts.path_and_query = Some(path_and_query);
        if let Ok(uri) = http::Uri::from_parts(parts) {
            *request.uri_mut() = uri;
        }
    }
}

async fn health(app: &App) -> Response {
    match app.part::<super::Boot>().run().await {
        Ok(()) => Html(HEALTHY).into_response(),
        Err(error) => {
            crate::foundation::telemetry::logging(
                &error,
                || tracing::error!(target: REQUEST_TARGET, %error, "the health check failed: the application can't boot"),
            );
            (StatusCode::SERVICE_UNAVAILABLE, Html(UNHEALTHY)).into_response()
        }
    }
}

const HEALTHY: &str = r#"<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><title>Application up</title>
<style>html{min-height:100%;background:linear-gradient(oklch(84.5% 0.143 164.978),#fff)}</style></head><body></body></html>"#;

const UNHEALTHY: &str = r#"<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><title>Application down</title>
<style>html{min-height:100%;background:linear-gradient(oklch(70.4% 0.191 22.216),#fff)}</style></head><body></body></html>"#;

#[cfg(test)]
mod tests {
    use std::sync::Arc;
    use std::time::Duration;

    use tokio::sync::Notify;

    use std::pin::Pin;
    use std::task::{self, Poll};

    use axum::body::{Body, Bytes};
    use http_body::{Body as HttpBody, Frame, SizeHint};

    use crate::Application;
    use crate::context::Context;
    use crate::routing::Router;
    use crate::testing::MakesHttpRequests;

    struct Lazy(bool);

    impl HttpBody for Lazy {
        type Data = Bytes;
        type Error = std::convert::Infallible;

        fn poll_frame(
            self: Pin<&mut Self>,
            _cx: &mut task::Context<'_>,
        ) -> Poll<Option<Result<Frame<Bytes>, Self::Error>>> {
            if std::mem::replace(&mut self.get_mut().0, true) {
                return Poll::Ready(None);
            }
            let read_in = if Context::current().is_some() { "ctx" } else { "no!" };
            Poll::Ready(Some(Ok(Frame::data(Bytes::from_static(read_in.as_bytes())))))
        }

        fn size_hint(&self) -> SizeHint {
            SizeHint::with_exact(3)
        }
    }

    #[derive(Default)]
    struct Gate {
        started: Notify,
        released: Notify,
    }

    fn app(gate: &Arc<Gate>) -> Application {
        let gate = Arc::clone(gate);

        Application::configure()
            .replace_env(crate::config::Env::from_iter([("APP_KEY", "")]))
            .with_routing(|routing, _| {
                routing.api(move |route: &mut Router| {
                    route.get("/lazy", || async { Body::new(Lazy(false)) });
                    route.get("/empty", || async { http::StatusCode::NO_CONTENT });
                    route.get("/held", move || {
                        let gate = Arc::clone(&gate);
                        async move {
                            gate.started.notify_one();
                            gate.released.notified().await;
                            "finished"
                        }
                    });
                    route.get("/pending-body", || async {
                        Body::from_stream(futures_util::stream::pending::<Result<Bytes, std::io::Error>>())
                    });
                    route.get("/panicking-body", || async {
                        let chunks = futures_util::stream::iter([false, true]);
                        crate::http::Streamed::new(futures_util::StreamExt::map(chunks, |fail| {
                            assert!(!fail, "the stream broke");
                            "partial"
                        }))
                    });
                });
            })
            .create()
    }

    fn get(uri: &str) -> http::Request<Body> {
        http::Request::get(uri)
            .header("host", "localhost")
            .body(Body::empty())
            .unwrap()
    }

    #[tokio::test]
    async fn bodies_keep_their_length_and_end() {
        let router = app(&Arc::default()).into_router();

        let lazy = tower::ServiceExt::oneshot(router.clone(), get("/api/lazy"))
            .await
            .unwrap();
        assert_eq!(lazy.body().size_hint().exact(), Some(3));
        assert!(!lazy.body().is_end_stream());

        let empty = tower::ServiceExt::oneshot(router, get("/api/empty")).await.unwrap();
        assert!(empty.body().is_end_stream());
    }

    #[tokio::test]
    async fn bodies_of_known_length_are_read_in_the_context() {
        app(&Arc::default())
            .get("/api/lazy")
            .await
            .assert_ok()
            .assert_see("ctx");
    }

    #[tokio::test]
    async fn a_body_that_panics_is_reported_and_fails() {
        let reports = crate::errors::RecordReports::default();
        let mut request = get("/api/panicking-body");
        request.extensions_mut().insert(reports.clone());

        let response = tower::ServiceExt::oneshot(app(&Arc::default()).into_router(), request)
            .await
            .unwrap();
        let body = http_body_util::BodyExt::collect(response.into_body()).await;

        assert!(body.is_err(), "the client can tell the response was cut short");
        let reports = reports.0.lock().unwrap();
        assert_eq!(reports.len(), 1, "{reports:?}");
        let message = reports[0].to_string();
        assert!(message.starts_with(concat!("panic at ", file!(), ":")), "{message}");
        assert!(message.ends_with(": the stream broke"), "{message}");
    }

    #[tokio::test]
    async fn requests_running_when_the_server_begins_to_stop_finish() {
        let gate = Arc::default();
        let app = app(&gate);

        let stop = async {
            gate.started.notified().await;
            app.begin_shutdown();
            gate.released.notify_one();
        };
        let (response, ()) = tokio::join!(app.get("/api/held"), stop);

        response.assert_ok().assert_see("finished");
    }

    #[tokio::test]
    async fn requests_still_running_are_cut_off() {
        let gate = Arc::default();
        let app = app(&gate);

        let cut_off = async {
            gate.started.notified().await;
            app.cut_off_requests();
        };
        let handled = tokio::time::timeout(Duration::from_secs(5), app.get("/api/held"));
        let (response, ()) = tokio::join!(handled, cut_off);

        response
            .expect("the request is cut off")
            .assert_status(503)
            .assert_see("The server stopped before the request finished.");
    }

    #[tokio::test]
    async fn bodies_still_streaming_are_cut_off() {
        let app = app(&Arc::default());
        let router = app.clone().into_router();
        let pending = tower::ServiceExt::oneshot(router.clone(), get("/api/pending-body"))
            .await
            .unwrap();
        let ready = tower::ServiceExt::oneshot(router, get("/api/lazy")).await.unwrap();

        app.cut_off_requests();
        for response in [pending, ready] {
            let body = tokio::time::timeout(
                Duration::from_secs(5),
                http_body_util::BodyExt::collect(response.into_body()),
            )
            .await;

            assert!(body.expect("the body is cut off").is_err());
        }
    }
}