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
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
//! Date-based API versions: resolving the `Api-Version` header, deprecation and retirement, and
//! the version changes that let older clients keep the shape they were built against.

use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;

use laravel::http::{Request, Response};
use serde_json::{Map, Value, json};

use crate::errors::{ApiError, ApiErrorCode};
use crate::time;

/// The header that pins a request to a version, and that responses echo.
pub const HEADER: &str = "api-version";

/// A date-based API version: `YYYY-MM-DD` with an optional release name, as in `2027-01-15.atlas`.
/// Versions compare by date; the name is a label for the release the version belongs to.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ApiVersion {
    /// The date, `YYYY-MM-DD`.
    pub date: String,
    /// The release name, such as `atlas`.
    pub name: Option<String>,
}

impl ApiVersion {
    /// Parses a version, or returns `None` when it is not `YYYY-MM-DD[.name]` or the date does
    /// not exist.
    #[must_use]
    pub fn parse(value: &str) -> Option<Self> {
        let (date, name) = match value.split_once('.') {
            Some((date, name)) => (date, Some(name)),
            None => (value, None),
        };
        time::parse_date(date)?;
        if let Some(name) = name {
            let mut chars = name.chars();
            let first_ok = chars.next().is_some_and(|c| c.is_ascii_lowercase());
            if !first_ok || !chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
            {
                return None;
            }
        }
        Some(Self {
            date: date.to_owned(),
            name: name.map(str::to_owned),
        })
    }

    fn must(value: &str) -> Self {
        Self::parse(value).unwrap_or_else(|| {
            panic!("[{value}] is not a valid API version. Use YYYY-MM-DD or YYYY-MM-DD.name.")
        })
    }
}

impl fmt::Display for ApiVersion {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.name {
            Some(name) => write!(f, "{}.{name}", self.date),
            None => f.write_str(&self.date),
        }
    }
}

/// A frozen handler that serves a route to versions older than the change that froze it.
pub type LegacyHandler = Arc<
    dyn Fn(Request) -> Pin<Box<dyn Future<Output = laravel::Result<Response>> + Send>>
        + Send
        + Sync,
>;

/// Wraps an async handler as a [`LegacyHandler`].
pub fn legacy<F, Fut>(handler: F) -> LegacyHandler
where
    F: Fn(Request) -> Fut + Send + Sync + 'static,
    Fut: Future<Output = laravel::Result<Response>> + Send + 'static,
{
    Arc::new(move |request| Box::pin(handler(request)))
}

/// One backwards-incompatible change, registered under the version that introduced it.
///
/// Routes are named by method and URI pattern, as `GET /v1/orders/{order}/summary`; `*` matches
/// anything. Resources are JSON:API types, such as `customers`, or route patterns.
pub trait VersionChange: Send + Sync + 'static {
    /// What changed, for the changelog.
    fn description(&self) -> &str;

    /// The resource types or routes the transforms apply to. Empty means every response.
    fn resources(&self) -> &[&'static str] {
        &[]
    }

    /// Routes this version added: older versions get a 404.
    fn added_routes(&self) -> &[&'static str] {
        &[]
    }

    /// Routes this version removed: it and newer versions get a 404.
    fn removed_routes(&self) -> &[&'static str] {
        &[]
    }

    /// Routes older versions may no longer use: they get a 410 `endpoint_unavailable_for_version`.
    fn unavailable_to_older_versions(&self) -> &[&'static str] {
        &[]
    }

    /// Routes older versions keep being served by a frozen handler.
    fn legacy_handlers(&self) -> Vec<(&'static str, LegacyHandler)> {
        Vec::new()
    }

    /// Upgrades a request body from the older shape to this version's shape.
    fn transform_request(&self, payload: &mut Map<String, Value>) {
        let _ = payload;
    }

    /// Downgrades a response document from this version's shape to the older shape.
    fn transform_response(&self, document: &mut Value) {
        let _ = document;
    }
}

/// When a version stops working, and the brownouts before then.
#[derive(Debug, Clone, Default)]
pub struct Deprecated {
    since: Option<String>,
    sunset: Option<String>,
    brownouts: Vec<(String, String)>,
}

