fusion-stack-laravel-rust 0.3.0

Fusion Stack for Laravel for Rust: versioned, documented JSON APIs with standard errors
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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
//! Fusion Stack for Laravel for Rust: the same API format as the `fusion-stack/laravel` PHP
//! package, so `@fusion-stack/client` works unchanged against either backend.
//!
//! Register [`FusionStack`] as a service provider, which renders every error as a JSON:API error
//! document, and attach it as middleware to your API routes:
//!
//! ```no_run
//! use fusion_stack::{Config, FusionStack};
//! use fusion_stack::versioning::Versions;
//! use laravel::prelude::*;
//!
//! # async fn index() -> &'static str { "[]" }
//! let api = FusionStack::new(Config::new().versions(Versions::new("2026-11-30")));
//!
//! Application::configure()
//!     .with_providers({
//!         let api = api.clone();
//!         move |providers| {
//!             providers.add(api);
//!         }
//!     })
//!     .with_routing(move |routing, _| {
//!         let api = api.clone();
//!         routing.api(move |route| {
//!             route.prefix("/v1").middleware(api).group(|route| {
//!                 route.get("/orders", index);
//!             });
//!         });
//!     });
//! ```

// Resource rendering, query strings and name translation serve ApiQuery, which needs a database.
#![cfg_attr(not(feature = "database"), allow(dead_code))]

pub mod auth;
pub mod console;
pub mod docs;
pub mod errors;
mod http_cache;
pub mod idempotency;
pub mod openapi;
#[cfg(feature = "database")]
pub mod query;
mod query_string;
pub mod rate_limit;
pub mod request_id;
pub mod resources;
pub mod response_cache;
pub mod testing;
mod time;
#[cfg(feature = "database")]
pub mod usage;
pub mod versioning;
pub mod webhooks;

use std::sync::{Arc, OnceLock};

use laravel::axum::body::{Body, to_bytes};
use laravel::axum::http::{HeaderName, HeaderValue};
use laravel::container::Registrar;
use laravel::foundation::ServiceProvider;
use laravel::http::{Middleware, Next, Request, Response};
use serde_json::Value;

pub use crate::auth::RequiresScope;
pub use crate::http_cache::CacheControl;
pub use crate::response_cache::CacheResponse;

use crate::errors::ApiError;
use crate::resources::Resource;
use crate::versioning::{ApiVersion, Registry, VersionChange, Versions};

/// Fusion Stack's settings, mirroring `config/api.php` in the PHP package.
#[derive(Clone)]
pub struct Config {
    pub(crate) request_ids: bool,
    pub(crate) error_paths: Vec<String>,
    versions: Option<Versions>,
    pub(crate) resources: Vec<Resource>,
    pub(crate) page_size: u64,
    pub(crate) max_page_size: u64,
    pub(crate) max_include_depth: usize,
    pub(crate) http_cache: HttpCacheConfig,
    pub(crate) response_cache: ResponseCacheConfig,
    pub(crate) idempotency: IdempotencyConfig,
    pub(crate) auth: bool,
    pub(crate) client_resolver: Option<auth::ClientResolver>,
    #[cfg(feature = "database")]
    pub(crate) test_keys_in_production: bool,
    pub(crate) rate_limit: RateLimitConfig,
    pub(crate) track_usage: bool,
    pub(crate) openapi: openapi::Settings,
    pub(crate) docs: docs::Docs,
    #[cfg(feature = "database")]
    pub(crate) webhooks: webhooks::Settings,
}

/// `api.rate_limit` in the PHP package.
#[derive(Clone)]
pub(crate) struct RateLimitConfig {
    pub(crate) enabled: bool,
    pub(crate) tiers: Vec<(String, rate_limit::Tier)>,
}

/// `api.idempotency` in the PHP package.
#[derive(Clone)]
pub(crate) struct IdempotencyConfig {
    pub(crate) enabled: bool,
    pub(crate) methods: Vec<String>,
    pub(crate) ttl: u64,
    pub(crate) lock_seconds: u64,
    pub(crate) store: Option<String>,
}

