[control] Phase 2 control plane: routes repo via git, journaled apply with trial/watch/revert, undo and restore, push with retry, share links, API tokens, REST API with OpenAPI, --dev
This commit is contained in:
@@ -0,0 +1,143 @@
|
||||
// This Source Code Form is subject to the terms of the Mozilla Public
|
||||
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
|
||||
//! Small shared helpers: time, randomness, hashing, atomic file writes.
|
||||
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use ring::rand::{SecureRandom, SystemRandom};
|
||||
use serde::Serialize;
|
||||
use serde::de::DeserializeOwned;
|
||||
|
||||
pub fn now() -> u64 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map(|d| d.as_secs())
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
pub fn rfc3339(t: u64) -> String {
|
||||
ianitor_core::time::rfc3339(t)
|
||||
}
|
||||
|
||||
pub fn random<const N: usize>() -> Result<[u8; N], std::io::Error> {
|
||||
let mut b = [0u8; N];
|
||||
SystemRandom::new()
|
||||
.fill(&mut b)
|
||||
.map_err(|_| std::io::Error::other("the system random generator failed"))?;
|
||||
Ok(b)
|
||||
}
|
||||
|
||||
pub fn hex(bytes: &[u8]) -> String {
|
||||
bytes.iter().map(|b| format!("{b:02x}")).collect()
|
||||
}
|
||||
|
||||
pub fn sha256_hex(data: &[u8]) -> String {
|
||||
hex(ring::digest::digest(&ring::digest::SHA256, data).as_ref())
|
||||
}
|
||||
|
||||
/// Compare two byte strings in time that depends only on their length.
|
||||
pub fn ct_eq(a: &[u8], b: &[u8]) -> bool {
|
||||
if a.len() != b.len() {
|
||||
return false;
|
||||
}
|
||||
let mut d = 0u8;
|
||||
for (x, y) in a.iter().zip(b) {
|
||||
d |= x ^ y;
|
||||
}
|
||||
std::hint::black_box(d) == 0
|
||||
}
|
||||
|
||||
/// Write `data` to `path` so that readers see the old or the new content, never a mix, and
|
||||
/// the new content survives a crash once this returns: temporary file in the same directory,
|
||||
/// fsync, rename, fsync of the directory.
|
||||
pub fn write_atomic(path: &Path, data: &[u8], mode: u32) -> std::io::Result<()> {
|
||||
let dir = path
|
||||
.parent()
|
||||
.filter(|p| !p.as_os_str().is_empty())
|
||||
.unwrap_or(Path::new("."));
|
||||
std::fs::create_dir_all(dir)?;
|
||||
let mut name = path.file_name().unwrap_or_default().to_os_string();
|
||||
name.push(format!(".tmp-{}", std::process::id()));
|
||||
let tmp = dir.join(name);
|
||||
{
|
||||
let mut opts = std::fs::OpenOptions::new();
|
||||
opts.write(true).create(true).truncate(true);
|
||||
#[cfg(unix)]
|
||||
std::os::unix::fs::OpenOptionsExt::mode(&mut opts, mode);
|
||||
#[cfg(not(unix))]
|
||||
let _ = mode;
|
||||
let mut f = opts.open(&tmp)?;
|
||||
f.write_all(data)?;
|
||||
f.sync_all()?;
|
||||
}
|
||||
std::fs::rename(&tmp, path)?;
|
||||
sync_dir(dir)
|
||||
}
|
||||
|
||||
/// Rename `from` to `to` atomically and durably.
|
||||
pub fn rename_durable(from: &Path, to: &Path) -> std::io::Result<()> {
|
||||
std::fs::rename(from, to)?;
|
||||
sync_dir(to.parent().unwrap_or(Path::new(".")))
|
||||
}
|
||||
|
||||
pub fn sync_dir(dir: &Path) -> std::io::Result<()> {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
std::fs::File::open(dir)?.sync_all()?;
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
let _ = dir;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn remove_if_exists(path: &Path) -> std::io::Result<()> {
|
||||
match std::fs::remove_file(path) {
|
||||
Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(e),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Read a JSON state file; `Ok(None)` when it does not exist.
|
||||
pub fn read_json<T: DeserializeOwned>(path: &Path) -> Result<Option<T>, String> {
|
||||
match std::fs::read(path) {
|
||||
Ok(b) => serde_json::from_slice(&b)
|
||||
.map(Some)
|
||||
.map_err(|e| format!("{} is damaged: {e}", path.display())),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
|
||||
Err(e) => Err(format!("cannot read {}: {e}", path.display())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Write a JSON state file atomically, readable by its owner only.
|
||||
pub fn write_json<T: Serialize>(path: &Path, value: &T) -> Result<(), String> {
|
||||
let mut text = serde_json::to_vec_pretty(value).map_err(|e| e.to_string())?;
|
||||
text.push(b'\n');
|
||||
write_atomic(path, &text, 0o600).map_err(|e| format!("cannot write {}: {e}", path.display()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used)]
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn constant_time_compare() {
|
||||
assert!(ct_eq(b"abc", b"abc"));
|
||||
assert!(!ct_eq(b"abc", b"abd"));
|
||||
assert!(!ct_eq(b"abc", b"ab"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn atomic_write_replaces() {
|
||||
let d = std::env::temp_dir().join(format!("ianitor-util-{}", std::process::id()));
|
||||
let p = d.join("f.json");
|
||||
write_atomic(&p, b"one", 0o600).unwrap();
|
||||
write_atomic(&p, b"two", 0o600).unwrap();
|
||||
assert_eq!(std::fs::read(&p).unwrap(), b"two");
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user