impl Deprecated {
    /// A deprecation with no sunset yet.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// When the version was deprecated. Defaults to the next released version's date.
    #[must_use]
    pub fn since(mut self, moment: &str) -> Self {
        self.since = Some(moment.to_owned());
        self
    }

    /// When the version stops working, such as `2027-06-01`.
    #[must_use]
    pub fn sunset(mut self, moment: &str) -> Self {
        self.sunset = Some(moment.to_owned());
        self
    }

    /// A window, in UTC, when the version is switched off as a reminder, such as
    /// `("2027-05-04 14:00", "2027-05-04 15:00")`.
    #[must_use]
    pub fn brownout(mut self, start: &str, end: &str) -> Self {
        self.brownouts.push((start.to_owned(), end.to_owned()));
        self
    }
}

/// The versioning configuration, mirroring `api.versions` in the PHP package.
#[derive(Clone)]
pub struct Versions {
    latest: String,
    default: Option<String>,
    changes: Vec<(String, Vec<Arc<dyn VersionChange>>)>,
    retired: Vec<String>,
    keep: Option<usize>,
    deprecated: Vec<(String, Deprecated)>,
    pub(crate) upgrade_guide_url: Option<String>,
    pub(crate) changelog_url: Option<String>,
}

impl Versions {
    /// Versioning with `latest` as the newest released version.
    #[must_use]
    pub fn new(latest: &str) -> Self {
        Self {
            latest: latest.to_owned(),
            default: None,
            changes: Vec::new(),
            retired: Vec::new(),
            keep: Some(2),
            deprecated: Vec::new(),
            upgrade_guide_url: None,
            changelog_url: None,
        }
    }

    /// The version for requests without an `Api-Version` header. Defaults to `latest`.
    #[must_use]
    pub fn default_version(mut self, version: &str) -> Self {
        self.default = Some(version.to_owned());
        self
    }

    /// Registers a version and the changes it introduced. A version with only additive changes
    /// is registered with none.
    #[must_use]
    pub fn version(mut self, version: &str, changes: Vec<Arc<dyn VersionChange>>) -> Self {
        self.changes.push((version.to_owned(), changes));
        self
    }

    /// Retires a version: it gets a 410 `api_version_retired`.
    #[must_use]
    pub fn retired(mut self, version: &str) -> Self {
        self.retired.push(version.to_owned());
        self
    }

    /// Released versions older than the newest `keep` are deprecated. `None` keeps them all.
    #[must_use]
    pub const fn keep(mut self, keep: Option<usize>) -> Self {
        self.keep = keep;
        self
    }

    /// Deprecates a version explicitly.
    #[must_use]
    pub fn deprecated(mut self, version: &str, deprecated: Deprecated) -> Self {
        self.deprecated.push((version.to_owned(), deprecated));
        self
    }

    /// Where retired and brownout errors link to.
    #[must_use]
    pub fn upgrade_guide_url(mut self, url: &str) -> Self {
        self.upgrade_guide_url = Some(url.to_owned());
        self
    }

    /// Where the `Link` header of deprecated versions points.
    #[must_use]
    pub fn changelog_url(mut self, url: &str) -> Self {
        self.changelog_url = Some(url.to_owned());
        self
    }
}

/// A version's deprecation, as Unix timestamps.
#[derive(Debug, Clone)]
pub(crate) struct Deprecation {
    pub(crate) since: i64,
    pub(crate) sunset: Option<i64>,
    brownouts: Vec<(i64, i64)>,
}

impl Deprecation {
    fn brownout_end(&self, now: i64) -> Option<i64> {
        self.brownouts
            .iter()
            .find(|(start, end)| now >= *start && now < *end)
            .map(|(_, end)| *end)
    }
}

/// The API's versions, built and checked from [`Versions`].
pub(crate) struct Registry {
    versions: BTreeMap<String, ApiVersion>,
    pub(crate) latest: ApiVersion,
    pub(crate) default: ApiVersion,
    retired: BTreeSet<String>,
    changes: BTreeMap<String, Vec<Arc<dyn VersionChange>>>,
    deprecations: BTreeMap<String, Deprecation>,
    pub(crate) upgrade_guide_url: Option<String>,
    pub(crate) changelog_url: Option<String>,
}

