Skip to main content

vortex_edition/
session.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Session variables for registered and enabled editions.
5
6use std::any::Any;
7use std::collections::BTreeMap;
8use std::collections::BTreeSet;
9use std::sync::Arc;
10
11use parking_lot::RwLock;
12use vortex_error::VortexResult;
13use vortex_error::vortex_bail;
14use vortex_session::ArcSwapMap;
15use vortex_session::SessionExt;
16use vortex_session::SessionGuard;
17use vortex_session::SessionVar;
18use vortex_session::registry::Id;
19
20use crate::ComponentKind;
21use crate::Edition;
22use crate::EditionDeclaration;
23use crate::EditionFamily;
24use crate::EditionId;
25use crate::EditionInclusion;
26use crate::parse_release;
27
28/// The session's registry of editions and edition inclusions.
29///
30/// Starts empty and is populated at initialization time: the `vortex` facade seeds the
31/// first-party declarations (`vortex::editions`), and crates registering additional
32/// encodings declare their inclusions (and, for new families, editions) alongside their
33/// encoding registration. Clones share the same underlying registry, matching the other
34/// session registries.
35#[derive(Clone, Debug, Default)]
36pub struct EditionSession {
37    inner: Arc<RwLock<Inner>>,
38}
39
40#[derive(Debug, Default)]
41struct Inner {
42    /// Keyed by family name.
43    families: BTreeMap<String, EditionFamily>,
44    /// Keyed by the display form of the edition id.
45    editions: BTreeMap<String, Edition>,
46    /// One map per member kind, each keyed by interned member id, because ids are only unique
47    /// within a kind. An id may have one inclusion per family. Ordered by kind, then by the id's
48    /// string form.
49    inclusions: BTreeMap<ComponentKind, BTreeMap<Id, Vec<EditionInclusion>>>,
50}
51
52impl Inner {
53    fn check_edition(&self, edition: Edition) -> VortexResult<String> {
54        let key = edition.id.to_string();
55        if self.editions.contains_key(&key) {
56            vortex_bail!("duplicate edition {key}");
57        }
58        Ok(key)
59    }
60
61    fn check_inclusion(&self, inclusion: &EditionInclusion) -> VortexResult<()> {
62        let previous = self
63            .inclusions
64            .get(&inclusion.kind)
65            .and_then(|by_id| by_id.get(&inclusion.component_id))
66            .and_then(|history| {
67                history
68                    .iter()
69                    .filter(|existing| existing.since.family == inclusion.since.family)
70                    .max_by_key(|existing| {
71                        (
72                            existing.since.year,
73                            existing.since.month,
74                            existing.since.version,
75                        )
76                    })
77            });
78
79        if let Some(previous) = previous {
80            vortex_bail!(
81                "{} {} already joined family {} in edition {}",
82                inclusion.kind,
83                inclusion.component_id,
84                inclusion.since.family,
85                previous.since,
86            );
87        }
88        Ok(())
89    }
90
91    fn insert_inclusion(&mut self, inclusion: EditionInclusion) {
92        let history = self
93            .inclusions
94            .entry(inclusion.kind)
95            .or_default()
96            .entry(inclusion.component_id)
97            .or_default();
98        history.push(inclusion);
99        history.sort_by_key(|entry| {
100            (
101                entry.since.family,
102                entry.since.year,
103                entry.since.month,
104                entry.since.version,
105            )
106        });
107    }
108}
109
110/// Registry of enabled editions, keyed by interned edition family.
111type EditionsByFamily = ArcSwapMap<Id, EditionId>;
112
113/// The editions enabled for writing in a session.
114///
115/// At most one edition is enabled per family. Enabling a newer or older edition from the
116/// same family replaces the previous selection. This is separate from [`EditionSession`]:
117/// registration describes what a session knows how to reason about, while enabling is the
118/// explicit writer policy.
119///
120/// Backed by an [`ArcSwapMap`] keyed by edition family, so clones observe the same selection
121/// and enabling an edition replaces the family's previous entry.
122#[derive(Clone, Debug, Default)]
123pub struct EnabledEditions {
124    inner: EditionsByFamily,
125}
126
127impl EnabledEditions {
128    /// Return the enabled editions.
129    pub fn editions(&self) -> Vec<EditionId> {
130        self.inner.read(|map| map.values().copied().collect())
131    }
132
133    fn enable(&self, edition: EditionId) {
134        // The family is a `&'static str`; `Into<Id>` interns it once at enable time (a rare
135        // config-time write, never on the read path).
136        self.inner.insert(Id::from(edition.family), edition);
137    }
138}
139
140impl EditionSession {
141    /// Create a session variable with no declarations.
142    pub fn empty() -> Self {
143        Self {
144            inner: Arc::new(RwLock::new(Inner::default())),
145        }
146    }
147
148    /// Declare an edition together with the members added at it. Each entry's membership
149    /// (`since`) is the declared edition; earlier entries are inherited and must not be restated.
150    ///
151    /// The declaration is validated in full before anything is registered: on error, neither the
152    /// edition nor any of its members is published.
153    pub fn declare(&self, declaration: &EditionDeclaration) -> VortexResult<()> {
154        let mut inner = self.inner.write();
155        let key = inner.check_edition(declaration.edition)?;
156
157        let mut seen = BTreeSet::new();
158        let mut inclusions = Vec::with_capacity(declaration.added.len());
159        for member in declaration.added {
160            let inclusion =
161                EditionInclusion::new(member.kind, member.component, declaration.edition.id);
162            inner.check_inclusion(&inclusion)?;
163            if !seen.insert((inclusion.kind, inclusion.component_id)) {
164                vortex_bail!(
165                    "{} {} is listed more than once in edition {}",
166                    inclusion.kind,
167                    inclusion.component_id,
168                    inclusion.since,
169                );
170            }
171            inclusions.push(inclusion);
172        }
173
174        inner.editions.insert(key, declaration.edition);
175        for inclusion in inclusions {
176            inner.insert_inclusion(inclusion);
177        }
178        Ok(())
179    }
180
181    /// Declare an edition family. Errors if a family with the same name is already
182    /// declared. Every family must be declared before [`EditionSession::validate`] will
183    /// accept editions belonging to it.
184    pub fn declare_family(&self, family: &EditionFamily) -> VortexResult<()> {
185        let mut inner = self.inner.write();
186        if inner.families.contains_key(family.name) {
187            vortex_bail!("duplicate edition family {}", family.name);
188        }
189        inner.families.insert(family.name.to_string(), *family);
190        Ok(())
191    }
192
193    /// All declared families, sorted by name.
194    pub fn families(&self) -> Vec<EditionFamily> {
195        self.inner.read().families.values().copied().collect()
196    }
197
198    /// Find a declared family by name.
199    pub fn find_family(&self, name: &str) -> Option<EditionFamily> {
200        self.inner.read().families.get(name).copied()
201    }
202
203    /// Declare an edition. Errors if an edition with the same id is already declared.
204    pub fn declare_edition(&self, edition: Edition) -> VortexResult<()> {
205        let mut inner = self.inner.write();
206        let key = inner.check_edition(edition)?;
207        inner.editions.insert(key, edition);
208        Ok(())
209    }
210
211    /// Declare an edition inclusion. A component may belong to multiple families but joins each
212    /// family only once. A newer wire representation uses a new component ID. Kind is part of the
213    /// key, so an array encoding and a layout may share an id.
214    pub fn declare_inclusion(&self, inclusion: EditionInclusion) -> VortexResult<()> {
215        let mut inner = self.inner.write();
216        inner.check_inclusion(&inclusion)?;
217        inner.insert_inclusion(inclusion);
218        Ok(())
219    }
220
221    /// All declared editions, sorted by family and then chronologically. The newest frozen
222    /// edition of each family is that family's `current` edition; unversioned editions are
223    /// drafts.
224    pub fn editions(&self) -> Vec<Edition> {
225        let mut editions: Vec<Edition> = self.inner.read().editions.values().copied().collect();
226        editions.sort_by_key(|e| (e.id.family, e.id.year, e.id.month, e.id.version));
227        editions
228    }
229
230    /// Find a declared edition by id.
231    pub fn find(&self, id: &EditionId) -> Option<Edition> {
232        self.inner.read().editions.get(&id.to_string()).copied()
233    }
234
235    /// Find a declared edition by its name, for example `core2025.10.0`.
236    pub fn find_by_name(&self, name: &str) -> Option<Edition> {
237        self.inner.read().editions.get(name).copied()
238    }
239
240    /// The newest frozen edition of a family, if any. Drafts are never current.
241    pub fn current(&self, family: &str) -> Option<Edition> {
242        self.editions()
243            .into_iter()
244            .rfind(|e| e.id.family == family && !e.is_draft())
245    }
246
247    /// Compute an edition's members of one kind, sorted by component id. For each id, this returns
248    /// its inclusion in the edition's family when it joined at or before the requested edition.
249    /// Only that kind's declarations are scanned.
250    pub fn components_in(&self, edition: &EditionId, kind: ComponentKind) -> Vec<EditionInclusion> {
251        let inner = self.inner.read();
252        let Some(by_id) = inner.inclusions.get(&kind) else {
253            return vec![];
254        };
255        by_id
256            .values()
257            .filter_map(|history| {
258                history
259                    .iter()
260                    .filter(|inclusion| inclusion.since.is_at_or_before(edition))
261                    .max_by_key(|inclusion| {
262                        (
263                            inclusion.since.year,
264                            inclusion.since.month,
265                            inclusion.since.version,
266                        )
267                    })
268                    .copied()
269            })
270            .collect()
271    }
272
273    /// Validate all registered declarations. Errors on editions in undeclared families,
274    /// inclusions referencing undeclared editions, editions out of chronological order within
275    /// a family (unversioned drafts must be newest), malformed version strings, and members
276    /// requiring a release newer than their edition declares.
277    pub fn validate(&self) -> VortexResult<()> {
278        let editions = self.editions();
279
280        for family in self.families() {
281            family.validate()?;
282        }
283
284        for edition in &editions {
285            edition.id.validate()?;
286            if self.find_family(edition.id.family).is_none() {
287                vortex_bail!(
288                    "edition {} belongs to undeclared family {}; declare the family before \
289                     its editions",
290                    edition.id,
291                    edition.id.family,
292                );
293            }
294            if !edition.immutable && !edition.is_draft() {
295                vortex_bail!(
296                    "edition {} never freezes, so it cannot record a min_library_version; \
297                     promote members into a new edition",
298                    edition.id
299                );
300            }
301            if let Some(version) = edition.min_library_version
302                && parse_release(version).is_none()
303            {
304                vortex_bail!(
305                    "edition {} declares malformed min_library_version {version:?}",
306                    edition.id
307                );
308            }
309        }
310
311        // Within each family, frozen editions must precede drafts: a frozen edition after
312        // an unversioned one would imply the draft was skipped.
313        for pair in editions.windows(2) {
314            let (prev, next) = (&pair[0], &pair[1]);
315            if prev.id.family == next.id.family && prev.is_draft() && !next.is_draft() {
316                vortex_bail!(
317                    "frozen edition {} follows draft {}; drafts must be newest in a family",
318                    next.id,
319                    prev.id,
320                );
321            }
322        }
323
324        let inner = self.inner.read();
325        for inclusion in inner
326            .inclusions
327            .values()
328            .flat_map(|by_id| by_id.values())
329            .flatten()
330        {
331            inclusion.validate()?;
332
333            let Some(edition) = inner.editions.get(&inclusion.since.to_string()) else {
334                vortex_bail!(
335                    "{} {} is included in undeclared edition {}",
336                    inclusion.kind,
337                    inclusion.component_id,
338                    inclusion.since
339                );
340            };
341
342            if let Some(required) = inclusion.required_vortex_release.and_then(parse_release)
343                && let Some(declared) = edition.min_library_version.and_then(parse_release)
344                && required > declared
345            {
346                vortex_bail!(
347                    "{} {} requires release {}, newer than edition {}'s declared \
348                     min_library_version",
349                    inclusion.kind,
350                    inclusion.component_id,
351                    inclusion.required_vortex_release.unwrap_or_default(),
352                    edition.id,
353                );
354            }
355        }
356
357        Ok(())
358    }
359}
360
361impl SessionVar for EditionSession {
362    fn as_any(&self) -> &dyn Any {
363        self
364    }
365
366    fn as_any_mut(&mut self) -> &mut dyn Any {
367        self
368    }
369}
370
371impl SessionVar for EnabledEditions {
372    fn as_any(&self) -> &dyn Any {
373        self
374    }
375
376    fn as_any_mut(&mut self) -> &mut dyn Any {
377        self
378    }
379}
380
381/// Session data for Vortex editions.
382pub trait EditionSessionExt: SessionExt {
383    /// Returns the edition registry.
384    fn editions(&self) -> SessionGuard<'_, EditionSession> {
385        self.get::<EditionSession>()
386    }
387
388    /// Returns the editions enabled for writing.
389    ///
390    /// Accessing this method installs the enabled-editions session variable if it is absent, with
391    /// an initially empty selection.
392    fn enabled_editions(&self) -> SessionGuard<'_, EnabledEditions> {
393        self.get::<EnabledEditions>()
394    }
395
396    /// Register an edition declaration with this session.
397    fn register_edition(&self, declaration: &EditionDeclaration) -> VortexResult<()> {
398        self.editions().declare(declaration)
399    }
400
401    /// Enable a registered edition for writing.
402    ///
403    /// Enabling an edition replaces the enabled edition from the same family. An edition
404    /// must be registered first so a typo or unavailable third-party declaration cannot
405    /// silently produce an empty writable set.
406    fn enable_edition(&self, edition: EditionId) -> VortexResult<()> {
407        if self.editions().find(&edition).is_none() {
408            vortex_bail!("cannot enable unregistered edition {edition}");
409        }
410        self.enabled_editions().enable(edition);
411        Ok(())
412    }
413
414    /// Resolve the ids of one [`ComponentKind`] across all enabled editions: what a writer may
415    /// emit for that kind.
416    ///
417    /// Ids are only unique within a kind, so this never mixes kinds. An empty result means the
418    /// enabled editions permit no components of this kind.
419    fn enabled_component_ids(&self, kind: ComponentKind) -> Vec<Id> {
420        let Some(enabled) = self.get_opt::<EnabledEditions>() else {
421            return vec![];
422        };
423        let editions = self.editions();
424        let mut ids: Vec<Id> = enabled
425            .editions()
426            .iter()
427            .flat_map(|edition| editions.components_in(edition, kind))
428            .map(|inclusion| inclusion.component_id)
429            .collect();
430        ids.sort_unstable();
431        ids.dedup();
432        ids
433    }
434}
435
436impl<S: SessionExt> EditionSessionExt for S {}