Skip to main content

fusion_stack/
versioning.rs

1//! Date-based API versions: resolving the `Api-Version` header, deprecation and retirement, and
2//! the version changes that let older clients keep the shape they were built against.
3
4use std::collections::{BTreeMap, BTreeSet};
5use std::fmt;
6use std::future::Future;
7use std::pin::Pin;
8use std::sync::Arc;
9
10use laravel::http::{Request, Response};
11use serde_json::{Map, Value, json};
12
13use crate::errors::{ApiError, ApiErrorCode};
14use crate::time;
15
16/// The header that pins a request to a version, and that responses echo.
17pub const HEADER: &str = "api-version";
18
19/// A date-based API version: `YYYY-MM-DD` with an optional release name, as in `2027-01-15.atlas`.
20/// Versions compare by date; the name is a label for the release the version belongs to.
21#[derive(Debug, Clone, PartialEq, Eq, Hash)]
22pub struct ApiVersion {
23    /// The date, `YYYY-MM-DD`.
24    pub date: String,
25    /// The release name, such as `atlas`.
26    pub name: Option<String>,
27}
28
29impl ApiVersion {
30    /// Parses a version, or returns `None` when it is not `YYYY-MM-DD[.name]` or the date does
31    /// not exist.
32    #[must_use]
33    pub fn parse(value: &str) -> Option<Self> {
34        let (date, name) = match value.split_once('.') {
35            Some((date, name)) => (date, Some(name)),
36            None => (value, None),
37        };
38        time::parse_date(date)?;
39        if let Some(name) = name {
40            let mut chars = name.chars();
41            let first_ok = chars.next().is_some_and(|c| c.is_ascii_lowercase());
42            if !first_ok || !chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
43            {
44                return None;
45            }
46        }
47        Some(Self {
48            date: date.to_owned(),
49            name: name.map(str::to_owned),
50        })
51    }
52
53    fn must(value: &str) -> Self {
54        Self::parse(value).unwrap_or_else(|| {
55            panic!("[{value}] is not a valid API version. Use YYYY-MM-DD or YYYY-MM-DD.name.")
56        })
57    }
58}
59
60impl fmt::Display for ApiVersion {
61    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62        match &self.name {
63            Some(name) => write!(f, "{}.{name}", self.date),
64            None => f.write_str(&self.date),
65        }
66    }
67}
68
69/// A frozen handler that serves a route to versions older than the change that froze it.
70pub type LegacyHandler = Arc<
71    dyn Fn(Request) -> Pin<Box<dyn Future<Output = laravel::Result<Response>> + Send>>
72        + Send
73        + Sync,
74>;
75
76/// Wraps an async handler as a [`LegacyHandler`].
77pub fn legacy<F, Fut>(handler: F) -> LegacyHandler
78where
79    F: Fn(Request) -> Fut + Send + Sync + 'static,
80    Fut: Future<Output = laravel::Result<Response>> + Send + 'static,
81{
82    Arc::new(move |request| Box::pin(handler(request)))
83}
84
85/// One backwards-incompatible change, registered under the version that introduced it.
86///
87/// Routes are named by method and URI pattern, as `GET /v1/orders/{order}/summary`; `*` matches
88/// anything. Resources are JSON:API types, such as `customers`, or route patterns.
89pub trait VersionChange: Send + Sync + 'static {
90    /// What changed, for the changelog.
91    fn description(&self) -> &str;
92
93    /// The resource types or routes the transforms apply to. Empty means every response.
94    fn resources(&self) -> &[&'static str] {
95        &[]
96    }
97
98    /// Routes this version added: older versions get a 404.
99    fn added_routes(&self) -> &[&'static str] {
100        &[]
101    }
102
103    /// Routes this version removed: it and newer versions get a 404.
104    fn removed_routes(&self) -> &[&'static str] {
105        &[]
106    }
107
108    /// Routes older versions may no longer use: they get a 410 `endpoint_unavailable_for_version`.
109    fn unavailable_to_older_versions(&self) -> &[&'static str] {
110        &[]
111    }
112
113    /// Routes older versions keep being served by a frozen handler.
114    fn legacy_handlers(&self) -> Vec<(&'static str, LegacyHandler)> {
115        Vec::new()
116    }
117
118    /// Upgrades a request body from the older shape to this version's shape.
119    fn transform_request(&self, payload: &mut Map<String, Value>) {
120        let _ = payload;
121    }
122
123    /// Downgrades a response document from this version's shape to the older shape.
124    fn transform_response(&self, document: &mut Value) {
125        let _ = document;
126    }
127}
128
129/// When a version stops working, and the brownouts before then.
130#[derive(Debug, Clone, Default)]
131pub struct Deprecated {
132    since: Option<String>,
133    sunset: Option<String>,
134    brownouts: Vec<(String, String)>,
135}
136
137impl Deprecated {
138    /// A deprecation with no sunset yet.
139    #[must_use]
140    pub fn new() -> Self {
141        Self::default()
142    }
143
144    /// When the version was deprecated. Defaults to the next released version's date.
145    #[must_use]
146    pub fn since(mut self, moment: &str) -> Self {
147        self.since = Some(moment.to_owned());
148        self
149    }
150
151    /// When the version stops working, such as `2027-06-01`.
152    #[must_use]
153    pub fn sunset(mut self, moment: &str) -> Self {
154        self.sunset = Some(moment.to_owned());
155        self
156    }
157
158    /// A window, in UTC, when the version is switched off as a reminder, such as
159    /// `("2027-05-04 14:00", "2027-05-04 15:00")`.
160    #[must_use]
161    pub fn brownout(mut self, start: &str, end: &str) -> Self {
162        self.brownouts.push((start.to_owned(), end.to_owned()));
163        self
164    }
165}
166
167/// The versioning configuration, mirroring `api.versions` in the PHP package.
168#[derive(Clone)]
169pub struct Versions {
170    latest: String,
171    default: Option<String>,
172    changes: Vec<(String, Vec<Arc<dyn VersionChange>>)>,
173    retired: Vec<String>,
174    keep: Option<usize>,
175    deprecated: Vec<(String, Deprecated)>,
176    pub(crate) upgrade_guide_url: Option<String>,
177    pub(crate) changelog_url: Option<String>,
178}
179
180impl Versions {
181    /// Versioning with `latest` as the newest released version.
182    #[must_use]
183    pub fn new(latest: &str) -> Self {
184        Self {
185            latest: latest.to_owned(),
186            default: None,
187            changes: Vec::new(),
188            retired: Vec::new(),
189            keep: Some(2),
190            deprecated: Vec::new(),
191            upgrade_guide_url: None,
192            changelog_url: None,
193        }
194    }
195
196    /// The version for requests without an `Api-Version` header. Defaults to `latest`.
197    #[must_use]
198    pub fn default_version(mut self, version: &str) -> Self {
199        self.default = Some(version.to_owned());
200        self
201    }
202
203    /// Registers a version and the changes it introduced. A version with only additive changes
204    /// is registered with none.
205    #[must_use]
206    pub fn version(mut self, version: &str, changes: Vec<Arc<dyn VersionChange>>) -> Self {
207        self.changes.push((version.to_owned(), changes));
208        self
209    }
210
211    /// Retires a version: it gets a 410 `api_version_retired`.
212    #[must_use]
213    pub fn retired(mut self, version: &str) -> Self {
214        self.retired.push(version.to_owned());
215        self
216    }
217
218    /// Released versions older than the newest `keep` are deprecated. `None` keeps them all.
219    #[must_use]
220    pub const fn keep(mut self, keep: Option<usize>) -> Self {
221        self.keep = keep;
222        self
223    }
224
225    /// Deprecates a version explicitly.
226    #[must_use]
227    pub fn deprecated(mut self, version: &str, deprecated: Deprecated) -> Self {
228        self.deprecated.push((version.to_owned(), deprecated));
229        self
230    }
231
232    /// Where retired and brownout errors link to.
233    #[must_use]
234    pub fn upgrade_guide_url(mut self, url: &str) -> Self {
235        self.upgrade_guide_url = Some(url.to_owned());
236        self
237    }
238
239    /// Where the `Link` header of deprecated versions points.
240    #[must_use]
241    pub fn changelog_url(mut self, url: &str) -> Self {
242        self.changelog_url = Some(url.to_owned());
243        self
244    }
245}
246
247/// A version's deprecation, as Unix timestamps.
248#[derive(Debug, Clone)]
249pub(crate) struct Deprecation {
250    pub(crate) since: i64,
251    pub(crate) sunset: Option<i64>,
252    brownouts: Vec<(i64, i64)>,
253}
254
255impl Deprecation {
256    fn brownout_end(&self, now: i64) -> Option<i64> {
257        self.brownouts
258            .iter()
259            .find(|(start, end)| now >= *start && now < *end)
260            .map(|(_, end)| *end)
261    }
262}
263
264/// The API's versions, built and checked from [`Versions`].
265pub(crate) struct Registry {
266    versions: BTreeMap<String, ApiVersion>,
267    pub(crate) latest: ApiVersion,
268    pub(crate) default: ApiVersion,
269    retired: BTreeSet<String>,
270    changes: BTreeMap<String, Vec<Arc<dyn VersionChange>>>,
271    deprecations: BTreeMap<String, Deprecation>,
272    pub(crate) upgrade_guide_url: Option<String>,
273    pub(crate) changelog_url: Option<String>,
274}
275
276fn moment(value: &str, field: &str) -> i64 {
277    time::parse_moment(value).unwrap_or_else(|| {
278        panic!("{field} needs dates such as \"2027-06-01\" or \"2027-05-04 14:00\".")
279    })
280}
281
282impl Registry {
283    /// Builds the registry, panicking on configuration the PHP package rejects.
284    pub(crate) fn new(config: &Versions) -> Self {
285        let latest = ApiVersion::must(&config.latest);
286        let default = config
287            .default
288            .as_deref()
289            .map_or_else(|| latest.clone(), ApiVersion::must);
290        let changed: Vec<ApiVersion> = config
291            .changes
292            .iter()
293            .map(|(version, _)| ApiVersion::must(version))
294            .collect();
295        let retired: Vec<ApiVersion> = config
296            .retired
297            .iter()
298            .map(|version| ApiVersion::must(version))
299            .collect();
300
301        for version in std::iter::once(&default).chain(&retired) {
302            assert!(
303                version.date <= latest.date,
304                "API version [{version}] is newer than the latest version [{latest}]."
305            );
306        }
307
308        let mut versions: BTreeMap<String, ApiVersion> = BTreeMap::new();
309        for version in [&latest, &default]
310            .into_iter()
311            .chain(&changed)
312            .chain(&retired)
313        {
314            if let Some(existing) = versions.get(&version.date) {
315                assert!(
316                    existing.name == version.name,
317                    "API versions [{existing}] and [{version}] share a date. Each date can have only one version."
318                );
319            }
320            versions.insert(version.date.clone(), version.clone());
321        }
322
323        let retired_dates: BTreeSet<String> =
324            retired.iter().map(|version| version.date.clone()).collect();
325        for version in [&latest, &default] {
326            assert!(
327                !retired_dates.contains(&version.date),
328                "API version [{version}] is the latest or default version, so it cannot be retired."
329            );
330        }
331
332        let mut changes = BTreeMap::new();
333        for ((_, classes), version) in config.changes.iter().zip(&changed) {
334            changes.insert(version.date.clone(), classes.clone());
335        }
336
337        let released: Vec<&ApiVersion> = versions
338            .values()
339            .filter(|version| version.date <= latest.date && !retired_dates.contains(&version.date))
340            .collect();
341
342        let mut deprecations = BTreeMap::new();
343        if let Some(keep) = config.keep {
344            assert!(
345                keep >= 1,
346                "keep must be at least 1, or None to keep every version."
347            );
348            let cut = released.len().saturating_sub(keep);
349            for (index, version) in released.iter().take(cut).enumerate() {
350                let since = moment(&released[index + keep].date, "keep");
351                deprecations.insert(
352                    version.date.clone(),
353                    Deprecation {
354                        since,
355                        sunset: None,
356                        brownouts: Vec::new(),
357                    },
358                );
359            }
360        }
361        for (key, settings) in &config.deprecated {
362            let version = ApiVersion::must(key);
363            let known = versions.get(&version.date);
364            assert!(
365                known.is_some_and(|known| version.name.is_none() || version.name == known.name),
366                "API version [{key}] is deprecated but is not a version of this API."
367            );
368            assert!(
369                version.date < latest.date,
370                "API version [{key}] is the latest version or newer, so it cannot be deprecated."
371            );
372            let next = released
373                .iter()
374                .find(|newer| newer.date > version.date)
375                .map_or(&latest, |newer| *newer);
376            let field = format!("deprecated.{key}");
377            let brownouts = settings
378                .brownouts
379                .iter()
380                .map(|(start, end)| {
381                    let (start, end) = (moment(start, &field), moment(end, &field));
382                    assert!(end > start, "A brownout in {field} ends before it starts.");
383                    (start, end)
384                })
385                .collect();
386            deprecations.insert(
387                version.date.clone(),
388                Deprecation {
389                    since: moment(settings.since.as_deref().unwrap_or(&next.date), &field),
390                    sunset: settings
391                        .sunset
392                        .as_deref()
393                        .map(|sunset| moment(sunset, &field)),
394                    brownouts,
395                },
396            );
397        }
398
399        Self {
400            versions,
401            latest,
402            default,
403            retired: retired_dates,
404            changes,
405            deprecations,
406            upgrade_guide_url: config.upgrade_guide_url.clone(),
407            changelog_url: config.changelog_url.clone(),
408        }
409    }
410
411    pub(crate) fn is_unreleased(&self, version: &ApiVersion) -> bool {
412        version.date > self.latest.date
413    }
414
415    /// The known version on a date, released or not.
416    pub(crate) fn by_date(&self, date: &str) -> Option<&ApiVersion> {
417        self.versions.get(date)
418    }
419
420    /// Every known version with the changes it introduced, newest first.
421    pub(crate) fn history(&self) -> Vec<(&ApiVersion, &[Arc<dyn VersionChange>])> {
422        self.versions
423            .iter()
424            .rev()
425            .map(|(date, version)| {
426                (
427                    version,
428                    self.changes.get(date).map_or(&[][..], Vec::as_slice),
429                )
430            })
431            .collect()
432    }
433
434    /// The version's status, such as `default, deprecated (sunset 2027-06-01)`, or empty.
435    pub(crate) fn status(&self, version: &ApiVersion, now: i64) -> String {
436        let retired = self.is_retired(version, now);
437        let deprecated = self.deprecation(version).filter(|_| !retired).map(|d| {
438            d.sunset.map_or_else(
439                || "deprecated".to_owned(),
440                |sunset| format!("deprecated (sunset {})", time::date(sunset)),
441            )
442        });
443        [
444            self.is_unreleased(version).then(|| "unreleased".to_owned()),
445            (*version == self.latest).then(|| "latest".to_owned()),
446            (*version == self.default).then(|| "default".to_owned()),
447            retired.then(|| "retired".to_owned()),
448            deprecated,
449        ]
450        .into_iter()
451        .flatten()
452        .collect::<Vec<_>>()
453        .join(", ")
454    }
455
456    /// The released version for a requested one. A request that also names a release must name
457    /// the same release.
458    fn find(&self, requested: &ApiVersion) -> Option<&ApiVersion> {
459        let version = self.versions.get(&requested.date)?;
460        if self.is_unreleased(version)
461            || (requested.name.is_some() && requested.name != version.name)
462        {
463            return None;
464        }
465        Some(version)
466    }
467
468    pub(crate) fn deprecation(&self, version: &ApiVersion) -> Option<&Deprecation> {
469        if self.retired.contains(&version.date) {
470            None
471        } else {
472            self.deprecations.get(&version.date)
473        }
474    }
475
476    pub(crate) fn is_retired(&self, version: &ApiVersion, now: i64) -> bool {
477        self.retired.contains(&version.date)
478            || self
479                .deprecation(version)
480                .and_then(|d| d.sunset)
481                .is_some_and(|sunset| now >= sunset)
482    }
483
484    fn about(&self, error: ApiError) -> ApiError {
485        match &self.upgrade_guide_url {
486            Some(url) => error.link("about", url.clone()),
487            None => error,
488        }
489    }
490
491    /// The version a request is pinned to: the `Api-Version` header when present, else the default.
492    /// The version a name such as `2026-06-01` or `2026-11-30.atlas` names, retired or not.
493    pub(crate) fn named(&self, name: &str) -> Option<ApiVersion> {
494        ApiVersion::parse(name)
495            .and_then(|requested| self.find(&requested))
496            .cloned()
497    }
498
499    pub(crate) fn resolve(
500        &self,
501        header: Option<&str>,
502        now: i64,
503    ) -> Result<ApiVersion, Box<ApiError>> {
504        let header = header.map(str::trim).unwrap_or_default();
505        if header.is_empty() {
506            return Ok(self.default.clone());
507        }
508        let latest = self.latest.to_string();
509        let Some(version) = ApiVersion::parse(header)
510            .and_then(|requested| self.find(&requested))
511            .cloned()
512        else {
513            return Err(Box::new(
514                ApiError::new(
515                    ApiErrorCode::InvalidApiVersion,
516                    format!(
517                        "[{header}] is not a version of this API. The latest version is {latest}."
518                    ),
519                )
520                .meta("latest_version", &latest),
521            ));
522        };
523
524        if self.is_retired(&version, now) {
525            return Err(Box::new(
526                self.about(
527                    ApiError::new(
528                        ApiErrorCode::ApiVersionRetired,
529                        format!("API version {version} has been retired. Upgrade to {latest}."),
530                    )
531                    .meta("latest_version", &latest),
532                ),
533            ));
534        }
535
536        if let Some(deprecation) = self.deprecation(&version)
537            && let Some(end) = deprecation.brownout_end(now)
538        {
539            let sunset = deprecation
540                .sunset
541                .map(|sunset| format!(" that it stops working on {}", time::date(sunset)))
542                .unwrap_or_default();
543            let mut error = ApiError::new(
544                ApiErrorCode::ApiVersionBrownout,
545                format!(
546                    "API version {version} is deprecated and is switched off until {} UTC as a reminder{sunset}. Upgrade to {latest}.",
547                    time::date_time(end)
548                ),
549            )
550            .meta("latest_version", &latest)
551            .meta("brownout_ends_at", time::atom(end));
552            if let Some(sunset) = deprecation.sunset {
553                error = error.meta("sunset", time::atom(sunset));
554            }
555            return Err(Box::new(
556                self.about(error)
557                    .header("Retry-After", (end - now).max(1).to_string()),
558            ));
559        }
560
561        Ok(version)
562    }
563
564    /// Checks the matched route exists in the version, using the routes version changes added,
565    /// removed or made unavailable.
566    pub(crate) fn assert_route_available(
567        &self,
568        route: &str,
569        method: &str,
570        path: &str,
571        version: &ApiVersion,
572    ) -> Result<(), Box<ApiError>> {
573        for (date, changes) in &self.changes {
574            let older = version.date < *date;
575            for change in changes {
576                if (older && matches(change.added_routes(), route))
577                    || (!older && matches(change.removed_routes(), route))
578                {
579                    return Err(Box::new(ApiError::new(
580                        ApiErrorCode::NotFound,
581                        format!("The route {path} could not be found."),
582                    )));
583                }
584                if older && matches(change.unavailable_to_older_versions(), route) {
585                    let introduced = self
586                        .versions
587                        .get(date)
588                        .map_or_else(|| date.clone(), ToString::to_string);
589                    return Err(Box::new(self.about(
590                        ApiError::new(
591                            ApiErrorCode::EndpointUnavailableForVersion,
592                            format!("{method} /{path} is not available in API version {version}. Upgrade to {introduced} or later to use it."),
593                        )
594                        .meta("minimum_version", &introduced)
595                        .meta("latest_version", self.latest.to_string()),
596                    )));
597                }
598            }
599        }
600        Ok(())
601    }
602
603    /// The frozen handler that serves the route to the version, and the date of the change that
604    /// froze it. The oldest such change wins, since its handler is the closest to the client's shape.
605    pub(crate) fn legacy_handler(
606        &self,
607        route: &str,
608        version: &ApiVersion,
609    ) -> Option<(LegacyHandler, String)> {
610        for (date, changes) in self.changes.range::<String, _>((
611            std::ops::Bound::Excluded(&version.date),
612            std::ops::Bound::Unbounded,
613        )) {
614            for change in changes {
615                if let Some((_, handler)) = change
616                    .legacy_handlers()
617                    .into_iter()
618                    .find(|(pattern, _)| crate::glob(pattern, route))
619                {
620                    return Some((handler, date.clone()));
621                }
622            }
623        }
624        None
625    }
626
627    /// The changes introduced after the version and before `before`, oldest first.
628    pub(crate) fn changes_after(
629        &self,
630        version: &ApiVersion,
631        before: Option<&str>,
632    ) -> Vec<Arc<dyn VersionChange>> {
633        self.changes
634            .iter()
635            .filter(|(date, _)| {
636                **date > version.date && before.is_none_or(|before| date.as_str() < before)
637            })
638            .flat_map(|(_, changes)| changes.iter().cloned())
639            .collect()
640    }
641}
642
643fn matches(patterns: &[&str], route: &str) -> bool {
644    patterns.iter().any(|pattern| crate::glob(pattern, route))
645}
646
647/// Whether a change applies to a document with these resource types, on this route.
648pub(crate) fn applies_to(change: &dyn VersionChange, types: &[String], route: &str) -> bool {
649    let resources = change.resources();
650    resources.is_empty()
651        || resources
652            .iter()
653            .any(|resource| types.iter().any(|t| t == resource) || crate::glob(resource, route))
654}
655
656const ATTRIBUTE_MARKER: &str = "\u{0}fusion-stack:attribute";
657const RELATIONSHIP_MARKER: &str = "\u{0}fusion-stack:relationship";
658
659/// The latest version's names for a resource type and, optionally, one of its attributes or
660/// relationships, given the names an older version uses. Runs each change's request transform
661/// over a probe document, oldest change first.
662pub(crate) fn upgrade_name(
663    changes: &[Arc<dyn VersionChange>],
664    route: &str,
665    kind: &str,
666    field: Option<&str>,
667) -> (String, Option<String>) {
668    let (mut kind, mut field) = (kind.to_owned(), field.map(str::to_owned));
669    for change in changes {
670        if applies_to(change.as_ref(), std::slice::from_ref(&kind), route) {
671            (kind, field) = probe(&kind, field.as_deref(), |document| {
672                if let Value::Object(payload) = document {
673                    change.transform_request(payload);
674                }
675            });
676        }
677    }
678    (kind, field)
679}
680
681/// The older version's names, given the latest names: the reverse of [`upgrade_name`], for
682/// naming fields in errors the way the client knows them.
683pub(crate) fn downgrade_name(
684    changes: &[Arc<dyn VersionChange>],
685    route: &str,
686    kind: &str,
687    field: Option<&str>,
688) -> (String, Option<String>) {
689    let (mut kind, mut field) = (kind.to_owned(), field.map(str::to_owned));
690    for change in changes.iter().rev() {
691        if applies_to(change.as_ref(), std::slice::from_ref(&kind), route) {
692            (kind, field) = probe(&kind, field.as_deref(), |document| {
693                change.transform_response(document)
694            });
695        }
696    }
697    (kind, field)
698}
699
700/// Runs a transform over a document holding one resource of the type, whose attribute and
701/// relationship named `field` hold markers, and reads the names the markers end up under. A field
702/// the change removes leaves the names as they are.
703fn probe(
704    kind: &str,
705    field: Option<&str>,
706    transform: impl Fn(&mut Value),
707) -> (String, Option<String>) {
708    let mut resource = Map::new();
709    resource.insert("type".into(), Value::String(kind.to_owned()));
710    if let Some(field) = field {
711        resource.insert("attributes".into(), json!({ field: ATTRIBUTE_MARKER }));
712        resource.insert(
713            "relationships".into(),
714            json!({ field: { "data": RELATIONSHIP_MARKER } }),
715        );
716    }
717    let mut document = json!({ "data": resource });
718    transform(&mut document);
719    let Some(data) = document.get("data").filter(|data| data.is_object()) else {
720        return (kind.to_owned(), field.map(str::to_owned));
721    };
722    let kind = data
723        .get("type")
724        .and_then(Value::as_str)
725        .unwrap_or(kind)
726        .to_owned();
727    let Some(field) = field else {
728        return (kind, None);
729    };
730    let attribute = data
731        .get("attributes")
732        .and_then(|attributes| find(attributes, ATTRIBUTE_MARKER));
733    let relationship = data
734        .get("relationships")
735        .and_then(|relationships| find(relationships, RELATIONSHIP_MARKER))
736        .map(|path| path.into_iter().take(1).collect::<Vec<_>>());
737    // Whichever marker moved: a field is an attribute or a relationship, not both.
738    let moved = [attribute, relationship]
739        .into_iter()
740        .flatten()
741        .find(|path| !path.is_empty() && path.as_slice() != [field.to_owned()]);
742    (
743        kind,
744        Some(moved.map_or_else(|| field.to_owned(), |path| path.join("."))),
745    )
746}
747
748/// The keys leading to `marker` inside `value`.
749fn find(value: &Value, marker: &str) -> Option<Vec<String>> {
750    match value {
751        Value::String(text) if text == marker => Some(Vec::new()),
752        Value::Object(map) => map.iter().find_map(|(key, value)| {
753            find(value, marker).map(|mut path| {
754                path.insert(0, key.clone());
755                path
756            })
757        }),
758        Value::Array(items) => items.iter().enumerate().find_map(|(index, value)| {
759            find(value, marker).map(|mut path| {
760                path.insert(0, index.to_string());
761                path
762            })
763        }),
764        _ => None,
765    }
766}
767
768/// Helpers for writing [`VersionChange`] transforms over JSON:API documents and plain JSON.
769pub mod document {
770    use serde_json::{Map, Value};
771
772    fn is_json_api(document: &Value) -> bool {
773        document.get("data").is_some() || document.get("errors").is_some()
774    }
775
776    /// The resource types in a JSON:API document, in `data` and `included`.
777    #[must_use]
778    pub fn types(document: &Value) -> Vec<String> {
779        let mut types = Vec::new();
780        let mut collect = |resource: &Value| {
781            if let Some(kind) = resource.get("type").and_then(Value::as_str)
782                && !types.iter().any(|t| t == kind)
783            {
784                types.push(kind.to_owned());
785            }
786        };
787        match document.get("data") {
788            Some(Value::Array(items)) => items.iter().for_each(&mut collect),
789            Some(item @ Value::Object(_)) => collect(item),
790            _ => {}
791        }
792        if let Some(Value::Array(items)) = document.get("included") {
793            items.iter().for_each(collect);
794        }
795        types
796    }
797
798    /// Applies a callback to the attributes of each resource whose type is listed (or every
799    /// resource when `types` is empty). A plain JSON object counts as one resource's attributes.
800    pub fn map_attributes(
801        document: &mut Value,
802        types: &[&str],
803        mut callback: impl FnMut(&mut Map<String, Value>),
804    ) {
805        if !is_json_api(document) {
806            if let Value::Object(attributes) = document {
807                callback(attributes);
808            }
809            return;
810        }
811        let mut apply = |resource: &mut Value| {
812            let kind = resource
813                .get("type")
814                .and_then(Value::as_str)
815                .unwrap_or_default()
816                .to_owned();
817            if !types.is_empty() && !types.contains(&kind.as_str()) {
818                return;
819            }
820            if let Some(Value::Object(attributes)) = resource.get_mut("attributes") {
821                callback(attributes);
822            }
823        };
824        match document.get_mut("data") {
825            Some(Value::Array(items)) => items.iter_mut().for_each(&mut apply),
826            Some(item @ Value::Object(_)) => apply(item),
827            _ => {}
828        }
829        if let Some(Value::Array(items)) = document.get_mut("included") {
830            items.iter_mut().for_each(apply);
831        }
832    }
833
834    /// Renames a key in place, keeping the order of the keys.
835    pub fn rename_key(map: &mut Map<String, Value>, from: &str, to: &str) {
836        if !map.contains_key(from) {
837            return;
838        }
839        let old = std::mem::take(map);
840        for (key, value) in old {
841            if key == from {
842                map.insert(to.to_owned(), value);
843            } else if key != to {
844                map.insert(key, value);
845            }
846        }
847    }
848
849    /// Renames an attribute of the listed resource types, and moves error pointers that name it,
850    /// so `/data/attributes/full_name` becomes `/data/attributes/name` and `/full_name` becomes `/name`.
851    pub fn rename_attribute(document: &mut Value, types: &[&str], from: &str, to: &str) {
852        map_attributes(document, types, |attributes| {
853            rename_key(attributes, from, to)
854        });
855        if let Some(Value::Array(errors)) = document.get_mut("errors") {
856            for error in errors {
857                if let Some(Value::String(pointer)) = error
858                    .get_mut("source")
859                    .and_then(|source| source.get_mut("pointer"))
860                {
861                    for prefix in ["/data/attributes/", "/"] {
862                        if let Some(rest) = pointer.strip_prefix(prefix) {
863                            if rest == from || rest.starts_with(&format!("{from}/")) {
864                                *pointer = format!("{prefix}{to}{}", &rest[from.len()..]);
865                            }
866                            break;
867                        }
868                    }
869                }
870            }
871        }
872    }
873
874    /// Removes an attribute of the listed resource types.
875    pub fn remove_attribute(document: &mut Value, types: &[&str], attribute: &str) {
876        map_attributes(document, types, |attributes| {
877            attributes.shift_remove(attribute);
878        });
879    }
880
881    /// Adds an attribute where it is missing, such as one a newer version removed.
882    pub fn add_attribute(
883        document: &mut Value,
884        types: &[&str],
885        attribute: &str,
886        value: impl Fn(&Map<String, Value>) -> Value,
887    ) {
888        map_attributes(document, types, |attributes| {
889            if !attributes.contains_key(attribute) {
890                let computed = value(attributes);
891                attributes.insert(attribute.to_owned(), computed);
892            }
893        });
894    }
895}
896
897#[cfg(test)]
898mod tests {
899    use serde_json::json;
900
901    use super::*;
902
903    struct Rename;
904
905    impl VersionChange for Rename {
906        fn description(&self) -> &str {
907            "customer.name renamed to customer.full_name"
908        }
909        fn resources(&self) -> &[&'static str] {
910            &["customers"]
911        }
912        fn added_routes(&self) -> &[&'static str] {
913            &["GET /v1/customers/{customer}/orders"]
914        }
915        fn transform_response(&self, document: &mut Value) {
916            document::rename_attribute(document, self.resources(), "full_name", "name");
917        }
918    }
919
920    fn registry() -> Registry {
921        Registry::new(
922            &Versions::new("2026-11-30.atlas")
923                .default_version("2026-06-01")
924                .version("2026-06-01", vec![])
925                .version("2026-11-30.atlas", vec![Arc::new(Rename)])
926                .retired("2025-12-01")
927                .deprecated(
928                    "2026-06-01",
929                    Deprecated::new()
930                        .sunset("2027-06-01")
931                        .brownout("2027-05-04 14:00", "2027-05-04 15:00"),
932                ),
933        )
934    }
935
936    #[test]
937    fn versions_parse_like_the_php_package() {
938        assert_eq!(
939            ApiVersion::parse("2026-11-30.atlas").unwrap().to_string(),
940            "2026-11-30.atlas"
941        );
942        assert!(ApiVersion::parse("2026-02-30").is_none());
943        assert!(ApiVersion::parse("2026-1-30").is_none());
944        assert!(ApiVersion::parse("2026-11-30.Atlas").is_none());
945        assert!(ApiVersion::parse("2026-11-30.").is_none());
946    }
947
948    #[test]
949    fn requests_resolve_to_the_default_a_named_version_or_an_error() {
950        let registry = registry();
951        let now = time::parse_moment("2026-12-01").unwrap();
952        assert_eq!(
953            registry.resolve(None, now).unwrap().to_string(),
954            "2026-06-01"
955        );
956        assert_eq!(
957            registry
958                .resolve(Some("2026-11-30"), now)
959                .unwrap()
960                .to_string(),
961            "2026-11-30.atlas"
962        );
963        assert_eq!(
964            registry
965                .resolve(Some("2026-06-01.atlas"), now)
966                .unwrap_err()
967                .code(),
968            "invalid_api_version"
969        );
970        assert_eq!(
971            registry
972                .resolve(Some("2025-12-01"), now)
973                .unwrap_err()
974                .code(),
975            "api_version_retired"
976        );
977    }
978
979    #[test]
980    fn deprecated_versions_brown_out_then_retire_at_their_sunset() {
981        let registry = registry();
982        let during = time::parse_moment("2027-05-04 14:30").unwrap();
983        let error = registry.resolve(Some("2026-06-01"), during).unwrap_err();
984        assert_eq!(error.code(), "api_version_brownout");
985        assert_eq!(error.status(), 410);
986        let after = time::parse_moment("2027-05-04 15:00").unwrap();
987        assert!(registry.resolve(Some("2026-06-01"), after).is_ok());
988        let sunset = time::parse_moment("2027-06-01").unwrap();
989        assert_eq!(
990            registry
991                .resolve(Some("2026-06-01"), sunset)
992                .unwrap_err()
993                .code(),
994            "api_version_retired"
995        );
996    }
997
998    #[test]
999    fn deprecation_since_defaults_to_the_next_released_version() {
1000        let registry = registry();
1001        let deprecation = registry
1002            .deprecation(&ApiVersion::must("2026-06-01"))
1003            .unwrap();
1004        assert_eq!(deprecation.since, 1_795_996_800); // 2026-11-30T00:00:00Z
1005    }
1006
1007    #[test]
1008    fn routes_added_later_are_missing_from_older_versions_only() {
1009        let registry = registry();
1010        let route = "GET /v1/customers/{customer}/orders";
1011        assert!(
1012            registry
1013                .assert_route_available(
1014                    route,
1015                    "GET",
1016                    "v1/customers/1/orders",
1017                    &ApiVersion::must("2026-06-01")
1018                )
1019                .is_err()
1020        );
1021        assert!(
1022            registry
1023                .assert_route_available(
1024                    route,
1025                    "GET",
1026                    "v1/customers/1/orders",
1027                    &ApiVersion::must("2026-11-30.atlas")
1028                )
1029                .is_ok()
1030        );
1031    }
1032
1033    #[test]
1034    fn rename_keeps_key_order_and_moves_error_pointers() {
1035        let mut document = json!({"data": {"type": "customers", "attributes": {"full_name": "A", "email": "a@x"}}});
1036        Rename.transform_response(&mut document);
1037        assert_eq!(
1038            serde_json::to_string(&document).unwrap(),
1039            r#"{"data":{"type":"customers","attributes":{"name":"A","email":"a@x"}}}"#
1040        );
1041
1042        let mut other = json!({"data": {"type": "orders", "attributes": {"full_name": "A"}}});
1043        Rename.transform_response(&mut other);
1044        assert_eq!(other["data"]["attributes"]["full_name"], "A");
1045
1046        let mut errors = json!({"errors": [{"source": {"pointer": "/data/attributes/full_name"}}, {"source": {"pointer": "/full_name"}}]});
1047        Rename.transform_response(&mut errors);
1048        assert_eq!(
1049            errors["errors"][0]["source"]["pointer"],
1050            "/data/attributes/name"
1051        );
1052        assert_eq!(errors["errors"][1]["source"]["pointer"], "/name");
1053    }
1054}