fn moment(value: &str, field: &str) -> i64 {
    time::parse_moment(value).unwrap_or_else(|| {
        panic!("{field} needs dates such as \"2027-06-01\" or \"2027-05-04 14:00\".")
    })
}

impl Registry {
    /// Builds the registry, panicking on configuration the PHP package rejects.
    pub(crate) fn new(config: &Versions) -> Self {
        let latest = ApiVersion::must(&config.latest);
        let default = config
            .default
            .as_deref()
            .map_or_else(|| latest.clone(), ApiVersion::must);
        let changed: Vec<ApiVersion> = config
            .changes
            .iter()
            .map(|(version, _)| ApiVersion::must(version))
            .collect();
        let retired: Vec<ApiVersion> = config
            .retired
            .iter()
            .map(|version| ApiVersion::must(version))
            .collect();

        for version in std::iter::once(&default).chain(&retired) {
            assert!(
                version.date <= latest.date,
                "API version [{version}] is newer than the latest version [{latest}]."
            );
        }

        let mut versions: BTreeMap<String, ApiVersion> = BTreeMap::new();
        for version in [&latest, &default]
            .into_iter()
            .chain(&changed)
            .chain(&retired)
        {
            if let Some(existing) = versions.get(&version.date) {
                assert!(
                    existing.name == version.name,
                    "API versions [{existing}] and [{version}] share a date. Each date can have only one version."
                );
            }
            versions.insert(version.date.clone(), version.clone());
        }

        let retired_dates: BTreeSet<String> =
            retired.iter().map(|version| version.date.clone()).collect();
        for version in [&latest, &default] {
            assert!(
                !retired_dates.contains(&version.date),
                "API version [{version}] is the latest or default version, so it cannot be retired."
            );
        }

        let mut changes = BTreeMap::new();
        for ((_, classes), version) in config.changes.iter().zip(&changed) {
            changes.insert(version.date.clone(), classes.clone());
        }

        let released: Vec<&ApiVersion> = versions
            .values()
            .filter(|version| version.date <= latest.date && !retired_dates.contains(&version.date))
            .collect();

        let mut deprecations = BTreeMap::new();
        if let Some(keep) = config.keep {
            assert!(
                keep >= 1,
                "keep must be at least 1, or None to keep every version."
            );
            let cut = released.len().saturating_sub(keep);
            for (index, version) in released.iter().take(cut).enumerate() {
                let since = moment(&released[index + keep].date, "keep");
                deprecations.insert(
                    version.date.clone(),
                    Deprecation {
                        since,
                        sunset: None,
                        brownouts: Vec::new(),
                    },
                );
            }
        }
        for (key, settings) in &config.deprecated {
            let version = ApiVersion::must(key);
            let known = versions.get(&version.date);
            assert!(
                known.is_some_and(|known| version.name.is_none() || version.name == known.name),
                "API version [{key}] is deprecated but is not a version of this API."
            );
            assert!(
                version.date < latest.date,
                "API version [{key}] is the latest version or newer, so it cannot be deprecated."
            );
            let next = released
                .iter()
                .find(|newer| newer.date > version.date)
                .map_or(&latest, |newer| *newer);
            let field = format!("deprecated.{key}");
            let brownouts = settings
                .brownouts
                .iter()
                .map(|(start, end)| {
                    let (start, end) = (moment(start, &field), moment(end, &field));
                    assert!(end > start, "A brownout in {field} ends before it starts.");
                    (start, end)
                })
                .collect();
            deprecations.insert(
                version.date.clone(),
                Deprecation {
                    since: moment(settings.since.as_deref().unwrap_or(&next.date), &field),
                    sunset: settings
                        .sunset
                        .as_deref()
                        .map(|sunset| moment(sunset, &field)),
                    brownouts,
                },
            );
        }

        Self {
            versions,
            latest,
            default,
            retired: retired_dates,
            changes,
            deprecations,
            upgrade_guide_url: config.upgrade_guide_url.clone(),
            changelog_url: config.changelog_url.clone(),
        }
    }

    pub(crate) fn is_unreleased(&self, version: &ApiVersion) -> bool {
        version.date > self.latest.date
    }