/// `api.response_cache` in the PHP package.
#[derive(Clone)]
pub(crate) struct ResponseCacheConfig {
    pub(crate) enabled: bool,
    pub(crate) store: Option<String>,
}

/// `api.http_cache` in the PHP package.
#[derive(Clone)]
pub(crate) struct HttpCacheConfig {
    pub(crate) etags: bool,
    pub(crate) cache_control: Option<String>,
    vary: Vec<String>,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            request_ids: true,
            error_paths: vec!["*".to_owned()],
            versions: None,
            resources: Vec::new(),
            page_size: 25,
            max_page_size: 100,
            max_include_depth: 3,
            http_cache: HttpCacheConfig {
                etags: true,
                cache_control: Some("private, no-cache".to_owned()),
                vary: ["Api-Version", "Authorization", "Accept"]
                    .map(str::to_owned)
                    .to_vec(),
            },
            response_cache: ResponseCacheConfig {
                enabled: true,
                store: None,
            },
            auth: true,
            client_resolver: None,
            #[cfg(feature = "database")]
            test_keys_in_production: false,
            track_usage: true,
            openapi: openapi::Settings::default(),
            docs: docs::Docs::default(),
            #[cfg(feature = "database")]
            webhooks: webhooks::Settings::default(),
            rate_limit: RateLimitConfig {
                enabled: true,
                tiers: vec![
                    ("guest".to_owned(), rate_limit::Tier::new(60, 60)),
                    ("default".to_owned(), rate_limit::Tier::new(300, 60)),
                ],
            },
            idempotency: IdempotencyConfig {
                enabled: true,
                methods: ["POST", "PATCH", "DELETE"].map(str::to_owned).to_vec(),
                ttl: 60 * 60 * 24,
                lock_seconds: 60,
                store: None,
            },
        }
    }
}

impl Config {
    /// The defaults: request IDs on, every path's errors rendered as JSON:API, versioning off.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Whether responses carry `X-Request-Id` and errors `meta.request_id`.
    #[must_use]
    pub const fn request_ids(mut self, enabled: bool) -> Self {
        self.request_ids = enabled;
        self
    }

    /// The paths whose errors render as JSON:API error documents, such as `v1/*`. `*` matches anything.
    #[must_use]
    pub fn error_paths<I: IntoIterator<Item = S>, S: Into<String>>(mut self, paths: I) -> Self {
        self.error_paths = paths.into_iter().map(Into::into).collect();
        self
    }

    /// Turns on date-based versioning.
    #[must_use]
    pub fn versions(mut self, versions: Versions) -> Self {
        self.versions = Some(versions);
        self
    }

    /// Registers a JSON:API resource type, for queries, includes and the OpenAPI document.
    #[must_use]
    pub fn resource(mut self, resource: Resource) -> Self {
        self.resources.retain(|known| known.kind != resource.kind);
        self.resources.push(resource);
        self
    }

    /// The page size when a request sets none (`api.query.page_size`, 25), and the largest a
    /// request may ask for (`api.query.max_page_size`, 100).
    #[must_use]
    pub const fn page_sizes(mut self, default: u64, max: u64) -> Self {
        self.page_size = default;
        self.max_page_size = max;
        self
    }

    /// How deep `include` paths may nest (`api.query.max_include_depth`, 3).
    #[must_use]
    pub const fn max_include_depth(mut self, depth: usize) -> Self {
        self.max_include_depth = depth;
        self
    }

    /// Whether successful GET responses carry a weak `ETag` and answer `If-None-Match` with a 304
    /// (`api.http_cache.etags`, on).
    #[must_use]
    pub const fn etags(mut self, enabled: bool) -> Self {
        self.http_cache.etags = enabled;
        self
    }

    /// The `Cache-Control` of successful GET responses whose route sets none with
    /// [`CacheControl`] (`api.http_cache.cache_control`, `private, no-cache`). `None` leaves the
    /// handler's own, or the default `no-cache, private`.
    #[must_use]
    pub fn cache_control(mut self, directives: Option<&str>) -> Self {
        self.http_cache.cache_control = directives.map(str::to_owned);
        self
    }

