use std::collections::BTreeMap;
use std::fs::File;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Instance {
pub sandbox: String,
#[serde(default)]
pub instance_id: String,
#[serde(default)]
pub project: String,
pub container: String,
pub folder: PathBuf,
#[serde(default)]
pub base_folder: PathBuf,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub worktree: Option<PathBuf>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub branch: Option<String>,
#[serde(default = "yes", skip_serializing_if = "is_true")]
pub branch_created: bool,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub folders: Vec<FolderMount>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub shell_history: Option<PathBuf>,
pub workspace: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub workspace_file: Option<String>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub remote_env: BTreeMap<String, String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub remote_user: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub home: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub browser_sandbox: Option<crate::commands::run::BrowserSandbox>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub tool_env: BTreeMap<String, String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ssh_auth_sock: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub devsbd_arch: Option<crate::devsbd::Arch>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub devsbd_error: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub volumes: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub bind_dirs: Vec<PathBuf>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub dispatcher: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub profile: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub config_dir: Option<PathBuf>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub extra_env: BTreeMap<String, String>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub forwarded_ports: BTreeMap<String, u16>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub incarnation: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub claims: Vec<crate::credentials::instance::InstanceClaim>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub intercept: Option<crate::credentials::instance::Intercept>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub github_repos: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub build_notes: Vec<String>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub git_env: BTreeMap<String, String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub done: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub progress: Option<Progress>,
pub created_unix: u64,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(into = "ProgressToml", try_from = "ProgressToml")]
pub struct Progress {
pub phase: Phase,
pub pid: u32,
pub boot: Option<String>,
pub error: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Phase {
Preparing,
Building,
Creating,
Lifecycle(String),
Failed { at: String },
}
impl Phase {
pub fn label(&self) -> &str {
match self {
Phase::Preparing => "preparing",
Phase::Building => "building",
Phase::Creating => "creating",
Phase::Lifecycle(step) => step,
Phase::Failed { .. } => "failed",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PhaseView {
InFlight(String),
Failed { at: String, error: String },
}
impl Progress {
pub fn view(&self, alive: impl Fn(u32) -> bool, boot: Option<&str>) -> PhaseView {
if let Phase::Failed { at } = &self.phase {
return PhaseView::Failed {
at: at.clone(),
error: self.error.clone().unwrap_or_else(|| "failed".into()),
};
}
let rebooted = matches!((self.boot.as_deref(), boot), (Some(then), Some(now)) if then != now);
if rebooted || !alive(self.pid) {
return PhaseView::Failed { at: self.phase.label().into(), error: "interrupted".into() };
}
PhaseView::InFlight(self.phase.label().into())
}
pub fn current_view(&self) -> PhaseView {
self.view(pid_alive, crate::commands::autostart::boot_id().as_deref())
}
}
pub fn pid_alive(pid: u32) -> bool {
#[cfg(unix)]
{
let Ok(pid @ 1..) = libc::pid_t::try_from(pid) else { return false };
let ok = unsafe { libc::kill(pid, 0) } == 0;
ok || std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
}
#[cfg(not(unix))]
{
let _ = pid;
true
}
}
#[derive(Serialize, Deserialize)]
struct ProgressToml {
phase: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
step: Option<String>,
pid: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
boot: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
error: Option<String>,
}
impl From<Progress> for ProgressToml {
fn from(p: Progress) -> Self {
let (phase, step) = match p.phase {
Phase::Preparing => ("preparing", None),
Phase::Building => ("building", None),
Phase::Creating => ("creating", None),
Phase::Lifecycle(step) => ("lifecycle", Some(step)),
Phase::Failed { at } => ("failed", Some(at)),
};
ProgressToml { phase: phase.into(), step, pid: p.pid, boot: p.boot, error: p.error }
}
}
impl TryFrom<ProgressToml> for Progress {
type Error = String;
fn try_from(t: ProgressToml) -> Result<Self, String> {
let step = |phase: &str| t.step.clone().unwrap_or_else(|| phase.to_string());
let phase = match t.phase.as_str() {
"preparing" => Phase::Preparing,
"building" => Phase::Building,
"creating" => Phase::Creating,
"lifecycle" => Phase::Lifecycle(step("lifecycle")),
"failed" => Phase::Failed { at: step("failed") },
other => Phase::Lifecycle(other.to_string()),
};
Ok(Progress { phase, pid: t.pid, boot: t.boot, error: t.error })
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FolderMount {
pub target: String,
pub base: PathBuf,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub worktree: Option<PathBuf>,
}
fn yes() -> bool {
true
}
fn is_true(b: &bool) -> bool {
*b
}
impl Instance {
pub fn now() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0)
}
pub fn exec_env(&self) -> BTreeMap<String, String> {
let mut env = self.tool_env.clone();
env.extend(self.home.iter().map(|h| ("HOME".to_string(), h.clone())));
env.extend(self.remote_env.iter().map(|(k, v)| (k.clone(), v.clone())));
env.extend(self.extra_env.iter().map(|(k, v)| (k.clone(), v.clone())));
env.extend(self.git_env.iter().map(|(k, v)| (k.clone(), v.clone())));
env
}
pub fn phase_view(&self) -> Option<PhaseView> {
self.progress.as_ref().map(Progress::current_view)
}
}
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct State {
#[serde(default, rename = "instance")]
pub instances: BTreeMap<String, Instance>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub autostart_boot: BTreeMap<String, String>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub identity_acks: BTreeMap<String, std::collections::BTreeSet<String>>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub global_forwarded_ports: BTreeMap<String, BTreeMap<String, u16>>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub last_profile: BTreeMap<String, BTreeMap<String, String>>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub trusted_origins: BTreeMap<String, String>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub identity_probes: BTreeMap<String, crate::runtime::identity::Probe>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub image_facts: BTreeMap<String, ImageFacts>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub folder_remotes: BTreeMap<String, FolderRemotes>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub github_ids: BTreeMap<String, GithubPin>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub updates: BTreeMap<String, BTreeMap<String, UpdateRecord>>,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct UpdateRecord {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ok: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tried: Option<u64>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct GithubPin {
pub id: u64,
pub node_id: String,
#[serde(default)]
pub pinned_at: u64,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct FolderRemotes {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub remotes: Vec<FolderRemote>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub github: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub unread: Option<String>,
#[serde(default)]
pub recorded_at: u64,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct FolderRemote {
pub name: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub urls: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub pushurls: Vec<String>,
}
pub const IMAGE_FACTS_CAP: usize = 32;
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ImageFacts {
#[serde(default)]
pub env: Vec<(String, String)>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub user: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub passwd: Option<String>,
#[serde(default)]
pub at: u64,
}
impl State {
pub fn remember_image_facts(&mut self, id: String, facts: ImageFacts) {
self.image_facts.insert(id, facts);
while self.image_facts.len() > IMAGE_FACTS_CAP {
let oldest = self.image_facts.iter().min_by_key(|(_, f)| f.at).map(|(id, _)| id.clone());
match oldest {
Some(id) => self.image_facts.remove(&id),
None => break,
};
}
}
pub fn path() -> Result<PathBuf> {
let base = std::env::var_os("XDG_DATA_HOME")
.map(PathBuf::from)
.or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".local/share")))
.context("cannot determine user data dir ($XDG_DATA_HOME or $HOME)")?;
Ok(base.join("devsandbox/state.toml"))
}
pub fn load() -> Result<Self> {
Self::load_at(&Self::path()?)
}
pub(crate) fn load_at(path: &Path) -> Result<Self> {
match std::fs::read_to_string(path) {
Ok(contents) => {
let mut state: Self = toml::from_str(&contents)
.with_context(|| format!("invalid state file {}", path.display()))?;
for (key, instance) in &mut state.instances {
if instance.instance_id.is_empty() {
instance.instance_id = key.clone();
}
}
Ok(state)
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Self::default()),
Err(e) => Err(e).with_context(|| format!("cannot read {}", path.display())),
}
}
pub fn update<T>(f: impl FnOnce(&mut State) -> Result<T>) -> Result<T> {
Self::update_at(&Self::path()?, f)
}
pub(crate) fn update_at<T>(path: &Path, f: impl FnOnce(&mut State) -> Result<T>) -> Result<T> {
let dir = path.parent().context("state path has no parent")?;
std::fs::create_dir_all(dir).with_context(|| format!("cannot create {}", dir.display()))?;
let lock_path = path.with_file_name("state.lock");
let _lock = File::options()
.create(true)
.read(true)
.write(true)
.truncate(false)
.open(&lock_path)
.and_then(|file| file.lock().map(|()| file))
.with_context(|| format!("cannot lock {}", lock_path.display()))?;
let mut state = Self::load_at(path)?;
let before = toml::to_string_pretty(&state).context("cannot serialize state")?;
let out = f(&mut state)?;
let after = toml::to_string_pretty(&state).context("cannot serialize state")?;
if after != before {
let tmp = path.with_file_name(format!(".state.toml.{}.tmp", std::process::id()));
std::fs::write(&tmp, after).with_context(|| format!("cannot write {}", tmp.display()))?;
std::fs::rename(&tmp, path).with_context(|| format!("cannot write {}", path.display()))?;
}
Ok(out)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn roundtrips() {
let mut state = State::default();
state.instances.insert(
"repo-abc1".into(),
Instance {
sandbox: "repository-1".into(),
instance_id: "repo-abc1".into(),
project: "abc12345".into(),
container: "devsandbox-repo-abc1".into(),
folder: "/home/u/repository-1".into(),
base_folder: "/home/u/repository-1".into(),
worktree: None,
branch: None,
branch_created: true,
folders: Vec::new(),
shell_history: None,
workspace: "/workspaces/repository-1".into(),
workspace_file: None,
remote_env: BTreeMap::new(),
remote_user: None,
home: Some("/home/vscode".into()),
browser_sandbox: None,
tool_env: Default::default(),
ssh_auth_sock: None,
devsbd_arch: None,
devsbd_error: None,
volumes: Vec::new(),
bind_dirs: Vec::new(),
dispatcher: Some("pr-dispatcher".into()),
profile: Some("work".into()),
config_dir: Some("/home/u/.devsandboxes".into()),
extra_env: BTreeMap::from([("PR_NUMBER".into(), "42".into())]),
forwarded_ports: BTreeMap::from([("8080:3000".into(), 8081)]),
done: Some(1_790_900_000),
incarnation: Some("Zx9".into()),
claims: vec![crate::credentials::instance::InstanceClaim {
kind: "sentry".into(),
feature: "./features/sentry".into(),
version: "ab12".into(),
claim: "{\"kind\":\"sentry\"}".into(),
phantom: "sntrys_x".into(),
listeners: vec![crate::credentials::instance::Listener { port: 29000, upstream: "sentry.io".into() }],
files: vec![crate::credentials::instance::File {
path: "/home/vscode/.sentryclirc".into(),
owner: "vscode".into(),
content: "[auth]\ntoken = sntrys_x\n".into(),
}],
git_hosts: Vec::new(),
}],
intercept: Some(crate::credentials::instance::Intercept {
port: 29001,
hosts: vec!["api.github.com".into()],
git: Some(crate::credentials::instance::ProxyPort { port: 29002, hosts: vec!["github.com".into()] }),
lfs: Some(29003),
proxy_env: vec![("HTTPS_PROXY".into(), "http://corp:3128".into())],
bundle: "/etc/ssl/certs/ca-certificates.crt".into(),
installed: Some("ab".repeat(32)),
}),
github_repos: vec!["o/r".into()],
build_notes: vec!["warning: w".into()],
git_env: Default::default(),
progress: None,
created_unix: Instance::now(),
},
);
state.autostart_boot.insert("abc12345".into(), "3f2c-boot".into());
let probe = crate::runtime::identity::Probe { mode: crate::runtime::identity::Mode::RootlessPodman, selinux: true };
state.identity_probes.insert("podman:host=unix:///run/user/1000/podman/podman.sock".into(), probe);
let remotes = FolderRemotes {
remotes: vec![FolderRemote {
name: "origin".into(),
urls: vec!["git@github.com:o/r.git".into()],
pushurls: vec!["https://github.com/o/r".into()],
}],
github: vec!["o/r".into()],
unread: None,
recorded_at: 7,
};
state.folder_remotes.insert("/home/u/repository-1".into(), remotes.clone());
let text = toml::to_string_pretty(&state).unwrap();
let back: State = toml::from_str(&text).unwrap();
assert_eq!(back.identity_probes["podman:host=unix:///run/user/1000/podman/podman.sock"], probe);
assert_eq!(back.instances["repo-abc1"].sandbox, "repository-1");
assert_eq!(back.instances["repo-abc1"].instance_id, "repo-abc1");
assert_eq!(back.autostart_boot["abc12345"], "3f2c-boot");
assert_eq!(back.instances["repo-abc1"].dispatcher.as_deref(), Some("pr-dispatcher"));
assert_eq!(
back.instances["repo-abc1"].config_dir.as_deref(),
Some(std::path::Path::new("/home/u/.devsandboxes"))
);
assert_eq!(back.instances["repo-abc1"].extra_env["PR_NUMBER"], "42");
assert_eq!(back.instances["repo-abc1"].forwarded_ports["8080:3000"], 8081);
assert_eq!(back.instances["repo-abc1"].done, Some(1_790_900_000));
assert_eq!(back.instances["repo-abc1"].home.as_deref(), Some("/home/vscode"));
assert_eq!(back.instances["repo-abc1"].profile.as_deref(), Some("work"));
assert_eq!(back.instances["repo-abc1"].incarnation.as_deref(), Some("Zx9"));
assert_eq!(back.instances["repo-abc1"].claims, state.instances["repo-abc1"].claims);
assert_eq!(back.instances["repo-abc1"].intercept, state.instances["repo-abc1"].intercept);
assert_eq!(back.instances["repo-abc1"].created_unix, state.instances["repo-abc1"].created_unix);
assert_eq!(back.instances["repo-abc1"].github_repos, ["o/r"]);
assert_eq!(back.instances["repo-abc1"].build_notes, ["warning: w"]);
assert_eq!(back.folder_remotes["/home/u/repository-1"], remotes);
}
#[test]
fn last_profile_roundtrips_and_empty_is_omitted() {
let text = toml::to_string_pretty(&State::default()).unwrap();
assert!(!text.contains("last_profile"), "{text}");
let mut state = State::default();
state.last_profile.entry("abc12345".into()).or_default().insert("web".into(), "work".into());
let back: State = toml::from_str(&toml::to_string_pretty(&state).unwrap()).unwrap();
assert_eq!(back.last_profile, state.last_profile);
}
#[test]
fn empty_autostart_boot_is_omitted() {
let text = toml::to_string_pretty(&State::default()).unwrap();
assert!(!text.contains("autostart_boot"), "{text}");
let back: State = toml::from_str(&text).unwrap();
assert!(back.autostart_boot.is_empty());
}
#[test]
fn identity_acks_roundtrip_and_empty_is_omitted() {
let text = toml::to_string_pretty(&State::default()).unwrap();
assert!(!text.contains("identity_acks"), "{text}");
let mut state = State::default();
state.identity_acks.insert("abc12345".into(), ["f1".to_string(), "f2".to_string()].into());
let back: State = toml::from_str(&toml::to_string_pretty(&state).unwrap()).unwrap();
assert_eq!(back.identity_acks, state.identity_acks);
}
#[test]
fn image_facts_roundtrip_and_empty_is_omitted() {
let text = toml::to_string_pretty(&State::default()).unwrap();
assert!(!text.contains("image_facts"), "{text}");
let mut state = State::default();
let facts = ImageFacts {
env: vec![("PATH".into(), "/usr/bin:/bin".into()), ("OPTS".into(), "a=b".into())],
user: Some("node".into()),
passwd: Some("root:x:0:0:root:/root:/bin/sh\nnode:x:1000:1000::/home/node:/bin/sh\n".into()),
at: 7,
};
state.remember_image_facts("sha256:abc".into(), facts.clone());
state.remember_image_facts("sha256:none".into(), ImageFacts::default());
let back: State = toml::from_str(&toml::to_string_pretty(&state).unwrap()).unwrap();
assert_eq!(back.image_facts["sha256:abc"], facts);
assert_eq!(back.image_facts["sha256:none"], ImageFacts::default());
}
#[test]
fn image_facts_cap_drops_the_oldest() {
let mut state = State::default();
for i in 0..IMAGE_FACTS_CAP as u64 {
state.remember_image_facts(format!("sha256:{i:02}"), ImageFacts { at: 1000 - i, ..Default::default() });
}
assert_eq!(state.image_facts.len(), IMAGE_FACTS_CAP);
state.remember_image_facts("sha256:new".into(), ImageFacts { at: 2000, ..Default::default() });
assert_eq!(state.image_facts.len(), IMAGE_FACTS_CAP);
let oldest = format!("sha256:{:02}", IMAGE_FACTS_CAP - 1);
assert!(!state.image_facts.contains_key(&oldest));
assert!(state.image_facts.contains_key("sha256:new") && state.image_facts.contains_key("sha256:00"));
}
#[test]
fn empty_identity_probes_is_omitted() {
let text = toml::to_string_pretty(&State::default()).unwrap();
assert!(!text.contains("identity_probes"), "{text}");
let back: State = toml::from_str(&text).unwrap();
assert!(back.identity_probes.is_empty());
}
#[test]
fn missing_instance_id_deserializes_empty() {
let state: State = toml::from_str(
r#"
[instance.repo]
sandbox = "web"
container = "devsandbox-repo"
folder = "/home/u/web"
workspace = "/workspaces/web"
created_unix = 0
"#,
)
.unwrap();
assert_eq!(state.instances["repo"].instance_id, "");
assert_eq!(state.instances["repo"].dispatcher, None);
assert_eq!(state.instances["repo"].profile, None);
assert_eq!(state.instances["repo"].config_dir, None);
assert!(state.instances["repo"].extra_env.is_empty());
assert_eq!(state.instances["repo"].done, None);
assert!(state.instances["repo"].branch_created);
let text = toml::to_string_pretty(&state).unwrap();
assert!(!text.contains("dispatcher") && !text.contains("config_dir"), "{text}");
assert!(!text.contains("profile"), "{text}");
assert!(!text.contains("branch_created"), "{text}");
assert!(!text.contains("extra_env"), "{text}");
assert!(!text.contains("done"), "{text}");
assert_eq!(state.instances["repo"].home, None);
assert!(!text.contains("home ="), "{text}");
assert_eq!(state.instances["repo"].browser_sandbox, None);
assert!(state.instances["repo"].tool_env.is_empty());
assert!(!text.contains("browser_sandbox") && !text.contains("tool_env"), "{text}");
}
#[test]
fn browser_sandbox_and_tool_env_roundtrip() {
use crate::commands::run::BrowserSandbox;
let mut state: State = toml::from_str(
"[instance.a]\nsandbox = \"web\"\ncontainer = \"c\"\nfolder = \"/f\"\nworkspace = \"/w\"\ncreated_unix = 0\n",
)
.unwrap();
let inst = state.instances.get_mut("a").unwrap();
inst.browser_sandbox = Some(BrowserSandbox::On);
inst.tool_env = BTreeMap::from([("DEVSANDBOX_BROWSER_SANDBOX".into(), "1".into())]);
let text = toml::to_string_pretty(&state).unwrap();
assert!(text.contains("browser_sandbox = \"on\""), "{text}");
let back: State = toml::from_str(&text).unwrap();
assert_eq!(back.instances["a"].browser_sandbox, Some(BrowserSandbox::On));
assert_eq!(back.instances["a"].tool_env["DEVSANDBOX_BROWSER_SANDBOX"], "1");
let why = "no user namespaces: seccomp";
state.instances.get_mut("a").unwrap().browser_sandbox = Some(BrowserSandbox::Off(why.into()));
let text = toml::to_string_pretty(&state).unwrap();
let back: State = toml::from_str(&text).unwrap();
assert_eq!(back.instances["a"].browser_sandbox, Some(BrowserSandbox::Off(why.into())), "{text}");
}
#[test]
fn exec_env_overlays_extra_env_on_remote_env() {
let mut state: State = toml::from_str(
"[instance.a]\nsandbox = \"web\"\ncontainer = \"c\"\nfolder = \"/f\"\nworkspace = \"/w\"\ncreated_unix = 0\n",
)
.unwrap();
let inst = state.instances.get_mut("a").unwrap();
assert!(inst.exec_env().is_empty());
inst.remote_env = BTreeMap::from([("A".into(), "remote".into()), ("B".into(), "b".into())]);
inst.extra_env = BTreeMap::from([("A".into(), "extra".into()), ("C".into(), "c".into())]);
assert_eq!(
inst.exec_env(),
BTreeMap::from([
("A".into(), "extra".into()),
("B".into(), "b".into()),
("C".into(), "c".into()),
])
);
inst.home = Some("/home/vscode".into());
assert_eq!(inst.exec_env()["HOME"], "/home/vscode");
inst.remote_env.insert("HOME".into(), "/srv/me".into());
assert_eq!(inst.exec_env()["HOME"], "/srv/me");
inst.extra_env.insert("HOME".into(), "/tmp/x".into());
assert_eq!(inst.exec_env()["HOME"], "/tmp/x");
inst.tool_env = BTreeMap::from([("B".into(), "tool".into()), ("T".into(), "t".into())]);
assert_eq!((inst.exec_env()["B"].as_str(), inst.exec_env()["T"].as_str()), ("b", "t"));
}
#[test]
fn updates_apply_to_the_current_file_not_a_snapshot() {
let dir = std::env::temp_dir().join(format!("devsandbox-state-update-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let path = dir.join("state.toml");
let entry = |name: &str| -> Instance {
toml::from_str(&format!(
"sandbox = \"web\"\ninstance_id = \"{name}\"\ncontainer = \"devsandbox-{name}\"\nfolder = \"/f\"\nworkspace = \"/w\"\ncreated_unix = 0\n"
))
.unwrap()
};
State::update_at(&path, |s| {
s.instances.insert("a".into(), entry("a"));
Ok(())
})
.unwrap();
let stale = State::load_at(&path).unwrap();
State::update_at(&path, |s| {
s.instances.insert("child".into(), entry("child"));
Ok(())
})
.unwrap();
assert!(!stale.instances.contains_key("child"));
State::update_at(&path, |s| {
s.instances.remove("a");
Ok(())
})
.unwrap();
let now = State::load_at(&path).unwrap();
assert_eq!(now.instances.keys().collect::<Vec<_>>(), ["child"]);
let mtime = || std::fs::metadata(&path).unwrap().modified().unwrap();
let before = mtime();
std::thread::sleep(std::time::Duration::from_millis(20));
let err = State::update_at(&path, |s| -> Result<()> {
s.instances.clear();
anyhow::bail!("boom")
});
assert!(err.is_err());
State::update_at(&path, |_| Ok(())).unwrap();
assert_eq!(mtime(), before);
assert!(State::load_at(&path).unwrap().instances.contains_key("child"));
std::fs::remove_dir_all(&dir).unwrap();
}
fn progress(phase: Phase) -> Progress {
Progress { phase, pid: 4242, boot: Some("boot-a".into()), error: None }
}
#[test]
fn progress_roundtrips_every_phase() {
let phases = [
Phase::Preparing,
Phase::Building,
Phase::Creating,
Phase::Lifecycle("postCreateCommand".into()),
Phase::Lifecycle("shell-rc".into()),
Phase::Failed { at: "building".into() },
];
for phase in phases {
let mut state: State = toml::from_str(
"[instance.a]\nsandbox = \"web\"\ncontainer = \"c\"\nfolder = \"/f\"\nworkspace = \"/w\"\ncreated_unix = 0\n",
)
.unwrap();
let mut p = progress(phase);
if matches!(p.phase, Phase::Failed { .. }) {
p.error = Some("docker build exited 1".into());
}
state.instances.get_mut("a").unwrap().progress = Some(p.clone());
let text = toml::to_string_pretty(&state).unwrap();
let back: State = toml::from_str(&text).unwrap();
assert_eq!(back.instances["a"].progress, Some(p), "{text}");
}
}
#[test]
fn progress_toml_shape() {
let mut state: State = toml::from_str(
"[instance.a]\nsandbox = \"web\"\ncontainer = \"c\"\nfolder = \"/f\"\nworkspace = \"/w\"\ncreated_unix = 0\n",
)
.unwrap();
state.instances.get_mut("a").unwrap().progress = Some(progress(Phase::Lifecycle("postCreateCommand".into())));
let text = toml::to_string_pretty(&state).unwrap();
let back: toml::Table = toml::from_str(&text).unwrap();
let p = back["instance"]["a"]["progress"].as_table().unwrap();
assert_eq!(p["phase"].as_str(), Some("lifecycle"), "{text}");
assert_eq!(p["step"].as_str(), Some("postCreateCommand"), "{text}");
assert_eq!(p["pid"].as_integer(), Some(4242), "{text}");
assert_eq!(p["boot"].as_str(), Some("boot-a"), "{text}");
assert!(!p.contains_key("error"), "{text}");
}
#[test]
fn no_progress_loads_and_is_omitted() {
let state: State = toml::from_str(
"[instance.a]\nsandbox = \"web\"\ncontainer = \"c\"\nfolder = \"/f\"\nworkspace = \"/w\"\ncreated_unix = 0\n",
)
.unwrap();
assert_eq!(state.instances["a"].progress, None);
let text = toml::to_string_pretty(&state).unwrap();
assert!(!text.contains("progress"), "{text}");
}
#[test]
fn odd_progress_still_loads() {
let base = "[instance.a]\nsandbox = \"web\"\ncontainer = \"c\"\nfolder = \"/f\"\nworkspace = \"/w\"\ncreated_unix = 0\n";
for (progress, phase) in [
("phase = \"lifecycle\"\npid = 1\n", Phase::Lifecycle("lifecycle".into())),
("phase = \"failed\"\npid = 1\n", Phase::Failed { at: "failed".into() }),
("phase = \"teleporting\"\npid = 1\n", Phase::Lifecycle("teleporting".into())),
] {
let text = format!("{base}[instance.a.progress]\n{progress}");
let state: State = toml::from_str(&text).unwrap();
assert_eq!(state.instances["a"].progress.as_ref().unwrap().phase, phase, "{text}");
}
}
#[test]
fn view_in_flight_when_alive_and_same_boot() {
let alive = |_| true;
assert_eq!(progress(Phase::Preparing).view(alive, Some("boot-a")), PhaseView::InFlight("preparing".into()));
assert_eq!(progress(Phase::Building).view(alive, Some("boot-a")), PhaseView::InFlight("building".into()));
assert_eq!(progress(Phase::Creating).view(alive, Some("boot-a")), PhaseView::InFlight("creating".into()));
assert_eq!(
progress(Phase::Lifecycle("postCreateCommand".into())).view(alive, Some("boot-a")),
PhaseView::InFlight("postCreateCommand".into())
);
assert_eq!(progress(Phase::Building).view(alive, None), PhaseView::InFlight("building".into()));
let mut unbooted = progress(Phase::Building);
unbooted.boot = None;
assert_eq!(unbooted.view(alive, Some("boot-b")), PhaseView::InFlight("building".into()));
}
#[test]
fn view_interrupted_when_dead_or_rebooted() {
let interrupted = |at: &str| PhaseView::Failed { at: at.into(), error: "interrupted".into() };
let p = progress(Phase::Lifecycle("shell-rc".into()));
assert_eq!(p.view(|pid| pid != 4242, Some("boot-a")), interrupted("shell-rc"));
assert_eq!(p.view(|_| true, Some("boot-b")), interrupted("shell-rc"));
assert_eq!(progress(Phase::Creating).view(|_| false, None), interrupted("creating"));
}
#[test]
fn view_failed_stays_failed() {
let mut p = progress(Phase::Failed { at: "postCreateCommand".into() });
p.error = Some("exit status 1".into());
let failed = PhaseView::Failed { at: "postCreateCommand".into(), error: "exit status 1".into() };
assert_eq!(p.view(|_| true, Some("boot-a")), failed);
assert_eq!(p.view(|_| false, Some("boot-b")), failed);
p.error = None;
assert_eq!(
p.view(|_| true, Some("boot-a")),
PhaseView::Failed { at: "postCreateCommand".into(), error: "failed".into() }
);
}
#[test]
fn pid_alive_probes_real_processes() {
assert!(pid_alive(std::process::id()));
#[cfg(unix)]
{
assert!(!pid_alive(i32::MAX as u32));
assert!(!pid_alive(u32::MAX));
assert!(!pid_alive(0));
assert!(pid_alive(1));
}
}
#[test]
fn reused_branch_roundtrips() {
let mut state: State = toml::from_str(
"[instance.a]\nsandbox = \"web\"\ncontainer = \"c\"\nfolder = \"/f\"\nworkspace = \"/w\"\ncreated_unix = 0\n",
)
.unwrap();
state.instances.get_mut("a").unwrap().branch_created = false;
let text = toml::to_string_pretty(&state).unwrap();
let back: State = toml::from_str(&text).unwrap();
assert!(!back.instances["a"].branch_created, "{text}");
}
}