aboutsummaryrefslogtreecommitdiffstats
path: root/src/store.rs
diff options
context:
space:
mode:
authortv <tv@krebsco.de>2026-11-29 14:21:34 +0000
committertv <tv@krebsco.de>2026-11-30 14:59:15 +0000
commiteaac60ba88728bb582778c726e5798156dddfc45 (patch)
tree557f4709762f95a7a440d1fa919dcce3bbf83cb4 /src/store.rs
parent70367d17613ebe501fb2d3e9fa72b16c2eb9c2bd (diff)
enstate: the receptor and the provider, a first version
One program on a library: --plan and --apply of submissions (complete and partial, items required and optional, groups, removal, the chain as order), validators of types and across slots, views put in place by replacing a link, their reactions by systemctl; --status, --materialize; and --pack, a submission from a source list in JSON or TOML, by the config crate's sources. Programs by the protocol of design.md 5.2; tests with shell scripts as validators and renderers.
Diffstat (limited to 'src/store.rs')
-rw-r--r--src/store.rs225
1 files changed, 225 insertions, 0 deletions
diff --git a/src/store.rs b/src/store.rs
new file mode 100644
index 0000000..b25495e
--- /dev/null
+++ b/src/store.rs
@@ -0,0 +1,225 @@
+//! Snapshots on disk, and the views in place (docs/design.md, 5.8).
+//!
+//! ```text
+//! STATE/lock
+//! STATE/channels/CHANNEL/current -> snapshots/ID
+//! 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
+//! RUN/views/VIEW -> .generations/VIEW.ID
+//! RUN/tmp/ scratch
+//! ```
+//!
+//! Entries are root's (mode 0600). A new snapshot or view generation is written
+//! next to the old one and put in place by replacing a symbolic link, so a reader
+//! sees one or the other, never a mix.
+
+use std::fs::File;
+use std::os::unix::fs::DirBuilderExt;
+use std::path::{Path, PathBuf};
+
+use anyhow::{Context, Result, bail};
+use serde::{Deserialize, Serialize};
+
+use crate::content::{self, Content};
+use crate::scratch::Scratch;
+
+pub struct Store {
+ pub state: PathBuf,
+ pub run: PathBuf,
+}
+
+#[derive(Debug, Clone)]
+pub struct Snapshot {
+ pub id: String,
+ pub base: Option<String>,
+ pub content: Content,
+ /// The schema it was accepted under, as it was.
+ pub schema: Vec<u8>,
+}
+
+#[derive(Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+struct SnapshotFile {
+ id: String,
+ channel: String,
+ base: Option<String>,
+}
+
+/// Held while the store is used; released when dropped.
+pub struct Lock(#[allow(dead_code)] File);
+
+impl Store {
+ /// The store in `state` and `run`, made absolute: programs run in a directory of
+ /// their own.
+ pub fn new(state: &Path, run: &Path) -> Self {
+ let absolute = |path: &Path| std::path::absolute(path).unwrap_or_else(|_| path.to_owned());
+ Self {
+ state: absolute(state),
+ run: absolute(run),
+ }
+ }
+
+ /// Waits for, and takes, the store's lock: one receptor at a time.
+ pub fn lock(&self) -> Result<Lock> {
+ create_dir(&self.state, 0o700)?;
+ let path = self.state.join("lock");
+ let file = File::options()
+ .create(true)
+ .truncate(false)
+ .write(true)
+ .open(&path)
+ .with_context(|| format!("opening {}", path.display()))?;
+ file.lock()
+ .with_context(|| format!("locking {}", path.display()))?;
+ Ok(Lock(file))
+ }
+
+ /// Where programs get their scratch directories.
+ pub fn scratch(&self) -> PathBuf {
+ self.run.join("tmp")
+ }
+
+ fn channel_dir(&self, channel: &str) -> PathBuf {
+ self.state.join("channels").join(channel)
+ }
+
+ /// The channels that have a snapshot.
+ pub fn channels(&self) -> Result<Vec<String>> {
+ let dir = self.state.join("channels");
+ let mut channels = Vec::new();
+ match std::fs::read_dir(&dir) {
+ Ok(entries) => {
+ for entry in entries {
+ if let Ok(name) = entry?.file_name().into_string() {
+ channels.push(name);
+ }
+ }
+ }
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
+ Err(error) => return Err(error).with_context(|| format!("reading {}", dir.display())),
+ }
+ channels.sort();
+ Ok(channels)
+ }
+
+ /// The current snapshot of `channel`, if there is one.
+ pub fn current(&self, channel: &str) -> Result<Option<Snapshot>> {
+ let link = self.channel_dir(channel).join("current");
+ let target = match std::fs::read_link(&link) {
+ Ok(target) => target,
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
+ Err(error) => return Err(error).with_context(|| format!("reading {}", link.display())),
+ };
+ let dir = self.channel_dir(channel).join(target);
+ let path = dir.join("snapshot.json");
+ let file: SnapshotFile = serde_json::from_slice(
+ &std::fs::read(&path).with_context(|| format!("reading {}", path.display()))?,
+ )
+ .with_context(|| format!("reading {}", path.display()))?;
+ if file.channel != channel {
+ bail!("{} is of channel {}", path.display(), file.channel);
+ }
+ let schema = std::fs::read(dir.join("schema.json"))
+ .with_context(|| format!("reading {}", dir.join("schema.json").display()))?;
+ Ok(Some(Snapshot {
+ id: file.id,
+ base: file.base,
+ content: content::read_dir(&dir.join("entries"))?,
+ schema,
+ }))
+ }
+
+ /// Makes `content` 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,
+ base: Option<&str>,
+ schema: &[u8],
+ ) -> Result<String> {
+ let id = crate::new_id()?;
+ let snapshots = self.channel_dir(channel).join("snapshots");
+ create_dir(&snapshots, 0o700)?;
+ let new = snapshots.join(format!(".{id}.new"));
+ create_dir(&new, 0o700)?;
+ let file = SnapshotFile {
+ id: id.clone(),
+ channel: channel.to_owned(),
+ base: base.map(str::to_owned),
+ };
+ content::write_file(
+ &new.join("snapshot.json"),
+ &serde_json::to_vec_pretty(&file)?,
+ 0o600,
+ )?;
+ content::write_file(&new.join("schema.json"), schema, 0o600)?;
+ content::write_dir(content, &new.join("entries"), 0o600)?;
+ std::fs::rename(&new, snapshots.join(&id))?;
+ let old = std::fs::read_link(self.channel_dir(channel).join("current")).ok();
+ replace_link(
+ &self.channel_dir(channel).join("current"),
+ &Path::new("snapshots").join(&id),
+ )?;
+ if let Some(old) = old {
+ std::fs::remove_dir_all(self.channel_dir(channel).join(old))?;
+ }
+ Ok(id)
+ }
+
+ /// 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);
+ std::fs::read_link(&link).ok()?;
+ Some(link)
+ }
+
+ /// Puts what was rendered for the view `name` in place (or, if nothing was, takes
+ /// it away), readable by root only if it is secret.
+ pub fn install_view(&self, name: &str, rendered: Option<Scratch>, secret: bool) -> Result<()> {
+ let views = self.run.join("views");
+ create_dir(&views, 0o755)?;
+ let link = views.join(name);
+ let old = std::fs::read_link(&link).ok();
+ match rendered {
+ Some(rendered) => {
+ let generations = views.join(".generations");
+ create_dir(&generations, 0o755)?;
+ let mode = if secret { 0o600 } else { 0o644 };
+ rendered.set_modes(mode)?;
+ let target = Path::new(".generations").join(format!("{name}.{}", crate::new_id()?));
+ std::fs::rename(rendered.path(), views.join(&target))
+ .with_context(|| format!("moving view {name} in place"))?;
+ rendered.keep();
+ replace_link(&link, &target)?;
+ }
+ None => {
+ if old.is_some() {
+ std::fs::remove_file(&link)?;
+ }
+ }
+ }
+ if let Some(old) = old {
+ std::fs::remove_dir_all(views.join(old))?;
+ }
+ Ok(())
+ }
+}
+
+fn create_dir(path: &Path, mode: u32) -> Result<()> {
+ std::fs::DirBuilder::new()
+ .recursive(true)
+ .mode(mode)
+ .create(path)
+ .with_context(|| format!("creating {}", path.display()))
+}
+
+/// Points the symbolic link `link` at `target`, atomically.
+fn replace_link(link: &Path, target: &Path) -> Result<()> {
+ let name = link.file_name().unwrap_or_default().to_string_lossy();
+ let new = link.with_file_name(format!(".{name}.new-link"));
+ let _ = std::fs::remove_file(&new);
+ std::os::unix::fs::symlink(target, &new)?;
+ std::fs::rename(&new, link).with_context(|| format!("replacing {}", link.display()))
+}