    /// The known version on a date, released or not.
    pub(crate) fn by_date(&self, date: &str) -> Option<&ApiVersion> {
        self.versions.get(date)
    }

    /// Every known version with the changes it introduced, newest first.
    pub(crate) fn history(&self) -> Vec<(&ApiVersion, &[Arc<dyn VersionChange>])> {
        self.versions
            .iter()
            .rev()
            .map(|(date, version)| {
                (
                    version,
                    self.changes.get(date).map_or(&[][..], Vec::as_slice),
                )
            })
            .collect()
    }

    /// The version's status, such as `default, deprecated (sunset 2027-06-01)`, or empty.
    pub(crate) fn status(&self, version: &ApiVersion, now: i64) -> String {
        let retired = self.is_retired(version, now);
        let deprecated = self.deprecation(version).filter(|_| !retired).map(|d| {
            d.sunset.map_or_else(
                || "deprecated".to_owned(),
                |sunset| format!("deprecated (sunset {})", time::date(sunset)),
            )
        });
        [
            self.is_unreleased(version).then(|| "unreleased".to_owned()),
            (*version == self.latest).then(|| "latest".to_owned()),
            (*version == self.default).then(|| "default".to_owned()),
            retired.then(|| "retired".to_owned()),
            deprecated,
        ]
        .into_iter()
        .flatten()
        .collect::<Vec<_>>()
        .join(", ")
    }

    /// The released version for a requested one. A request that also names a release must name
    /// the same release.
    fn find(&self, requested: &ApiVersion) -> Option<&ApiVersion> {
        let version = self.versions.get(&requested.date)?;
        if self.is_unreleased(version)
            || (requested.name.is_some() && requested.name != version.name)
        {
            return None;
        }
        Some(version)
    }

    pub(crate) fn deprecation(&self, version: &ApiVersion) -> Option<&Deprecation> {
        if self.retired.contains(&version.date) {
            None
        } else {
            self.deprecations.get(&version.date)
        }
    }

    pub(crate) fn is_retired(&self, version: &ApiVersion, now: i64) -> bool {
        self.retired.contains(&version.date)
            || self
                .deprecation(version)
                .and_then(|d| d.sunset)
                .is_some_and(|sunset| now >= sunset)
    }

    fn about(&self, error: ApiError) -> ApiError {
        match &self.upgrade_guide_url {
            Some(url) => error.link("about", url.clone()),
            None => error,
        }
    }

    /// The version a request is pinned to: the `Api-Version` header when present, else the default.
    /// The version a name such as `2026-06-01` or `2026-11-30.atlas` names, retired or not.
    pub(crate) fn named(&self, name: &str) -> Option<ApiVersion> {
        ApiVersion::parse(name)
            .and_then(|requested| self.find(&requested))
            .cloned()
    }

    pub(crate) fn resolve(
        &self,
        header: Option<&str>,
        now: i64,
    ) -> Result<ApiVersion, Box<ApiError>> {
        let header = header.map(str::trim).unwrap_or_default();
        if header.is_empty() {
            return Ok(self.default.clone());
        }
        let latest = self.latest.to_string();
        let Some(version) = ApiVersion::parse(header)
            .and_then(|requested| self.find(&requested))
            .cloned()
        else {
            return Err(Box::new(
                ApiError::new(
                    ApiErrorCode::InvalidApiVersion,
                    format!(
                        "[{header}] is not a version of this API. The latest version is {latest}."
                    ),
                )
                .meta("latest_version", &latest),
            ));
        };

        if self.is_retired(&version, now) {
            return Err(Box::new(
                self.about(
                    ApiError::new(
                        ApiErrorCode::ApiVersionRetired,
                        format!("API version {version} has been retired. Upgrade to {latest}."),
                    )
                    .meta("latest_version", &latest),
                ),
            ));
        }

        if let Some(deprecation) = self.deprecation(&version)
            && let Some(end) = deprecation.brownout_end(now)
        {
            let sunset = deprecation
                .sunset
                .map(|sunset| format!(" that it stops working on {}", time::date(sunset)))
                .unwrap_or_default();
            let mut error = ApiError::new(
                ApiErrorCode::ApiVersionBrownout,
                format!(
                    "API version {version} is deprecated and is switched off until {} UTC as a reminder{sunset}. Upgrade to {latest}.",
                    time::date_time(end)
                ),
            )
            .meta("latest_version", &latest)
            .meta("brownout_ends_at", time::atom(end));
            if let Some(sunset) = deprecation.sunset {
                error = error.meta("sunset", time::atom(sunset));
            }
            return Err(Box::new(
                self.about(error)
                    .header("Retry-After", (end - now).max(1).to_string()),
            ));
        }

        Ok(version)
    }

