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