Skip to main content

fusion_stack/
lib.rs

1//! Fusion Stack for Laravel for Rust: the same API format as the `fusion-stack/laravel` PHP
2//! package, so `@fusion-stack/client` works unchanged against either backend.
3//!
4//! Register [`FusionStack`] as a service provider, which renders every error as a JSON:API error
5//! document, and attach it as middleware to your API routes:
6//!
7//! ```no_run
8//! use fusion_stack::{Config, FusionStack};
9//! use fusion_stack::versioning::Versions;
10//! use laravel::prelude::*;
11//!
12//! # async fn index() -> &'static str { "[]" }
13//! let api = FusionStack::new(Config::new().versions(Versions::new("2026-11-30")));
14//!
15//! Application::configure()
16//!     .with_providers({
17//!         let api = api.clone();
18//!         move |providers| {
19//!             providers.add(api);
20//!         }
21//!     })
22//!     .with_routing(move |routing, _| {
23//!         let api = api.clone();
24//!         routing.api(move |route| {
25//!             route.prefix("/v1").middleware(api).group(|route| {
26//!                 route.get("/orders", index);
27//!             });
28//!         });
29//!     });
30//! ```
31
32// Resource rendering, query strings and name translation serve ApiQuery, which needs a database.
33#![cfg_attr(not(feature = "database"), allow(dead_code))]
34
35pub mod auth;
36pub mod console;
37pub mod docs;
38pub mod errors;
39mod http_cache;
40pub mod idempotency;
41pub mod openapi;
42#[cfg(feature = "database")]
43pub mod query;
44mod query_string;
45pub mod rate_limit;
46pub mod request_id;
47pub mod resources;
48pub mod response_cache;
49pub mod testing;
50mod time;
51#[cfg(feature = "database")]
52pub mod usage;
53pub mod versioning;
54pub mod webhooks;
55
56use std::sync::{Arc, OnceLock};
57
58use laravel::axum::body::{Body, to_bytes};
59use laravel::axum::http::{HeaderName, HeaderValue};
60use laravel::container::Registrar;
61use laravel::foundation::ServiceProvider;
62use laravel::http::{Middleware, Next, Request, Response};
63use serde_json::Value;
64
65pub use crate::auth::RequiresScope;
66pub use crate::http_cache::CacheControl;
67pub use crate::response_cache::CacheResponse;
68
69use crate::errors::ApiError;
70use crate::resources::Resource;
71use crate::versioning::{ApiVersion, Registry, VersionChange, Versions};
72
73/// Fusion Stack's settings, mirroring `config/api.php` in the PHP package.
74#[derive(Clone)]
75pub struct Config {
76    pub(crate) request_ids: bool,
77    pub(crate) error_paths: Vec<String>,
78    versions: Option<Versions>,
79    pub(crate) resources: Vec<Resource>,
80    pub(crate) page_size: u64,
81    pub(crate) max_page_size: u64,
82    pub(crate) max_include_depth: usize,
83    pub(crate) http_cache: HttpCacheConfig,
84    pub(crate) response_cache: ResponseCacheConfig,
85    pub(crate) idempotency: IdempotencyConfig,
86    pub(crate) auth: bool,
87    pub(crate) client_resolver: Option<auth::ClientResolver>,
88    pub(crate) rate_limit: RateLimitConfig,
89    pub(crate) track_usage: bool,
90    pub(crate) openapi: openapi::Settings,
91    pub(crate) docs: docs::Docs,
92    #[cfg(feature = "database")]
93    pub(crate) webhooks: webhooks::Settings,
94}
95
96/// `api.rate_limit` in the PHP package.
97#[derive(Clone)]
98pub(crate) struct RateLimitConfig {
99    pub(crate) enabled: bool,
100    pub(crate) tiers: Vec<(String, rate_limit::Tier)>,
101}
102
103/// `api.idempotency` in the PHP package.
104#[derive(Clone)]
105pub(crate) struct IdempotencyConfig {
106    pub(crate) enabled: bool,
107    pub(crate) methods: Vec<String>,
108    pub(crate) ttl: u64,
109    pub(crate) lock_seconds: u64,
110    pub(crate) store: Option<String>,
111}
112
113/// `api.response_cache` in the PHP package.
114#[derive(Clone)]
115pub(crate) struct ResponseCacheConfig {
116    pub(crate) enabled: bool,
117    pub(crate) store: Option<String>,
118}
119
120/// `api.http_cache` in the PHP package.
121#[derive(Clone)]
122pub(crate) struct HttpCacheConfig {
123    pub(crate) etags: bool,
124    pub(crate) cache_control: Option<String>,
125    vary: Vec<String>,
126}
127
128impl Default for Config {
129    fn default() -> Self {
130        Self {
131            request_ids: true,
132            error_paths: vec!["*".to_owned()],
133            versions: None,
134            resources: Vec::new(),
135            page_size: 25,
136            max_page_size: 100,
137            max_include_depth: 3,
138            http_cache: HttpCacheConfig {
139                etags: true,
140                cache_control: Some("private, no-cache".to_owned()),
141                vary: ["Api-Version", "Authorization", "Accept"]
142                    .map(str::to_owned)
143                    .to_vec(),
144            },
145            response_cache: ResponseCacheConfig {
146                enabled: true,
147                store: None,
148            },
149            auth: true,
150            client_resolver: None,
151            track_usage: true,
152            openapi: openapi::Settings::default(),
153            docs: docs::Docs::default(),
154            #[cfg(feature = "database")]
155            webhooks: webhooks::Settings::default(),
156            rate_limit: RateLimitConfig {
157                enabled: true,
158                tiers: vec![
159                    ("guest".to_owned(), rate_limit::Tier::new(60, 60)),
160                    ("default".to_owned(), rate_limit::Tier::new(300, 60)),
161                ],
162            },
163            idempotency: IdempotencyConfig {
164                enabled: true,
165                methods: ["POST", "PATCH", "DELETE"].map(str::to_owned).to_vec(),
166                ttl: 60 * 60 * 24,
167                lock_seconds: 60,
168                store: None,
169            },
170        }
171    }
172}
173
174impl Config {
175    /// The defaults: request IDs on, every path's errors rendered as JSON:API, versioning off.
176    #[must_use]
177    pub fn new() -> Self {
178        Self::default()
179    }
180
181    /// Whether responses carry `X-Request-Id` and errors `meta.request_id`.
182    #[must_use]
183    pub const fn request_ids(mut self, enabled: bool) -> Self {
184        self.request_ids = enabled;
185        self
186    }
187
188    /// The paths whose errors render as JSON:API error documents, such as `v1/*`. `*` matches anything.
189    #[must_use]
190    pub fn error_paths<I: IntoIterator<Item = S>, S: Into<String>>(mut self, paths: I) -> Self {
191        self.error_paths = paths.into_iter().map(Into::into).collect();
192        self
193    }
194
195    /// Turns on date-based versioning.
196    #[must_use]
197    pub fn versions(mut self, versions: Versions) -> Self {
198        self.versions = Some(versions);
199        self
200    }
201
202    /// Registers a JSON:API resource type, for queries, includes and the OpenAPI document.
203    #[must_use]
204    pub fn resource(mut self, resource: Resource) -> Self {
205        self.resources.retain(|known| known.kind != resource.kind);
206        self.resources.push(resource);
207        self
208    }
209
210    /// The page size when a request sets none (`api.query.page_size`, 25), and the largest a
211    /// request may ask for (`api.query.max_page_size`, 100).
212    #[must_use]
213    pub const fn page_sizes(mut self, default: u64, max: u64) -> Self {
214        self.page_size = default;
215        self.max_page_size = max;
216        self
217    }
218
219    /// How deep `include` paths may nest (`api.query.max_include_depth`, 3).
220    #[must_use]
221    pub const fn max_include_depth(mut self, depth: usize) -> Self {
222        self.max_include_depth = depth;
223        self
224    }
225
226    /// Whether successful GET responses carry a weak `ETag` and answer `If-None-Match` with a 304
227    /// (`api.http_cache.etags`, on).
228    #[must_use]
229    pub const fn etags(mut self, enabled: bool) -> Self {
230        self.http_cache.etags = enabled;
231        self
232    }
233
234    /// The `Cache-Control` of successful GET responses whose route sets none with
235    /// [`CacheControl`] (`api.http_cache.cache_control`, `private, no-cache`). `None` leaves the
236    /// handler's own, or the default `no-cache, private`.
237    #[must_use]
238    pub fn cache_control(mut self, directives: Option<&str>) -> Self {
239        self.http_cache.cache_control = directives.map(str::to_owned);
240        self
241    }
242
243    /// The request headers GET and HEAD responses vary on (`api.http_cache.vary`,
244    /// `Api-Version, Authorization, Accept`). `Api-Version` is left out while versioning is off.
245    #[must_use]
246    pub fn vary<I: IntoIterator<Item = S>, S: Into<String>>(mut self, headers: I) -> Self {
247        self.http_cache.vary = headers.into_iter().map(Into::into).collect();
248        self
249    }
250
251    /// Whether routes with [`CacheResponse`] are cached (`api.response_cache.enabled`, on).
252    #[must_use]
253    pub const fn response_cache(mut self, enabled: bool) -> Self {
254        self.response_cache.enabled = enabled;
255        self
256    }
257
258    /// The cache store that keeps cached responses (`api.response_cache.store`), or `None` for
259    /// the default store. Pass the same name to [`response_cache::flush_in`].
260    #[must_use]
261    pub fn response_cache_store(mut self, store: Option<&str>) -> Self {
262        self.response_cache.store = store.map(str::to_owned);
263        self
264    }
265
266    /// Whether requests are resolved to API clients (`api.auth.enabled`, on). Off, every request
267    /// is a guest's.
268    #[must_use]
269    pub const fn auth(mut self, enabled: bool) -> Self {
270        self.auth = enabled;
271        self
272    }
273
274    /// Your own authentication, tried before the crate's API keys, as `api.auth.guards` and
275    /// `api.auth.resolvers` add guards in PHP. See [`auth::resolver`].
276    #[must_use]
277    pub fn client_resolver(mut self, resolver: auth::ClientResolver) -> Self {
278        self.client_resolver = Some(resolver);
279        self
280    }
281
282    /// Whether each client's versions are recorded in `api_version_usage`, once a day per version
283    /// (`api.versions.track_usage`, on). Needs the `database` feature.
284    #[must_use]
285    pub const fn track_usage(mut self, enabled: bool) -> Self {
286        self.track_usage = enabled;
287        self
288    }
289
290    /// How webhook deliveries are sent: the request timeout in seconds (`api.webhooks.timeout`,
291    /// 10), the delays in seconds before each retry (`api.webhooks.backoff`, a minute up to 12
292    /// hours), and after how many failed deliveries in a row an endpoint is disabled
293    /// (`api.webhooks.disable_after`, 5; `None` never disables it).
294    #[cfg(feature = "database")]
295    #[must_use]
296    pub fn webhook_delivery(
297        mut self,
298        timeout: u64,
299        backoff: Vec<u64>,
300        disable_after: Option<i64>,
301    ) -> Self {
302        self.webhooks.timeout = timeout;
303        self.webhooks.backoff = backoff;
304        self.webhooks.disable_after = disable_after;
305        self
306    }
307
308    /// The queue connection and queue webhook deliveries go to (`api.webhooks.connection` and
309    /// `api.webhooks.queue`), or `None` for the defaults.
310    #[cfg(feature = "database")]
311    #[must_use]
312    pub fn webhook_queue(mut self, connection: Option<&str>, queue: Option<&str>) -> Self {
313        self.webhooks.connection = connection.map(str::to_owned);
314        self.webhooks.queue = queue.map(str::to_owned);
315        self
316    }
317
318    /// Describes an endpoint for the OpenAPI document, by its method and URI, such as
319    /// `GET /v1/orders`.
320    #[must_use]
321    pub fn endpoint(mut self, route: &str, endpoint: openapi::Endpoint) -> Self {
322        self.openapi.endpoints.retain(|(known, _)| known != route);
323        self.openapi.endpoints.push((route.to_owned(), endpoint));
324        self
325    }
326
327    /// The API reference and changelog pages that [`docs::routes`] mounts (`api.docs`).
328    #[must_use]
329    pub fn docs(mut self, docs: docs::Docs) -> Self {
330        self.docs = docs;
331        self
332    }
333
334    /// The OpenAPI document's title and description (`api.openapi.title`, the app's name, and
335    /// `api.openapi.description`).
336    #[must_use]
337    pub fn openapi_info(mut self, title: &str, description: Option<&str>) -> Self {
338        self.openapi.title = Some(title.to_owned());
339        self.openapi.description = description.map(str::to_owned);
340        self
341    }
342
343    /// The servers the OpenAPI document lists (`api.openapi.servers`, `APP_URL`).
344    #[must_use]
345    pub fn openapi_servers<I: IntoIterator<Item = S>, S: Into<String>>(mut self, urls: I) -> Self {
346        self.openapi.servers = Some(urls.into_iter().map(Into::into).collect());
347        self
348    }
349
350    /// The document's version while API versioning is off (`api.openapi.version`, `1.0.0`).
351    #[must_use]
352    pub fn openapi_version(mut self, version: &str) -> Self {
353        version.clone_into(&mut self.openapi.version);
354        self
355    }
356
357    /// The application's own error codes, listed in the OpenAPI document with the package's
358    /// (`api.openapi.error_codes`).
359    #[must_use]
360    pub fn error_codes<I: IntoIterator<Item = Arc<dyn errors::ErrorCode>>>(
361        mut self,
362        codes: I,
363    ) -> Self {
364        self.openapi.error_codes.extend(codes);
365        self
366    }
367
368    /// Whether requests are rate limited (`api.rate_limit.enabled`, on).
369    #[must_use]
370    pub const fn rate_limit(mut self, enabled: bool) -> Self {
371        self.rate_limit.enabled = enabled;
372        self
373    }
374
375    /// Sets a rate limit tier (`api.rate_limit.tiers`), or removes it with `None`. Guests use
376    /// `guest` (60 requests a minute), and clients their own tier or `default` (300 a minute).
377    #[must_use]
378    pub fn rate_limit_tier(
379        mut self,
380        name: &str,
381        tier: impl Into<Option<rate_limit::Tier>>,
382    ) -> Self {
383        self.rate_limit.tiers.retain(|(known, _)| known != name);
384        if let Some(tier) = tier.into() {
385            self.rate_limit.tiers.push((name.to_owned(), tier));
386        }
387        self
388    }
389
390    /// Whether requests with an `Idempotency-Key` run once (`api.idempotency.enabled`, on).
391    #[must_use]
392    pub const fn idempotency(mut self, enabled: bool) -> Self {
393        self.idempotency.enabled = enabled;
394        self
395    }
396
397    /// The methods idempotency keys apply to (`api.idempotency.methods`, POST, PATCH and DELETE).
398    #[must_use]
399    pub fn idempotent_methods<I: IntoIterator<Item = S>, S: Into<String>>(
400        mut self,
401        methods: I,
402    ) -> Self {
403        self.idempotency.methods = methods
404            .into_iter()
405            .map(|method| method.into().to_uppercase())
406            .collect();
407        self
408    }
409
410    /// How long responses are kept for replays, in seconds (`api.idempotency.ttl`, a day), and how
411    /// long a request holds its key while it runs (`api.idempotency.lock_seconds`, 60).
412    #[must_use]
413    pub const fn idempotency_times(mut self, ttl: u64, lock_seconds: u64) -> Self {
414        self.idempotency.ttl = ttl;
415        self.idempotency.lock_seconds = lock_seconds;
416        self
417    }
418
419    /// The cache store that keeps idempotent responses and locks (`api.idempotency.store`), or
420    /// `None` for the default store. It must support atomic locks.
421    #[must_use]
422    pub fn idempotency_store(mut self, store: Option<&str>) -> Self {
423        self.idempotency.store = store.map(str::to_owned);
424        self
425    }
426
427    pub(crate) fn vary_headers(&self) -> Vec<String> {
428        self.http_cache
429            .vary
430            .iter()
431            .filter(|name| {
432                self.versions.is_some() || !name.eq_ignore_ascii_case(versioning::HEADER)
433            })
434            .cloned()
435            .collect()
436    }
437
438    pub(crate) fn resource_named(&self, kind: &str) -> Option<&Resource> {
439        self.resources.iter().find(|resource| resource.kind == kind)
440    }
441}
442
443/// What the middleware learned about a request, for handlers' queries: the configuration, the
444/// resolved version with the changes newer than it, and the route's name.
445#[derive(Clone)]
446pub(crate) struct Context {
447    pub(crate) state: Arc<State>,
448    pub(crate) version: Option<(ApiVersion, Vec<Arc<dyn VersionChange>>)>,
449    pub(crate) route: String,
450    /// The API client, or `None` for a guest.
451    pub(crate) client: Option<auth::ApiClient>,
452}
453
454pub(crate) struct State {
455    pub(crate) config: Config,
456    registry: Option<Registry>,
457}
458
459/// Fusion Stack: a service provider that renders errors, and the middleware for API routes.
460/// Cloning it is cheap, and every clone shares the same configuration.
461#[derive(Clone)]
462pub struct FusionStack(Arc<State>);
463
464impl FusionStack {
465    /// Builds Fusion Stack from its configuration.
466    ///
467    /// # Panics
468    ///
469    /// When the versioning configuration is invalid, such as a default newer than the latest
470    /// version, with a message that says what to fix.
471    #[must_use]
472    pub fn new(config: Config) -> Self {
473        let registry = config.versions.as_ref().map(Registry::new);
474        Self(Arc::new(State { config, registry }))
475    }
476}
477
478/// The registered Fusion Stack, for work outside a request, such as webhook deliveries.
479static STATE: OnceLock<Arc<State>> = OnceLock::new();
480
481impl ServiceProvider for FusionStack {
482    fn register(&self, app: &mut Registrar) {
483        let _ = STATE.set(Arc::clone(&self.0));
484        let state = Arc::clone(&self.0);
485        app.errors().respond(move |response, error, request| {
486            errors::render(&state, response, error, request)
487        });
488        app.middleware().append(errors::AllowHeader);
489        console::register(app.commands());
490        app.middleware().append(http_cache::DefaultCacheControl);
491        // The api_keys, api_version_usage and webhook tables, as the PHP package's migrations make them.
492        #[cfg(feature = "database")]
493        app.migrations()
494            .add(laravel::db::migrations!("database/migrations"));
495    }
496}
497
498impl Middleware for FusionStack {
499    fn handle(
500        &self,
501        request: Request,
502        next: Next,
503    ) -> impl Future<Output = laravel::Result<Response>> + Send {
504        handle(Arc::clone(&self.0), request, next)
505    }
506}
507
508fn set(response: Response, name: &str, value: &str) -> Response {
509    let mut http = response.into_http();
510    if let (Ok(name), Ok(value)) = (HeaderName::try_from(name), HeaderValue::try_from(value)) {
511        http.headers_mut().insert(name, value);
512    }
513    Response::from_http(http)
514}
515
516async fn handle(state: Arc<State>, mut request: Request, next: Next) -> laravel::Result<Response> {
517    let id = state
518        .config
519        .request_ids
520        .then(|| request_id::assign(&mut request));
521    let client = if state.config.auth {
522        auth::resolve(state.config.client_resolver.as_ref(), &request).await?
523    } else {
524        None
525    };
526    let context = Context {
527        state: Arc::clone(&state),
528        version: None,
529        route: route_of(&request),
530        client,
531    };
532    request.extensions_mut().insert(context);
533
534    let response = match &state.registry {
535        None => {
536            let client = request
537                .extension::<Context>()
538                .and_then(|c| c.client.clone());
539            let counted =
540                match rate_limit::hit(&state.config, client.as_ref(), &request.ip().to_string())
541                    .await
542                {
543                    Ok(counted) => counted,
544                    Err(error) => return Ok(finish(error_response(&state, *error, &request), id)),
545                };
546            let outcome = idempotency::guard(&state.config, "", request, async |request| {
547                let (method, if_none_match) = cache_inputs(&request);
548                let response = next.run(request).await;
549                http_cache::apply(
550                    &state.config,
551                    &method,
552                    if_none_match.as_deref(),
553                    "",
554                    response,
555                )
556                .await
557            })
558            .await;
559            let response = match outcome {
560                Ok(response) => response,
561                Err(failed) => error_response(&state, failed.0, &failed.1),
562            };
563            rate_limit::add_headers(counted, response).await
564        }
565        Some(registry) => versioned(&state, registry, request, next).await?,
566    };
567
568    Ok(finish(response, id))
569}
570
571fn finish(response: Response, id: Option<request_id::RequestId>) -> Response {
572    match id {
573        Some(id) => set(response, request_id::HEADER, id.as_str()),
574        None => response,
575    }
576}
577
578fn cache_inputs(request: &Request) -> (laravel::axum::http::Method, Option<String>) {
579    (
580        request.method().clone(),
581        request.header("if-none-match").map(str::to_owned),
582    )
583}
584
585/// The route as version changes name it: its method and URI pattern, such as `GET /v1/orders/{order}`.
586fn route_of(request: &Request) -> String {
587    let uri = request
588        .current_route()
589        .map_or_else(|| request.path().to_owned(), |route| route.uri().to_owned());
590    format!("{} {uri}", request.method())
591}
592
593async fn versioned(
594    state: &State,
595    registry: &Registry,
596    mut request: Request,
597    next: Next,
598) -> laravel::Result<Response> {
599    // Errors here have no version yet, so they go to the application's error handler as they are.
600    // The header, then the client's pinned version, then the default.
601    let pinned = request
602        .extension::<Context>()
603        .and_then(|context| context.client.as_ref()?.version.clone());
604    let header = request
605        .header(versioning::HEADER)
606        .map(str::trim)
607        .filter(|header| !header.is_empty())
608        .or(pinned.as_deref());
609    let version = registry
610        .resolve(header, time::now())
611        .map_err(|error| error.into_error())?;
612
613    #[cfg(feature = "database")]
614    if state.config.track_usage
615        && let Some(client) = request
616            .extension::<Context>()
617            .and_then(|context| context.client.as_ref())
618    {
619        usage::record(client, &version).await;
620    }
621
622    let route = route_of(&request);
623    let path = request.path().trim_start_matches('/').to_owned();
624    let method = request.method().to_string();
625
626    let response = match registry.assert_route_available(&route, &method, &path, &version) {
627        Err(error) => error_response(state, *error, &request),
628        Ok(()) => {
629            let legacy = registry.legacy_handler(&route, &version);
630            let before = legacy.as_ref().map(|(_, date)| date.clone());
631            let changes = registry.changes_after(&version, before.as_deref());
632            if let Some(context) = request.extensions_mut().get_mut::<Context>() {
633                context.version = Some((version.clone(), changes.clone()));
634            }
635
636            let client = request
637                .extension::<Context>()
638                .and_then(|c| c.client.clone());
639            let counted =
640                match rate_limit::hit(&state.config, client.as_ref(), &request.ip().to_string())
641                    .await
642                {
643                    Ok(counted) => counted,
644                    Err(error) => {
645                        return Ok(headers_for(
646                            registry,
647                            &version,
648                            error_response(state, *error, &request),
649                        ));
650                    }
651                };
652            let variant = format!(
653                "{version}\n{}",
654                changes
655                    .iter()
656                    .map(|change| change.description())
657                    .collect::<Vec<_>>()
658                    .join(",")
659            );
660            let outcome = idempotency::guard(
661                &state.config,
662                &version.to_string(),
663                request,
664                async |mut request| {
665                    if !changes.is_empty() {
666                        let (changes, route) = (changes.clone(), route.clone());
667                        request.transform_input(move |payload| {
668                            let types =
669                                versioning::document::types(&Value::Object(payload.clone()));
670                            for change in &changes {
671                                if versioning::applies_to(change.as_ref(), &types, &route) {
672                                    change.transform_request(payload);
673                                }
674                            }
675                        });
676                    }
677                    let (method, if_none_match) = cache_inputs(&request);
678                    let response = match legacy {
679                        Some((handler, _)) => match handler(request).await {
680                            Ok(response) => response,
681                            // The error handler renders it on the way out, as it would a handler's error.
682                            Err(error) => Response::new(error),
683                        },
684                        None => next.run(request).await,
685                    };
686                    let response = http_cache::apply(
687                        &state.config,
688                        &method,
689                        if_none_match.as_deref(),
690                        &variant,
691                        response,
692                    )
693                    .await;
694                    transform_response(response, &changes, &route).await
695                },
696            )
697            .await;
698            let response = match outcome {
699                Ok(response) => response,
700                Err(failed) => error_response(state, failed.0, &failed.1),
701            };
702            rate_limit::add_headers(counted, response).await
703        }
704    };
705
706    Ok(headers_for(registry, &version, response))
707}
708
709/// Renders an error to a response here, rather than returning it, so the version and deprecation
710/// headers still go on it.
711fn error_response(state: &State, error: ApiError, request: &Request) -> Response {
712    let status = laravel::http::StatusCode::from_u16(error.status())
713        .unwrap_or(laravel::http::StatusCode::INTERNAL_SERVER_ERROR);
714    let headers = error.headers.clone();
715    let error = error.into_error();
716    let mut response = errors::render(state, Response::new(status), &error, request);
717    for (name, value) in headers {
718        response = set(response, &name, &value);
719    }
720    response
721}
722
723/// Adds the `Api-Version` header and, for deprecated versions, `Deprecation`, `Sunset` and `Link`.
724fn headers_for(registry: &Registry, version: &ApiVersion, response: Response) -> Response {
725    let mut response = set(response, "api-version", &version.to_string());
726    if let Some(deprecation) = registry.deprecation(version) {
727        response = set(response, "deprecation", &format!("@{}", deprecation.since));
728        if let Some(sunset) = deprecation.sunset {
729            response = set(response, "sunset", &time::http_date(sunset));
730        }
731        if let Some(url) = registry
732            .changelog_url
733            .as_ref()
734            .or(registry.upgrade_guide_url.as_ref())
735        {
736            response = set(
737                response,
738                "link",
739                &format!("<{url}>; rel=\"deprecation\"; type=\"text/html\""),
740            );
741        }
742    }
743    response
744}
745
746/// Runs the version changes' response transforms, newest first, on a JSON response.
747async fn transform_response(
748    response: Response,
749    changes: &[Arc<dyn versioning::VersionChange>],
750    route: &str,
751) -> Response {
752    if changes.is_empty() {
753        return response;
754    }
755    let http = response.into_http();
756    let is_json = http
757        .headers()
758        .get(laravel::axum::http::header::CONTENT_TYPE)
759        .and_then(|value| value.to_str().ok())
760        .is_some_and(|value| value.contains("json"));
761    if !is_json {
762        return Response::from_http(http);
763    }
764
765    let (mut parts, body) = http.into_parts();
766    let Ok(bytes) = to_bytes(body, usize::MAX).await else {
767        return Response::from_http(laravel::axum::http::Response::from_parts(
768            parts,
769            Body::empty(),
770        ));
771    };
772    let Ok(mut document) = serde_json::from_slice::<Value>(&bytes) else {
773        return Response::from_http(laravel::axum::http::Response::from_parts(
774            parts,
775            Body::from(bytes),
776        ));
777    };
778
779    let types = versioning::document::types(&document);
780    for change in changes.iter().rev() {
781        if versioning::applies_to(change.as_ref(), &types, route) {
782            change.transform_response(&mut document);
783        }
784    }
785
786    let body = serde_json::to_vec(&document).unwrap_or_else(|_| bytes.to_vec());
787    parts
788        .headers
789        .remove(laravel::axum::http::header::CONTENT_LENGTH);
790    Response::from_http(laravel::axum::http::Response::from_parts(
791        parts,
792        Body::from(body),
793    ))
794}
795
796/// Whether `text` matches `pattern`, where `*` matches any run of characters.
797pub(crate) fn glob(pattern: &str, text: &str) -> bool {
798    let mut parts = pattern.split('*');
799    let first = parts.next().unwrap_or_default();
800    let Some(mut rest) = text.strip_prefix(first) else {
801        return false;
802    };
803    let parts: Vec<&str> = parts.collect();
804    let Some((last, middle)) = parts.split_last() else {
805        return rest.is_empty();
806    };
807    for part in middle {
808        match rest.find(part) {
809            Some(index) => rest = &rest[index + part.len()..],
810            None => return false,
811        }
812    }
813    rest.len() >= last.len() && rest.ends_with(last)
814}
815
816#[cfg(test)]
817mod tests {
818    use super::glob;
819
820    #[test]
821    fn globs_match_like_laravels_str_is() {
822        assert!(glob("*", "anything"));
823        assert!(glob("v1/*", "v1/orders/1"));
824        assert!(!glob("v1/*", "v2/orders"));
825        assert!(glob(
826            "GET /v1/orders/*/summary",
827            "GET /v1/orders/{order}/summary"
828        ));
829        assert!(!glob("GET /v1/orders", "GET /v1/orders/{order}"));
830        assert!(glob("a*b*c", "abc"));
831        assert!(!glob("a*bc", "abc*"));
832    }
833}