    /// Checks the matched route exists in the version, using the routes version changes added,
    /// removed or made unavailable.
    pub(crate) fn assert_route_available(
        &self,
        route: &str,
        method: &str,
        path: &str,
        version: &ApiVersion,
    ) -> Result<(), Box<ApiError>> {
        for (date, changes) in &self.changes {
            let older = version.date < *date;
            for change in changes {
                if (older && matches(change.added_routes(), route))
                    || (!older && matches(change.removed_routes(), route))
                {
                    return Err(Box::new(ApiError::new(
                        ApiErrorCode::NotFound,
                        format!("The route {path} could not be found."),
                    )));
                }
                if older && matches(change.unavailable_to_older_versions(), route) {
                    let introduced = self
                        .versions
                        .get(date)
                        .map_or_else(|| date.clone(), ToString::to_string);
                    return Err(Box::new(self.about(
                        ApiError::new(
                            ApiErrorCode::EndpointUnavailableForVersion,
                            format!("{method} /{path} is not available in API version {version}. Upgrade to {introduced} or later to use it."),
                        )
                        .meta("minimum_version", &introduced)
                        .meta("latest_version", self.latest.to_string()),
                    )));
                }
            }
        }
        Ok(())
    }

    /// The frozen handler that serves the route to the version, and the date of the change that
    /// froze it. The oldest such change wins, since its handler is the closest to the client's shape.
    pub(crate) fn legacy_handler(
        &self,
        route: &str,
        version: &ApiVersion,
    ) -> Option<(LegacyHandler, String)> {
        for (date, changes) in self.changes.range::<String, _>((
            std::ops::Bound::Excluded(&version.date),
            std::ops::Bound::Unbounded,
        )) {
            for change in changes {
                if let Some((_, handler)) = change
                    .legacy_handlers()
                    .into_iter()
                    .find(|(pattern, _)| crate::glob(pattern, route))
                {
                    return Some((handler, date.clone()));
                }
            }
        }
        None
    }

    /// The changes introduced after the version and before `before`, oldest first.
    pub(crate) fn changes_after(
        &self,
        version: &ApiVersion,
        before: Option<&str>,
    ) -> Vec<Arc<dyn VersionChange>> {
        self.changes
            .iter()
            .filter(|(date, _)| {
                **date > version.date && before.is_none_or(|before| date.as_str() < before)
            })
            .flat_map(|(_, changes)| changes.iter().cloned())
            .collect()
    }
}

fn matches(patterns: &[&str], route: &str) -> bool {
    patterns.iter().any(|pattern| crate::glob(pattern, route))
}

/// Whether a change applies to a document with these resource types, on this route.
pub(crate) fn applies_to(change: &dyn VersionChange, types: &[String], route: &str) -> bool {
    let resources = change.resources();
    resources.is_empty()
        || resources
            .iter()
            .any(|resource| types.iter().any(|t| t == resource) || crate::glob(resource, route))
}

const ATTRIBUTE_MARKER: &str = "\u{0}fusion-stack:attribute";
const RELATIONSHIP_MARKER: &str = "\u{0}fusion-stack:relationship";

/// The latest version's names for a resource type and, optionally, one of its attributes or
/// relationships, given the names an older version uses. Runs each change's request transform
/// over a probe document, oldest change first.
pub(crate) fn upgrade_name(
    changes: &[Arc<dyn VersionChange>],
    route: &str,
    kind: &str,
    field: Option<&str>,
) -> (String, Option<String>) {
    let (mut kind, mut field) = (kind.to_owned(), field.map(str::to_owned));
    for change in changes {
        if applies_to(change.as_ref(), std::slice::from_ref(&kind), route) {
            (kind, field) = probe(&kind, field.as_deref(), |document| {
                if let Value::Object(payload) = document {
                    change.transform_request(payload);
                }
            });
        }
    }
    (kind, field)
}