    /// The request headers GET and HEAD responses vary on (`api.http_cache.vary`,
    /// `Api-Version, Authorization, Accept`). `Api-Version` is left out while versioning is off.
    #[must_use]
    pub fn vary<I: IntoIterator<Item = S>, S: Into<String>>(mut self, headers: I) -> Self {
        self.http_cache.vary = headers.into_iter().map(Into::into).collect();
        self
    }

    /// Whether routes with [`CacheResponse`] are cached (`api.response_cache.enabled`, on).
    #[must_use]
    pub const fn response_cache(mut self, enabled: bool) -> Self {
        self.response_cache.enabled = enabled;
        self
    }

    /// The cache store that keeps cached responses (`api.response_cache.store`), or `None` for
    /// the default store. Pass the same name to [`response_cache::flush_in`].
    #[must_use]
    pub fn response_cache_store(mut self, store: Option<&str>) -> Self {
        self.response_cache.store = store.map(str::to_owned);
        self
    }

    /// Whether requests are resolved to API clients (`api.auth.enabled`, on). Off, every request
    /// is a guest's.
    #[must_use]
    pub const fn auth(mut self, enabled: bool) -> Self {
        self.auth = enabled;
        self
    }

    /// Your own authentication, tried before the crate's API keys, as `api.auth.guards` and
    /// `api.auth.resolvers` add guards in PHP. See [`auth::resolver`].
    #[must_use]
    pub fn client_resolver(mut self, resolver: auth::ClientResolver) -> Self {
        self.client_resolver = Some(resolver);
        self
    }

    /// Whether `fs_test_` API keys work in production (`api.auth.test_keys_in_production`, off).
    /// Test keys are for development and staging, where they are easiest to leak, so production
    /// turns them away. Needs the `database` feature.
    #[cfg(feature = "database")]
    #[must_use]
    pub const fn test_keys_in_production(mut self, allow: bool) -> Self {
        self.test_keys_in_production = allow;
        self
    }

    /// Whether each client's versions are recorded in `api_version_usage`, once a day per version
    /// (`api.versions.track_usage`, on). Needs the `database` feature.
    #[must_use]
    pub const fn track_usage(mut self, enabled: bool) -> Self {
        self.track_usage = enabled;
        self
    }

    /// How webhook deliveries are sent: the request timeout in seconds (`api.webhooks.timeout`,
    /// 10), the delays in seconds before each retry (`api.webhooks.backoff`, a minute up to 12
    /// hours), and after how many failed deliveries in a row an endpoint is disabled
    /// (`api.webhooks.disable_after`, 5; `None` never disables it).
    #[cfg(feature = "database")]
    #[must_use]
    pub fn webhook_delivery(
        mut self,
        timeout: u64,
        backoff: Vec<u64>,
        disable_after: Option<i64>,
    ) -> Self {
        self.webhooks.timeout = timeout;
        self.webhooks.backoff = backoff;
        self.webhooks.disable_after = disable_after;
        self
    }

    /// Whether webhooks may be delivered to addresses that are not on the public internet, such
    /// as localhost and private networks (`api.webhooks.allow_private_addresses`, off). Endpoint
    /// URLs often come from users, so turn it on only in development or to deliver to your own
    /// internal services. Redirects are never followed.
    #[cfg(feature = "database")]
    #[must_use]
    pub const fn webhook_private_addresses(mut self, allow: bool) -> Self {
        self.webhooks.allow_private_addresses = allow;
        self
    }

    /// The queue connection and queue webhook deliveries go to (`api.webhooks.connection` and
    /// `api.webhooks.queue`), or `None` for the defaults.
    #[cfg(feature = "database")]
    #[must_use]
    pub fn webhook_queue(mut self, connection: Option<&str>, queue: Option<&str>) -> Self {
        self.webhooks.connection = connection.map(str::to_owned);
        self.webhooks.queue = queue.map(str::to_owned);
        self
    }

    /// Describes an endpoint for the OpenAPI document, by its method and URI, such as
    /// `GET /v1/orders`.
    #[must_use]
    pub fn endpoint(mut self, route: &str, endpoint: openapi::Endpoint) -> Self {
        self.openapi.endpoints.retain(|(known, _)| known != route);
        self.openapi.endpoints.push((route.to_owned(), endpoint));
        self
    }

