Rebuild Idunn around typed authority ports

This commit is contained in:
Meta Vens 2026-09-02 23:13:36 +02:00
commit 330e4cd75d
7 changed files with 3148 additions and 13883 deletions

View file

@ -0,0 +1,698 @@
use std::collections::BTreeMap;
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use std::thread;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use anyhow::{Context, Result, anyhow, bail, ensure};
use cultcache_rs::{
CultCacheEnvelope, CultCacheExpectedEnvelope, DatabaseEntry, SingleFileMessagePackBackingStore,
};
use uuid::Uuid;
use crate::deployment::OperatorBinding;
use crate::drivers::ProcessIdentity;
const DEPLOYMENT_COMMAND_SCHEMA: &str = "idunn.deployment_command.v1";
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
#[cultcache(
type = "idunn.deployment_command",
schema = "idunn.deployment_command.v1"
)]
struct DeploymentCommandRecord {
#[cultcache(key = 0)]
schema_version: String,
#[cultcache(key = 1)]
command_id: String,
#[cultcache(key = 2)]
selector: String,
#[cultcache(key = 3)]
requested_by: String,
#[cultcache(key = 4)]
requested_at_unix_millis: u64,
#[cultcache(key = 5)]
state: String,
#[cultcache(key = 6)]
owner_instance_id: Option<String>,
#[cultcache(key = 7)]
started_at_unix_millis: Option<u64>,
#[cultcache(key = 8)]
completed_at_unix_millis: Option<u64>,
#[cultcache(key = 9)]
detail: String,
}
impl DeploymentCommandRecord {
fn validate(&self) -> Result<()> {
ensure!(
self.schema_version == DEPLOYMENT_COMMAND_SCHEMA,
"deployment command schema is unsupported"
);
require_id(&self.command_id, "deployment command id")?;
require_selector(&self.selector)?;
require_value(&self.requested_by, "deployment requester")?;
ensure!(
self.requested_at_unix_millis > 0,
"deployment command has no request time"
);
ensure!(
matches!(
self.state.as_str(),
"pending" | "running" | "succeeded" | "failed"
),
"deployment command state is invalid"
);
ensure!(
self.detail.len() <= 2048 && !self.detail.contains('\0'),
"deployment command detail is invalid"
);
match self.state.as_str() {
"pending" => {
ensure!(
self.owner_instance_id.is_none()
&& self.started_at_unix_millis.is_none()
&& self.completed_at_unix_millis.is_none(),
"pending deployment command has execution state"
);
}
"running" => {
ensure!(
self.owner_instance_id.is_some()
&& self.started_at_unix_millis.is_some()
&& self.completed_at_unix_millis.is_none(),
"running deployment command has partial ownership"
);
}
"succeeded" | "failed" => {
ensure!(
self.owner_instance_id.is_some()
&& self.started_at_unix_millis.is_some()
&& self.completed_at_unix_millis.is_some(),
"terminal deployment command has partial receipt state"
);
}
_ => unreachable!(),
}
Ok(())
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct RuntimeOptions {
state_store: PathBuf,
bindings_dir: PathBuf,
source_root: PathBuf,
staging_root: PathBuf,
topology_store: PathBuf,
odin_correlation_store: PathBuf,
odin_trust_anchor: PathBuf,
source_identity: Option<ProcessIdentity>,
poll_millis: u64,
}
impl Default for RuntimeOptions {
fn default() -> Self {
Self {
state_store: PathBuf::from("/var/lib/gamecult/idunn/control.cc"),
bindings_dir: PathBuf::from("/etc/gamecult/idunn/bindings"),
source_root: PathBuf::from("/var/lib/gamecult/idunn/sources"),
staging_root: PathBuf::from("/var/lib/gamecult/idunn/staging"),
topology_store: PathBuf::from("/var/lib/gamecult/idunn/topology.cc"),
odin_correlation_store: PathBuf::from(
"/var/lib/gamecult/odin/idunn-runtime-topology.cc",
),
odin_trust_anchor: PathBuf::from("/etc/gamecult/idunn/odin-topology-anchor.cc"),
source_identity: None,
poll_millis: 500,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
enum Command {
Serve(RuntimeOptions),
Up {
selector: String,
requested_by: String,
state_store: PathBuf,
wait: bool,
timeout_seconds: u64,
},
Status {
state_store: PathBuf,
command_id: Option<String>,
},
}
pub fn run(args: impl Iterator<Item = String>) -> Result<()> {
match parse(args)? {
Command::Serve(options) => serve(options),
Command::Up {
selector,
requested_by,
state_store,
wait,
timeout_seconds,
} => submit(
&state_store,
&selector,
&requested_by,
wait,
timeout_seconds,
),
Command::Status {
state_store,
command_id,
} => status(&state_store, command_id.as_deref()),
}
}
fn parse(args: impl Iterator<Item = String>) -> Result<Command> {
let mut args = args.peekable();
let command = args.next().ok_or_else(|| anyhow!(usage()))?;
match command.as_str() {
"serve" => parse_serve(args),
"up" => parse_up(args),
"status" => parse_status(args),
"--help" | "-h" | "help" => bail!(usage()),
_ => bail!("unknown Idunn command {command:?}\n\n{}", usage()),
}
}
fn parse_serve(mut args: impl Iterator<Item = String>) -> Result<Command> {
let mut options = RuntimeOptions::default();
let mut source_uid = None;
let mut source_gid = None;
while let Some(argument) = args.next() {
match argument.as_str() {
"--state-store" => options.state_store = path_value(&mut args, &argument)?,
"--bindings-dir" => options.bindings_dir = path_value(&mut args, &argument)?,
"--source-root" => options.source_root = path_value(&mut args, &argument)?,
"--staging-root" => options.staging_root = path_value(&mut args, &argument)?,
"--topology-store" => options.topology_store = path_value(&mut args, &argument)?,
"--odin-correlation-store" => {
options.odin_correlation_store = path_value(&mut args, &argument)?
}
"--odin-trust-anchor" => options.odin_trust_anchor = path_value(&mut args, &argument)?,
"--source-uid" => source_uid = Some(u32_value(&mut args, &argument)?),
"--source-gid" => source_gid = Some(u32_value(&mut args, &argument)?),
"--poll-millis" => options.poll_millis = u64_value(&mut args, &argument)?,
"--help" | "-h" => bail!(usage()),
_ => bail!("unknown Idunn serve option {argument:?}"),
}
}
ensure!(options.poll_millis > 0, "--poll-millis must be positive");
options.source_identity = match (source_uid, source_gid) {
(Some(uid), Some(gid)) => Some(ProcessIdentity { uid, gid }),
(None, None) => None,
_ => bail!("--source-uid and --source-gid must be supplied together"),
};
Ok(Command::Serve(options))
}
fn parse_up(mut args: impl Iterator<Item = String>) -> Result<Command> {
let selector = args
.next()
.ok_or_else(|| anyhow!("idunn up requires a service or profile selector"))?;
require_selector(&selector)?;
let mut state_store = RuntimeOptions::default().state_store;
let mut requested_by = env::var("SUDO_USER")
.or_else(|_| env::var("USER"))
.or_else(|_| env::var("USERNAME"))
.unwrap_or_else(|_| "operator".into());
let mut wait = true;
let mut timeout_seconds = 1800;
while let Some(argument) = args.next() {
match argument.as_str() {
"--state-store" => state_store = path_value(&mut args, &argument)?,
"--requested-by" => requested_by = string_value(&mut args, &argument)?,
"--no-wait" => wait = false,
"--timeout-seconds" => timeout_seconds = u64_value(&mut args, &argument)?,
"--help" | "-h" => bail!(usage()),
_ => bail!("unknown Idunn up option {argument:?}"),
}
}
ensure!(timeout_seconds > 0, "--timeout-seconds must be positive");
require_value(&requested_by, "deployment requester")?;
Ok(Command::Up {
selector,
requested_by,
state_store,
wait,
timeout_seconds,
})
}
fn parse_status(mut args: impl Iterator<Item = String>) -> Result<Command> {
let mut state_store = RuntimeOptions::default().state_store;
let mut command_id = None;
while let Some(argument) = args.next() {
match argument.as_str() {
"--state-store" => state_store = path_value(&mut args, &argument)?,
"--command" => command_id = Some(string_value(&mut args, &argument)?),
"--help" | "-h" => bail!(usage()),
_ => bail!("unknown Idunn status option {argument:?}"),
}
}
Ok(Command::Status {
state_store,
command_id,
})
}
fn serve(options: RuntimeOptions) -> Result<()> {
for path in [
&options.state_store,
&options.topology_store,
&options.staging_root,
] {
let directory = if path.extension().is_some() {
path.parent()
.context("configured Idunn path has no parent")?
} else {
path.as_path()
};
fs::create_dir_all(directory)
.with_context(|| format!("creating Idunn directory {}", directory.display()))?;
}
let instance_id = format!("idunn-{}", Uuid::new_v4());
loop {
if let Some(command) = claim_next(&options.state_store, &instance_id)? {
let result = execute(&options, &command);
complete(&options.state_store, &command, result)?;
} else {
thread::sleep(Duration::from_millis(options.poll_millis));
}
}
}
fn execute(options: &RuntimeOptions, command: &DeploymentCommandRecord) -> Result<String> {
let bindings = load_bindings(&options.bindings_dir)?;
let targets = resolve_selector(&bindings, &command.selector)?;
ensure!(
!targets.is_empty(),
"deployment selector resolved to no targets"
);
bail!(
"typed deployment drivers are not yet connected for {}",
targets.join(",")
)
}
fn load_bindings(directory: &Path) -> Result<BTreeMap<String, OperatorBinding>> {
let mut paths = fs::read_dir(directory)
.with_context(|| format!("reading Idunn binding directory {}", directory.display()))?
.map(|entry| entry.map(|entry| entry.path()))
.collect::<std::io::Result<Vec<_>>>()?;
paths.retain(|path| path.extension() == Some(std::ffi::OsStr::new("toml")));
paths.sort();
let mut bindings = BTreeMap::new();
for path in paths {
let bytes = fs::read(&path)
.with_context(|| format!("reading operator binding {}", path.display()))?;
let text = std::str::from_utf8(&bytes)
.with_context(|| format!("operator binding {} is not UTF-8", path.display()))?;
let binding = OperatorBinding::parse(text)
.with_context(|| format!("validating operator binding {}", path.display()))?;
let target = binding.target.clone();
ensure!(
bindings.insert(target.clone(), binding).is_none(),
"operator binding target {target} is duplicated"
);
}
ensure!(!bindings.is_empty(), "Idunn binding directory is empty");
Ok(bindings)
}
fn resolve_selector(
bindings: &BTreeMap<String, OperatorBinding>,
selector: &str,
) -> Result<Vec<String>> {
let targets = if let Some(profile) = selector.strip_prefix("profile:") {
bindings
.values()
.filter(|binding| binding.profiles.contains(profile))
.map(|binding| binding.target.clone())
.collect::<Vec<_>>()
} else {
ensure!(
bindings.contains_key(selector),
"unknown deployment target {selector}"
);
vec![selector.to_owned()]
};
ensure!(
!targets.is_empty(),
"unknown or empty deployment profile {selector}"
);
Ok(targets)
}
fn submit(
store_path: &Path,
selector: &str,
requested_by: &str,
wait: bool,
timeout_seconds: u64,
) -> Result<()> {
if let Some(parent) = store_path.parent() {
fs::create_dir_all(parent)?;
}
let now = now_millis()?;
let record = DeploymentCommandRecord {
schema_version: DEPLOYMENT_COMMAND_SCHEMA.into(),
command_id: format!("up-{}", Uuid::new_v4()),
selector: selector.into(),
requested_by: requested_by.into(),
requested_at_unix_millis: now,
state: "pending".into(),
owner_instance_id: None,
started_at_unix_millis: None,
completed_at_unix_millis: None,
detail: String::new(),
};
record.validate()?;
let store = SingleFileMessagePackBackingStore::new(store_path);
let next = typed_envelope(&record, now)?;
if !store.compare_exchange(
&[CultCacheExpectedEnvelope {
r#type: DeploymentCommandRecord::TYPE.into(),
key: record.command_id.clone(),
current: None,
}],
&[next],
)? {
bail!("deployment command id collided")
}
println!("{}", record.command_id);
if !wait {
return Ok(());
}
let deadline = now.saturating_add(timeout_seconds.saturating_mul(1000));
loop {
let current = read_command(store_path, &record.command_id)?
.context("submitted deployment command disappeared")?;
match current.state.as_str() {
"succeeded" => {
println!("succeeded {}", current.detail);
return Ok(());
}
"failed" => bail!("deployment failed: {}", current.detail),
_ if now_millis()? >= deadline => bail!("deployment command timed out"),
_ => thread::sleep(Duration::from_millis(250)),
}
}
}
fn status(store_path: &Path, command_id: Option<&str>) -> Result<()> {
let mut commands = read_commands(store_path)?;
if let Some(command_id) = command_id {
commands.retain(|command| command.command_id == command_id);
ensure!(!commands.is_empty(), "deployment command is unknown");
}
commands.sort_by_key(|command| command.requested_at_unix_millis);
for command in commands {
println!(
"{} {} {} {}",
command.command_id, command.selector, command.state, command.detail
);
}
Ok(())
}
fn claim_next(store_path: &Path, instance_id: &str) -> Result<Option<DeploymentCommandRecord>> {
let store = SingleFileMessagePackBackingStore::new(store_path);
let mut candidates = read_command_envelopes(store_path)?
.into_iter()
.filter(|(_, record)| record.state == "pending")
.collect::<Vec<_>>();
candidates.sort_by_key(|(_, command)| command.requested_at_unix_millis);
for (current, mut command) in candidates {
let now = now_millis()?;
command.state = "running".into();
command.owner_instance_id = Some(instance_id.into());
command.started_at_unix_millis = Some(now);
command.validate()?;
if store.compare_exchange(
&[CultCacheExpectedEnvelope {
r#type: DeploymentCommandRecord::TYPE.into(),
key: command.command_id.clone(),
current: Some(current),
}],
&[typed_envelope(&command, now)?],
)? {
return Ok(Some(command));
}
}
Ok(None)
}
fn complete(
store_path: &Path,
running: &DeploymentCommandRecord,
result: Result<String>,
) -> Result<()> {
let store = SingleFileMessagePackBackingStore::new(store_path);
let current = read_command_envelopes(store_path)?
.into_iter()
.find(|(_, command)| command.command_id == running.command_id)
.context("running deployment command disappeared")?;
ensure!(
current.1 == *running,
"deployment command changed while its owner was executing"
);
let now = now_millis()?;
let mut terminal = running.clone();
terminal.completed_at_unix_millis = Some(now);
match result {
Ok(detail) => {
terminal.state = "succeeded".into();
terminal.detail = detail;
}
Err(error) => {
terminal.state = "failed".into();
terminal.detail = truncate(&format!("{error:#}"), 2048);
}
}
terminal.validate()?;
ensure!(
store.compare_exchange(
&[CultCacheExpectedEnvelope {
r#type: DeploymentCommandRecord::TYPE.into(),
key: terminal.command_id.clone(),
current: Some(current.0),
}],
&[typed_envelope(&terminal, now)?],
)?,
"deployment command changed before its terminal receipt"
);
Ok(())
}
fn read_commands(path: &Path) -> Result<Vec<DeploymentCommandRecord>> {
Ok(read_command_envelopes(path)?
.into_iter()
.map(|(_, record)| record)
.collect())
}
fn read_command(path: &Path, command_id: &str) -> Result<Option<DeploymentCommandRecord>> {
Ok(read_commands(path)?
.into_iter()
.find(|command| command.command_id == command_id))
}
fn read_command_envelopes(
path: &Path,
) -> Result<Vec<(CultCacheEnvelope, DeploymentCommandRecord)>> {
if !path.exists() {
return Ok(Vec::new());
}
SingleFileMessagePackBackingStore::new(path)
.pull_all_read_only_snapshot()?
.into_iter()
.map(|envelope| {
ensure!(
envelope.r#type == DeploymentCommandRecord::TYPE
&& envelope.schema_id.as_deref() == Some(DEPLOYMENT_COMMAND_SCHEMA),
"Idunn control store contains a foreign document"
);
let record: DeploymentCommandRecord = rmp_serde::from_slice(&envelope.payload)?;
ensure!(
rmp_serde::to_vec(&record)? == envelope.payload
&& envelope.key == record.command_id,
"Idunn control store contains a noncanonical command"
);
record.validate()?;
Ok((envelope, record))
})
.collect()
}
fn typed_envelope(record: &DeploymentCommandRecord, millis: u64) -> Result<CultCacheEnvelope> {
record.validate()?;
let stored_at = chrono::DateTime::from_timestamp_millis(i64::try_from(millis)?)
.context("deployment command timestamp is out of range")?
.to_rfc3339();
Ok(CultCacheEnvelope {
key: record.command_id.clone(),
r#type: DeploymentCommandRecord::TYPE.into(),
payload: rmp_serde::to_vec(record)?,
stored_at,
schema_id: Some(DEPLOYMENT_COMMAND_SCHEMA.into()),
})
}
fn now_millis() -> Result<u64> {
Ok(SystemTime::now()
.duration_since(UNIX_EPOCH)
.context("system clock predates Unix epoch")?
.as_millis()
.try_into()?)
}
fn string_value(args: &mut impl Iterator<Item = String>, name: &str) -> Result<String> {
args.next()
.ok_or_else(|| anyhow!("{name} requires a value"))
}
fn path_value(args: &mut impl Iterator<Item = String>, name: &str) -> Result<PathBuf> {
Ok(PathBuf::from(string_value(args, name)?))
}
fn u32_value(args: &mut impl Iterator<Item = String>, name: &str) -> Result<u32> {
string_value(args, name)?
.parse()
.with_context(|| format!("{name} requires a u32"))
}
fn u64_value(args: &mut impl Iterator<Item = String>, name: &str) -> Result<u64> {
string_value(args, name)?
.parse()
.with_context(|| format!("{name} requires a u64"))
}
fn require_selector(value: &str) -> Result<()> {
let value = value.strip_prefix("profile:").unwrap_or(value);
require_id(value, "deployment selector")
}
fn require_id(value: &str, label: &str) -> Result<()> {
ensure!(
!value.is_empty()
&& value.len() <= 256
&& value.bytes().all(|byte| {
byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b':' | b'/')
}),
"{label} is invalid"
);
Ok(())
}
fn require_value(value: &str, label: &str) -> Result<()> {
ensure!(
!value.trim().is_empty()
&& value == value.trim()
&& value.len() <= 1024
&& !value.contains('\0'),
"{label} is invalid"
);
Ok(())
}
fn truncate(value: &str, length: usize) -> String {
value.chars().take(length).collect()
}
fn usage() -> &'static str {
"Idunn deployment and continuity control plane\n\n\
idunn serve [runtime options]\n\
idunn up <service|profile:name> [--state-store PATH] [--no-wait]\n\
idunn status [--state-store PATH] [--command ID]\n\n\
Recipes declare build, package, launch, health, state, and capability semantics.\n\
Operator bindings select source, runner, workload, route, brakes, and placement."
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn cli_has_no_raw_command_or_compiled_profile_authority() {
for arguments in [
vec!["up", "ghostlight", "--deploy-command", "sh -c bad"],
vec!["serve", "--swarm-profile", "yggdrasil-local"],
vec!["serve", "--restart-command", "bad"],
vec!["validate-runtime-admission"],
] {
assert!(parse(arguments.into_iter().map(str::to_owned)).is_err());
}
}
#[test]
fn garden_path_accepts_service_and_profile_selectors() {
for selector in ["ghostlight", "profile:aetheria", "profile:full-gamecult"] {
let parsed =
parse(["up", selector, "--no-wait"].into_iter().map(str::to_owned)).unwrap();
let Command::Up {
selector: actual, ..
} = parsed
else {
panic!("expected up command")
};
assert_eq!(actual, selector);
}
}
#[test]
fn source_identity_is_explicit_and_atomic() {
let partial = parse(
["serve", "--source-uid", "1001"]
.into_iter()
.map(str::to_owned),
)
.unwrap_err()
.to_string();
assert!(partial.contains("supplied together"));
let Command::Serve(options) = parse(
["serve", "--source-uid", "1001", "--source-gid", "1002"]
.into_iter()
.map(str::to_owned),
)
.unwrap() else {
panic!("expected serve")
};
assert_eq!(
options.source_identity,
Some(ProcessIdentity {
uid: 1001,
gid: 1002
})
);
}
#[test]
fn deployment_command_receipt_is_positional_and_fail_closed() -> Result<()> {
let record = DeploymentCommandRecord {
schema_version: DEPLOYMENT_COMMAND_SCHEMA.into(),
command_id: "up-test".into(),
selector: "ghostlight".into(),
requested_by: "operator".into(),
requested_at_unix_millis: 100,
state: "pending".into(),
owner_instance_id: None,
started_at_unix_millis: None,
completed_at_unix_millis: None,
detail: String::new(),
};
record.validate()?;
let payload = rmp_serde::to_vec(&record)?;
assert_eq!(payload[0], 0x9a);
let mut invalid = record;
invalid.state = "succeeded".into();
assert!(invalid.validate().is_err());
Ok(())
}
}

View file

@ -6,6 +6,7 @@ use serde::{Deserialize, Serialize};
pub const TARGET_DECLARATION_SCHEMA: &str = "gamecult.idunn.target_declaration.v1";
pub const OPERATOR_BINDING_SCHEMA: &str = "gamecult.idunn.operator_binding.v1";
pub const IDUNN_RUNTIME_BUNDLE_ENVIRONMENT: &str = "GAMECULT_IDUNN_RUNTIME_BUNDLE";
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
@ -598,6 +599,12 @@ impl TargetDeclaration {
for name in &self.service.required_environment {
require_environment_name(name)?;
}
ensure!(
self.service
.required_environment
.contains(IDUNN_RUNTIME_BUNDLE_ENVIRONMENT),
"service does not require the standard Idunn runtime bundle"
);
for name in &self.service.optional_environment {
require_environment_name(name)?;
ensure!(
@ -827,6 +834,9 @@ impl OperatorBinding {
for name in runner.environment.keys().chain(runner.secret_files.keys()) {
require_environment_name(name)?;
}
for value in runner.environment.values() {
require_value(value, "runner environment value")?;
}
for path in runner.secret_files.values() {
require_absolute_path(path, "runner secret file")?;
}
@ -915,6 +925,9 @@ impl OperatorBinding {
{
require_environment_name(name)?;
}
for value in self.workload.environment.values() {
require_value(value, "workload environment value")?;
}
for name in self.workload.argument_bindings.keys() {
require_id(name, "argument binding")?;
}
@ -1109,13 +1122,25 @@ impl OperatorBinding {
input.id
);
}
let available_environment: BTreeSet<_> = self
ensure!(
!self
.workload
.environment
.contains_key(IDUNN_RUNTIME_BUNDLE_ENVIRONMENT)
&& !self
.workload
.secret_files
.contains_key(IDUNN_RUNTIME_BUNDLE_ENVIRONMENT),
"operator binding cannot replace the standard Idunn runtime bundle"
);
let mut available_environment: BTreeSet<_> = self
.workload
.environment
.keys()
.chain(self.workload.secret_files.keys())
.cloned()
.collect();
available_environment.insert(IDUNN_RUNTIME_BUNDLE_ENVIRONMENT.into());
ensure!(
declaration
.service
@ -1257,7 +1282,10 @@ fn require_capability_contract(capability: &str, schema: &str, compatibility: &s
fn require_value(value: &str, label: &str) -> Result<()> {
ensure!(!value.trim().is_empty(), "{label} is empty");
ensure!(!value.contains('\0'), "{label} contains NUL");
ensure!(
!value.chars().any(char::is_control),
"{label} contains a control character"
);
ensure!(value.len() <= 4_096, "{label} is too long");
Ok(())
}
@ -1455,7 +1483,7 @@ arguments = [
]
transport = "http"
route_required = true
required_environment = ["TEST_SERVICE_BIND"]
required_environment = ["GAMECULT_IDUNN_RUNTIME_BUNDLE", "TEST_SERVICE_BIND"]
[service.health]
contract = "test-service.cultnet-service-health"

View file

@ -2,18 +2,22 @@ use std::collections::{BTreeMap, BTreeSet};
use std::path::PathBuf;
use anyhow::{Context, Result, bail, ensure};
pub use cultnet_rs::IdunnExpectedIncarnationRecord as ExpectedIncarnation;
use cultnet_rs::{
GameCultRuntimeCapability, IDUNN_EXPECTED_INCARNATION_SCHEMA, IdunnExpectedDependency,
IdunnExpectedRoute,
};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use crate::deployment::{
CapabilityDependency, DependencyKind, ExternalCapabilityBinding, OperatorBinding,
ProvidedCapability, ServiceTransport, SourceSelectionPolicy, StateDeclaration,
TargetDeclaration, capability_compatible,
ServiceTransport, SourceSelectionPolicy, StartupOrder, StateDeclaration, TargetDeclaration,
capability_compatible,
};
pub const SOURCE_SELECTION_FACTS_SCHEMA: &str = "idunn.source_selection_facts.v1";
pub const COMPILED_DEPLOYMENT_PLAN_SCHEMA: &str = "idunn.compiled_deployment_plan.v1";
pub const EXPECTED_INCARNATION_SCHEMA: &str = "idunn.expected_incarnation.v1";
pub const SEALED_RELEASE_SCHEMA: &str = "idunn.sealed_release.v1";
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
@ -305,6 +309,47 @@ impl DependencySelection {
}
Ok(())
}
fn expected_projection(&self) -> Result<IdunnExpectedDependency> {
self.validate()?;
let (
provider_id,
provider_authority,
provider_expected_projection_sha256,
provider_endpoint,
) = match &self.provider {
None => (None, None, None, None),
Some(provider) => match &provider.authority {
ExpectedProviderAuthority::ManagedIncarnation {
expected_projection_sha256,
..
} => (
Some(provider.provider_id.clone()),
Some("managed-incarnation".into()),
Some(expected_projection_sha256.clone()),
provider.endpoint.clone(),
),
ExpectedProviderAuthority::ExternalOperatorBinding { .. } => (
Some(provider.provider_id.clone()),
Some("external-operator-binding".into()),
None,
provider.endpoint.clone(),
),
},
};
Ok(IdunnExpectedDependency {
kind: dependency_kind_name(self.requirement.kind).into(),
capability: self.requirement.capability.clone(),
schema: self.requirement.schema.clone(),
compatibility: self.requirement.compatibility.clone(),
minimum_capacity: self.requirement.minimum_capacity,
startup: startup_order_name(self.requirement.startup).into(),
provider_id,
provider_authority,
provider_expected_projection_sha256,
provider_endpoint,
})
}
}
pub fn select_dependencies(
@ -374,137 +419,10 @@ pub fn select_dependencies(
.collect()
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ExpectedRoute {
pub route_id: String,
pub transport: ServiceTransport,
pub stable_endpoint: String,
pub candidate_endpoint: String,
}
impl ExpectedRoute {
fn validate(&self) -> Result<()> {
require_token(&self.route_id, "expected route id")?;
require_value(&self.stable_endpoint, "expected stable endpoint")?;
require_value(&self.candidate_endpoint, "expected candidate endpoint")?;
match self.transport {
ServiceTransport::Http => ensure!(
self.stable_endpoint.starts_with("http://")
|| self.stable_endpoint.starts_with("https://"),
"expected HTTP stable endpoint is not an HTTP URI"
),
ServiceTransport::Tcp => ensure!(
self.stable_endpoint.starts_with("tcp://"),
"expected TCP stable endpoint is not a TCP URI"
),
_ => bail!("routed expected incarnation has a non-routable transport"),
}
ensure!(
self.candidate_endpoint
.starts_with(&format!("{}://", endpoint_scheme(self.transport)?)),
"expected candidate endpoint transport disagrees"
);
Ok(())
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ExpectedIncarnation {
pub schema: String,
pub plan_id: String,
pub sealed_release_id: String,
pub target: String,
pub incarnation_id: String,
pub runtime_id: String,
pub expected_signer_identity_id: String,
pub health_contract: String,
pub executable_artifact_sha256: String,
pub state_schema_generation: Option<String>,
pub state_contract_sha256: Option<String>,
pub write_lease_required: bool,
pub source_revision: String,
pub node: String,
pub route: Option<ExpectedRoute>,
pub capabilities: Vec<ProvidedCapability>,
pub dependencies: Vec<DependencySelection>,
}
impl ExpectedIncarnation {
pub fn validate(&self) -> Result<()> {
ensure!(
self.schema == EXPECTED_INCARNATION_SCHEMA,
"unsupported expected-incarnation schema"
);
require_sha256(&self.plan_id, "expected plan")?;
require_sha256(&self.sealed_release_id, "expected sealed release")?;
require_token(&self.target, "expected target")?;
require_token(&self.incarnation_id, "expected incarnation")?;
require_token(&self.runtime_id, "expected runtime id")?;
require_token(
&self.expected_signer_identity_id,
"expected signer identity id",
)?;
require_token(&self.health_contract, "expected health contract")?;
require_sha256(
&self.executable_artifact_sha256,
"expected executable artifact",
)?;
match (&self.state_schema_generation, &self.state_contract_sha256) {
(Some(generation), Some(contract)) => {
require_token(generation, "expected state schema generation")?;
require_sha256(contract, "expected state contract")?;
}
(None, None) => ensure!(
!self.write_lease_required,
"stateless expected incarnation requires a write lease"
),
_ => bail!("expected state generation and contract digest disagree"),
}
require_sha1(&self.source_revision, "expected source revision")?;
require_token(&self.node, "expected node")?;
if let Some(route) = &self.route {
route.validate()?;
}
let mut capabilities = BTreeSet::new();
for capability in &self.capabilities {
require_contract(
&capability.capability,
&capability.schema,
&capability.compatibility,
)?;
ensure!(
capability.capacity > 0,
"expected capability capacity is zero"
);
ensure!(
capabilities.insert((
capability.capability.as_str(),
capability.schema.as_str(),
capability.compatibility.as_str(),
)),
"expected capability is duplicated"
);
}
for dependency in &self.dependencies {
dependency.validate()?;
}
Ok(())
}
pub fn canonical_sha256(&self) -> Result<String> {
self.validate()?;
Ok(sha256_id(
&rmp_serde::to_vec(self).context("encoding managed expected projection")?,
))
}
}
/// Private Idunn control-plane state. This contains host binding details and is
/// never an Odin/CultMesh projection. `ExpectedIncarnation` is the sanitized
/// topology projection derived only after a release validates against this
/// plan.
/// never an Odin/CultMesh projection. The shared CultNet Expected incarnation
/// is the sanitized topology projection derived only after a release validates
/// against this plan.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CompiledDeploymentPlan {
@ -568,7 +486,7 @@ impl CompiledDeploymentPlan {
Ok(())
}
fn parsed_inputs(&self) -> Result<(TargetDeclaration, OperatorBinding)> {
pub(crate) fn parsed_inputs(&self) -> Result<(TargetDeclaration, OperatorBinding)> {
let recipe_text = std::str::from_utf8(&self.recipe_blob)
.context("stored deployment recipe is not UTF-8")?;
let binding_text = std::str::from_utf8(&self.binding_blob)
@ -754,17 +672,10 @@ impl SealedRelease {
) -> Result<ExpectedIncarnation> {
self.validate_against(plan)?;
let (declaration, binding) = plan.parsed_inputs()?;
let node = binding
.placement
.nodes
.iter()
.next()
.context("validated singleton binding has no node")?
.clone();
let route = match (&binding.route, plan.candidate_port) {
(Some(bound), Some(port)) => Some(ExpectedRoute {
(Some(bound), Some(port)) => Some(IdunnExpectedRoute {
route_id: bound.route_id.clone(),
transport: declaration.service.transport,
transport: endpoint_scheme(declaration.service.transport)?.into(),
stable_endpoint: bound.stable_endpoint.clone(),
candidate_endpoint: format!(
"{}://{}:{port}",
@ -775,26 +686,58 @@ impl SealedRelease {
(None, None) => None,
_ => bail!("plan route and candidate port disagree"),
};
let executable_artifact_sha256 = self
let artifact_sha256 = self
.artifacts
.iter()
.find(|artifact| artifact.artifact_id == declaration.service.executable_artifact)
.context("sealed release has no executable service artifact")?
.sha256
.clone();
let mut capabilities = declaration
.provides
.iter()
.map(|capability| GameCultRuntimeCapability {
capability: capability.capability.clone(),
schema: capability.schema.clone(),
compatibility: capability.compatibility.clone(),
capacity: capability.capacity,
})
.collect::<Vec<_>>();
capabilities.sort_by(|left, right| {
(&left.capability, &left.schema, &left.compatibility).cmp(&(
&right.capability,
&right.schema,
&right.compatibility,
))
});
let mut dependencies = plan
.dependencies
.iter()
.map(DependencySelection::expected_projection)
.collect::<Result<Vec<_>>>()?;
dependencies.sort_by(|left, right| {
(&left.capability, &left.schema, &left.compatibility).cmp(&(
&right.capability,
&right.schema,
&right.compatibility,
))
});
let expected = ExpectedIncarnation {
schema: EXPECTED_INCARNATION_SCHEMA.into(),
plan_id: plan.plan_id.clone(),
sealed_release_id: self.sealed_release_id.clone(),
schema_version: IDUNN_EXPECTED_INCARNATION_SCHEMA.into(),
target: declaration.target.clone(),
plan_id: plan.plan_id.clone(),
incarnation_id: plan.incarnation_id.clone(),
sealed_release_id: self.sealed_release_id.clone(),
source_repository: canonical_repository_identity(&plan.source.origin)?,
source_revision: plan.source.revision.clone(),
recipe_sha256: plan.source.recipe_blob_sha256.clone(),
runtime_id: binding.runtime_identity.runtime_id.clone(),
expected_signer_identity_id: binding
.runtime_identity
.expected_signer_identity_id
.clone(),
health_contract: declaration.service.health.contract.clone(),
executable_artifact_sha256,
artifact_sha256,
state_schema_generation: declaration
.state
.as_ref()
@ -805,11 +748,9 @@ impl SealedRelease {
.map(canonical_state_contract_sha256)
.transpose()?,
write_lease_required: declaration.write_lease_required(),
source_revision: plan.source.revision.clone(),
node,
route,
capabilities: declaration.provides.clone(),
dependencies: plan.dependencies.clone(),
capabilities,
dependencies,
};
expected.validate()?;
Ok(expected)
@ -910,6 +851,32 @@ fn endpoint_scheme(transport: ServiceTransport) -> Result<&'static str> {
}
}
fn dependency_kind_name(kind: DependencyKind) -> &'static str {
match kind {
DependencyKind::Bootstrap => "bootstrap",
DependencyKind::Required => "required",
DependencyKind::Optional => "optional",
DependencyKind::SharedInfrastructure => "shared-infrastructure",
DependencyKind::Private => "private",
DependencyKind::ExternalOperatorBinding => "external-operator-binding",
}
}
fn startup_order_name(startup: StartupOrder) -> &'static str {
match startup {
StartupOrder::BeforePromotion => "before-promotion",
StartupOrder::BeforeStart => "before-start",
}
}
fn canonical_repository_identity(origin: &str) -> Result<String> {
let identity = origin
.strip_prefix("https://")
.and_then(|origin| origin.strip_suffix(".git"))
.context("validated Git origin is not a canonical HTTPS repository")?;
Ok(identity.to_owned())
}
fn prefixed_sha256(raw_sha256: &str) -> String {
format!("sha256-{raw_sha256}")
}
@ -1015,7 +982,7 @@ executable = true
executable_artifact = "daemon"
transport = "http"
route_required = true
required_environment = ["SERVICE_BIND"]
required_environment = ["GAMECULT_IDUNN_RUNTIME_BUNDLE", "SERVICE_BIND"]
[service.health]
contract = "service.health"
@ -1134,27 +1101,28 @@ nodes = ["yggdrasil"]
fn odin() -> ExpectedIncarnation {
ExpectedIncarnation {
schema: EXPECTED_INCARNATION_SCHEMA.into(),
plan_id: digest(b'a'),
sealed_release_id: digest(b'e'),
schema_version: IDUNN_EXPECTED_INCARNATION_SCHEMA.into(),
target: "odin".into(),
plan_id: digest(b'a'),
incarnation_id: "odin-incarnation-1".into(),
sealed_release_id: digest(b'e'),
source_repository: "github.com/GameCult/Odin".into(),
source_revision: "2222222222222222222222222222222222222222".into(),
recipe_sha256: digest(b'b'),
runtime_id: "odin-yggdrasil".into(),
expected_signer_identity_id: "odin-runtime-signer".into(),
health_contract: "odin.cultnet-service-health".into(),
executable_artifact_sha256: digest(b'f'),
artifact_sha256: digest(b'f'),
state_schema_generation: None,
state_contract_sha256: None,
write_lease_required: false,
source_revision: "2222222222222222222222222222222222222222".into(),
node: "yggdrasil".into(),
route: Some(ExpectedRoute {
route: Some(IdunnExpectedRoute {
route_id: "odin-private".into(),
transport: ServiceTransport::Tcp,
transport: "tcp".into(),
stable_endpoint: "tcp://10.77.0.1:17871".into(),
candidate_endpoint: "tcp://127.0.0.1:17871".into(),
}),
capabilities: vec![ProvidedCapability {
capabilities: vec![GameCultRuntimeCapability {
capability: "odin.verse-rendezvous".into(),
schema: "odin.verse-topology.v1".into(),
compatibility: "v1".into(),
@ -1336,29 +1304,80 @@ nodes = ["yggdrasil"]
"service-runtime-signer"
);
assert_eq!(expected.health_contract, "service.health");
assert_eq!(expected.executable_artifact_sha256, digest(b'c'));
assert_eq!(expected.artifact_sha256, digest(b'c'));
assert_eq!(expected.source_repository, "github.com/GameCult/Service");
assert_eq!(expected.source_revision, plan.source.revision);
assert_eq!(expected.recipe_sha256, plan.source.recipe_blob_sha256);
assert_eq!(expected.state_schema_generation.as_deref(), Some("v1"));
assert!(expected.state_contract_sha256.is_some());
assert!(!expected.write_lease_required);
assert_eq!(expected.node, "yggdrasil");
assert_eq!(
expected.dependencies[0]
.provider
.as_ref()
.unwrap()
.provider_id,
"odin-yggdrasil"
expected.dependencies[0].provider_id.as_deref(),
Some("odin-yggdrasil")
);
assert_eq!(
expected.dependencies[0].provider_authority.as_deref(),
Some("managed-incarnation")
);
assert_eq!(
expected.route.as_ref().unwrap().candidate_endpoint,
"http://127.0.0.1:18001"
);
assert_eq!(expected.route.as_ref().unwrap().transport, "http");
assert!(expected.canonical_sha256().unwrap().starts_with("sha256-"));
let mut invalid_release = release;
invalid_release.artifacts[0].size_bytes += 1;
assert!(invalid_release.expected_projection(&plan).is_err());
}
#[test]
fn expected_projection_sorts_shared_capability_and_dependency_claims() {
let recipe = RECIPE
.replace(
"[[provides]]\ncapability = \"service.runtime\"",
"[[provides]]\ncapability = \"zeta.runtime\"\nschema = \"zeta.runtime.v1\"\ncompatibility = \"v1\"\n\n[[provides]]\ncapability = \"service.runtime\"",
)
.replace(
"[[dependencies]]\nkind = \"shared-infrastructure\"",
"[[dependencies]]\nkind = \"optional\"\ncapability = \"zeta.optional\"\nschema = \"zeta.optional.v1\"\ncompatibility = \"v1\"\n\n[[dependencies]]\nkind = \"shared-infrastructure\"",
);
let plan = compile_deployment_plan(
recipe.as_bytes(),
BINDING.as_bytes(),
source(&recipe),
"service-incarnation-sorted",
Some(18002),
111,
&[odin()],
)
.unwrap();
let release = SealedRelease::new(
&plan,
vec![artifact_receipt()],
vec![external_input_receipt()],
120,
)
.unwrap();
let expected = release.expected_projection(&plan).unwrap();
assert_eq!(
expected
.capabilities
.iter()
.map(|capability| capability.capability.as_str())
.collect::<Vec<_>>(),
["service.runtime", "zeta.runtime"]
);
assert_eq!(
expected
.dependencies
.iter()
.map(|dependency| dependency.capability.as_str())
.collect::<Vec<_>>(),
["odin.verse-rendezvous", "zeta.optional"]
);
expected.validate().unwrap();
}
#[test]
fn sealed_release_address_covers_artifacts_and_external_inputs() {
let receipt = artifact_receipt();

File diff suppressed because it is too large Load diff

View file

@ -1,3 +1,5 @@
pub mod control_plane;
pub mod deployment;
pub mod deployment_plan;
pub mod drivers;
pub mod provisioning;

File diff suppressed because it is too large Load diff

2
vendor/cultnet-rs vendored

@ -1 +1 @@
Subproject commit 87d0b0f2c829ef2e7defa2bf774f1e3b9cc6a1d0
Subproject commit e45e039ebecb005fad65602b7822b7b8a37f2428