/// The older version's names, given the latest names: the reverse of [`upgrade_name`], for
/// naming fields in errors the way the client knows them.
pub(crate) fn downgrade_name(
    changes: &[Arc<dyn VersionChange>],
    route: &str,
    kind: &str,
    field: Option<&str>,
) -> (String, Option<String>) {
    let (mut kind, mut field) = (kind.to_owned(), field.map(str::to_owned));
    for change in changes.iter().rev() {
        if applies_to(change.as_ref(), std::slice::from_ref(&kind), route) {
            (kind, field) = probe(&kind, field.as_deref(), |document| {
                change.transform_response(document)
            });
        }
    }
    (kind, field)
}

/// Runs a transform over a document holding one resource of the type, whose attribute and
/// relationship named `field` hold markers, and reads the names the markers end up under. A field
/// the change removes leaves the names as they are.
fn probe(
    kind: &str,
    field: Option<&str>,
    transform: impl Fn(&mut Value),
) -> (String, Option<String>) {
    let mut resource = Map::new();
    resource.insert("type".into(), Value::String(kind.to_owned()));
    if let Some(field) = field {
        resource.insert("attributes".into(), json!({ field: ATTRIBUTE_MARKER }));
        resource.insert(
            "relationships".into(),
            json!({ field: { "data": RELATIONSHIP_MARKER } }),
        );
    }
    let mut document = json!({ "data": resource });
    transform(&mut document);
    let Some(data) = document.get("data").filter(|data| data.is_object()) else {
        return (kind.to_owned(), field.map(str::to_owned));
    };
    let kind = data
        .get("type")
        .and_then(Value::as_str)
        .unwrap_or(kind)
        .to_owned();
    let Some(field) = field else {
        return (kind, None);
    };
    let attribute = data
        .get("attributes")
        .and_then(|attributes| find(attributes, ATTRIBUTE_MARKER));
    let relationship = data
        .get("relationships")
        .and_then(|relationships| find(relationships, RELATIONSHIP_MARKER))
        .map(|path| path.into_iter().take(1).collect::<Vec<_>>());
    // Whichever marker moved: a field is an attribute or a relationship, not both.
    let moved = [attribute, relationship]
        .into_iter()
        .flatten()
        .find(|path| !path.is_empty() && path.as_slice() != [field.to_owned()]);
    (
        kind,
        Some(moved.map_or_else(|| field.to_owned(), |path| path.join("."))),
    )
}

/// The keys leading to `marker` inside `value`.
fn find(value: &Value, marker: &str) -> Option<Vec<String>> {
    match value {
        Value::String(text) if text == marker => Some(Vec::new()),
        Value::Object(map) => map.iter().find_map(|(key, value)| {
            find(value, marker).map(|mut path| {
                path.insert(0, key.clone());
                path
            })
        }),
        Value::Array(items) => items.iter().enumerate().find_map(|(index, value)| {
            find(value, marker).map(|mut path| {
                path.insert(0, index.to_string());
                path
            })
        }),
        _ => None,
    }
}

/// Helpers for writing [`VersionChange`] transforms over JSON:API documents and plain JSON.
pub mod document {
    use serde_json::{Map, Value};

    fn is_json_api(document: &Value) -> bool {
        document.get("data").is_some() || document.get("errors").is_some()
    }

    /// The resource types in a JSON:API document, in `data` and `included`.
    #[must_use]
    pub fn types(document: &Value) -> Vec<String> {
        let mut types = Vec::new();
        let mut collect = |resource: &Value| {
            if let Some(kind) = resource.get("type").and_then(Value::as_str)
                && !types.iter().any(|t| t == kind)
            {
                types.push(kind.to_owned());
            }
        };
        match document.get("data") {
            Some(Value::Array(items)) => items.iter().for_each(&mut collect),
            Some(item @ Value::Object(_)) => collect(item),
            _ => {}
        }
        if let Some(Value::Array(items)) = document.get("included") {
            items.iter().for_each(collect);
        }
        types
    }