    /// The API reference and changelog pages that [`docs::routes`] mounts (`api.docs`).
    #[must_use]
    pub fn docs(mut self, docs: docs::Docs) -> Self {
        self.docs = docs;
        self
    }

    /// The OpenAPI document's title and description (`api.openapi.title`, the app's name, and
    /// `api.openapi.description`).
    #[must_use]
    pub fn openapi_info(mut self, title: &str, description: Option<&str>) -> Self {
        self.openapi.title = Some(title.to_owned());
        self.openapi.description = description.map(str::to_owned);
        self
    }

    /// The servers the OpenAPI document lists (`api.openapi.servers`, `APP_URL`).
    #[must_use]
    pub fn openapi_servers<I: IntoIterator<Item = S>, S: Into<String>>(mut self, urls: I) -> Self {
        self.openapi.servers = Some(urls.into_iter().map(Into::into).collect());
        self
    }

    /// The document's version while API versioning is off (`api.openapi.version`, `1.0.0`).
    #[must_use]
    pub fn openapi_version(mut self, version: &str) -> Self {
        version.clone_into(&mut self.openapi.version);
        self
    }

    /// The application's own error codes, listed in the OpenAPI document with the package's
    /// (`api.openapi.error_codes`).
    #[must_use]
    pub fn error_codes<I: IntoIterator<Item = Arc<dyn errors::ErrorCode>>>(
        mut self,
        codes: I,
    ) -> Self {
        self.openapi.error_codes.extend(codes);
        self
    }

    /// Whether requests are rate limited (`api.rate_limit.enabled`, on).
    #[must_use]
    pub const fn rate_limit(mut self, enabled: bool) -> Self {
        self.rate_limit.enabled = enabled;
        self
    }

    /// Sets a rate limit tier (`api.rate_limit.tiers`), or removes it with `None`. Guests use
    /// `guest` (60 requests a minute), and clients their own tier or `default` (300 a minute).
    #[must_use]
    pub fn rate_limit_tier(
        mut self,
        name: &str,
        tier: impl Into<Option<rate_limit::Tier>>,
    ) -> Self {
        self.rate_limit.tiers.retain(|(known, _)| known != name);
        if let Some(tier) = tier.into() {
            self.rate_limit.tiers.push((name.to_owned(), tier));
        }
        self
    }

    /// Whether requests with an `Idempotency-Key` run once (`api.idempotency.enabled`, on).
    #[must_use]
    pub const fn idempotency(mut self, enabled: bool) -> Self {
        self.idempotency.enabled = enabled;
        self
    }

    /// The methods idempotency keys apply to (`api.idempotency.methods`, POST, PATCH and DELETE).
    #[must_use]
    pub fn idempotent_methods<I: IntoIterator<Item = S>, S: Into<String>>(
        mut self,
        methods: I,
    ) -> Self {
        self.idempotency.methods = methods
            .into_iter()
            .map(|method| method.into().to_uppercase())
            .collect();
        self
    }

    /// How long responses are kept for replays, in seconds (`api.idempotency.ttl`, a day), and how
    /// long a request holds its key while it runs (`api.idempotency.lock_seconds`, 60).
    #[must_use]
    pub const fn idempotency_times(mut self, ttl: u64, lock_seconds: u64) -> Self {
        self.idempotency.ttl = ttl;
        self.idempotency.lock_seconds = lock_seconds;
        self
    }

    /// The cache store that keeps idempotent responses and locks (`api.idempotency.store`), or
    /// `None` for the default store. It must support atomic locks.
    #[must_use]
    pub fn idempotency_store(mut self, store: Option<&str>) -> Self {
        self.idempotency.store = store.map(str::to_owned);
        self
    }

    pub(crate) fn vary_headers(&self) -> Vec<String> {
        self.http_cache
            .vary
            .iter()
            .filter(|name| {
                self.versions.is_some() || !name.eq_ignore_ascii_case(versioning::HEADER)
            })
            .cloned()
            .collect()
    }

