aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authortv <tv@krebsco.de>2026-11-29 15:02:23 +0000
committertv <tv@krebsco.de>2026-11-30 14:59:15 +0000
commita0f22c88d54d351b060c2d0d9f0a8cbf5f412ba2 (patch)
treed65495f9ed222fb978bc09afcb3bd644a99aa7c5 /src
parent83f1d36bbaeb193ae1c663b5b1b7956661ecac8c (diff)
enstate: --migrate, renames both ways, kept entries
What a generation sees of a snapshot accepted under another schema: same name and type, renamedFrom, a rename in the stored schema read backwards, and entries kept, with their types, in the snapshot's kept/. Plans start from what is seen, and store it under the running schema; a generation change rewrites no snapshot. --migrate (and --dry-run) says what each channel sees, refuses for required slots nothing fills, puts the views in place and runs their reactions; --materialize and --status go by what is seen, too. A view made from an unfilled required slot isn't there. The rollback cases of migrations.md that need no converters or steps are tests.
Diffstat (limited to 'src')
-rw-r--r--src/lib.rs2
-rw-r--r--src/main.rs154
-rw-r--r--src/migrate.rs325
-rw-r--r--src/plan.rs104
-rw-r--r--src/schema.rs7
-rw-r--r--src/store.rs60
-rw-r--r--src/view.rs12
7 files changed, 545 insertions, 119 deletions
diff --git a/src/lib.rs b/src/lib.rs
index af7de7e..f78f51f 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -9,10 +9,12 @@
//! * [`view`]: rendering views, comparing them, installing them;
//! * [`store`]: snapshots on disk, and the views in place;
//! * [`plan`]: what a submission would do, and applying it;
+//! * [`migrate`]: what a generation sees of snapshots accepted under other schemas;
//! * [`pack`]: making a submission from a source list.
pub mod content;
pub mod media;
+pub mod migrate;
pub mod name;
pub mod pack;
pub mod plan;
diff --git a/src/main.rs b/src/main.rs
index 16c553d..3539d76 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -81,6 +81,10 @@ const COMMANDS: &[(&str, &str)] = &[
"Put every view in place from the snapshots (at boot, after a switch)",
),
(
+ "migrate",
+ "Serve the generation of --schema from the snapshots: what it sees, its views, their reactions",
+ ),
+ (
"pack",
"Make a submission in --out from the source list in PATH",
),
@@ -119,7 +123,13 @@ fn command() -> Command {
Arg::new("json")
.long("json")
.action(ArgAction::SetTrue)
- .help("Print JSON (--plan, --apply, --status, --materialize)"),
+ .help("Print JSON (--plan, --apply, --status, --materialize, --migrate)"),
+ )
+ .arg(
+ Arg::new("dry-run")
+ .long("dry-run")
+ .action(ArgAction::SetTrue)
+ .help("With --migrate: say what it would do, changing nothing"),
)
.arg(
Arg::new("out")
@@ -188,6 +198,9 @@ fn run() -> Result<ExitCode> {
if out.is_some() && command != "pack" {
bail!("--out is for --pack only");
}
+ if matches.get_flag("dry-run") && command != "migrate" {
+ bail!("--dry-run is for --migrate only");
+ }
if json && command == "pack" {
bail!("--json is not for --pack");
}
@@ -241,7 +254,7 @@ fn run() -> Result<ExitCode> {
})
}
"materialize" => {
- let views = plan::materialize(&schema, &store)?;
+ let views = enstate::migrate::materialize(&schema, &store)?;
if json {
println!("{}", serde_json::to_string_pretty(&views)?);
} else {
@@ -249,6 +262,26 @@ fn run() -> Result<ExitCode> {
}
Ok(ExitCode::SUCCESS)
}
+ "migrate" => {
+ let migration = enstate::migrate::migrate(
+ &schema,
+ &store,
+ matches.get_flag("dry-run"),
+ &systemctl,
+ )?;
+ if json {
+ println!("{}", serde_json::to_string_pretty(&migration)?);
+ } else {
+ print_migration(&migration)?;
+ }
+ Ok(if !migration.accepted {
+ ExitCode::from(1)
+ } else if !migration.failed.is_empty() {
+ ExitCode::from(3)
+ } else {
+ ExitCode::SUCCESS
+ })
+ }
"status" => {
let status = status(&schema, &store)?;
if json {
@@ -405,6 +438,8 @@ struct ChannelStatus {
missing: Vec<String>,
/// Kept, but in no slot of the schema.
kept: Vec<String>,
+ /// Where entries came from, what can't be taken.
+ notes: Vec<String>,
}
#[derive(serde::Serialize)]
@@ -413,27 +448,57 @@ struct ViewStatus {
installed: bool,
}
-fn status(schema: &Schema, store: &Store) -> Result<Status> {
- let mut channels = Vec::new();
- let mut names: Vec<String> = schema.channels.keys().cloned().collect();
- for channel in store.channels()? {
- if !names.contains(&channel) {
- names.push(channel);
+fn print_status(status: &Status) -> Result<()> {
+ let style = Style::new();
+ let mut out = std::io::stdout().lock();
+ for channel in &status.channels {
+ writeln!(
+ out,
+ "channel {}: snapshot {}",
+ channel.channel,
+ channel.snapshot.as_deref().unwrap_or("none")
+ )?;
+ for slot in &channel.filled {
+ writeln!(out, " {} {slot}", style.paint("32", "filled"))?;
+ }
+ for slot in &channel.unfilled {
+ let missing = channel.missing.contains(slot);
+ let label = if missing {
+ style.paint("31", "missing")
+ } else {
+ "unfilled".to_owned()
+ };
+ writeln!(out, " {label} {slot}")?;
+ }
+ for slot in &channel.kept {
+ writeln!(out, " {} {slot}", style.paint("33", "kept"))?;
+ }
+ for note in &channel.notes {
+ writeln!(out, " {note}")?;
}
}
- for channel in names {
- let snapshot = store.current(&channel)?;
- let content = snapshot
- .as_ref()
- .map(|snapshot| snapshot.content.clone())
- .unwrap_or_default();
+ for view in &status.views {
+ let state = if view.installed {
+ style.paint("32", "in place")
+ } else {
+ style.paint("33", "not in place")
+ };
+ writeln!(out, "view {}: {state}", view.view)?;
+ }
+ Ok(())
+}
+
+fn status(schema: &Schema, store: &Store) -> Result<Status> {
+ let mut channels = Vec::new();
+ for (channel, seen) in enstate::migrate::seen_all(schema, store)? {
let slots = schema
.channel(&channel)
.map(|spec| spec.slots.clone())
.unwrap_or_default();
+ let content = &seen.content;
channels.push(ChannelStatus {
channel: channel.clone(),
- snapshot: snapshot.map(|snapshot| snapshot.id),
+ snapshot: store.current(&channel)?.map(|snapshot| snapshot.id),
filled: slots
.keys()
.filter(|slot| content.contains_key(*slot))
@@ -449,11 +514,8 @@ fn status(schema: &Schema, store: &Store) -> Result<Status> {
.filter(|(slot, spec)| spec.required && !content.contains_key(*slot))
.map(|(slot, _)| slot.clone())
.collect(),
- kept: content
- .keys()
- .filter(|slot| !slots.contains_key(*slot))
- .cloned()
- .collect(),
+ kept: seen.kept_names(),
+ notes: seen.notes.clone(),
});
}
let views = schema
@@ -467,39 +529,41 @@ fn status(schema: &Schema, store: &Store) -> Result<Status> {
Ok(Status { channels, views })
}
-fn print_status(status: &Status) -> Result<()> {
+fn print_migration(migration: &enstate::migrate::Migration) -> Result<()> {
let style = Style::new();
let mut out = std::io::stdout().lock();
- for channel in &status.channels {
+ let verdict = if migration.accepted {
+ style.paint("32", "every required slot is filled")
+ } else {
+ style.paint("31", "refused")
+ };
+ let dry_run = if migration.dry_run { " (dry run)" } else { "" };
+ writeln!(out, "migration{dry_run}: {verdict}")?;
+ for reason in &migration.refused {
+ writeln!(out, " {} {reason}", style.paint("31", "refused:"))?;
+ }
+ for (channel, channel_migration) in &migration.channels {
writeln!(
out,
- "channel {}: snapshot {}",
- channel.channel,
- channel.snapshot.as_deref().unwrap_or("none")
+ "channel {channel}: snapshot {}",
+ channel_migration.snapshot.as_deref().unwrap_or("none")
)?;
- for slot in &channel.filled {
- writeln!(out, " {} {slot}", style.paint("32", "filled"))?;
- }
- for slot in &channel.unfilled {
- let missing = channel.missing.contains(slot);
- let label = if missing {
- style.paint("31", "missing")
- } else {
- "unfilled".to_owned()
- };
- writeln!(out, " {label} {slot}")?;
+ for note in &channel_migration.seen.notes {
+ writeln!(out, " {note}")?;
}
- for slot in &channel.kept {
- writeln!(out, " {} {slot}", style.paint("33", "kept"))?;
+ for slot in &channel_migration.kept {
+ writeln!(out, " {} {channel}/{slot}", style.paint("33", "kept"))?;
}
}
- for view in &status.views {
- let state = if view.installed {
- style.paint("32", "in place")
- } else {
- style.paint("33", "not in place")
- };
- writeln!(out, "view {}: {state}", view.view)?;
+ print_views(&mut out, &migration.views, true)?;
+ if !migration.reactions.restart.is_empty() {
+ writeln!(out, "restart: {}", migration.reactions.restart.join(" "))?;
+ }
+ if !migration.reactions.reload.is_empty() {
+ writeln!(out, "reload: {}", migration.reactions.reload.join(" "))?;
+ }
+ for failed in &migration.failed {
+ writeln!(out, "{} {failed}", style.paint("31", "failed:"))?;
}
Ok(())
}
diff --git a/src/migrate.rs b/src/migrate.rs
new file mode 100644
index 0000000..340180f
--- /dev/null
+++ b/src/migrate.rs
@@ -0,0 +1,325 @@
+//! Migrations (docs/design.md, section 6): what a generation sees of the snapshots,
+//! which were accepted under other schemas, and putting views in place for it.
+//!
+//! What a slot of the running schema is filled with, from the stored snapshot and the
+//! schema it was accepted under, the first that fits:
+//!
+//! 1. the entry of the same name, of the same type;
+//! 2. the entry of the name the slot says it was `renamedFrom`;
+//! 3. the entry of a slot that says, in the stored schema, it was renamed from this
+//! one: the way back after a rollback;
+//! 4. an entry kept under the same name, of the same type, unless the stored snapshot
+//! has an entry of that name: kept entries are older than any stored.
+//!
+//! Entries no slot takes are kept, with their types. A generation change never
+//! rewrites a snapshot: what is seen is computed each time, and stored only when a
+//! submission is applied. Not yet: converters, derived slots, steps.
+
+use std::collections::{BTreeMap, BTreeSet};
+use std::path::Path;
+
+use anyhow::{Context, Result};
+use serde::Serialize;
+
+use crate::content::Content;
+use crate::name::Address;
+use crate::plan::{ViewOutcome, react};
+use crate::schema::{Reactions, Schema};
+use crate::scratch::Scratch;
+use crate::store::{Kept, Snapshot, Store};
+use crate::view;
+
+/// What the running generation sees of one channel.
+#[derive(Debug, Clone, Default, Serialize)]
+pub struct Seen {
+ #[serde(skip)]
+ pub content: Content,
+ #[serde(skip)]
+ pub kept: Kept,
+ /// Where entries came from, where that isn't their own slot; what can't be taken.
+ pub notes: Vec<String>,
+ /// Required slots nothing fills.
+ pub unfilled: Vec<String>,
+}
+
+impl Seen {
+ /// The names of the entries kept.
+ pub fn kept_names(&self) -> Vec<String> {
+ self.kept.keys().cloned().collect()
+ }
+}
+
+/// What `schema` sees of `channel`, whose current snapshot is `snapshot`.
+pub fn seen(schema: &Schema, channel: &str, snapshot: Option<&Snapshot>) -> Result<Seen> {
+ let mut seen = Seen::default();
+ let empty_slots = BTreeMap::new();
+ let slots = schema
+ .channel(channel)
+ .map(|spec| &spec.slots)
+ .unwrap_or(&empty_slots);
+ let Some(snapshot) = snapshot else {
+ seen.unfilled = slots
+ .iter()
+ .filter(|(_, spec)| spec.required)
+ .map(|(slot, _)| format!("{channel}/{slot}"))
+ .collect();
+ return Ok(seen);
+ };
+ let stored = Schema::from_slice(&snapshot.schema)
+ .with_context(|| format!("the schema channel {channel}'s snapshot was accepted under"))?;
+ let stored_slots = stored
+ .channel(channel)
+ .map(|spec| spec.slots.clone())
+ .unwrap_or_default();
+ let stored_type = |slot: &str| {
+ stored
+ .slot(&Address::entry(channel, slot))
+ .map(|spec| spec.media_type.clone())
+ };
+ let entries = &snapshot.content;
+ let mut taken: BTreeSet<&str> = BTreeSet::new();
+ let mut kept_taken: BTreeSet<&str> = BTreeSet::new();
+ let mut filled: BTreeSet<&str> = BTreeSet::new();
+ // 1. Same name, same type.
+ for (slot, spec) in slots {
+ let Some(bytes) = entries.get(slot) else {
+ continue;
+ };
+ match stored_type(slot) {
+ Some(media_type) if media_type == spec.media_type => {
+ seen.content.insert(slot.clone(), bytes.clone());
+ taken.insert(slot);
+ filled.insert(slot);
+ }
+ Some(media_type) => seen.notes.push(format!(
+ "{channel}/{slot}: type {media_type} is now {}, and there is no converter",
+ spec.media_type
+ )),
+ None => {}
+ }
+ }
+ // 2. Renamed from.
+ for (slot, spec) in slots {
+ if filled.contains(slot.as_str()) {
+ continue;
+ }
+ let Some(old) = &spec.renamed_from else {
+ continue;
+ };
+ if let Some(bytes) = entries.get(old)
+ && !taken.contains(old.as_str())
+ && stored_type(old).as_ref() == Some(&spec.media_type)
+ {
+ seen.content.insert(slot.clone(), bytes.clone());
+ seen.notes
+ .push(format!("{channel}/{slot}: from {channel}/{old}, renamed"));
+ taken.insert(old);
+ filled.insert(slot);
+ }
+ }
+ // 3. Renamed, by the stored schema, from this one.
+ for (slot, spec) in slots {
+ if filled.contains(slot.as_str()) {
+ continue;
+ }
+ let newer = stored_slots.iter().find(|(newer, newer_spec)| {
+ newer_spec.renamed_from.as_deref() == Some(slot.as_str())
+ && newer_spec.media_type == spec.media_type
+ && entries.contains_key(*newer)
+ && !taken.contains(newer.as_str())
+ });
+ if let Some((newer, _)) = newer {
+ let (newer, bytes) = entries.get_key_value(newer).unwrap();
+ seen.content.insert(slot.clone(), bytes.clone());
+ seen.notes.push(format!(
+ "{channel}/{slot}: from {channel}/{newer}, which the schema it was accepted under renamed from it"
+ ));
+ taken.insert(newer);
+ filled.insert(slot);
+ }
+ }
+ // 4. Kept, under the same name, of the same type, unless there is a newer entry
+ // of that name: what was kept is never used once its slot was filled anew.
+ for (slot, spec) in slots {
+ if filled.contains(slot.as_str()) {
+ continue;
+ }
+ if let Some((media_type, bytes)) = snapshot.kept.get(slot)
+ && *media_type == spec.media_type
+ && !entries.contains_key(slot)
+ {
+ seen.content.insert(slot.clone(), bytes.clone());
+ seen.notes
+ .push(format!("{channel}/{slot}: from what was kept"));
+ kept_taken.insert(slot);
+ filled.insert(slot);
+ }
+ }
+ for (slot, spec) in slots {
+ if spec.required && !filled.contains(slot.as_str()) {
+ seen.unfilled.push(format!("{channel}/{slot}"));
+ }
+ }
+ // What no slot took is kept: the stored entries, then what was kept before.
+ for (slot, bytes) in entries {
+ if !taken.contains(slot.as_str()) {
+ let media_type =
+ stored_type(slot).unwrap_or_else(|| "application/octet-stream".to_owned());
+ seen.kept.insert(slot.clone(), (media_type, bytes.clone()));
+ }
+ }
+ for (slot, kept) in &snapshot.kept {
+ if !kept_taken.contains(slot.as_str()) && !seen.kept.contains_key(slot) {
+ seen.kept.insert(slot.clone(), kept.clone());
+ }
+ }
+ Ok(seen)
+}
+
+/// What every channel of `schema` sees, by channel.
+pub fn seen_all(schema: &Schema, store: &Store) -> Result<BTreeMap<String, Seen>> {
+ let mut all = BTreeMap::new();
+ let mut channels: BTreeSet<String> = schema.channels.keys().cloned().collect();
+ channels.extend(store.channels()?);
+ for channel in channels {
+ let snapshot = store.current(&channel)?;
+ all.insert(channel.clone(), seen(schema, &channel, snapshot.as_ref())?);
+ }
+ Ok(all)
+}
+
+/// Renders every view of `schema` from `seen`, and, unless `dry_run`, puts those that
+/// differ from what is in place there, and takes away views the schema doesn't have.
+/// Returns how each view changes.
+pub fn put_views(
+ schema: &Schema,
+ store: &Store,
+ seen: &BTreeMap<String, Seen>,
+ dry_run: bool,
+) -> Result<Vec<ViewOutcome>> {
+ let entries: view::Entries = seen
+ .iter()
+ .map(|(name, seen)| (name.as_str(), &seen.content))
+ .collect();
+ let mut outcomes = Vec::new();
+ for (name, view_spec) in schema.views_of(None) {
+ let secret = schema.view_is_secret(view_spec);
+ let rendered = view::render(schema, name, view_spec, &entries, &store.scratch())
+ .with_context(|| format!("view {name}"))?;
+ let installed = store.installed_view(name);
+ let (change, files) = view::compare(
+ installed.as_deref(),
+ rendered.as_ref().map(Scratch::path),
+ secret,
+ )?;
+ if change != view::Change::Unchanged && !dry_run {
+ store.install_view(name, rendered, secret)?;
+ }
+ outcomes.push(ViewOutcome {
+ name: name.clone(),
+ secret,
+ change,
+ files,
+ });
+ }
+ for name in store.installed_views()? {
+ if !schema.views.contains_key(&name) {
+ if !dry_run {
+ store.install_view(&name, None, false)?;
+ }
+ outcomes.push(ViewOutcome {
+ name,
+ secret: false,
+ change: view::Change::Removed,
+ files: Vec::new(),
+ });
+ }
+ }
+ Ok(outcomes)
+}
+
+/// Puts every view of `schema` in place from the snapshots, and takes away those it
+/// doesn't have: at boot. Runs no reactions.
+pub fn materialize(schema: &Schema, store: &Store) -> Result<Vec<ViewOutcome>> {
+ put_views(schema, store, &seen_all(schema, store)?, false)
+}
+
+#[derive(Debug, Clone, Serialize)]
+pub struct Migration {
+ /// Whether the state fills every required slot of the schema.
+ pub accepted: bool,
+ pub refused: Vec<String>,
+ pub channels: BTreeMap<String, ChannelMigration>,
+ pub views: Vec<ViewOutcome>,
+ pub reactions: Reactions,
+ pub dry_run: bool,
+ #[serde(skip_serializing_if = "Vec::is_empty")]
+ pub failed: Vec<String>,
+}
+
+#[derive(Debug, Clone, Serialize)]
+pub struct ChannelMigration {
+ pub snapshot: Option<String>,
+ #[serde(flatten)]
+ pub seen: Seen,
+ pub kept: Vec<String>,
+}
+
+/// Serves the generation of `schema` from the snapshots, after a generation change, or
+/// before it (`dry_run`): what each channel sees, which required slots nothing fills
+/// (which refuses the switch), and how the views change. Unless `dry_run`, the views
+/// are put in place, those of unfilled required slots taken away, and the reactions of
+/// those that changed run by `systemctl`.
+pub fn migrate(
+ schema: &Schema,
+ store: &Store,
+ dry_run: bool,
+ systemctl: &Path,
+) -> Result<Migration> {
+ let seen = seen_all(schema, store)?;
+ let mut channels = BTreeMap::new();
+ let mut refused = Vec::new();
+ for (channel, channel_seen) in &seen {
+ for slot in &channel_seen.unfilled {
+ refused.push(format!("required slot {slot} can't be filled"));
+ }
+ channels.insert(
+ channel.clone(),
+ ChannelMigration {
+ snapshot: store.current(channel)?.map(|snapshot| snapshot.id),
+ seen: channel_seen.clone(),
+ kept: channel_seen.kept_names(),
+ },
+ );
+ }
+ let views = put_views(schema, store, &seen, dry_run)?;
+ let mut restart = BTreeSet::new();
+ let mut reload = BTreeSet::new();
+ for outcome in &views {
+ if outcome.change == view::Change::Unchanged {
+ continue;
+ }
+ if let Some(spec) = schema.views.get(&outcome.name) {
+ restart.extend(spec.reactions.restart.iter().cloned());
+ reload.extend(spec.reactions.reload.iter().cloned());
+ }
+ }
+ let reactions = Reactions {
+ reload: reload.difference(&restart).cloned().collect(),
+ restart: restart.into_iter().collect(),
+ };
+ let failed = if dry_run {
+ Vec::new()
+ } else {
+ react(&reactions, systemctl)
+ };
+ Ok(Migration {
+ accepted: refused.is_empty(),
+ refused,
+ channels,
+ views,
+ reactions,
+ dry_run,
+ failed,
+ })
+}
diff --git a/src/plan.rs b/src/plan.rs
index 952f3aa..80e2bad 100644
--- a/src/plan.rs
+++ b/src/plan.rs
@@ -16,11 +16,12 @@ use serde::Serialize;
use crate::content::{self, Content};
use crate::media;
+use crate::migrate;
use crate::name::Address;
use crate::program::{self, Given, ProgramFailed, Role};
use crate::schema::{Reactions, Schema};
use crate::scratch::Scratch;
-use crate::store::Store;
+use crate::store::{Kept, Store};
use crate::submission::{Change, Item, Submission};
use crate::view::{self, FileChange};
@@ -72,6 +73,7 @@ pub struct ViewOutcome {
pub struct Planned {
pub plan: Plan,
content: Content,
+ kept: Kept,
content_changes: bool,
rendered: Vec<(String, Option<Scratch>, bool)>,
}
@@ -81,6 +83,7 @@ fn refused(plan: Plan) -> Result<Planned> {
Ok(Planned {
plan,
content: Content::new(),
+ kept: Kept::new(),
content_changes: false,
rendered: Vec::new(),
})
@@ -134,8 +137,11 @@ pub fn plan(schema: &Schema, store: &Store, submission: &Submission) -> Result<P
}
}
let empty = Content::new();
+ // What this generation sees of the snapshot, which may have been accepted under
+ // another schema.
+ let seen = migrate::seen(schema, channel, current.as_ref())?;
let base_content = match (&current, submission.complete) {
- (Some(snapshot), false) => &snapshot.content,
+ (Some(_), false) => &seen.content,
_ => &empty,
};
// Other channels, for validators and views given their slots.
@@ -156,10 +162,7 @@ pub fn plan(schema: &Schema, store: &Store, submission: &Submission) -> Result<P
}
}
for other in other_channels {
- let content = store
- .current(other)?
- .map(|snapshot| snapshot.content)
- .unwrap_or_default();
+ let content = migrate::seen(schema, other, store.current(other)?.as_ref())?.content;
others.insert(other.to_owned(), content);
}
@@ -310,13 +313,31 @@ pub fn plan(schema: &Schema, store: &Store, submission: &Submission) -> Result<P
}
}
};
- for slot in candidate.keys() {
- if !channel_spec.slots.contains_key(slot) {
+ // What no slot wants: kept, unless the submission is complete.
+ let kept = if submission.complete {
+ for slot in seen.kept.keys() {
plan.warnings.push(format!(
- "kept, but in no slot of the schema: {channel}/{slot}"
+ "goes, as the submission is complete: {channel}/{slot}, which was kept"
));
}
- }
+ Kept::new()
+ } else {
+ let mut kept = seen.kept.clone();
+ kept.retain(|slot, (media_type, _)| {
+ let superseded = candidate.contains_key(slot);
+ if superseded {
+ plan.warnings.push(format!(
+ "goes, as {channel}/{slot} is filled anew: the entry of type {media_type} kept from before"
+ ));
+ }
+ !superseded
+ });
+ for slot in kept.keys() {
+ plan.warnings
+ .push(format!("kept, in no slot of the schema: {channel}/{slot}"));
+ }
+ kept
+ };
// Views.
let mut rendered_views = Vec::new();
@@ -370,7 +391,7 @@ pub fn plan(schema: &Schema, store: &Store, submission: &Submission) -> Result<P
restart: restart.into_iter().collect(),
reload: reload.into_iter().collect(),
};
- let content_changes = current.as_ref().map(|snapshot| &snapshot.content) != Some(&candidate);
+ let content_changes = current.is_none() || candidate != seen.content || kept != seen.kept;
plan.changes = content_changes
|| plan
.views
@@ -380,6 +401,7 @@ pub fn plan(schema: &Schema, store: &Store, submission: &Submission) -> Result<P
Ok(Planned {
plan,
content: candidate,
+ kept,
content_changes,
rendered: rendered_views,
})
@@ -457,6 +479,7 @@ impl Planned {
plan.snapshot = Some(store.commit(
&plan.channel,
&self.content,
+ &self.kept,
plan.current.as_deref(),
schema_bytes,
)?);
@@ -505,62 +528,3 @@ pub fn react(reactions: &Reactions, systemctl: &Path) -> Vec<String> {
}
failed
}
-
-/// Renders every view of `schema` from the current snapshots, puts those that differ
-/// from what is in place there, and takes away views the schema doesn't have: at boot,
-/// and after a generation change. Runs no reactions. Returns how each view changed.
-pub fn materialize(schema: &Schema, store: &Store) -> Result<Vec<ViewOutcome>> {
- let mut contents: BTreeMap<String, Content> = BTreeMap::new();
- for channel in schema.channels.keys() {
- if let Some(snapshot) = store.current(channel)? {
- contents.insert(channel.clone(), snapshot.content);
- }
- }
- let entries: view::Entries = contents
- .iter()
- .map(|(name, content)| (name.as_str(), content))
- .collect();
- let mut outcomes = Vec::new();
- for (name, view_spec) in schema.views_of(None) {
- let secret = schema.view_is_secret(view_spec);
- let rendered = view::render(schema, name, view_spec, &entries, &store.scratch())
- .with_context(|| format!("view {name}"))?;
- let installed = store.installed_view(name);
- let (change, files) = view::compare(
- installed.as_deref(),
- rendered.as_ref().map(Scratch::path),
- secret,
- )?;
- if change != view::Change::Unchanged {
- store.install_view(name, rendered, secret)?;
- }
- outcomes.push(ViewOutcome {
- name: name.clone(),
- secret,
- change,
- files,
- });
- }
- let views = store.run.join("views");
- if let Ok(entries) = std::fs::read_dir(&views) {
- for entry in entries {
- let name = entry?.file_name().to_string_lossy().into_owned();
- if name == ".generations"
- || name.ends_with(".new-link")
- || schema.views.contains_key(&name)
- {
- continue;
- }
- if store.installed_view(&name).is_some() {
- store.install_view(&name, None, false)?;
- outcomes.push(ViewOutcome {
- name,
- secret: false,
- change: view::Change::Removed,
- files: Vec::new(),
- });
- }
- }
- }
- Ok(outcomes)
-}
diff --git a/src/schema.rs b/src/schema.rs
index a44f6f8..8b20777 100644
--- a/src/schema.rs
+++ b/src/schema.rs
@@ -66,6 +66,9 @@ pub struct SlotSpec {
pub required: bool,
#[serde(default)]
pub secret: bool,
+ /// The name the slot had in an earlier schema (docs/design.md, section 6).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub renamed_from: Option<String>,
}
fn yes() -> bool {
@@ -123,6 +126,10 @@ impl Schema {
name::check("channel", channel)?;
for (slot, spec) in &mut spec.slots {
name::check("slot", slot)?;
+ if let Some(old) = &spec.renamed_from {
+ name::check("slot", old)
+ .with_context(|| format!("slot {channel}/{slot}: renamedFrom"))?;
+ }
spec.media_type = media::normalize(&spec.media_type)
.with_context(|| format!("slot {channel}/{slot}"))?;
}
diff --git a/src/store.rs b/src/store.rs
index b25495e..4ac5ef2 100644
--- a/src/store.rs
+++ b/src/store.rs
@@ -6,6 +6,7 @@
//! STATE/channels/CHANNEL/snapshots/ID/snapshot.json id, and the id it was built on
//! STATE/channels/CHANNEL/snapshots/ID/schema.json the schema it was accepted under
//! STATE/channels/CHANNEL/snapshots/ID/entries/SLOT
+//! STATE/channels/CHANNEL/snapshots/ID/kept/SLOT what no slot wanted, types in snapshot.json
//! RUN/views/VIEW -> .generations/VIEW.ID
//! RUN/tmp/ scratch
//! ```
@@ -24,6 +25,9 @@ use serde::{Deserialize, Serialize};
use crate::content::{self, Content};
use crate::scratch::Scratch;
+/// Entries kept: by slot name, the type each had, and the entry.
+pub type Kept = std::collections::BTreeMap<String, (String, Vec<u8>)>;
+
pub struct Store {
pub state: PathBuf,
pub run: PathBuf,
@@ -34,6 +38,9 @@ pub struct Snapshot {
pub id: String,
pub base: Option<String>,
pub content: Content,
+ /// Entries no slot of the schema it was accepted under wanted, by slot name, with
+ /// the types they had (docs/design.md, section 6).
+ pub kept: Kept,
/// The schema it was accepted under, as it was.
pub schema: Vec<u8>,
}
@@ -44,6 +51,9 @@ struct SnapshotFile {
id: String,
channel: String,
base: Option<String>,
+ /// The types of the entries in `kept/`.
+ #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
+ kept: std::collections::BTreeMap<String, String>,
}
/// Held while the store is used; released when dropped.
@@ -122,20 +132,33 @@ impl Store {
}
let schema = std::fs::read(dir.join("schema.json"))
.with_context(|| format!("reading {}", dir.join("schema.json").display()))?;
+ let mut kept_entries = content::read_dir(&dir.join("kept"))?;
+ let mut kept = Kept::new();
+ for (slot, media_type) in file.kept {
+ let bytes = kept_entries
+ .remove(&slot)
+ .with_context(|| format!("{}: kept {slot} is missing", dir.display()))?;
+ kept.insert(slot, (media_type, bytes));
+ }
+ if let Some(slot) = kept_entries.keys().next() {
+ bail!("{}: kept {slot} has no type", dir.display());
+ }
Ok(Some(Snapshot {
id: file.id,
base: file.base,
content: content::read_dir(&dir.join("entries"))?,
+ kept,
schema,
}))
}
- /// Makes `content` the current snapshot of `channel`, accepted under `schema`,
- /// built on `base`; returns its id. The snapshot it replaces is removed.
+ /// Makes `content`, and `kept`, the current snapshot of `channel`, accepted under
+ /// `schema`, built on `base`; returns its id. The snapshot it replaces is removed.
pub fn commit(
&self,
channel: &str,
content: &Content,
+ kept: &Kept,
base: Option<&str>,
schema: &[u8],
) -> Result<String> {
@@ -148,6 +171,10 @@ impl Store {
id: id.clone(),
channel: channel.to_owned(),
base: base.map(str::to_owned),
+ kept: kept
+ .iter()
+ .map(|(slot, (media_type, _))| (slot.clone(), media_type.clone()))
+ .collect(),
};
content::write_file(
&new.join("snapshot.json"),
@@ -156,6 +183,13 @@ impl Store {
)?;
content::write_file(&new.join("schema.json"), schema, 0o600)?;
content::write_dir(content, &new.join("entries"), 0o600)?;
+ if !kept.is_empty() {
+ let kept: Content = kept
+ .iter()
+ .map(|(slot, (_, bytes))| (slot.clone(), bytes.clone()))
+ .collect();
+ content::write_dir(&kept, &new.join("kept"), 0o600)?;
+ }
std::fs::rename(&new, snapshots.join(&id))?;
let old = std::fs::read_link(self.channel_dir(channel).join("current")).ok();
replace_link(
@@ -168,6 +202,28 @@ impl Store {
Ok(id)
}
+ /// The views in place.
+ pub fn installed_views(&self) -> Result<Vec<String>> {
+ let views = self.run.join("views");
+ let mut names = Vec::new();
+ let entries = match std::fs::read_dir(&views) {
+ Ok(entries) => entries,
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(names),
+ Err(error) => {
+ return Err(error).with_context(|| format!("reading {}", views.display()));
+ }
+ };
+ for entry in entries {
+ let entry = entry?;
+ let name = entry.file_name().to_string_lossy().into_owned();
+ if entry.file_type()?.is_symlink() && !name.ends_with(".new-link") {
+ names.push(name);
+ }
+ }
+ names.sort();
+ Ok(names)
+ }
+
/// The directory the view `name` is in place at, if it is.
pub fn installed_view(&self, name: &str) -> Option<PathBuf> {
let link = self.run.join("views").join(name);
diff --git a/src/view.rs b/src/view.rs
index b7bab6c..bd4b8f5 100644
--- a/src/view.rs
+++ b/src/view.rs
@@ -17,8 +17,9 @@ use crate::scratch::Scratch;
/// would be, the others as they are.
pub type Entries<'a> = BTreeMap<&'a str, &'a Content>;
-/// Renders the view `name` from `entries` into scratch below `scratch`; nothing if it
-/// is an entry's own and that entry isn't there.
+/// Renders the view `name` from `entries` into scratch below `scratch`; nothing if a
+/// required slot it is made from is unfilled, or it is an entry's own and that entry
+/// isn't there.
pub fn render(
schema: &Schema,
name: &str,
@@ -31,6 +32,13 @@ pub fn render(
.get(address.channel.as_str())
.and_then(|content| content.get(&address.slot))
};
+ // A view made from a required slot that is unfilled isn't there (docs/design.md,
+ // section 7).
+ if view.from.iter().any(|address| {
+ schema.slot(address).is_some_and(|slot| slot.required) && entry(address).is_none()
+ }) {
+ return Ok(None);
+ }
match &view.renderer {
None => {
let address = &view.from[0];