    /// Applies a callback to the attributes of each resource whose type is listed (or every
    /// resource when `types` is empty). A plain JSON object counts as one resource's attributes.
    pub fn map_attributes(
        document: &mut Value,
        types: &[&str],
        mut callback: impl FnMut(&mut Map<String, Value>),
    ) {
        if !is_json_api(document) {
            if let Value::Object(attributes) = document {
                callback(attributes);
            }
            return;
        }
        let mut apply = |resource: &mut Value| {
            let kind = resource
                .get("type")
                .and_then(Value::as_str)
                .unwrap_or_default()
                .to_owned();
            if !types.is_empty() && !types.contains(&kind.as_str()) {
                return;
            }
            if let Some(Value::Object(attributes)) = resource.get_mut("attributes") {
                callback(attributes);
            }
        };
        match document.get_mut("data") {
            Some(Value::Array(items)) => items.iter_mut().for_each(&mut apply),
            Some(item @ Value::Object(_)) => apply(item),
            _ => {}
        }
        if let Some(Value::Array(items)) = document.get_mut("included") {
            items.iter_mut().for_each(apply);
        }
    }

    /// Renames a key in place, keeping the order of the keys.
    pub fn rename_key(map: &mut Map<String, Value>, from: &str, to: &str) {
        if !map.contains_key(from) {
            return;
        }
        let old = std::mem::take(map);
        for (key, value) in old {
            if key == from {
                map.insert(to.to_owned(), value);
            } else if key != to {
                map.insert(key, value);
            }
        }
    }

    /// Renames an attribute of the listed resource types, and moves error pointers that name it,
    /// so `/data/attributes/full_name` becomes `/data/attributes/name` and `/full_name` becomes `/name`.
    pub fn rename_attribute(document: &mut Value, types: &[&str], from: &str, to: &str) {
        map_attributes(document, types, |attributes| {
            rename_key(attributes, from, to)
        });
        if let Some(Value::Array(errors)) = document.get_mut("errors") {
            for error in errors {
                if let Some(Value::String(pointer)) = error
                    .get_mut("source")
                    .and_then(|source| source.get_mut("pointer"))
                {
                    for prefix in ["/data/attributes/", "/"] {
                        if let Some(rest) = pointer.strip_prefix(prefix) {
                            if rest == from || rest.starts_with(&format!("{from}/")) {
                                *pointer = format!("{prefix}{to}{}", &rest[from.len()..]);
                            }
                            break;
                        }
                    }
                }
            }
        }
    }

    /// Removes an attribute of the listed resource types.
    pub fn remove_attribute(document: &mut Value, types: &[&str], attribute: &str) {
        map_attributes(document, types, |attributes| {
            attributes.shift_remove(attribute);
        });
    }

    /// Adds an attribute where it is missing, such as one a newer version removed.
    pub fn add_attribute(
        document: &mut Value,
        types: &[&str],
        attribute: &str,
        value: impl Fn(&Map<String, Value>) -> Value,
    ) {
        map_attributes(document, types, |attributes| {
            if !attributes.contains_key(attribute) {
                let computed = value(attributes);
                attributes.insert(attribute.to_owned(), computed);
            }
        });
    }
}

#[cfg(test)]
mod tests {
    use serde_json::json;

    use super::*;

    struct Rename;

    impl VersionChange for Rename {
        fn description(&self) -> &str {
            "customer.name renamed to customer.full_name"
        }
        fn resources(&self) -> &[&'static str] {
            &["customers"]
        }
        fn added_routes(&self) -> &[&'static str] {
            &["GET /v1/customers/{customer}/orders"]
        }
        fn transform_response(&self, document: &mut Value) {
            document::rename_attribute(document, self.resources(), "full_name", "name");
        }
    }

    fn registry() -> Registry {
        Registry::new(
            &Versions::new("2026-11-30.atlas")
                .default_version("2026-06-01")
                .version("2026-06-01", vec![])
                .version("2026-11-30.atlas", vec![Arc::new(Rename)])
                .retired("2025-12-01")
                .deprecated(
                    "2026-06-01",
                    Deprecated::new()
                        .sunset("2027-06-01")
                        .brownout("2027-05-04 14:00", "2027-05-04 15:00"),
                ),
        )
    }