    pub(crate) fn resource_named(&self, kind: &str) -> Option<&Resource> {
        self.resources.iter().find(|resource| resource.kind == kind)
    }
}

/// What the middleware learned about a request, for handlers' queries: the configuration, the
/// resolved version with the changes newer than it, and the route's name.
#[derive(Clone)]
pub(crate) struct Context {
    pub(crate) state: Arc<State>,
    pub(crate) version: Option<(ApiVersion, Vec<Arc<dyn VersionChange>>)>,
    pub(crate) route: String,
    /// The API client, or `None` for a guest.
    pub(crate) client: Option<auth::ApiClient>,
}

pub(crate) struct State {
    pub(crate) config: Config,
    registry: Option<Registry>,
}

/// Fusion Stack: a service provider that renders errors, and the middleware for API routes.
/// Cloning it is cheap, and every clone shares the same configuration.
#[derive(Clone)]
pub struct FusionStack(Arc<State>);

impl FusionStack {
    /// Builds Fusion Stack from its configuration.
    ///
    /// # Panics
    ///
    /// When the versioning configuration is invalid, such as a default newer than the latest
    /// version, with a message that says what to fix.
    #[must_use]
    pub fn new(config: Config) -> Self {
        let registry = config.versions.as_ref().map(Registry::new);
        Self(Arc::new(State { config, registry }))
    }
}

/// The registered Fusion Stack, for work outside a request, such as webhook deliveries.
static STATE: OnceLock<Arc<State>> = OnceLock::new();

impl ServiceProvider for FusionStack {
    fn register(&self, app: &mut Registrar) {
        let _ = STATE.set(Arc::clone(&self.0));
        let state = Arc::clone(&self.0);
        app.errors().respond(move |response, error, request| {
            errors::render(&state, response, error, request)
        });
        app.middleware().append(errors::AllowHeader);
        console::register(app.commands());
        app.middleware().append(http_cache::DefaultCacheControl);
        // The api_keys, api_version_usage and webhook tables, as the PHP package's migrations make them.
        #[cfg(feature = "database")]
        app.migrations()
            .add(laravel::db::migrations!("database/migrations"));
    }
}

impl Middleware for FusionStack {
    fn handle(
        &self,
        request: Request,
        next: Next,
    ) -> impl Future<Output = laravel::Result<Response>> + Send {
        handle(Arc::clone(&self.0), request, next)
    }
}

fn set(response: Response, name: &str, value: &str) -> Response {
    let mut http = response.into_http();
    if let (Ok(name), Ok(value)) = (HeaderName::try_from(name), HeaderValue::try_from(value)) {
        http.headers_mut().insert(name, value);
    }
    Response::from_http(http)
}

async fn handle(state: Arc<State>, mut request: Request, next: Next) -> laravel::Result<Response> {
    let id = state
        .config
        .request_ids
        .then(|| request_id::assign(&mut request));
    let client = if state.config.auth {
        auth::resolve(&state.config, &request).await?
    } else {
        None
    };
    let context = Context {
        state: Arc::clone(&state),
        version: None,
        route: route_of(&request),
        client,
    };
    request.extensions_mut().insert(context);

    let response = match &state.registry {
        None => {
            let client = request
                .extension::<Context>()
                .and_then(|c| c.client.clone());
            let counted =
                match rate_limit::hit(&state.config, client.as_ref(), &request.ip().to_string())
                    .await
                {
                    Ok(counted) => counted,
                    Err(error) => return Ok(finish(error_response(&state, *error, &request), id)),
                };
            let outcome = idempotency::guard(&state.config, "", request, async |request| {
                let (method, if_none_match) = cache_inputs(&request);
                let response = next.run(request).await;
                http_cache::apply(
                    &state.config,
                    &method,
                    if_none_match.as_deref(),
                    "",
                    response,
                )
                .await
            })
            .await;
            let response = match outcome {
                Ok(response) => response,
                Err(failed) => error_response(&state, failed.0, &failed.1),
            };
            rate_limit::add_headers(counted, response).await
        }
        Some(registry) => versioned(&state, registry, request, next).await?,
    };

    Ok(finish(response, id))
}

fn finish(response: Response, id: Option<request_id::RequestId>) -> Response {
    match id {
        Some(id) => set(response, request_id::HEADER, id.as_str()),
        None => response,
    }
}

fn cache_inputs(request: &Request) -> (laravel::axum::http::Method, Option<String>) {
    (
        request.method().clone(),
        request.header("if-none-match").map(str::to_owned),
    )
}

/// The route as version changes name it: its method and URI pattern, such as `GET /v1/orders/{order}`.
fn route_of(request: &Request) -> String {
    let uri = request
        .current_route()
        .map_or_else(|| request.path().to_owned(), |route| route.uri().to_owned());
    format!("{} {uri}", request.method())
}

async fn versioned(
    state: &State,
    registry: &Registry,
    mut request: Request,
    next: Next,
) -> laravel::Result<Response> {
    // Errors here have no version yet, so they go to the application's error handler as they are.
    // The header, then the client's pinned version, then the default.
    let pinned = request
        .extension::<Context>()
        .and_then(|context| context.client.as_ref()?.version.clone());
    let header = request
        .header(versioning::HEADER)
        .map(str::trim)
        .filter(|header| !header.is_empty())
        .or(pinned.as_deref());
    let version = registry
        .resolve(header, time::now())
        .map_err(|error| error.into_error())?;

    #[cfg(feature = "database")]
    if state.config.track_usage
        && let Some(client) = request
            .extension::<Context>()
            .and_then(|context| context.client.as_ref())
    {
        usage::record(client, &version).await;
    }

    let route = route_of(&request);
    let path = request.path().trim_start_matches('/').to_owned();
    let method = request.method().to_string();

    let response = match registry.assert_route_available(&route, &method, &path, &version) {
        Err(error) => error_response(state, *error, &request),
        Ok(()) => {
            let legacy = registry.legacy_handler(&route, &version);
            let before = legacy.as_ref().map(|(_, date)| date.clone());
            let changes = registry.changes_after(&version, before.as_deref());
            if let Some(context) = request.extensions_mut().get_mut::<Context>() {
                context.version = Some((version.clone(), changes.clone()));
            }

            let client = request
                .extension::<Context>()
                .and_then(|c| c.client.clone());
            let counted =
                match rate_limit::hit(&state.config, client.as_ref(), &request.ip().to_string())
                    .await
                {
                    Ok(counted) => counted,
                    Err(error) => {
                        return Ok(headers_for(
                            registry,
                            &version,
                            error_response(state, *error, &request),
                        ));
                    }
                };
            let variant = format!(
                "{version}\n{}",
                changes
                    .iter()
                    .map(|change| change.description())
                    .collect::<Vec<_>>()
                    .join(",")
            );
            let outcome = idempotency::guard(
                &state.config,
                &version.to_string(),
                request,
                async |mut request| {
                    if !changes.is_empty() {
                        let (changes, route) = (changes.clone(), route.clone());
                        request.transform_input(move |payload| {
                            let types =
                                versioning::document::types(&Value::Object(payload.clone()));
                            for change in &changes {
                                if versioning::applies_to(change.as_ref(), &types, &route) {
                                    change.transform_request(payload);
                                }
                            }
                        });
                    }
                    let (method, if_none_match) = cache_inputs(&request);
                    let response = match legacy {
                        Some((handler, _)) => match handler(request).await {
                            Ok(response) => response,
                            // The error handler renders it on the way out, as it would a handler's error.
                            Err(error) => Response::new(error),
                        },
                        None => next.run(request).await,
                    };
                    let response = http_cache::apply(
                        &state.config,
                        &method,
                        if_none_match.as_deref(),
                        &variant,
                        response,
                    )
                    .await;
                    transform_response(response, &changes, &route).await
                },
            )
            .await;
            let response = match outcome {
                Ok(response) => response,
                Err(failed) => error_response(state, failed.0, &failed.1),
            };
            rate_limit::add_headers(counted, response).await
        }
    };

    Ok(headers_for(registry, &version, response))
}