    #[test]
    fn versions_parse_like_the_php_package() {
        assert_eq!(
            ApiVersion::parse("2026-11-30.atlas").unwrap().to_string(),
            "2026-11-30.atlas"
        );
        assert!(ApiVersion::parse("2026-02-30").is_none());
        assert!(ApiVersion::parse("2026-1-30").is_none());
        assert!(ApiVersion::parse("2026-11-30.Atlas").is_none());
        assert!(ApiVersion::parse("2026-11-30.").is_none());
    }

    #[test]
    fn requests_resolve_to_the_default_a_named_version_or_an_error() {
        let registry = registry();
        let now = time::parse_moment("2026-12-01").unwrap();
        assert_eq!(
            registry.resolve(None, now).unwrap().to_string(),
            "2026-06-01"
        );
        assert_eq!(
            registry
                .resolve(Some("2026-11-30"), now)
                .unwrap()
                .to_string(),
            "2026-11-30.atlas"
        );
        assert_eq!(
            registry
                .resolve(Some("2026-06-01.atlas"), now)
                .unwrap_err()
                .code(),
            "invalid_api_version"
        );
        assert_eq!(
            registry
                .resolve(Some("2025-12-01"), now)
                .unwrap_err()
                .code(),
            "api_version_retired"
        );
    }

    #[test]
    fn deprecated_versions_brown_out_then_retire_at_their_sunset() {
        let registry = registry();
        let during = time::parse_moment("2027-05-04 14:30").unwrap();
        let error = registry.resolve(Some("2026-06-01"), during).unwrap_err();
        assert_eq!(error.code(), "api_version_brownout");
        assert_eq!(error.status(), 410);
        let after = time::parse_moment("2027-05-04 15:00").unwrap();
        assert!(registry.resolve(Some("2026-06-01"), after).is_ok());
        let sunset = time::parse_moment("2027-06-01").unwrap();
        assert_eq!(
            registry
                .resolve(Some("2026-06-01"), sunset)
                .unwrap_err()
                .code(),
            "api_version_retired"
        );
    }

    #[test]
    fn deprecation_since_defaults_to_the_next_released_version() {
        let registry = registry();
        let deprecation = registry
            .deprecation(&ApiVersion::must("2026-06-01"))
            .unwrap();
        assert_eq!(deprecation.since, 1_795_996_800); // 2026-11-30T00:00:00Z
    }

    #[test]
    fn routes_added_later_are_missing_from_older_versions_only() {
        let registry = registry();
        let route = "GET /v1/customers/{customer}/orders";
        assert!(
            registry
                .assert_route_available(
                    route,
                    "GET",
                    "v1/customers/1/orders",
                    &ApiVersion::must("2026-06-01")
                )
                .is_err()
        );
        assert!(
            registry
                .assert_route_available(
                    route,
                    "GET",
                    "v1/customers/1/orders",
                    &ApiVersion::must("2026-11-30.atlas")
                )
                .is_ok()
        );
    }

    #[test]
    fn rename_keeps_key_order_and_moves_error_pointers() {
        let mut document = json!({"data": {"type": "customers", "attributes": {"full_name": "A", "email": "a@x"}}});
        Rename.transform_response(&mut document);
        assert_eq!(
            serde_json::to_string(&document).unwrap(),
            r#"{"data":{"type":"customers","attributes":{"name":"A","email":"a@x"}}}"#
        );

        let mut other = json!({"data": {"type": "orders", "attributes": {"full_name": "A"}}});
        Rename.transform_response(&mut other);
        assert_eq!(other["data"]["attributes"]["full_name"], "A");

        let mut errors = json!({"errors": [{"source": {"pointer": "/data/attributes/full_name"}}, {"source": {"pointer": "/full_name"}}]});
        Rename.transform_response(&mut errors);
        assert_eq!(
            errors["errors"][0]["source"]["pointer"],
            "/data/attributes/name"
        );
        assert_eq!(errors["errors"][1]["source"]["pointer"], "/name");
    }
}