/// Renders an error to a response here, rather than returning it, so the version and deprecation
/// headers still go on it.
fn error_response(state: &State, error: ApiError, request: &Request) -> Response {
    let status = laravel::http::StatusCode::from_u16(error.status())
        .unwrap_or(laravel::http::StatusCode::INTERNAL_SERVER_ERROR);
    let headers = error.headers.clone();
    let error = error.into_error();
    let mut response = errors::render(state, Response::new(status), &error, request);
    for (name, value) in headers {
        response = set(response, &name, &value);
    }
    response
}

/// Adds the `Api-Version` header and, for deprecated versions, `Deprecation`, `Sunset` and `Link`.
fn headers_for(registry: &Registry, version: &ApiVersion, response: Response) -> Response {
    let mut response = set(response, "api-version", &version.to_string());
    if let Some(deprecation) = registry.deprecation(version) {
        response = set(response, "deprecation", &format!("@{}", deprecation.since));
        if let Some(sunset) = deprecation.sunset {
            response = set(response, "sunset", &time::http_date(sunset));
        }
        if let Some(url) = registry
            .changelog_url
            .as_ref()
            .or(registry.upgrade_guide_url.as_ref())
        {
            response = set(
                response,
                "link",
                &format!("<{url}>; rel=\"deprecation\"; type=\"text/html\""),
            );
        }
    }
    response
}

/// Runs the version changes' response transforms, newest first, on a JSON response.
async fn transform_response(
    response: Response,
    changes: &[Arc<dyn versioning::VersionChange>],
    route: &str,
) -> Response {
    if changes.is_empty() {
        return response;
    }
    let http = response.into_http();
    let is_json = http
        .headers()
        .get(laravel::axum::http::header::CONTENT_TYPE)
        .and_then(|value| value.to_str().ok())
        .is_some_and(|value| value.contains("json"));
    if !is_json {
        return Response::from_http(http);
    }

    let (mut parts, body) = http.into_parts();
    let Ok(bytes) = to_bytes(body, usize::MAX).await else {
        return Response::from_http(laravel::axum::http::Response::from_parts(
            parts,
            Body::empty(),
        ));
    };
    let Ok(mut document) = serde_json::from_slice::<Value>(&bytes) else {
        return Response::from_http(laravel::axum::http::Response::from_parts(
            parts,
            Body::from(bytes),
        ));
    };

    let types = versioning::document::types(&document);
    for change in changes.iter().rev() {
        if versioning::applies_to(change.as_ref(), &types, route) {
            change.transform_response(&mut document);
        }
    }

    let body = serde_json::to_vec(&document).unwrap_or_else(|_| bytes.to_vec());
    parts
        .headers
        .remove(laravel::axum::http::header::CONTENT_LENGTH);
    Response::from_http(laravel::axum::http::Response::from_parts(
        parts,
        Body::from(body),
    ))
}

/// Whether `text` matches `pattern`, where `*` matches any run of characters.
pub(crate) fn glob(pattern: &str, text: &str) -> bool {
    let mut parts = pattern.split('*');
    let first = parts.next().unwrap_or_default();
    let Some(mut rest) = text.strip_prefix(first) else {
        return false;
    };
    let parts: Vec<&str> = parts.collect();
    let Some((last, middle)) = parts.split_last() else {
        return rest.is_empty();
    };
    for part in middle {
        match rest.find(part) {
            Some(index) => rest = &rest[index + part.len()..],
            None => return false,
        }
    }
    rest.len() >= last.len() && rest.ends_with(last)
}

#[cfg(test)]
mod tests {
    use super::glob;

    #[test]
    fn globs_match_like_laravels_str_is() {
        assert!(glob("*", "anything"));
        assert!(glob("v1/*", "v1/orders/1"));
        assert!(!glob("v1/*", "v2/orders"));
        assert!(glob(
            "GET /v1/orders/*/summary",
            "GET /v1/orders/{order}/summary"
        ));
        assert!(!glob("GET /v1/orders", "GET /v1/orders/{order}"));
        assert!(glob("a*b*c", "abc"));
        assert!(!glob("a*bc", "abc*"));
    }
}