use std::path::{Path, PathBuf};
use std::time::Duration;
use crate::devsbd::bridge::Readiness;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use super::forwards::{AddRequest, Added, ForwardRow, Removed};
use crate::broker::asks::{self, Registry};
use crate::devsbd::rpc::Obj;
use crate::config_identity::ops as identity_ops;
use crate::inbox::wire::{self, Addr, resolve};
use crate::inbox::{Inbox, Kind, Op, View, ops};
pub use crate::inbox::wire::{ApiError, ThreadDetail};
pub struct Ctx<'a> {
pub inbox: &'a Path,
pub client: &'a str,
pub bridges: Option<&'a dyn Bridging>,
pub forwards: Option<&'a dyn Forwarding>,
pub access: Option<&'a Registry>,
pub host: Option<HostPaths<'a>>,
}
#[derive(Clone, Copy)]
pub struct HostPaths<'a> {
pub state: &'a Path,
pub home: Option<&'a Path>,
pub data: Option<&'a Path>,
pub member: Option<&'a Path>,
}
pub trait Forwarding {
fn list(&self, dir: Option<PathBuf>, machines: bool) -> Result<Vec<ForwardRow>, ApiError>;
fn add(&self, req: AddRequest) -> Result<Added, ApiError>;
fn rm(&self, id: u64) -> Result<Removed, ApiError>;
}
pub trait Bridging {
fn container(&self, instance: &str) -> anyhow::Result<Option<String>>;
fn report_agent(&self, path: PathBuf);
fn reconcile_now(&self, container: String) -> u64;
fn wait_ready(&self, container: &str, ticket: u64, timeout: Duration) -> Readiness;
}
pub const MAX_ENSURE_WAIT: Duration = Duration::from_secs(15);
type Answer = Result<Value, ApiError>;
pub fn call(method: &str, params: Value, ctx: &Ctx) -> Answer {
match method {
"inbox.threads.list" => threads_list(parse(params)?, ctx),
"inbox.thread.get" => thread_get(parse(params)?, ctx),
"inbox.thread.markRead" => {
let addr: Addr = parse(params)?;
mutate(ctx, |inbox| Ok(vec![Op::MarkRead(resolve(inbox, &addr)?.id)]))
}
"inbox.thread.act" => act(parse(params)?, ctx),
"inbox.thread.reply" => reply(parse(params)?, ctx),
"inbox.thread.done" => {
let addr: Addr = parse(params)?;
mutate(ctx, |inbox| wire::decide_done(inbox, &addr))
}
"inbox.thread.reopen" => {
let addr: Addr = parse(params)?;
mutate(ctx, |inbox| wire::decide_reopen(inbox, &addr))
}
"inbox.form.saveDraft" => form_save_draft(parse(params)?, ctx),
"inbox.form.submit" => form_submit(parse(params)?, ctx),
"inbox.notify.dismiss" => dismiss(parse(params)?, ctx),
"inbox.notify.markRead" => notify_mark_read(parse(params)?, ctx),
"instances.list" => instances_list(parse(params)?, &host_state(ctx)?),
"instances.resolve" => instances_resolve(parse(params)?, &host_state(ctx)?),
"instances.cancel" => {
instances_cancel(parse(params)?, &host_state(ctx)?, crate::commands::run::cancel::interrupt)
}
"instances.procs" => instances_procs(parse(params)?, &host_state(ctx)?, fetch_procs),
"instances.signal" => instances_signal(parse(params)?, &host_state(ctx)?, |c, pid, n| {
crate::runtime::backend().signal_proc(c, pid, n)
}),
"instances.rename" => instances_rename(parse(params)?, &host_state(ctx)?),
"instances.setProfile" => instances_set_profile(parse(params)?, &host_state(ctx)?),
"instances.done" => instances_done(parse(params)?, &host_state(ctx)?),
"instances.buildLog" => instances_build_log(parse(params)?, &host_state(ctx)?),
"sessions.list" => sessions_list(parse(params)?, &host_state(ctx)?, |c, m, p| helper_rpc(c, m, p, ctx.client)),
"sessions.rm" => sessions_rm(parse(params)?, &host_state(ctx)?, |c, m, p| helper_rpc(c, m, p, ctx.client)),
"containers.logs" => {
containers_logs(parse(params)?, |c, n| crate::runtime::backend().logs_tail(c, n).map_err(ApiError::internal))
}
"containers.inspect" => {
containers_inspect(parse(params)?, |c| crate::runtime::backend().inspect_json(c).map_err(ApiError::internal))
}
"sandboxes.list" => sandboxes_list(parse(params)?),
"roots.list" => {
let (state, home, data, member) = match ctx.host {
Some(host) => (
host.state.to_path_buf(),
host.home.map(Path::to_path_buf),
host.data.map(Path::to_path_buf),
host.member.map(Path::to_path_buf),
),
None => {
let state = state_path()?;
let data = state.parent().map(Path::to_path_buf);
(state, std::env::var_os("HOME").map(PathBuf::from), data, crate::serve::fleet::member::path().ok())
}
};
roots_list(&state, home.as_deref(), data.as_deref(), member.as_deref())
}
"sandboxes.get" => sandboxes_get(parse(params)?),
"services.get" => services_get(parse(params)?),
"config.findings" => {
let p: FindingsParams = parse(params)?;
to_value(identity_ops::findings(&p.root, &host_state(ctx)?, p.sandbox.as_deref())?)
}
"config.migrate" => {
let p: MigrateParams = parse(params)?;
to_value(identity_ops::migrate(&p.root, &host_state(ctx)?, p.ids.as_deref(), &p.keep, &p.file_hash)?)
}
"config.ack" => {
let p: AckParams = parse(params)?;
to_value(identity_ops::ack(&p.root, &host_state(ctx)?, &p.ids)?)
}
"bridges.ensure" => bridges_ensure(parse(params)?, ctx),
"forwards.list" => forwards_list(parse(params)?, ctx),
"forwards.add" => forwards_add(parse(params)?, ctx),
"forwards.rm" => forwards_rm(parse(params)?, ctx),
"access.pending" => access_pending(ctx),
"access.decide" => access_decide(parse(params)?, ctx),
other => Err(ApiError::unknown_method(other)),
}
}
pub(crate) fn parse<T: DeserializeOwned>(params: Value) -> Result<T, ApiError> {
let params = if params.is_null() { Value::Object(Default::default()) } else { params };
serde_json::from_value(params).map_err(|e| ApiError::invalid(format!("bad params: {e}")))
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum Topic {
Inbox,
Instances,
Forwards,
Opens,
Roots,
Access,
}
impl Topic {
pub fn parse(s: &str) -> Option<Topic> {
match s {
"inbox" => Some(Topic::Inbox),
"instances" => Some(Topic::Instances),
"forwards" => Some(Topic::Forwards),
"opens" => Some(Topic::Opens),
"roots" => Some(Topic::Roots),
"access" => Some(Topic::Access),
_ => None,
}
}
}
#[derive(Deserialize)]
struct TopicsParams {
topics: Vec<String>,
}
pub fn topics(params: Value) -> Result<Vec<Topic>, ApiError> {
let p: TopicsParams = parse(params)?;
p.topics
.iter()
.map(|t| Topic::parse(t).ok_or_else(|| ApiError::invalid(format!("unknown topic `{t}` (inbox, instances, forwards, opens, roots, access)"))))
.collect()
}
#[derive(Deserialize)]
struct WatchParams {
dir: PathBuf,
}
pub fn watch_dir(params: Value, exists: bool) -> Result<PathBuf, ApiError> {
let p: WatchParams = parse(params)?;
if !p.dir.is_absolute() {
return Err(ApiError::invalid(format!("`dir` must be absolute, got `{}`", p.dir.display())));
}
if exists && !p.dir.is_dir() {
return Err(ApiError::not_found(format!("no directory {}", p.dir.display())));
}
Ok(p.dir)
}
#[derive(Deserialize)]
struct WatchFlags {
#[serde(default)]
machines: bool,
}
pub fn watch_machines(params: &Value) -> Result<bool, ApiError> {
Ok(parse::<WatchFlags>(params.clone())?.machines)
}
pub fn audit_client(hello: &str) -> String {
match hello {
"tui" | "cli" => hello.to_string(),
"" => "api".to_string(),
name if name.starts_with("api:") => name.to_string(),
name => format!("api:{name}"),
}
}
#[derive(Debug, Serialize)]
pub struct ForwardRemoved {
pub ok: bool,
pub local: String,
pub configured: bool,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Resolved {
pub matches: Vec<String>,
#[serde(default)]
pub found: Vec<Found>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Found {
pub name: String,
#[serde(default)]
pub machine: Option<String>,
#[serde(default)]
pub root: Option<PathBuf>,
#[serde(default)]
pub sandbox: Option<String>,
}
#[derive(Debug, Serialize)]
pub struct Cancelled {
pub ok: bool,
pub pid: u32,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SandboxEntry {
pub name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub machine: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub root: Option<PathBuf>,
}
impl SandboxEntry {
pub(crate) fn named(name: String) -> Self {
Self { name, machine: None, root: None }
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct RootCandidate {
pub root: PathBuf,
pub sandboxes: Vec<SandboxEntry>,
pub error: Option<String>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub fleet: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub copy: Option<String>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub home: bool,
}
fn ok() -> Answer {
Ok(json!({ "ok": true }))
}
fn mutate(ctx: &Ctx, decide: impl FnOnce(&Inbox) -> Result<Vec<Op>, ApiError>) -> Answer {
ops::apply_if(ctx.inbox, ctx.client, decide).map_err(ApiError::internal)??;
ok()
}
fn load(ctx: &Ctx) -> Result<Inbox, ApiError> {
ops::load(ctx.inbox).map_err(ApiError::internal)
}
#[derive(Deserialize)]
struct ListParams {
#[serde(default)]
view: Option<String>,
}
fn threads_list(p: ListParams, ctx: &Ctx) -> Answer {
let view = match p.view.as_deref() {
None => View::All,
Some(name) => View::parse(name).ok_or_else(|| {
let names: Vec<&str> = View::ALL.iter().map(|v| v.as_str()).collect();
ApiError::invalid(format!("unknown view `{name}` ({})", names.join(", ")))
})?,
};
let inbox = load(ctx)?;
serde_json::to_value(wire::summaries(&inbox, view)).map_err(|e| ApiError::internal(e.into()))
}
fn thread_get(addr: Addr, ctx: &Ctx) -> Answer {
let inbox = load(ctx)?;
let t = resolve(&inbox, &addr)?;
serde_json::to_value(ThreadDetail::of(t)).map_err(|e| ApiError::internal(e.into()))
}
#[derive(Deserialize)]
struct ActParams {
#[serde(flatten)]
addr: Addr,
action: String,
}
fn act(p: ActParams, ctx: &Ctx) -> Answer {
mutate(ctx, |inbox| wire::decide_act(inbox, &p.addr, &p.action))
}
#[derive(Deserialize)]
struct ReplyParams {
#[serde(flatten)]
addr: Addr,
text: String,
}
fn reply(p: ReplyParams, ctx: &Ctx) -> Answer {
mutate(ctx, |inbox| wire::decide_reply(inbox, &p.addr, &p.text))
}
#[derive(Deserialize)]
struct FormParams {
#[serde(flatten)]
addr: Addr,
message: String,
#[serde(default)]
answers: serde_json::Map<String, Value>,
}
fn form_save_draft(p: FormParams, ctx: &Ctx) -> Answer {
mutate(ctx, |inbox| wire::decide_save_draft(inbox, &p.addr, &p.message, &p.answers))
}
fn form_submit(p: FormParams, ctx: &Ctx) -> Answer {
mutate(ctx, |inbox| wire::decide_submit(inbox, &p.addr, &p.message, &p.answers))
}
#[derive(Deserialize)]
struct DismissParams {
#[serde(default)]
all: bool,
#[serde(flatten)]
addr: Addr,
}
fn dismiss(p: DismissParams, ctx: &Ctx) -> Answer {
match (p.all, p.addr.is_empty()) {
(true, true) => return mutate(ctx, |_| Ok(vec![Op::ClearNotify])),
(true, false) => return Err(ApiError::invalid("`all` takes no thread")),
(false, _) => {}
}
mutate(ctx, |inbox| {
let t = resolve(inbox, &p.addr)?;
if t.kind != Kind::Notify {
return Err(ApiError::invalid(format!("thread {} is an owner thread; only notifications are dismissed", t.id)));
}
Ok(vec![Op::RemoveThread(t.id)])
})
}
fn notify_mark_read(p: DismissParams, ctx: &Ctx) -> Answer {
match (p.all, p.addr.is_empty()) {
(true, true) => return mutate(ctx, |_| Ok(vec![Op::MarkNotifyRead])),
(true, false) => return Err(ApiError::invalid("`all` takes no thread")),
(false, _) => {}
}
mutate(ctx, |inbox| {
let t = resolve(inbox, &p.addr)?;
if t.kind != Kind::Notify {
return Err(ApiError::invalid(format!("thread {} is an owner thread, not a notification", t.id)));
}
Ok(vec![Op::MarkRead(t.id)])
})
}
#[derive(Deserialize)]
struct InstancesParams {
dir: PathBuf,
#[serde(default)]
depth: Option<String>,
}
fn depth(name: Option<&str>) -> Result<crate::snapshot::Depth, ApiError> {
use crate::snapshot::Depth;
match name {
None | Some("full") => Ok(Depth::Full),
Some("listing") => Ok(Depth::Listing),
Some("disk") => Ok(Depth::Disk),
Some(other) => Err(ApiError::invalid(format!("unknown depth `{other}` (disk, listing, full)"))),
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct InstancesList {
#[serde(flatten)]
pub snapshot: crate::snapshot::Snapshot,
#[serde(default)]
pub thread_children: std::collections::BTreeMap<String, std::collections::BTreeMap<String, String>>,
}
fn instances_list(p: InstancesParams, state: &Path) -> Answer {
instances_list_with(p, state, crate::snapshot::collect_with)
}
fn instances_list_with(
p: InstancesParams,
state: &Path,
collect: impl FnOnce(&Path, crate::snapshot::Depth) -> crate::snapshot::Snapshot,
) -> Answer {
if !p.dir.is_absolute() {
return Err(ApiError::invalid(format!("`dir` must be absolute, got `{}`", p.dir.display())));
}
let depth = depth(p.depth.as_deref())?;
if !p.dir.is_dir() {
return Err(ApiError::not_found(format!("no directory {}", p.dir.display())));
}
let list = InstancesList::of(collect(&p.dir, depth), state);
serde_json::to_value(list).map_err(|e| ApiError::internal(e.into()))
}
impl InstancesList {
pub(crate) fn of(mut snapshot: crate::snapshot::Snapshot, state: &Path) -> Self {
let thread_children = crate::state::State::load_at(state)
.map(|s| crate::commands::dispatch::thread_children(&s))
.unwrap_or_default();
let data = state.parent().unwrap_or(Path::new("."));
let bindings = crate::serve::fleet::mesh::load_roots(&crate::serve::fleet::mesh::roots_path(data)).unwrap_or_default();
tag_mesh_roots(&mut snapshot, &bindings, data);
InstancesList { snapshot, thread_children }
}
}
fn tag_mesh_roots(snapshot: &mut crate::snapshot::Snapshot, bindings: &std::collections::BTreeMap<String, PathBuf>, data: &Path) {
let id = |root: &Option<String>| root.as_deref().and_then(|r| crate::serve::fleet::mesh::root_id(bindings, data, Path::new(r)));
for row in &mut snapshot.instances {
row.mesh_root = id(&row.root);
}
for row in &mut snapshot.sandboxes {
row.mesh_root = id(&row.root);
}
for row in &mut snapshot.services {
row.mesh_root = id(&row.root);
}
}
fn state_path() -> Result<PathBuf, ApiError> {
crate::state::State::path().map_err(ApiError::internal)
}
fn host_state(ctx: &Ctx) -> Result<PathBuf, ApiError> {
match ctx.host {
Some(host) => Ok(host.state.to_path_buf()),
None => state_path(),
}
}
fn load_state(path: &Path) -> Result<crate::state::State, ApiError> {
crate::state::State::load_at(path).map_err(ApiError::internal)
}
#[derive(Deserialize)]
struct NameParams {
name: String,
}
fn instances_resolve(p: NameParams, state: &Path) -> Answer {
let state = load_state(state)?;
let matches = crate::commands::instance_matches(&state, &p.name);
if matches.is_empty() {
return Err(ApiError::not_found(crate::commands::no_instance_matches(&p.name)));
}
let found = matches
.iter()
.map(|name| {
let instance = state.instances.get(name);
Found {
name: name.clone(),
machine: None,
root: instance.and_then(|i| i.config_dir.clone()),
sandbox: instance.map(|i| i.sandbox.clone()),
}
})
.collect();
serde_json::to_value(Resolved { matches, found }).map_err(|e| ApiError::internal(e.into()))
}
#[derive(Deserialize)]
pub(crate) struct CancelParams {
pub(crate) instance: String,
}
fn instances_cancel(p: CancelParams, state: &Path, signal: fn(u32) -> Result<(), String>) -> Answer {
use crate::commands::run::cancel::{NotCancelled, cancel_instance};
let pid = cancel_instance(&load_state(state)?, &p.instance, signal).map_err(|e| match e {
NotCancelled::Unknown => ApiError::not_found(format!("no instance `{}`", p.instance)),
NotCancelled::Done => ApiError::invalid(format!("`{}` is not building any more", p.instance)),
NotCancelled::Signal(e) => ApiError::internal(anyhow::anyhow!(e)),
})?;
serde_json::to_value(Cancelled { ok: true, pid }).map_err(|e| ApiError::internal(e.into()))
}
#[derive(Deserialize)]
struct SignalParams {
instance: String,
pid: String,
signal: String,
}
fn signal_number(name: &str) -> Option<i32> {
match name {
"TERM" => Some(15),
"KILL" => Some(9),
_ => None,
}
}
fn instances_signal(
p: SignalParams,
state: &Path,
send: impl FnOnce(&str, &str, i32) -> anyhow::Result<()>,
) -> Answer {
let num = signal_number(&p.signal)
.ok_or_else(|| ApiError::invalid(format!("unknown signal `{}` (TERM, KILL)", p.signal)))?;
if p.pid.is_empty() || !p.pid.bytes().all(|b| b.is_ascii_digit()) || p.pid.bytes().all(|b| b == b'0') {
return Err(ApiError::invalid(format!("`pid` must be a process id, got `{}`", p.pid)));
}
let s = load_state(state)?;
let instance =
s.instances.get(&p.instance).ok_or_else(|| ApiError::not_found(format!("no instance `{}`", p.instance)))?;
send(&instance.container, &p.pid, num).map_err(ApiError::internal)?;
ok()
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct RenameParams {
instance: String,
new_name: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Renamed {
pub instance: String,
}
fn instances_rename(p: RenameParams, state: &Path) -> Answer {
use crate::commands::rename::{Refused, rename_exact_at};
let instance = rename_exact_at(state, &p.instance, &p.new_name).map_err(|e| match e.downcast::<Refused>() {
Ok(Refused::Unknown(m)) => ApiError::not_found(m),
Ok(Refused::Invalid(m)) => ApiError::invalid(m),
Err(e) => ApiError::internal(e),
})?;
serde_json::to_value(Renamed { instance }).map_err(|e| ApiError::internal(e.into()))
}
#[derive(Deserialize)]
struct SetProfileParams {
instance: String,
profile: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct ProfileSet {
pub instance: String,
pub profile: String,
}
fn instances_set_profile(p: SetProfileParams, state: &Path) -> Answer {
use crate::commands::profile::{Refused, set_profile_at};
let profile = set_profile_at(state, &p.instance, &p.profile).map_err(|e| match e.downcast::<Refused>() {
Ok(Refused::Unknown(m)) => ApiError::not_found(m),
Ok(Refused::Invalid(m)) => ApiError::invalid(m),
Err(e) => ApiError::internal(e),
})?;
serde_json::to_value(ProfileSet { instance: p.instance, profile }).map_err(|e| ApiError::internal(e.into()))
}
#[derive(Deserialize)]
struct DoneParams {
instance: String,
done: bool,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct DoneSet {
pub instance: String,
pub done: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub warning: Option<String>,
}
fn instances_done(p: DoneParams, state: &Path) -> Answer {
use crate::commands::done::{UnknownInstance, set_saved_at};
set_saved_at(state, &p.instance, p.done).map_err(|e| match e.downcast::<UnknownInstance>() {
Ok(unknown) => ApiError::not_found(unknown.to_string()),
Err(e) => ApiError::internal(e),
})?;
serde_json::to_value(DoneSet { instance: p.instance, done: p.done, warning: None }).map_err(|e| ApiError::internal(e.into()))
}
#[derive(Deserialize)]
struct SessionsParams {
root: PathBuf,
instance: String,
}
#[derive(Deserialize)]
struct SessionRmParams {
root: PathBuf,
instance: String,
id: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct SessionsList {
pub sessions: Vec<String>,
}
fn session_container(state: &Path, root: &Path, name: &str) -> Result<String, ApiError> {
if !root.is_absolute() {
return Err(ApiError::invalid(format!("`root` must be absolute, got `{}`", root.display())));
}
let root = std::fs::canonicalize(root).map_err(|_| ApiError::not_found(format!("no directory {}", root.display())))?;
let s = load_state(state)?;
let found = s
.instances
.get_key_value(name)
.or_else(|| s.instances.iter().find(|(_, i)| i.instance_id == name))
.filter(|(_, i)| i.config_dir.as_deref().is_some_and(|d| crate::serve::fleet::lent::root_under(d, &root)));
let Some((key, instance)) = found else {
return Err(ApiError::not_found(format!("no instance `{name}` in {}", root.display())));
};
if instance.devsbd_arch.is_none() {
return Err(ApiError::unsupported(format!("`{key}` has no devsbd helper, so no sessions")));
}
Ok(instance.container.clone())
}
fn sessions_list(p: SessionsParams, state: &Path, rpc: impl FnOnce(&str, &str, Obj) -> Result<Obj, ApiError>) -> Answer {
let container = session_container(state, &p.root, &p.instance)?;
let result = rpc(&container, "session.ls", Obj::new())?;
let sessions = result.strs("sessions").ok_or_else(|| ApiError::failed("session.ls answered no `sessions`"))?.to_vec();
to_value(SessionsList { sessions })
}
fn sessions_rm(p: SessionRmParams, state: &Path, rpc: impl FnOnce(&str, &str, Obj) -> Result<Obj, ApiError>) -> Answer {
if !crate::devsbd::control::valid_run_id(&p.id) {
return Err(ApiError::invalid(format!("bad session id `{}`", p.id)));
}
let container = session_container(state, &p.root, &p.instance)?;
rpc(&container, "session.rm", Obj::new().with("id", p.id.as_str()))?;
ok()
}
fn helper_rpc(container: &str, method: &str, params: Obj, caller: &str) -> Result<Obj, ApiError> {
use super::helper::CallError;
use crate::devsbd::rpc::{Record, code};
let client = super::helper::shared().ok_or_else(|| ApiError::failed("this daemon runs no bridges"))?;
let mut call = client.call(container, method, params, Obj::new(), caller, &|| false).map_err(|e| match e {
CallError::NoBridge(_) => ApiError::not_found(e.to_string()),
CallError::Unsupported(_) => ApiError::unsupported(e.to_string()),
CallError::Abandoned | CallError::Io(_) => ApiError::failed(e.to_string()),
})?;
match call.next() {
Ok(Some(Record::Result(o))) => Ok(o),
Ok(Some(Record::Error { code: c, message })) if c == code::UNKNOWN_METHOD => Err(ApiError::unsupported(format!(
"the helper in {container} doesn't offer `{method}` (its daemon isn't root, or it's older): {message}"
))),
Ok(Some(Record::Error { code: c, message })) => Err(ApiError::failed(format!("{method}: {c}: {message}"))),
Ok(Some(other)) => Err(ApiError::failed(format!("{method}: unexpected {other:?}"))),
Ok(None) => Err(ApiError::failed(format!("{method}: no reply"))),
Err(e) => Err(ApiError::failed(format!("{method}: {e}"))),
}
}
#[derive(Deserialize)]
struct SandboxesParams {
root: PathBuf,
}
fn sandboxes_list(p: SandboxesParams) -> Answer {
let config = config_at(&p.root)?;
let root = std::fs::canonicalize(&p.root).unwrap_or(p.root);
let rows: Vec<SandboxEntry> = match config {
None => Vec::new(),
Some(config) => config
.sandboxes
.into_keys()
.map(|name| SandboxEntry { root: Some(root.clone()), ..SandboxEntry::named(name) })
.collect(),
};
serde_json::to_value(rows).map_err(|e| ApiError::internal(e.into()))
}
fn roots_list(state: &Path, home: Option<&Path>, data: Option<&Path>, member: Option<&Path>) -> Answer {
let member = member.and_then(|m| crate::serve::fleet::member::load(m).ok().flatten());
let roots = crate::serve::fleet::lent::listed_roots(member.as_ref(), &load_state(state)?, home, data);
let home_root = home.map(|h| h.join(".devsandboxes")).map(|d| std::fs::canonicalize(&d).unwrap_or(d));
let rows: Vec<RootCandidate> = roots
.into_iter()
.map(|root| {
let copy = data.and_then(|d| crate::serve::fleet::mesh::copy_of(d, &root)).filter(|(_, exact)| *exact).map(|(name, _)| name);
let home = home_root.as_ref() == Some(&root);
match config_at(&root) {
Ok(config) => {
let names = config.map(|c| c.sandboxes.into_keys().collect()).unwrap_or_else(Vec::new);
let sandboxes = names.into_iter().map(SandboxEntry::named).collect();
RootCandidate { root, sandboxes, error: None, fleet: false, copy, home }
}
Err(e) => RootCandidate { root, sandboxes: Vec::new(), error: Some(e.message), fleet: false, copy, home },
}
})
.collect();
serde_json::to_value(rows).map_err(|e| ApiError::internal(e.into()))
}
fn config_at(root: &Path) -> Result<Option<crate::config::Config>, ApiError> {
if !root.is_absolute() {
return Err(ApiError::invalid(format!("`root` must be absolute, got `{}`", root.display())));
}
if !root.is_dir() {
return Err(ApiError::not_found(format!("no directory {}", root.display())));
}
match crate::config::find(root) {
Ok(None) => Ok(None),
Ok(Some(_)) => crate::config::Config::load(root).map(Some).map_err(|e| ApiError::invalid(format!("{e:#}"))),
Err(e) => Err(ApiError::invalid(format!("{e:#}"))),
}
}
#[derive(Deserialize)]
struct ConfigEntryParams {
root: PathBuf,
name: String,
}
fn sandboxes_get(p: ConfigEntryParams) -> Answer {
let config = config_at(&p.root)?.unwrap_or_default();
if !config.sandboxes.contains_key(&p.name) {
return Err(ApiError::not_found(format!("no sandbox `{}` in {}", p.name, p.root.display())));
}
serde_json::to_value(config.sandbox_text(&p.name)).map_err(|e| ApiError::internal(e.into()))
}
#[derive(Deserialize)]
struct FindingsParams {
root: PathBuf,
#[serde(default)]
sandbox: Option<String>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct MigrateParams {
root: PathBuf,
#[serde(default)]
ids: Option<Vec<String>>,
#[serde(default)]
keep: Vec<String>,
file_hash: String,
}
#[derive(Deserialize)]
struct AckParams {
root: PathBuf,
ids: Vec<String>,
}
fn to_value(x: impl Serialize) -> Answer {
serde_json::to_value(x).map_err(|e| ApiError::internal(e.into()))
}
#[derive(Debug, Serialize, Deserialize)]
pub struct ServiceConfig {
pub original: String,
}
fn services_get(p: ConfigEntryParams) -> Answer {
let config = config_at(&p.root)?.unwrap_or_default();
let original = config
.service_text(&p.name)
.ok_or_else(|| ApiError::not_found(format!("no service `{}` in {}", p.name, p.root.display())))?;
serde_json::to_value(ServiceConfig { original }).map_err(|e| ApiError::internal(e.into()))
}
pub const MAX_LINES: usize = 10_000;
const DEFAULT_LOG_LINES: usize = 50;
const DEFAULT_BUILD_LOG_LINES: usize = 500;
#[derive(Deserialize)]
struct ProcsParams {
instances: Vec<String>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Process {
pub pid: String,
pub ppid: String,
pub args: String,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProcsListing {
pub processes: Vec<Process>,
pub signalable: bool,
pub runs: Vec<crate::runtime::procs::Run>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sessions: Option<Vec<crate::runtime::procs::Session>>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum InstanceProcs {
Listed(ProcsListing),
Failed { error: String },
}
pub type ProcsAnswer = std::collections::BTreeMap<String, InstanceProcs>;
fn instances_procs(
p: ProcsParams,
state: &Path,
fetch: impl Fn(&str) -> Result<ProcsListing, String>,
) -> Answer {
let state = load_state(state)?;
let answer: ProcsAnswer = p
.instances
.into_iter()
.map(|name| {
let entry = match state.instances.get(&name) {
None => Err(format!("no instance `{name}`")),
Some(instance) => fetch(&instance.container),
};
let entry = entry.map_or_else(|error| InstanceProcs::Failed { error }, InstanceProcs::Listed);
(name, entry)
})
.collect();
serde_json::to_value(answer).map_err(|e| ApiError::internal(e.into()))
}
fn fetch_procs(container: &str) -> Result<ProcsListing, String> {
use crate::runtime::procs::{parse_runs, parse_sessions, parse_top, run_ls, session_ls};
let backend = crate::runtime::backend();
if let Ok(Some(false)) = backend.is_running(container) {
return Err("not running".to_string());
}
let list = backend.proc_list(container).map_err(|e| format!("{e:#}"))?;
let processes =
parse_top(&list.text).into_iter().map(|(pid, ppid, args)| Process { pid, ppid, args }).collect();
let runs = run_ls(container).map(|text| parse_runs(&text)).unwrap_or_default();
let sessions = session_ls(container).map(|text| parse_sessions(&text));
Ok(ProcsListing { processes, signalable: list.container_pids, runs, sessions })
}
#[derive(Deserialize)]
struct BuildLogParams {
instance: String,
#[serde(default)]
lines: Option<usize>,
#[serde(default)]
ansi: bool,
#[serde(default)]
offset: Option<u64>,
}
fn instances_build_log(p: BuildLogParams, state: &Path) -> Answer {
let s = load_state(state)?;
let instance = match s.instances.get(&p.instance) {
Some(instance) => instance,
None => s
.instances
.values()
.find(|i| i.instance_id == p.instance)
.ok_or_else(|| ApiError::not_found(format!("no instance `{}`", p.instance)))?,
};
let id = &instance.instance_id;
let data = state.parent().unwrap_or(Path::new("."));
if let Some(offset) = p.offset {
let in_flight = crate::commands::logs::in_flight(Some(&instance.phase_view()));
let page = crate::build_log::page_in(data, id, offset, in_flight).map_err(ApiError::internal)?;
return serde_json::to_value(page).map_err(|e| ApiError::internal(e.into()));
}
let lines = p.lines.unwrap_or(DEFAULT_BUILD_LOG_LINES).min(MAX_LINES);
let tail = crate::build_log::tail_in(data, id, lines, p.ansi).map_err(ApiError::internal)?;
serde_json::to_value(tail).map_err(|e| ApiError::internal(e.into()))
}
#[derive(Deserialize)]
struct ContainerParams {
container: String,
#[serde(default)]
lines: Option<usize>,
}
fn own_container(container: &str) -> Result<(), ApiError> {
if container.starts_with(crate::runtime::NAME_PREFIX) {
Ok(())
} else {
let prefix = crate::runtime::NAME_PREFIX;
Err(ApiError::invalid(format!("`{container}` is not a devsandbox container (`{prefix}…`)")))
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct ContainerLogs {
pub text: String,
}
fn containers_logs(p: ContainerParams, logs: impl FnOnce(&str, usize) -> Result<String, ApiError>) -> Answer {
own_container(&p.container)?;
let lines = p.lines.unwrap_or(DEFAULT_LOG_LINES).min(MAX_LINES);
let text = logs(&p.container, lines)?;
serde_json::to_value(ContainerLogs { text }).map_err(|e| ApiError::internal(e.into()))
}
fn containers_inspect(p: ContainerParams, inspect: impl FnOnce(&str) -> Result<String, ApiError>) -> Answer {
own_container(&p.container)?;
let raw = inspect(&p.container)?;
serde_json::from_str(&raw)
.map_err(|e| ApiError::internal(anyhow::anyhow!("`{}`'s inspect output isn't JSON: {e}", p.container)))
}
#[derive(Deserialize)]
struct EnsureParams {
instance: String,
#[serde(default)]
agent: Option<PathBuf>,
#[serde(default)]
wait: Option<f64>,
}
fn bridges_ensure(p: EnsureParams, ctx: &Ctx) -> Answer {
let Some(bridges) = ctx.bridges else {
return Err(ApiError::internal(anyhow::anyhow!("this daemon runs no bridges")));
};
if let Some(agent) = &p.agent {
if !agent.is_absolute() {
return Err(ApiError::invalid(format!("`agent` must be an absolute path, got `{}`", agent.display())));
}
}
let wait = match p.wait {
None => None,
Some(secs) if secs.is_finite() && secs >= 0.0 => {
Some(Duration::from_secs_f64(secs.min(MAX_ENSURE_WAIT.as_secs_f64())))
}
Some(secs) => return Err(ApiError::invalid(format!("`wait` must be seconds >= 0, got {secs}"))),
};
let container = bridges
.container(&p.instance)
.map_err(ApiError::internal)?
.ok_or_else(|| ApiError::not_found(format!("no instance `{}`", p.instance)))?;
if let Some(agent) = p.agent {
bridges.report_agent(agent);
}
let ticket = bridges.reconcile_now(container.clone());
let Some(wait) = wait else { return ok() };
let r = bridges.wait_ready(&container, ticket, wait);
Ok(json!({ "ok": true, "ready": r.ready, "error": r.error }))
}
fn forwarding<'a>(ctx: &Ctx<'a>) -> Result<&'a dyn Forwarding, ApiError> {
ctx.forwards.ok_or_else(|| ApiError::internal(anyhow::anyhow!("this daemon runs no forwards")))
}
fn absolute_dir(dir: &Path) -> Result<(), ApiError> {
if dir.is_absolute() {
Ok(())
} else {
Err(ApiError::invalid(format!("`dir` must be absolute, got `{}`", dir.display())))
}
}
#[derive(Deserialize)]
struct ForwardsListParams {
#[serde(default)]
dir: Option<PathBuf>,
#[serde(default)]
machines: bool,
}
fn forwards_list(p: ForwardsListParams, ctx: &Ctx) -> Answer {
let forwards = forwarding(ctx)?;
if let Some(dir) = &p.dir {
absolute_dir(dir)?;
}
serde_json::to_value(forwards.list(p.dir, p.machines)?).map_err(|e| ApiError::internal(e.into()))
}
#[derive(Deserialize)]
struct ForwardsAddParams {
dir: PathBuf,
#[serde(default)]
instance: Option<String>,
#[serde(default)]
service: Option<String>,
#[serde(default)]
address: Option<String>,
spec: String,
#[serde(default)]
machine: Option<String>,
}
fn add_request(p: ForwardsAddParams) -> Result<AddRequest, ApiError> {
absolute_dir(&p.dir)?;
let instance = p.instance.filter(|s| !s.is_empty());
let service = p.service.filter(|s| !s.is_empty());
if instance.is_none() && service.is_none() {
return Err(ApiError::invalid("name an `instance`, a `service`, or both"));
}
let (host_port, container_port) = crate::commands::port::parse_port_spec(&p.spec).map_err(ApiError::invalid)?;
let bind = match &p.address {
Some(a) => a.parse().map_err(|_| ApiError::invalid(format!("bad address `{a}`")))?,
None => std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST),
};
let machine = p.machine.filter(|s| !s.is_empty());
Ok(AddRequest { dir: p.dir, instance, service, bind, host_port, container_port, machine })
}
fn forwards_add(p: ForwardsAddParams, ctx: &Ctx) -> Answer {
let forwards = forwarding(ctx)?;
let added = forwards.add(add_request(p)?)?;
serde_json::to_value(added).map_err(|e| ApiError::internal(e.into()))
}
#[derive(Deserialize)]
struct ForwardsRmParams {
id: u64,
}
fn forwards_rm(p: ForwardsRmParams, ctx: &Ctx) -> Answer {
let removed = forwarding(ctx)?.rm(p.id)?;
let view = ForwardRemoved { ok: true, local: removed.local, configured: removed.configured };
serde_json::to_value(view).map_err(|e| ApiError::internal(e.into()))
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AccessRequest {
pub id: String,
pub instance: String,
pub instance_id: String,
pub sandbox: String,
pub credential: String,
pub kind: String,
pub scope: String,
pub repo: Option<String>,
pub method: String,
pub route: String,
pub presence: Option<String>,
pub opened_at: u64,
pub held: bool,
pub waiting: usize,
}
impl AccessRequest {
pub fn new(r: &asks::Request) -> AccessRequest {
let printable = crate::open::printable;
AccessRequest {
id: r.id.clone(),
instance: r.instance.clone(),
instance_id: r.key.instance_id.clone(),
sandbox: r.sandbox.clone(),
credential: r.key.credential.clone(),
kind: r.kind.clone(),
scope: r.key.scope.clone(),
repo: r.key.repo.as_deref().map(printable),
method: printable(&r.method),
route: printable(&r.route),
presence: r.key.presence.as_ref().map(|p| printable(&p.target)),
opened_at: r.opened_unix,
held: r.waiting > 0,
waiting: r.waiting,
}
}
}
fn asking<'a>(ctx: &Ctx<'a>) -> Result<&'a Registry, ApiError> {
ctx.access.ok_or_else(|| ApiError::internal(anyhow::anyhow!("this daemon brokers no credentials")))
}
fn access_pending(ctx: &Ctx) -> Answer {
let requests: Vec<AccessRequest> = asking(ctx)?.pending().iter().map(AccessRequest::new).collect();
Ok(json!({ "requests": requests }))
}
#[derive(Deserialize)]
struct DecideParams {
request: String,
answer: String,
}
fn access_decide(p: DecideParams, ctx: &Ctx) -> Answer {
let registry = asking(ctx)?;
let answer = asks::Answer::parse(&p.answer)
.ok_or_else(|| ApiError::invalid(format!("unknown answer `{}` (once, instance, always, deny)", p.answer)))?;
let request = registry
.answer(&p.request, answer)
.map_err(|e| match e.downcast_ref::<asks::NotAlways>() {
Some(not) => ApiError::invalid(not.to_string()),
None => ApiError::internal(e),
})?
.ok_or_else(|| ApiError::not_found(format!("no pending request `{}`", crate::open::printable(&p.request))))?;
Ok(json!({ "request": AccessRequest::new(&request) }))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::devsbd::notify::{Level, Record};
use crate::inbox::form;
use crate::inbox::thread::HostVerb;
use crate::inbox::wire::*;
use crate::inbox::{Block, FormRecord};
use crate::inbox::{store, Action, Compose, State, ThreadPut};
fn store_path(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("devsandbox-api-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
dir.join("inbox.json")
}
fn action(id: &str) -> Action {
Action { id: id.into(), label: id.to_uppercase(), ..Action::default() }
}
fn put(path: &Path, owner: &str, name: &str, key: &str, state: State) {
let put = ThreadPut {
key: key.into(),
title: format!("{key} title"),
state,
compose: Some(Compose::default()),
actions: vec![action("go")],
..ThreadPut::default()
};
store::update_at(path, |i| i.put(owner, name, 10, put)).unwrap();
}
fn notify(path: &Path, owner: &str, msg: &str) {
let record = Record { level: Level::Warn, key: None, link: None, msg: msg.into(), at: 5 };
store::update_at(path, |i| i.push(owner.into(), owner.into(), record, true)).unwrap();
}
fn run(path: &Path, method: &str, params: Value) -> Answer {
call(method, params, &Ctx { inbox: path, client: "api:test", bridges: None, forwards: None, access: None, host: None })
}
#[derive(Default)]
struct FakeBridges {
agents: std::cell::RefCell<Vec<PathBuf>>,
woken: std::cell::RefCell<Vec<String>>,
waits: std::cell::RefCell<Vec<(u64, Duration)>>,
readiness: Option<Readiness>,
}
impl Bridging for FakeBridges {
fn container(&self, instance: &str) -> anyhow::Result<Option<String>> {
match instance {
"web" => Ok(Some("devsandbox-web".into())),
"broken" => anyhow::bail!("state unreadable"),
_ => Ok(None),
}
}
fn report_agent(&self, path: PathBuf) {
self.agents.borrow_mut().push(path);
}
fn reconcile_now(&self, container: String) -> u64 {
self.woken.borrow_mut().push(container);
self.woken.borrow().len() as u64
}
fn wait_ready(&self, container: &str, ticket: u64, timeout: Duration) -> Readiness {
assert_eq!(container, "devsandbox-web");
self.waits.borrow_mut().push((ticket, timeout));
self.readiness.clone().unwrap()
}
}
#[test]
fn bridges_ensure_waits_only_when_asked_and_caps_the_wait() {
let path = store_path("ensure-wait");
let not = Readiness { ready: false, error: Some("helper in devsandbox-web is outdated".into()) };
let fake = FakeBridges { readiness: Some(not), ..FakeBridges::default() };
let ensure = |params: Value| call("bridges.ensure", params, &Ctx { inbox: &path, client: "api:test", bridges: Some(&fake), forwards: None, access: None, host: None });
assert_eq!(ensure(json!({"instance": "web"})).unwrap(), json!({"ok": true}), "no wait: unchanged");
assert!(fake.waits.borrow().is_empty());
assert_eq!(
ensure(json!({"instance": "web", "wait": 10})).unwrap(),
json!({"ok": true, "ready": false, "error": "helper in devsandbox-web is outdated"})
);
ensure(json!({"instance": "web", "wait": 0.5})).unwrap();
ensure(json!({"instance": "web", "wait": 3600})).unwrap();
assert_eq!(
*fake.waits.borrow(),
[(2, Duration::from_secs(10)), (3, Duration::from_millis(500)), (4, MAX_ENSURE_WAIT)]
);
assert_eq!(code(ensure(json!({"instance": "web", "wait": -1}))), "invalid");
assert_eq!(code(ensure(json!({"instance": "web", "wait": "soon"}))), "invalid");
assert_eq!(fake.woken.borrow().len(), 4, "a bad wait wakes nothing");
let ready = FakeBridges { readiness: Some(Readiness { ready: true, error: None }), ..FakeBridges::default() };
let r = call("bridges.ensure", json!({"instance": "web", "wait": 10}), &Ctx { inbox: &path, client: "api:test", bridges: Some(&ready), forwards: None, access: None, host: None });
assert_eq!(r.unwrap(), json!({"ok": true, "ready": true, "error": null}));
}
#[test]
fn bridges_ensure_records_the_agent_and_reconciles_the_instance() {
let path = store_path("ensure");
let fake = FakeBridges::default();
let ensure = |params: Value| call("bridges.ensure", params, &Ctx { inbox: &path, client: "api:test", bridges: Some(&fake), forwards: None, access: None, host: None });
assert_eq!(ensure(json!({"instance": "web", "agent": "/tmp/ssh-x/agent.1"})).unwrap(), json!({"ok": true}));
assert_eq!(ensure(json!({"instance": "web", "agent": null})).unwrap(), json!({"ok": true}));
assert_eq!(ensure(json!({"instance": "web"})).unwrap(), json!({"ok": true}));
assert_eq!(*fake.agents.borrow(), [PathBuf::from("/tmp/ssh-x/agent.1")]);
assert_eq!(*fake.woken.borrow(), ["devsandbox-web"; 3]);
assert_eq!(code(ensure(json!({"instance": "nope", "agent": "/a"}))), "not-found");
assert_eq!(code(ensure(json!({"instance": "web", "agent": "rel/agent"}))), "invalid");
assert_eq!(code(ensure(json!({"instance": "web", "agent": ""}))), "invalid");
assert_eq!(code(ensure(json!({"agent": "/a"}))), "invalid");
assert_eq!(code(ensure(json!({"instance": "broken"}))), "internal");
assert_eq!(fake.agents.borrow().len(), 1);
assert_eq!(fake.woken.borrow().len(), 3);
assert_eq!(code(run(&path, "bridges.ensure", json!({"instance": "web"}))), "internal");
}
fn code(r: Answer) -> &'static str {
r.unwrap_err().code
}
fn id_of(path: &Path, owner: &str, key: &str) -> u64 {
ops::thread_id(&ops::load(path).unwrap(), owner, key).unwrap()
}
#[test]
fn list_filters_like_the_dashboard_views() {
let path = store_path("views");
put(&path, "d-id", "d", "asks", State::NeedsYou);
put(&path, "d-id", "d", "busy", State::Active);
put(&path, "d-id", "d", "over", State::Done);
put(&path, "gone-id", "gone", "old", State::Active);
store::update_at(&path, |i| i.archive_owner("gone-id")).unwrap();
notify(&path, "w-id", "built\nsecond line");
let inbox = ops::load(&path).unwrap();
for view in View::ALL {
let r = run(&path, "inbox.threads.list", json!({ "view": view.as_str() })).unwrap();
let mut got: Vec<u64> = r.as_array().unwrap().iter().map(|t| t["id"].as_u64().unwrap()).collect();
let mut want: Vec<u64> = inbox.threads.iter().filter(|t| view.shows(t)).map(|t| t.id).collect();
got.sort();
want.sort();
assert_eq!(got, want, "{view:?}");
}
let all = run(&path, "inbox.threads.list", Value::Null).unwrap();
assert_eq!(all.as_array().unwrap().len(), 5);
let needs = run(&path, "inbox.threads.list", json!({"view":"needs-you"})).unwrap();
let titles: Vec<&str> = needs.as_array().unwrap().iter().map(|t| t["title"].as_str().unwrap()).collect();
assert_eq!(titles, ["asks title", "built"], "notify title is its first line; newest change first");
assert_eq!(code(run(&path, "inbox.threads.list", json!({"view":"nope"}))), "invalid");
assert_eq!(code(run(&path, "inbox.threads.list", json!({"view":3}))), "invalid");
}
#[test]
fn summary_wire_shape() {
let path = store_path("shape");
put(&path, "d-id", "d", "pr-1", State::NeedsYou);
let r = run(&path, "inbox.threads.list", json!({})).unwrap();
let t = &r[0];
assert_eq!(t["owner"], "d-id");
assert_eq!(t["owner_name"], "d");
assert_eq!(t["key"], "pr-1");
assert_eq!(t["kind"], "thread");
assert_eq!(t["state"], "needs-you");
assert_eq!(t["status"], Value::Null);
assert_eq!(t["unread"], true);
assert_eq!(t["archived"], false);
assert_eq!(t["needs_you"], true);
assert_eq!(t["changed_at"], 10);
assert!(t["id"].is_u64());
}
#[test]
fn get_addresses_by_id_or_owner_and_key() {
let path = store_path("get");
put(&path, "d-id", "d", "pr-1", State::NeedsYou);
notify(&path, "w-id", "hello");
let id = id_of(&path, "d-id", "pr-1");
let by_id = run(&path, "inbox.thread.get", json!({ "thread": id })).unwrap();
let by_owner_id = run(&path, "inbox.thread.get", json!({"owner":"d-id","key":"pr-1"})).unwrap();
let by_name = run(&path, "inbox.thread.get", json!({"owner":"d","key":"pr-1"})).unwrap();
assert_eq!(by_id, by_owner_id);
assert_eq!(by_id, by_name);
assert_eq!(by_id["title"], "pr-1 title");
assert_eq!(by_id["actions"][0]["id"], "go");
assert_eq!(by_id["actions"][0]["sends_event"], true);
assert_eq!(by_id["actions"][0]["host"], Value::Null);
assert_eq!(by_id["compose"], json!({"placeholder": null, "hint": null}));
assert_eq!(by_id["feed"], json!([]), "a new thread's feed is empty");
assert_eq!(by_id["events_pending"], 0);
assert_eq!(by_id["notes"], json!([]));
let n = ops::load(&path).unwrap().threads.iter().find(|t| t.kind == Kind::Notify).unwrap().id;
let note = run(&path, "inbox.thread.get", json!({ "thread": n })).unwrap();
assert_eq!((note["kind"].as_str(), note["level"].as_str()), (Some("notify"), Some("warn")));
assert_eq!(note["notes"][0]["msg"], "hello");
assert_eq!(code(run(&path, "inbox.thread.get", json!({"thread": 999}))), "not-found");
assert_eq!(code(run(&path, "inbox.thread.get", json!({"owner":"d","key":"pr-9"}))), "not-found");
assert_eq!(code(run(&path, "inbox.thread.get", json!({"owner":"d"}))), "invalid");
assert_eq!(code(run(&path, "inbox.thread.get", json!({"thread": id, "owner":"d","key":"pr-1"}))), "invalid");
assert_eq!(code(run(&path, "inbox.thread.get", json!({}))), "invalid");
assert_eq!(code(run(&path, "inbox.thread.get", json!({"thread": "x"}))), "invalid");
}
#[test]
fn detail_feed_wire_shape() {
let path = store_path("feed");
let header = |state: State, status: &str| ThreadPut {
key: "pr-1".into(),
title: "t".into(),
state,
status: Some(status.into()),
compose: Some(Compose { placeholder: Some("p".into()), hint: Some("h".into()) }),
actions: vec![action("go"), Action { done: true, ..action("fin") }],
..ThreadPut::default()
};
let send = |text: &str| crate::inbox::MessageSend {
thread: "pr-1".into(),
id: "m".into(),
blocks: vec![Block::Markdown { text: text.into() }],
};
store::update_at(&path, |i| {
i.put("d-id", "d", 10, header(State::Active, "a"));
i.send("d-id", 10, send("hello"));
})
.unwrap();
let id = id_of(&path, "d-id", "pr-1");
run(&path, "inbox.thread.act", json!({"thread": id, "action": "go"})).unwrap();
run(&path, "inbox.thread.reply", json!({"thread": id, "text": "hi"})).unwrap();
run(&path, "inbox.thread.done", json!({"thread": id})).unwrap();
run(&path, "inbox.thread.reopen", json!({"thread": id})).unwrap();
store::update_at(&path, |i| {
i.put("d-id", "d", 20, header(State::NeedsYou, "b"));
i.send("d-id", 20, send("hello again"));
})
.unwrap();
let t = run(&path, "inbox.thread.get", json!({"thread": id})).unwrap();
assert_eq!(t["compose"], json!({"placeholder": "p", "hint": "h"}));
let mut feed = t["feed"].clone();
for item in feed.as_array_mut().unwrap() {
assert!(item["seq"].is_u64(), "{item}");
assert!(item["at"].is_u64(), "{item}");
let item = item.as_object_mut().unwrap();
item.remove("seq");
item.remove("at");
}
assert_eq!(
feed,
json!([
{"type": "message", "id": "m", "blocks": [{"type": "markdown", "text": "hello again"}], "edited": true, "withdrawn": false},
{"type": "action", "action": "go", "label": "GO"},
{"type": "reply", "text": "hi"},
{"type": "marker", "marker": "done", "from": null, "to": null},
{"type": "marker", "marker": "reopen", "from": null, "to": null},
{"type": "marker", "marker": "state", "from": "active", "to": "needs-you"},
{"type": "marker", "marker": "status", "from": "a", "to": "b"},
])
);
let wire = t.to_string();
assert!(!wire.contains("client") && !wire.contains("api:test"), "{wire}");
let stored = ops::load(&path).unwrap().to_json().unwrap();
assert!(stored.contains("api:test"));
}
#[test]
fn audit_client_names() {
assert_eq!(audit_client("tui"), "tui");
assert_eq!(audit_client("cli"), "cli");
assert_eq!(audit_client("npm:my-ext"), "api:npm:my-ext");
assert_eq!(audit_client("api:x"), "api:x");
assert_eq!(audit_client(""), "api");
}
#[test]
fn owner_name_prefers_the_live_thread() {
let path = store_path("names");
put(&path, "old-id", "d", "pr-1", State::Active);
store::update_at(&path, |i| i.archive_owner("old-id")).unwrap();
put(&path, "new-id", "d", "pr-1", State::NeedsYou);
let t = run(&path, "inbox.thread.get", json!({"owner":"d","key":"pr-1"})).unwrap();
assert_eq!(t["owner"], "new-id");
let t = run(&path, "inbox.thread.get", json!({"owner":"old-id","key":"pr-1"})).unwrap();
assert_eq!(t["archived"], true);
}
#[test]
fn user_ops_enqueue_events_and_check_their_target() {
let path = store_path("ops");
put(&path, "d-id", "d", "pr-1", State::NeedsYou);
let id = id_of(&path, "d-id", "pr-1");
let by_key = json!({"owner":"d","key":"pr-1"});
assert_eq!(run(&path, "inbox.thread.markRead", by_key.clone()).unwrap(), json!({"ok": true}));
assert!(!ops::load(&path).unwrap().threads[0].unread);
run(&path, "inbox.thread.act", json!({"thread": id, "action": "go"})).unwrap();
run(&path, "inbox.thread.reply", json!({"thread": id, "text": " hi "})).unwrap();
run(&path, "inbox.thread.done", by_key.clone()).unwrap();
run(&path, "inbox.thread.reopen", json!({ "thread": id })).unwrap();
let events: Vec<(String, Option<String>, Option<String>)> = ops::events(&path, "d-id")
.unwrap()
.into_iter()
.map(|(_, e)| (e.kind.as_str().to_string(), e.action, e.text))
.collect();
assert_eq!(
events,
[
("action".into(), Some("go".into()), None),
("reply".into(), None, Some("hi".into())),
("done".into(), None, None),
("reopen".into(), None, None),
]
);
assert_eq!(code(run(&path, "inbox.thread.act", json!({"thread": id, "action": "nope"}))), "not-found");
assert_eq!(code(run(&path, "inbox.thread.act", json!({ "thread": id }))), "invalid");
assert_eq!(code(run(&path, "inbox.thread.reply", json!({"thread": id, "text": " "}))), "invalid");
assert_eq!(code(run(&path, "inbox.thread.done", json!({"thread": 999}))), "not-found");
assert_eq!(code(run(&path, "inbox.thread.markRead", json!({"thread": 999}))), "not-found");
assert_eq!(code(run(&path, "inbox.thread.reopen", json!({"owner":"x","key":"pr-1"}))), "not-found");
notify(&path, "w-id", "n");
let n = ops::load(&path).unwrap().threads.iter().find(|t| t.kind == Kind::Notify).unwrap().id;
assert_eq!(code(run(&path, "inbox.thread.done", json!({ "thread": n }))), "invalid");
store::update_at(&path, |i| i.archive_owner("d-id")).unwrap();
assert_eq!(code(run(&path, "inbox.thread.reply", json!({"thread": id, "text": "x"}))), "denied");
assert_eq!(ops::events(&path, "d-id").unwrap().len(), 4, "refused ops enqueue nothing");
}
fn with_form(path: &Path) -> u64 {
put(path, "d-id", "d", "pr-1", State::NeedsYou);
let blocks = vec![Block::Form(form::tests::mixed())];
let send = crate::inbox::MessageSend { thread: "pr-1".into(), id: "run-1".into(), blocks };
store::update_at(path, |i| i.send("d-id", 11, send)).unwrap();
id_of(path, "d-id", "pr-1")
}
#[test]
fn form_methods_check_before_applying() {
let path = store_path("forms");
let id = with_form(&path);
let call = |method: &str, answers: Value| run(&path, method, json!({"thread": id, "message": "run-1", "answers": answers}));
assert_eq!(call("inbox.form.saveDraft", json!({"pick": "b"})).unwrap(), json!({"ok": true}));
assert_eq!(call("inbox.form.saveDraft", json!({"tags": ["y"]})).unwrap(), json!({"ok": true}));
let t = run(&path, "inbox.thread.get", json!({"thread": id})).unwrap();
let block = &t["feed"][0]["blocks"][0];
assert_eq!((block["state"].clone(), block["draft"].clone()), (json!("open"), json!({"pick": "b", "tags": ["y"]})));
assert_eq!(block["answers"], Value::Null);
for bad in [json!({"nope": "a"}), json!({"pick": "z"}), json!({"pick": ["a"]}), json!({"note": "toolong"}), json!({"sure": "yes"})] {
assert_eq!(code(call("inbox.form.saveDraft", bad.clone())), "invalid", "{bad}");
}
let missing = call("inbox.form.submit", json!({})).unwrap_err();
assert_eq!((missing.code, missing.message.as_str()), ("invalid", "required questions unanswered: note"));
assert_eq!(code(call("inbox.form.submit", json!({"note": "hi", "tags": "x"}))), "invalid");
assert!(ops::events(&path, "d-id").unwrap().is_empty(), "refused ops enqueue nothing");
assert_eq!(call("inbox.form.submit", json!({"note": "hi"})).unwrap(), json!({"ok": true}));
let events = ops::events(&path, "d-id").unwrap();
let [(_, e)] = &events[..] else { panic!("{events:?}") };
assert_eq!(e.answers, Some(json!({"pick": "b", "tags": ["y"], "note": "hi", "sure": null})));
assert_eq!(code(call("inbox.form.submit", json!({}))), "closed-form");
assert_eq!(code(call("inbox.form.saveDraft", json!({"note": "x"}))), "closed-form");
let t = run(&path, "inbox.thread.get", json!({"thread": id})).unwrap();
let block = &t["feed"][0]["blocks"][0];
assert_eq!(block["state"], "submitted");
assert_eq!(block["draft"], json!({}));
assert_eq!(block["answers"], json!({"pick": "b", "tags": ["y"], "note": "hi", "sure": null}));
let sub = &t["feed"][1];
assert_eq!((sub["type"].as_str(), sub["message"].as_str(), sub["form"].as_str()), (Some("submission"), Some("run-1"), Some("f")));
assert_eq!(sub["answers"], json!({"pick": "b", "tags": ["y"], "note": "hi", "sure": null}));
assert!(!t.to_string().contains("api:test"), "{t}");
let by_key = json!({"owner": "d", "key": "pr-1", "message": "run-1", "answers": {}});
assert_eq!(code(run(&path, "inbox.form.submit", by_key)), "closed-form");
let none = json!({"thread": id, "message": "nope", "answers": {}});
assert_eq!(code(run(&path, "inbox.form.saveDraft", none)), "not-found");
assert_eq!(code(run(&path, "inbox.form.submit", json!({"thread": 999, "message": "run-1"}))), "not-found");
assert_eq!(code(run(&path, "inbox.form.submit", json!({"thread": id}))), "invalid", "no message");
store::update_at(&path, |i| {
let send = crate::inbox::MessageSend { thread: "pr-1".into(), id: "plain".into(), blocks: vec![Block::Markdown { text: "x".into() }] };
i.send("d-id", 12, send)
})
.unwrap();
assert_eq!(code(run(&path, "inbox.form.submit", json!({"thread": id, "message": "plain"}))), "not-found");
let other = crate::inbox::MessageSend { thread: "pr-1".into(), id: "run-2".into(), blocks: vec![Block::Form(form::tests::mixed())] };
store::update_at(&path, |i| {
i.send("d-id", 13, other);
i.withdraw("d-id", "pr-1", "run-2")
})
.unwrap();
assert_eq!(code(run(&path, "inbox.form.submit", json!({"thread": id, "message": "run-2"}))), "closed-form");
}
#[test]
fn host_only_actions_and_replyless_threads_are_refused() {
let path = store_path("refused");
let put = ThreadPut {
key: "k".into(),
title: "t".into(),
actions: vec![Action {
host: Some(HostVerb::Logs(Default::default())),
..action("logs")
}],
..ThreadPut::default()
};
store::update_at(&path, |i| i.put("d-id", "d", 1, put)).unwrap();
let addr = json!({"owner":"d-id","key":"k","action":"logs","text":"hi"});
let t = run(&path, "inbox.thread.get", addr.clone()).unwrap();
assert_eq!((t["actions"][0]["host"].as_str(), t["actions"][0]["sends_event"].as_bool()), (Some("logs"), Some(false)));
assert_eq!(code(run(&path, "inbox.thread.act", addr.clone())), "invalid");
assert_eq!(code(run(&path, "inbox.thread.reply", addr)), "denied");
assert!(ops::events(&path, "d-id").unwrap().is_empty());
}
#[test]
fn dismiss_removes_notifications_only() {
let path = store_path("dismiss");
put(&path, "d-id", "d", "pr-1", State::Active);
notify(&path, "w-id", "a");
notify(&path, "w-id", "b");
let inbox = ops::load(&path).unwrap();
let notes: Vec<u64> = inbox.threads.iter().filter(|t| t.kind == Kind::Notify).map(|t| t.id).collect();
let thread = id_of(&path, "d-id", "pr-1");
run(&path, "inbox.notify.dismiss", json!({ "thread": notes[0] })).unwrap();
assert_eq!(ops::load(&path).unwrap().threads.len(), 2);
assert_eq!(code(run(&path, "inbox.notify.dismiss", json!({ "thread": notes[0] }))), "not-found");
assert_eq!(code(run(&path, "inbox.notify.dismiss", json!({ "thread": thread }))), "invalid");
assert_eq!(code(run(&path, "inbox.notify.dismiss", json!({"all": true, "thread": notes[1]}))), "invalid");
assert_eq!(code(run(&path, "inbox.notify.dismiss", json!({}))), "invalid");
run(&path, "inbox.notify.dismiss", json!({"all": true})).unwrap();
let left = ops::load(&path).unwrap();
assert_eq!(left.threads.len(), 1);
assert_eq!(left.threads[0].id, thread);
}
#[test]
fn notify_mark_read_reads_notifications_only() {
let path = store_path("markread");
put(&path, "d-id", "d", "pr-1", State::NeedsYou);
notify(&path, "w-id", "a");
notify(&path, "v-id", "b");
let unread = |path: &Path| -> Vec<(Kind, bool)> {
ops::load(path).unwrap().threads.iter().map(|t| (t.kind, t.unread)).collect()
};
let thread = id_of(&path, "d-id", "pr-1");
let notes: Vec<u64> = ops::load(&path).unwrap().threads.iter().filter(|t| t.kind == Kind::Notify).map(|t| t.id).collect();
run(&path, "inbox.notify.markRead", json!({ "thread": notes[0] })).unwrap();
assert_eq!(unread(&path).iter().filter(|(_, u)| *u).count(), 2);
assert_eq!(code(run(&path, "inbox.notify.markRead", json!({ "thread": thread }))), "invalid");
assert_eq!(code(run(&path, "inbox.notify.markRead", json!({ "thread": 999 }))), "not-found");
assert_eq!(code(run(&path, "inbox.notify.markRead", json!({"all": true, "thread": notes[1]}))), "invalid");
assert_eq!(code(run(&path, "inbox.notify.markRead", json!({}))), "invalid");
assert_eq!(run(&path, "inbox.notify.markRead", json!({"all": true})).unwrap(), json!({"ok": true}));
for (kind, unread) in unread(&path) {
assert_eq!(unread, kind == Kind::Thread, "{kind:?}");
}
}
#[test]
fn instances_list_checks_its_dir_and_unknown_methods_say_so() {
let path = store_path("instances");
assert_eq!(code(run(&path, "instances.list", json!({}))), "invalid");
assert_eq!(code(run(&path, "instances.list", json!({"dir": "rel/dir"}))), "invalid");
assert_eq!(code(run(&path, "instances.list", json!({"dir": "/nonexistent/devsandbox-api"}))), "not-found");
assert_eq!(code(run(&path, "inbox.poll.vote", json!({}))), "unknown-method");
}
fn state_file(name: &str, toml: &str) -> PathBuf {
let path = store_path(name).with_file_name("state.toml");
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(&path, toml).unwrap();
path
}
fn instance(key: &str, sandbox: &str, progress: &str) -> String {
format!(
"[instance.{key}]\nsandbox = \"{sandbox}\"\ncontainer = \"devsandbox-{key}\"\nfolder = \"/w\"\n\
workspace = \"/w\"\ncreated_unix = 1\n{progress}"
)
}
fn empty_snapshot() -> crate::snapshot::Snapshot {
crate::snapshot::Snapshot {
instances: Vec::new(),
sandboxes: Vec::new(),
services: Vec::new(),
sandbox_count: 0,
runtime_name: "docker".into(),
runtime_version: None,
collected_at: std::time::Instant::now(),
depth: crate::snapshot::Depth::Disk,
error: None,
no_runtime: false,
}
}
#[test]
fn rows_are_tagged_with_their_signed_root() {
let dir = std::env::temp_dir().join(format!("devsandbox-api-mesh-roots-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let data = dir.join("data");
let bound = dir.join("cfg");
let copy = crate::serve::fleet::mesh::tree_path(&data, "lent");
let other = dir.join("other");
for d in [&bound, ©.join("sub"), &other] {
std::fs::create_dir_all(d).unwrap();
}
std::fs::write(
crate::serve::fleet::mesh::roots_path(&data),
format!("cfg = {:?}\n", std::fs::canonicalize(&bound).unwrap().display().to_string()),
)
.unwrap();
let roots = [Some(bound.clone()), Some(copy.clone()), Some(copy.join("sub")), Some(other), None];
let text = |r: &Option<PathBuf>| r.as_ref().map(|r| r.display().to_string());
let mut snapshot = empty_snapshot();
snapshot.instances = roots
.iter()
.map(|r| crate::snapshot::InstanceRow { root: text(r), ..crate::serve::snapshots::tests::row("i", true, None) })
.collect();
let sandbox = |r: &Option<PathBuf>| -> crate::snapshot::SandboxRow {
serde_json::from_value(json!({"name": "s", "source": "?", "services": [], "extends": [], "config_hash": "",
"build_hash": "", "issues": [], "dispatcher": false, "root": text(r)}))
.unwrap()
};
let service = |r: &Option<PathBuf>| -> crate::snapshot::ServiceRow {
serde_json::from_value(json!({"name": "db", "scope": "global", "source": "?", "ports": [], "containers": [],
"used_by": [], "env_len": 0, "config_hash": "", "drift": false, "root": text(r)}))
.unwrap()
};
snapshot.sandboxes = roots.iter().map(sandbox).collect();
snapshot.services = roots.iter().map(service).collect();
let list = InstancesList::of(snapshot, &data.join("state.toml"));
let want = [Some("cfg"), Some("lent"), None, None, None].map(|n| n.map(str::to_string));
assert_eq!(list.snapshot.instances.iter().map(|r| r.mesh_root.clone()).collect::<Vec<_>>(), want);
assert_eq!(list.snapshot.sandboxes.iter().map(|r| r.mesh_root.clone()).collect::<Vec<_>>(), want);
assert_eq!(list.snapshot.services.iter().map(|r| r.mesh_root.clone()).collect::<Vec<_>>(), want);
let v = serde_json::to_value(&list).unwrap();
assert_eq!(v["sandboxes"][0]["mesh_root"], json!("cfg"));
assert!(v["sandboxes"][2].get("mesh_root").is_none());
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn instances_list_maps_depth_and_adds_thread_children() {
use crate::snapshot::Depth;
let state = state_file(
"list",
&[instance("d", "disp", ""), instance("web-one", "web", "dispatcher = \"d\"\n"), instance("p", "web", "")].concat(),
);
let dir = state.parent().unwrap().to_path_buf();
let list = |params: Value| {
let mut asked = None;
let r = instances_list_with(parse(params)?, &state, |_: &Path, d| {
asked = Some(d);
empty_snapshot()
});
r.map(|v| (v, asked))
};
for (depth, want) in [(json!(null), Depth::Full), (json!("full"), Depth::Full), (json!("listing"), Depth::Listing), (json!("disk"), Depth::Disk)] {
let (_, asked) = list(json!({"dir": dir, "depth": depth})).unwrap();
assert_eq!(asked, Some(want), "{depth}");
}
let (v, _) = list(json!({"dir": dir})).unwrap();
assert_eq!(v["thread_children"], json!({"d": {"one": "web-one"}}));
assert_eq!(v["runtime_name"], "docker");
assert_eq!(v["instances"], json!([]));
let bad = list(json!({"dir": dir, "depth": "deep"})).unwrap_err();
assert_eq!((bad.code, bad.message.as_str()), ("invalid", "unknown depth `deep` (disk, listing, full)"));
let none = instances_list_with(parse(json!({"dir": dir})).unwrap(), &state.with_file_name("absent.toml"), |_: &Path, _| empty_snapshot());
assert_eq!(none.unwrap()["thread_children"], json!({}));
}
#[test]
fn instances_resolve_returns_every_match_of_the_winning_tier() {
let rooted = format!("{}config_dir = \"/cfg\"\n", instance("web", "web", ""));
let state = state_file("resolve", &[rooted, instance("web-2", "web", ""), instance("x", "web", "")].concat());
let resolve = |params: Value| instances_resolve(parse(params)?, &state);
let found = |name: &str, root: Option<&str>| json!({"name": name, "machine": null, "root": root, "sandbox": "web"});
assert_eq!(
resolve(json!({"name": "web"})).unwrap(),
json!({"matches": ["web"], "found": [found("web", Some("/cfg"))]}),
"exact wins"
);
let all = resolve(json!({"name": "w"})).unwrap();
assert_eq!(all["matches"], json!(["web", "web-2", "x"]), "folder basename");
assert_eq!(all["found"], json!([found("web", Some("/cfg")), found("web-2", None), found("x", None)]));
assert_eq!(code(resolve(json!({"name": "nope"}))), "not-found");
assert_eq!(code(resolve(json!({}))), "invalid");
let none = instances_resolve(NameParams { name: "web".into() }, &state.with_file_name("absent.toml"));
assert_eq!(code(none), "not-found");
}
#[test]
fn instances_cancel_signals_only_while_in_flight() {
let me = std::process::id();
let progress = |key: &str, phase: &str| format!("[instance.{key}.progress]\nphase = \"{phase}\"\npid = {me}\n");
let state = state_file(
"cancel",
&[instance("w", "web", &progress("w", "building")), instance("f", "web", &progress("f", "failed")), instance("r", "web", "")].concat(),
);
fn sent(_: u32) -> Result<(), String> {
Ok(())
}
fn refused(_: u32) -> Result<(), String> {
Err("EPERM".into())
}
let cancel = |params: Value, signal| instances_cancel(parse(params)?, &state, signal);
assert_eq!(cancel(json!({"instance": "w"}), sent).unwrap(), json!({"ok": true, "pid": me}));
let done = cancel(json!({"instance": "f"}), sent).unwrap_err();
assert_eq!((done.code, done.message.as_str()), ("invalid", "`f` is not building any more"));
assert_eq!(code(cancel(json!({"instance": "r"}), sent)), "invalid", "ready");
assert_eq!(code(cancel(json!({"instance": "nope"}), sent)), "not-found");
assert_eq!(code(cancel(json!({"instance": "w"}), refused)), "internal");
assert_eq!(code(cancel(json!({}), sent)), "invalid");
}
#[test]
fn instances_signal_checks_before_reaching_the_runtime() {
let state = state_file("signal", &instance("web", "web", ""));
let sent = std::cell::RefCell::new(Vec::new());
let signal = |params: Value| {
instances_signal(parse(params)?, &state, |c, pid, n| {
sent.borrow_mut().push((c.to_string(), pid.to_string(), n));
Ok(())
})
};
assert_eq!(signal(json!({"instance": "web", "pid": "42", "signal": "TERM"})).unwrap(), json!({"ok": true}));
signal(json!({"instance": "web", "pid": "7", "signal": "KILL"})).unwrap();
assert_eq!(*sent.borrow(), [("devsandbox-web".to_string(), "42".to_string(), 15), ("devsandbox-web".to_string(), "7".to_string(), 9)]);
for bad in [
json!({"instance": "web", "pid": "42", "signal": "INT"}),
json!({"instance": "web", "pid": "42", "signal": "SIGTERM"}),
json!({"instance": "web", "pid": "-1", "signal": "TERM"}),
json!({"instance": "web", "pid": "0", "signal": "TERM"}),
json!({"instance": "web", "pid": "", "signal": "TERM"}),
json!({"instance": "web", "pid": "4 2", "signal": "TERM"}),
json!({"instance": "web", "pid": 42, "signal": "TERM"}),
json!({"instance": "web", "signal": "TERM"}),
] {
assert_eq!(code(signal(bad.clone())), "invalid", "{bad}");
}
assert_eq!(code(signal(json!({"instance": "nope", "pid": "42", "signal": "TERM"}))), "not-found");
assert_eq!(sent.borrow().len(), 2, "refused before the runtime");
let failing = instances_signal(parse(json!({"instance": "web", "pid": "42", "signal": "TERM"})).unwrap(), &state, |_, _, _| {
anyhow::bail!("No such container: devsandbox-web")
});
assert_eq!(code(failing), "internal");
}
#[test]
fn sessions_go_to_the_instances_helper_in_its_root() {
let dir = store_path("sessions").with_file_name("cfg");
let other = dir.with_file_name("other");
let rooted = |key: &str, helper: bool| {
format!(
"{}instance_id = \"id-{key}\"\nconfig_dir = {:?}\n{}",
instance(key, "web", ""),
dir.to_str().unwrap(),
if helper { "devsbd_arch = \"x86_64\"\n" } else { "" }
)
};
let state = state_file("sessions", &[rooted("web", true), rooted("bare", false)].concat());
std::fs::create_dir_all(&dir).unwrap();
std::fs::create_dir_all(&other).unwrap();
let asked = std::cell::RefCell::new(Vec::new());
let rpc = |answer: Result<Obj, ApiError>| {
let asked = &asked;
move |c: &str, m: &str, p: Obj| {
asked.borrow_mut().push((c.to_string(), m.to_string(), p));
answer
}
};
let lines = Obj::new().with("sessions", vec!["1700000000-ab12 running detached 2023-11-14T22:13:20Z sh".to_string()]);
let list = |params: Value, answer| sessions_list(parse(params)?, &state, rpc(answer));
assert_eq!(
list(json!({"root": dir, "instance": "id-web"}), Ok(lines.clone())).unwrap(),
json!({"sessions": ["1700000000-ab12 running detached 2023-11-14T22:13:20Z sh"]}),
"by id"
);
assert_eq!(*asked.borrow(), [("devsandbox-web".to_string(), "session.ls".to_string(), Obj::new())]);
assert_eq!(code(list(json!({"root": other, "instance": "web"}), Ok(lines.clone()))), "not-found", "another root's");
assert_eq!(code(list(json!({"root": dir, "instance": "bare"}), Ok(lines.clone()))), "unsupported", "no helper");
assert_eq!(code(list(json!({"root": "rel", "instance": "web"}), Ok(lines.clone()))), "invalid");
assert_eq!(code(list(json!({"root": dir}), Ok(lines.clone()))), "invalid");
assert_eq!(code(list(json!({"root": dir, "instance": "web"}), Ok(Obj::new()))), "failed", "no `sessions`");
assert_eq!(code(list(json!({"root": dir, "instance": "web"}), Err(ApiError::unsupported("not root")))), "unsupported");
assert_eq!(asked.borrow().len(), 3, "refused before the helper");
asked.borrow_mut().clear();
let rm = |params: Value| sessions_rm(parse(params)?, &state, rpc(Ok(Obj::new())));
assert_eq!(rm(json!({"root": dir, "instance": "web", "id": "1700000000-ab12"})).unwrap(), json!({"ok": true}));
assert_eq!(asked.borrow()[0].2, Obj::new().with("id", "1700000000-ab12"));
assert_eq!(code(rm(json!({"root": dir, "instance": "web", "id": "../x"}))), "invalid");
assert_eq!(code(rm(json!({"root": dir, "instance": "nope", "id": "1700000000-ab12"}))), "not-found");
assert_eq!(asked.borrow().len(), 1);
}
#[test]
fn instances_rename_moves_the_key_and_maps_refusals() {
let me = std::process::id();
let building = format!("[instance.b.progress]\nphase = \"building\"\npid = {me}\n");
let state = state_file("rename", &[instance("web", "web", ""), instance("api", "web", ""), instance("b", "web", &building)].concat());
let rename = |params: Value| instances_rename(parse(params)?, &state);
assert_eq!(rename(json!({"instance": "web", "newName": " web-x "})).unwrap(), json!({"instance": "web-x"}));
let s = crate::state::State::load_at(&state).unwrap();
assert!(!s.instances.contains_key("web"));
assert_eq!(s.instances["web-x"].container, "devsandbox-web", "only the key moves");
let taken = rename(json!({"instance": "web-x", "newName": "api"})).unwrap_err();
assert_eq!((taken.code, taken.message.as_str()), ("invalid", "an instance named `api` already exists"));
for new in ["", "a b", "web-x"] {
assert_eq!(code(rename(json!({"instance": "web-x", "newName": new}))), "invalid", "{new:?}");
}
assert_eq!(code(rename(json!({"instance": "b", "newName": "b2"}))), "invalid", "in flight");
assert_eq!(code(rename(json!({"instance": "web", "newName": "w"}))), "not-found");
assert_eq!(code(rename(json!({"instance": "api", "new_name": "w"}))), "invalid", "camelCase");
let after = crate::state::State::load_at(&state).unwrap();
assert_eq!(after.instances.keys().collect::<Vec<_>>(), ["api", "b", "web-x"]);
std::fs::write(&state, "not = [toml").unwrap();
assert_eq!(code(rename(json!({"instance": "api", "newName": "w"}))), "internal");
}
#[test]
fn instances_set_profile_switches_and_maps_refusals() {
let state = store_path("set-profile").with_file_name("state.toml");
let cfg = state.with_file_name("cfg");
std::fs::create_dir_all(&cfg).unwrap();
std::fs::write(
cfg.join("devsandboxes.toml"),
"[profiles.work]\n[profiles.personal]\n[sandbox.web]\nimage = \"x\"\nprofiles = [\"work\", \"personal\"]\n",
)
.unwrap();
let rooted = format!("project = \"abc12345\"\nconfig_dir = {:?}\n", cfg.to_str().unwrap());
std::fs::write(&state, [instance("web", "web", &rooted), instance("bare", "web", "")].concat()).unwrap();
let set = |params: Value| instances_set_profile(parse(params)?, &state);
assert_eq!(set(json!({"instance": "web", "profile": "personal"})).unwrap(), json!({"instance": "web", "profile": "personal"}));
let s = crate::state::State::load_at(&state).unwrap();
assert_eq!(s.instances["web"].profile.as_deref(), Some("personal"));
assert_eq!(s.last_profile["abc12345"]["web"], "personal");
let other = set(json!({"instance": "web", "profile": "other"})).unwrap_err();
assert_eq!(
(other.code, other.message.as_str()),
("invalid", "sandbox `web` doesn't allow profile `other`; allowed: work, personal")
);
assert_eq!(code(set(json!({"instance": "bare", "profile": "work"}))), "invalid", "no recorded root");
assert_eq!(code(set(json!({"instance": "nope", "profile": "work"}))), "not-found");
assert_eq!(code(set(json!({"instance": "web"}))), "invalid", "a profile is needed");
assert_eq!(crate::state::State::load_at(&state).unwrap().instances["web"].profile.as_deref(), Some("personal"));
std::fs::write(&state, "not = [toml").unwrap();
assert_eq!(code(set(json!({"instance": "web", "profile": "work"}))), "internal");
}
#[test]
fn instances_done_sets_and_clears_the_flag() {
let state = state_file("done", &instance("web", "web", ""));
let done = |params: Value| instances_done(parse(params)?, &state);
let flag = || crate::state::State::load_at(&state).unwrap().instances["web"].done;
assert_eq!(done(json!({"instance": "web", "done": true})).unwrap(), json!({"instance": "web", "done": true}));
let since = flag().expect("marked done");
done(json!({"instance": "web", "done": true})).unwrap();
assert_eq!(flag(), Some(since));
assert_eq!(done(json!({"instance": "web", "done": false})).unwrap(), json!({"instance": "web", "done": false}));
assert_eq!(flag(), None);
let unknown = done(json!({"instance": "nope", "done": true})).unwrap_err();
assert_eq!((unknown.code, unknown.message.as_str()), ("not-found", "no instance `nope`"));
assert_eq!(code(done(json!({"instance": "web"}))), "invalid");
}
#[test]
fn sandboxes_list_names_the_configs_sandboxes() {
let root = store_path("sandboxes").with_file_name("cfg");
std::fs::create_dir_all(&root).unwrap();
let list = |root: &Path| run(&store_path("sandboxes-x"), "sandboxes.list", json!({"root": root}));
assert_eq!(list(&root).unwrap(), json!([]), "no config: none");
std::fs::write(root.join(crate::config::CONFIG_FILE), "[sandbox.web]\nimage = \"alpine\"\n[sandbox.api]\nimage = \"alpine\"\n").unwrap();
let canon = std::fs::canonicalize(&root).unwrap();
assert_eq!(list(&root).unwrap(), json!([{"name": "api", "root": canon}, {"name": "web", "root": canon}]));
std::fs::write(root.join(crate::config::CONFIG_FILE), "[sandbox.web\n").unwrap();
let bad = list(&root).unwrap_err();
assert!(bad.code == "invalid" && bad.message.contains("devsandboxes.toml"), "{bad:?}");
assert_eq!(code(list(Path::new("rel"))), "invalid");
assert_eq!(code(list(Path::new("/nonexistent/devsandbox-api"))), "not-found");
assert_eq!(code(run(&root, "sandboxes.list", json!({}))), "invalid");
let _ = std::fs::remove_dir_all(root.parent().unwrap());
}
#[test]
fn roots_list_answers_the_recorded_roots_and_home() {
let base = store_path("roots").with_file_name("roots");
let (shared, bad, gone, home) = (base.join("shared"), base.join("bad"), base.join("gone"), base.join("home"));
let with_root = |key: &str, root: &Path| format!("{}config_dir = {:?}\n", instance(key, "web", ""), root.to_str().unwrap());
let state = state_file(
"roots",
&[
with_root("a", &shared),
with_root("b", &shared.join("../shared")),
with_root("c", &bad),
with_root("d", &gone),
instance("old", "web", ""),
]
.concat(),
);
for d in [&shared, &bad, &home.join(".devsandboxes")] {
std::fs::create_dir_all(d).unwrap();
}
std::fs::write(shared.join(crate::config::CONFIG_FILE), "[sandbox.web]\nimage = \"a\"\n[sandbox.api]\nimage = \"a\"\n").unwrap();
std::fs::write(bad.join(crate::config::CONFIG_FILE), "[sandbox.web\n").unwrap();
let canon = |p: &Path| std::fs::canonicalize(p).unwrap();
let mut want = vec![
json!({"root": canon(&shared), "sandboxes": [{"name": "api"}, {"name": "web"}], "error": null}),
json!({"root": canon(&bad), "sandboxes": [], "error": ""}),
json!({"root": gone, "sandboxes": [], "error": format!("no directory {}", gone.display())}),
json!({"root": canon(&home.join(".devsandboxes")), "sandboxes": [], "error": null, "home": true}),
];
want.sort_by(|a, b| a["root"].as_str().cmp(&b["root"].as_str()));
let mut got = roots_list(&state, Some(&home), None, None).unwrap();
for row in got.as_array_mut().unwrap() {
if row["root"] == json!(canon(&bad)) {
assert!(row["error"].as_str().unwrap().contains("devsandboxes.toml"), "{row}");
row["error"] = json!("");
}
}
assert_eq!(got, Value::Array(want));
let (picked, member) = (base.join("picked"), base.join("member.toml"));
std::fs::create_dir_all(&picked).unwrap();
let roots = vec![picked.clone(), shared.join("../shared"), base.join("lost")];
crate::serve::fleet::member::write_for_test(&member, &crate::serve::fleet::member::Member { roots, ..Default::default() });
let listed = roots_list(&state.with_file_name("absent.toml"), None, None, Some(&member)).unwrap();
let roots: Vec<&Value> = listed.as_array().unwrap().iter().map(|r| &r["root"]).collect();
let mut want = vec![json!(base.join("lost")), json!(canon(&picked)), json!(canon(&shared))];
want.sort_by(|a, b| a.as_str().cmp(&b.as_str()));
assert_eq!(roots, want.iter().collect::<Vec<_>>());
let lost = listed.as_array().unwrap().iter().find(|r| r["root"] == json!(base.join("lost"))).unwrap();
assert!(lost["error"].as_str().unwrap().starts_with("no directory"), "{lost}");
let (data, copy_member) = (base.join("data"), base.join("copy-member.toml"));
let copy = crate::serve::fleet::mesh::tree_path(&data, "cfg");
std::fs::create_dir_all(copy.join("sub")).unwrap();
let roots = vec![copy.clone(), copy.join("sub")];
crate::serve::fleet::member::write_for_test(©_member, &crate::serve::fleet::member::Member { roots, ..Default::default() });
let listed = roots_list(&state.with_file_name("absent.toml"), None, Some(&data), Some(©_member)).unwrap();
let copies: Vec<(&Value, &Value)> = listed.as_array().unwrap().iter().map(|r| (&r["root"], &r["copy"])).collect();
assert_eq!(copies, [(&json!(canon(©)), &json!("cfg")), (&json!(canon(©.join("sub"))), &Value::Null)]);
std::fs::write(&member, "trust = \"most\"\n").unwrap();
assert_eq!(roots_list(&state.with_file_name("absent.toml"), None, None, Some(&member)).unwrap(), json!([]));
let none = roots_list(&state.with_file_name("absent.toml"), Some(&base), None, None).unwrap();
assert_eq!(none, json!([]));
assert_eq!(roots_list(&state.with_file_name("absent.toml"), None, None, None).unwrap(), json!([]));
let _ = std::fs::remove_dir_all(base.parent().unwrap());
}
#[test]
fn roots_list_through_call_uses_the_ctx_home() {
let base = store_path("roots-call").with_file_name("roots-call");
let _ = std::fs::remove_dir_all(&base);
let home = base.join("home");
let state = base.join("state.toml");
let host = HostPaths { state: &state, home: Some(&home), data: None, member: None };
let ctx = Ctx { inbox: &base.join("inbox.json"), client: "api:test", bridges: None, forwards: None, access: None, host: Some(host) };
let candidates = call("roots.list", Value::Null, &ctx).unwrap();
assert_eq!(candidates, json!([]), "no state, no ~/.devsandboxes");
std::fs::create_dir_all(home.join(".devsandboxes")).unwrap();
let candidates = call("roots.list", json!({}), &ctx).unwrap();
assert_eq!(candidates[0]["root"], json!(std::fs::canonicalize(home.join(".devsandboxes")).unwrap()));
let _ = std::fs::remove_dir_all(&base);
}
fn listing(pid: &str) -> ProcsListing {
ProcsListing {
processes: vec![Process { pid: pid.into(), ppid: "0".into(), args: "sleep 9".into() }],
signalable: true,
runs: vec![crate::runtime::procs::Run {
id: "1790000000-a1b2".into(),
state: "exited 4".into(),
started: "2026-09-21T14:13:20Z".into(),
argv: "sh -c x".into(),
}],
sessions: Some(vec![crate::runtime::procs::Session {
id: "1790000001-0000".into(),
state: "running".into(),
attached: false,
started: "2026-09-21T14:13:21Z".into(),
argv: "bash".into(),
}]),
}
}
#[test]
fn instances_procs_answers_every_instance_failures_included() {
let state = state_file("procs", &[instance("web", "web", ""), instance("off", "web", "")].concat());
let fetch = |container: &str| match container {
"devsandbox-web" => Ok(listing("1")),
_ => Err("not running".to_string()),
};
let procs = |params: Value| instances_procs(parse(params)?, &state, fetch);
let r = procs(json!({"instances": ["web", "off", "nope", "web"]})).unwrap();
assert_eq!(
r,
json!({
"web": {
"processes": [{"pid": "1", "ppid": "0", "args": "sleep 9"}],
"signalable": true,
"runs": [{"id": "1790000000-a1b2", "state": "exited 4", "started": "2026-09-21T14:13:20Z", "argv": "sh -c x"}],
"sessions": [{"id": "1790000001-0000", "state": "running", "attached": false, "started": "2026-09-21T14:13:21Z", "argv": "bash"}],
},
"off": {"error": "not running"},
"nope": {"error": "no instance `nope`"},
})
);
let back: ProcsAnswer = serde_json::from_value(r).unwrap();
assert_eq!(back["web"], InstanceProcs::Listed(listing("1")));
assert_eq!(back["off"], InstanceProcs::Failed { error: "not running".into() });
assert_eq!(procs(json!({"instances": []})).unwrap(), json!({}));
assert_eq!(code(procs(json!({}))), "invalid");
std::fs::write(&state, "not = [toml").unwrap();
assert_eq!(code(procs(json!({"instances": ["web"]}))), "internal");
}
#[test]
fn instances_build_log_reads_by_name_or_id_next_to_the_state() {
let state = state_file(
"buildlog",
&[instance("web", "web", "instance_id = \"web-id\"\n"), instance("new", "web", "instance_id = \"new-id\"\n")].concat(),
);
let log = state.with_file_name("logs").join("web-id");
std::fs::create_dir_all(&log).unwrap();
std::fs::write(log.join(crate::build_log::FILE), "one\ntwo\nthree\n").unwrap();
let read = |params: Value| instances_build_log(parse(params)?, &state);
assert_eq!(read(json!({"instance": "web"})).unwrap(), json!({"text": "one\ntwo\nthree", "cut": false}));
assert_eq!(read(json!({"instance": "web-id", "lines": 2})).unwrap(), json!({"text": "two\nthree", "cut": true}));
assert_eq!(read(json!({"instance": "new"})).unwrap(), Value::Null, "no log yet");
assert_eq!(code(read(json!({"instance": "gone"}))), "not-found");
assert_eq!(code(read(json!({"instance": "web", "lines": -1}))), "invalid");
assert_eq!(code(read(json!({"instance": "web", "ansi": "yes"}))), "invalid");
assert_eq!(code(read(json!({}))), "invalid");
assert_eq!(read(json!({"instance": "web", "ansi": true})).unwrap(), json!({"text": "one\ntwo\nthree", "cut": false}));
let pty = "$ devsandbox run\n# 1970-01-01T00:00:00Z\n# tty 80x24\n\x1b[32mok\x1b[0m\r\n";
std::fs::write(log.join(crate::build_log::FILE), pty).unwrap();
let ask = |ansi: bool| read(json!({"instance": "web", "lines": 1, "ansi": ansi})).unwrap();
assert_eq!(ask(false), json!({"text": "ok", "cut": true}));
assert_eq!(ask(true), json!({"text": "\u{1b}[0;32mok\u{1b}[0m", "cut": true}));
let page = read(json!({"instance": "web", "offset": 52, "lines": 1, "ansi": true})).unwrap();
assert_eq!(page, json!({"text": "\x1b[32mok\x1b[0m\r\n", "next": pty.len(), "tty": true, "complete": true}));
assert_eq!(read(json!({"instance": "new", "offset": 0})).unwrap(), Value::Null, "no log yet");
assert_eq!(code(read(json!({"instance": "web", "offset": -1}))), "invalid");
}
#[test]
fn build_log_pages_say_whether_the_build_goes_on() {
let me = std::process::id();
let state = state_file(
"buildlog-page",
&instance("web", "web", &format!("instance_id = \"web-id\"\n[instance.web.progress]\nphase = \"building\"\npid = {me}\n")),
);
let log = state.with_file_name("logs").join("web-id");
std::fs::create_dir_all(&log).unwrap();
std::fs::write(log.join(crate::build_log::FILE), "$ devsandbox run\n# x\nstep 1\n").unwrap();
let page = instances_build_log(parse(json!({"instance": "web-id", "offset": 21})).unwrap(), &state).unwrap();
assert_eq!(page, json!({"text": "step 1\n", "next": 28, "tty": false, "complete": false}));
}
#[test]
fn containers_methods_take_only_devsandbox_containers() {
let asked = std::cell::RefCell::new(Vec::new());
let logs = |params: Value| {
containers_logs(parse(params)?, |c, n| {
asked.borrow_mut().push((c.to_string(), n));
Ok("hello\n".to_string())
})
};
assert_eq!(logs(json!({"container": "devsandbox-web"})).unwrap(), json!({"text": "hello\n"}));
logs(json!({"container": "devsandbox-web", "lines": 5})).unwrap();
logs(json!({"container": "devsandbox-web", "lines": 1_000_000})).unwrap();
assert_eq!(
*asked.borrow(),
[("devsandbox-web".to_string(), 50), ("devsandbox-web".to_string(), 5), ("devsandbox-web".to_string(), MAX_LINES)]
);
for bad in [json!({"container": "postgres"}), json!({"container": "x-devsandbox-web"}), json!({}), json!({"container": "devsandbox-web", "lines": "all"})] {
assert_eq!(code(logs(bad.clone())), "invalid", "{bad}");
}
assert_eq!(asked.borrow().len(), 3, "refused before the runtime");
let failing = containers_logs(parse(json!({"container": "devsandbox-x"})).unwrap(), |_, _| {
Err(ApiError::internal(anyhow::anyhow!("No such container: devsandbox-x")))
});
assert_eq!(failing.unwrap_err().message, "No such container: devsandbox-x");
let inspect = |container: &str, out: &'static str| {
containers_inspect(parse(json!({"container": container}))?, |_| Ok(out.to_string()))
};
assert_eq!(inspect("devsandbox-web", r#"[{"Id": "abc"}]"#).unwrap(), json!([{"Id": "abc"}]));
assert_eq!(code(inspect("devsandbox-web", "not json")), "internal");
assert_eq!(code(inspect("web", "[]")), "invalid");
}
#[test]
fn sandboxes_get_and_services_get_answer_the_config_text() {
let root = store_path("config-get").with_file_name("cfg");
std::fs::create_dir_all(&root).unwrap();
let get = |method: &str, name: &str| run(&root.join("x"), method, json!({"root": root, "name": name}));
assert_eq!(code(get("sandboxes.get", "web")), "not-found", "no config file: no sandbox");
assert_eq!(code(get("services.get", "db")), "not-found");
std::fs::write(
root.join(crate::config::CONFIG_FILE),
"[template.base]\nimage = \"alpine\"\n[sandbox.web]\nextends = [\"base\"]\nfolder = \"/w\"\n\
[sandbox.broken]\nextends = [\"missing\"]\n[services.db]\nimage = \"postgres\"\n",
)
.unwrap();
let web = get("sandboxes.get", "web").unwrap();
assert_eq!(web["original"], "extends = [\"base\"]\nfolder = \"/w\"\n");
assert_eq!(web["resolved"], "folder = \"/w\"\nimage = \"alpine\"\n");
let cfg = crate::config::Config::load(&root).unwrap();
assert_eq!(web["hash"], cfg.resolved_table("web").unwrap().1);
let back: crate::config::SandboxText = serde_json::from_value(web).unwrap();
assert_eq!(back, cfg.sandbox_text("web"));
let broken = get("sandboxes.get", "broken").unwrap();
assert!(broken["resolved"].as_str().unwrap().contains("missing"), "{broken}");
assert_eq!(broken["hash"], "");
assert_eq!(code(get("sandboxes.get", "nope")), "not-found");
assert_eq!(get("services.get", "db").unwrap(), json!({"original": "image = \"postgres\"\n"}));
assert_eq!(code(get("services.get", "web")), "not-found", "a sandbox isn't a service");
assert_eq!(code(run(&root, "sandboxes.get", json!({"root": "rel", "name": "web"}))), "invalid");
assert_eq!(code(run(&root, "services.get", json!({"root": "/nonexistent/devsandbox-api", "name": "db"}))), "not-found");
assert_eq!(code(run(&root, "sandboxes.get", json!({"root": root}))), "invalid");
std::fs::write(root.join(crate::config::CONFIG_FILE), "[sandbox.web\n").unwrap();
assert_eq!(code(get("sandboxes.get", "web")), "invalid");
let _ = std::fs::remove_dir_all(root.parent().unwrap());
}
#[test]
fn config_findings_migrate_and_ack() {
let state = state_file("identity", "");
let root = state.with_file_name("cfg");
std::fs::create_dir_all(&root).unwrap();
let host = HostPaths { state: &state, home: None, data: None, member: None };
let run = |method: &str, params: Value| {
call(method, params, &Ctx { inbox: &state.with_file_name("inbox.json"), client: "api:test", bridges: None, forwards: None, access: None, host: Some(host) })
};
let file = root.join(crate::config::CONFIG_FILE);
assert_eq!(code(run("config.findings", json!({"root": root}))), "not-found", "no config file");
assert_eq!(code(run("config.findings", json!({"root": "rel"}))), "invalid");
let toml = "[template.base]\nmounts = [\"source=/a,target=/root/.a\"]\n\
[sandbox.web]\nextends = \"base\"\nimage = \"img\"\n\
[sandbox.api]\nimage = \"img\"\nremoteUser = \"root\"\n[sandbox.ok]\nimage = \"img\"\n";
std::fs::write(&file, toml).unwrap();
let project = crate::commands::services::project_id(&root).unwrap();
std::fs::write(
&state,
[instance("web", "web", ""), instance("web-2", "web", ""), instance("api", "api", ""), instance("ok", "ok", "")]
.concat()
.replace("created_unix = 1\n", &format!("created_unix = 1\nproject = \"{project}\"\n")),
)
.unwrap();
let all = run("config.findings", json!({"root": root})).unwrap();
assert_eq!(all["file"], json!(file));
assert_eq!(all["format"], "toml");
assert_eq!(all["fileHash"], crate::config_identity::file_hash(toml));
let found = all["findings"].as_array().unwrap();
assert_eq!(found.len(), 2);
let (mount, user) = (&found[0], &found[1]);
assert_eq!(mount["table"], "template.base");
assert_eq!(mount["kind"], "root-target");
assert_eq!(mount["sandboxes"], json!(["web"]));
assert_eq!(mount["edit"], "template.base: mounts entry \"source=/a,target=/root/.a\" -> \"source=/a,target=${containerEnv:HOME}/.a\"");
assert_eq!(user["kind"], "root-user");
assert_eq!(user["acked"], false);
let api = run("config.findings", json!({"root": root, "sandbox": "api"})).unwrap();
assert_eq!(api["findings"].as_array().unwrap().len(), 1);
assert_eq!(api["findings"][0]["id"], user["id"]);
assert_eq!(run("config.findings", json!({"root": root, "sandbox": "ok"})).unwrap()["findings"], json!([]));
assert_eq!(code(run("config.findings", json!({"root": root, "sandbox": "nope"}))), "not-found");
assert_eq!(run("config.ack", json!({"root": root, "ids": [user["id"]]})).unwrap(), json!({"acked": [user["id"]]}));
let again = run("config.findings", json!({"root": root})).unwrap();
assert_eq!(again["findings"][1]["acked"], true);
assert_eq!(again["findings"][0]["acked"], false);
assert_eq!(code(run("config.ack", json!({"root": root, "ids": ["nope"]}))), "invalid");
let hash = all["fileHash"].clone();
assert_eq!(code(run("config.migrate", json!({"root": root, "fileHash": "stale"}))), "conflict");
assert_eq!(code(run("config.migrate", json!({"root": root, "ids": ["nope"], "fileHash": hash}))), "invalid");
assert_eq!(code(run("config.migrate", json!({"root": root}))), "invalid", "fileHash is required");
let got = run("config.migrate", json!({"root": root, "ids": [mount["id"]], "fileHash": hash})).unwrap();
assert_eq!(got, json!({"edits": 1, "drifted": ["web", "web-2"]}));
assert!(std::fs::read_to_string(&file).unwrap().contains("target=${containerEnv:HOME}/.a"));
assert_eq!(run("config.ack", json!({"root": root, "ids": []})).unwrap(), json!({"acked": [user["id"]]}));
let hash = run("config.findings", json!({"root": root})).unwrap()["fileHash"].clone();
let got = run("config.migrate", json!({"root": root, "ids": [], "keep": [user["id"]], "fileHash": hash})).unwrap();
assert_eq!(got, json!({"edits": 1, "drifted": ["api"]}));
assert_eq!(run("config.findings", json!({"root": root})).unwrap()["findings"], json!([]));
assert_eq!(run("config.ack", json!({"root": root, "ids": []})).unwrap(), json!({"acked": []}));
assert!(crate::state::State::load_at(&state).unwrap().identity_acks.is_empty());
std::fs::remove_file(&file).unwrap();
let yaml = "sandbox:\n web:\n image: img\n remoteUser: root\n";
std::fs::write(root.join("devsandboxes.yaml"), yaml).unwrap();
let y = run("config.findings", json!({"root": root})).unwrap();
assert_eq!(y["format"], "yaml");
let err = run("config.migrate", json!({"root": root, "fileHash": y["fileHash"]})).unwrap_err();
assert_eq!(err.code, "unsupported");
assert!(err.message.contains("sandbox.web: remove remoteUser = \"root\""), "{}", err.message);
assert_eq!(std::fs::read_to_string(root.join("devsandboxes.yaml")).unwrap(), yaml);
let _ = std::fs::remove_dir_all(root.parent().unwrap());
}
#[test_utils::docker_test]
fn containers_and_procs_against_docker() -> Result<(), &'static str> {
let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
let name = format!("devsandbox-api-test-{stamp}");
let cleanup = || {
let _ = crate::test_support::runtime_cmd().args(["rm", "-f", &name]).output();
};
crate::test_support::with_cleanup(cleanup, || {
let up = crate::test_support::runtime_cmd()
.args(["run", "-d", "--name", &name, "alpine:3.20", "sh", "-c", "echo hello-api; exec sleep 300"])
.output();
if !matches!(up, Ok(o) if o.status.success()) {
return Err("docker run alpine:3.20 failed");
}
let backend = crate::runtime::backend();
let mut text = String::new();
for _ in 0..50 {
let r = containers_logs(parse(json!({"container": name})).unwrap(), |c, n| {
backend.logs_tail(c, n).map_err(ApiError::internal)
})
.unwrap();
text = r["text"].as_str().unwrap().to_string();
if text.contains("hello-api") {
break;
}
std::thread::sleep(Duration::from_millis(100));
}
assert!(text.contains("hello-api"), "{text:?}");
let inspected = containers_inspect(parse(json!({"container": name})).unwrap(), |c| {
backend.inspect_json(c).map_err(ApiError::internal)
})
.unwrap();
assert_eq!(inspected[0]["Name"].as_str().map(|n| n.trim_start_matches('/')), Some(name.as_str()));
let listing = fetch_procs(&name).unwrap();
assert!(listing.signalable);
assert!(listing.processes.iter().any(|p| p.args == "sleep 300"), "{listing:?}");
assert!(listing.runs.is_empty());
let missing = containers_inspect(parse(json!({"container": format!("{name}-gone")})).unwrap(), |c| {
backend.inspect_json(c).map_err(ApiError::internal)
});
assert_eq!(code(missing), "internal");
crate::test_support::runtime_cmd().args(["stop", "-t", "0", &name]).output().map_err(|_| "docker stop failed")?;
assert_eq!(fetch_procs(&name).unwrap_err(), "not running");
Ok(())
})
}
#[test]
fn npm_typings_match_the_instance_and_sandbox_answers() {
use crate::serve::dts::{assert_matches, prop_type, union_members};
fn v(x: &impl Serialize) -> Value {
serde_json::to_value(x).unwrap()
}
let found = |machine: Option<&str>, root: Option<&str>| Found {
name: "web".into(),
machine: machine.map(Into::into),
root: root.map(Into::into),
sandbox: Some("web".into()),
};
let resolved = Resolved { matches: vec!["web".into(), "m/web".into()], found: vec![found(None, None), found(Some("m"), Some("/cfg"))] };
assert_matches("InstancesResolved", &v(&resolved));
assert_matches("ResolvedInstance", &v(&found(None, None)));
assert_matches("InstanceCancelled", &v(&Cancelled { ok: true, pid: 1 }));
assert_matches("SandboxEntry", &v(&SandboxEntry::named("web".into())));
let listed = SandboxEntry { name: "web".into(), machine: Some("m".into()), root: Some("/cfg".into()) };
assert_matches("SandboxEntry", &v(&listed));
let list = InstancesList { snapshot: empty_snapshot(), thread_children: Default::default() };
assert_matches("InstancesList", &v(&list));
let cfg = crate::config::Config::parse("[sandbox.web]\nimage = \"alpine\"\nremoteUser = \"root\"\n").unwrap();
let (rows, _) = crate::snapshot::sandbox_rows(&std::env::temp_dir(), &cfg, &Default::default());
assert_matches("SandboxRow", &v(&rows[0]));
assert_matches("IdentityNote", &v(&rows[0].identity[0]));
let listed = listing("1");
assert_matches("ProcsListing", &v(&listed));
assert_matches("ProcessRow", &v(&listed.processes[0]));
assert_matches("RunRow", &v(&listed.runs[0]));
assert_matches("SessionRow", &v(&listed.sessions.unwrap()[0]));
assert_matches("ProcsListing", &v(&ProcsListing { sessions: None, ..listing("1") }));
assert_matches("ProcsError", &v(&InstanceProcs::Failed { error: "not running".into() }));
assert_eq!(union_members("InstanceProcs"), ["ProcsListing", "ProcsError"]);
assert_matches("BuildLogTail", &v(&crate::build_log::Tail { text: "t".into(), cut: false }));
assert_matches("BuildLogPage", &v(&crate::build_log::Page { text: "t".into(), next: 1, tty: false, complete: false }));
assert_matches("ContainerLogs", &v(&ContainerLogs { text: "t".into() }));
assert_matches("SandboxConfig", &v(&cfg.sandbox_text("web")));
assert_matches("ServiceConfig", &v(&ServiceConfig { original: "t".into() }));
assert_matches("InstanceRenamed", &v(&Renamed { instance: "w".into() }));
assert_matches("InstanceProfileSet", &v(&ProfileSet { instance: "w".into(), profile: "work".into() }));
assert_matches("InstanceDone", &v(&DoneSet { instance: "w".into(), done: true, warning: None }));
assert_matches("InstanceDone", &v(&DoneSet { instance: "w".into(), done: true, warning: Some("no link".into()) }));
assert_matches("SessionsList", &v(&SessionsList { sessions: vec!["1700000000-ab12 running detached 2023-11-14T22:13:20Z sh".into()] }));
{
use crate::config_identity::ops::{ConfigAcked, ConfigFindings, ConfigMigrated, IdentityFinding};
let finding = IdentityFinding {
id: "i".into(),
table: "sandbox.web".into(),
kind: "root-user",
key: "remoteUser".into(),
value: "root".into(),
edit: None,
sandboxes: vec!["web".into()],
acked: false,
};
assert_matches("IdentityFinding", &v(&finding));
let findings = ConfigFindings { file: "/f".into(), format: "toml", file_hash: "h".into(), findings: vec![finding] };
assert_matches("ConfigFindings", &v(&findings));
assert_matches("ConfigMigrated", &v(&ConfigMigrated { edits: 1, drifted: vec!["web".into()] }));
assert_matches("ConfigAcked", &v(&ConfigAcked { acked: vec!["i".into()] }));
}
for (method, result) in [
("config.findings", "ConfigFindings"),
("config.migrate", "ConfigMigrated"),
("config.ack", "ConfigAcked"),
("instances.list", "InstancesList"),
("instances.watch", "OkResult"),
("instances.unwatch", "OkResult"),
("instances.resolve", "InstancesResolved"),
("instances.cancel", "InstanceCancelled"),
("instances.procs", "Record<string, InstanceProcs>"),
("instances.buildLog", "BuildLogTail | BuildLogPage | null"),
("instances.signal", "OkResult"),
("sessions.list", "SessionsList"),
("sessions.rm", "OkResult"),
("instances.rename", "InstanceRenamed"),
("instances.setProfile", "InstanceProfileSet"),
("instances.done", "InstanceDone"),
("containers.logs", "ContainerLogs"),
("containers.inspect", "unknown"),
("sandboxes.list", "SandboxEntry[]"),
("roots.list", "RootCandidate[]"),
("sandboxes.get", "SandboxConfig"),
("services.get", "ServiceConfig"),
("code.haves", "CodeHaves"),
("mesh.folders", "MeshFolders"),
("instances.fetch", "InstancesFetched"),
("placements.fetch", "PlacementsFetched"),
] {
let ty = prop_type("ApiMethods", method).unwrap_or_else(|| panic!("ApiMethods lacks `{method}`"));
assert!(ty.contains(&format!("result: {result} ")), "{method}: {ty}");
}
}
#[test]
fn watch_dirs_are_absolute_and_exist_to_watch() {
let tmp = std::env::temp_dir();
assert_eq!(watch_dir(json!({"dir": tmp}), true).unwrap(), tmp);
assert_eq!(watch_dir(json!({"dir": "rel"}), true).unwrap_err().code, "invalid");
assert_eq!(watch_dir(json!({"dir": "rel"}), false).unwrap_err().code, "invalid");
assert_eq!(watch_dir(json!({}), true).unwrap_err().code, "invalid");
let gone = tmp.join(format!("dsv-gone-{}", std::process::id()));
assert_eq!(watch_dir(json!({"dir": gone}), true).unwrap_err().code, "not-found");
assert_eq!(watch_dir(json!({"dir": gone}), false).unwrap(), gone);
}
#[test]
fn topics_parse_and_reject_unknown_ones() {
assert_eq!(
topics(json!({"topics":["inbox","instances","forwards","opens","roots","access"]})).unwrap(),
[Topic::Inbox, Topic::Instances, Topic::Forwards, Topic::Opens, Topic::Roots, Topic::Access]
);
let named = crate::serve::dts::union_members("ApiTopic");
assert_eq!(named, ["'inbox'", "'instances'", "'forwards'", "'opens'", "'roots'", "'access'"]);
let e = topics(json!({"topics":["ports"]})).unwrap_err();
for t in &named {
assert!(e.message.contains(t.trim_matches('\'')), "{}", e.message);
}
assert_eq!(topics(json!({"topics":["ports"]})).unwrap_err().code, "invalid");
assert_eq!(topics(Value::Null).unwrap_err().code, "invalid");
}
#[derive(Default)]
struct FakeForwards {
adds: std::cell::RefCell<Vec<AddRequest>>,
lists: std::cell::RefCell<Vec<(Option<PathBuf>, bool)>>,
}
impl Forwarding for FakeForwards {
fn list(&self, dir: Option<PathBuf>, machines: bool) -> Result<Vec<ForwardRow>, ApiError> {
self.lists.borrow_mut().push((dir, machines));
Ok(vec![ForwardRow {
id: 1,
dir: "/cfg".into(),
local: "127.0.0.1:3000".into(),
target: "web:3000".into(),
process: None,
state: "active".into(),
conns: 0,
configured: true,
open: false,
machine: None,
}])
}
fn add(&self, req: AddRequest) -> Result<Added, ApiError> {
if req.instance.as_deref().is_some_and(|i| i != "web") {
return Err(ApiError::not_found("no instance"));
}
self.adds.borrow_mut().push(req);
Ok(Added { id: 2, local: "127.0.0.1:3001".into(), target: "web:3000".into() })
}
fn rm(&self, id: u64) -> Result<Removed, ApiError> {
match id {
1 => Ok(Removed { local: "127.0.0.1:3000".into(), configured: true }),
_ => Err(ApiError::not_found(format!("no forward {id}"))),
}
}
}
#[test]
fn forwards_methods_validate_then_call_the_registry() {
use crate::devsbd::forward::HostPort;
let path = store_path("forwards");
let fake = FakeForwards::default();
let fwd = |method: &str, params: Value| call(method, params, &Ctx { inbox: &path, client: "api:test", bridges: None, forwards: Some(&fake), access: None, host: None });
let rows = fwd("forwards.list", json!({"dir": "/cfg"})).unwrap();
assert_eq!(rows[0]["id"], 1);
assert_eq!(rows[0]["configured"], true);
fwd("forwards.list", Value::Null).unwrap();
fwd("forwards.list", json!({"machines": true})).unwrap();
assert_eq!(*fake.lists.borrow(), [(Some(PathBuf::from("/cfg")), false), (None, false), (None, true)]);
assert_eq!(code(fwd("forwards.list", json!({"machines": "yes"}))), "invalid");
assert_eq!(code(fwd("forwards.list", json!({"dir": "rel"}))), "invalid");
let added = fwd("forwards.add", json!({"dir": "/cfg", "instance": "web", "spec": "8080:3000"})).unwrap();
assert_eq!(added, json!({"id": 2, "local": "127.0.0.1:3001", "target": "web:3000"}));
fwd("forwards.add", json!({"dir": "/cfg", "instance": "", "service": "db", "address": "0.0.0.0", "spec": "5432", "machine": ""}))
.unwrap();
fwd("forwards.add", json!({"dir": "/far/cfg", "instance": "web", "spec": "3000", "machine": "box"})).unwrap();
let adds = fake.adds.borrow().clone();
assert_eq!(
adds,
[
AddRequest {
dir: "/cfg".into(),
instance: Some("web".into()),
service: None,
bind: "127.0.0.1".parse().unwrap(),
host_port: HostPort::Fixed(8080),
container_port: 3000,
machine: None,
},
AddRequest {
dir: "/cfg".into(),
instance: None,
service: Some("db".into()),
bind: "0.0.0.0".parse().unwrap(),
host_port: HostPort::Prefer(5432),
container_port: 5432,
machine: None,
},
AddRequest {
dir: "/far/cfg".into(),
instance: Some("web".into()),
service: None,
bind: "127.0.0.1".parse().unwrap(),
host_port: HostPort::Prefer(3000),
container_port: 3000,
machine: Some("box".into()),
},
]
);
for bad in [
json!({"dir": "rel", "instance": "web", "spec": "3000"}),
json!({"dir": "/cfg", "spec": "3000"}),
json!({"dir": "/cfg", "instance": "web", "spec": "0"}),
json!({"dir": "/cfg", "instance": "web", "spec": "a:b"}),
json!({"dir": "/cfg", "instance": "web", "spec": "3000", "address": "localhost"}),
json!({"dir": "/cfg", "instance": "web"}),
json!({"dir": "rel", "instance": "web", "spec": "3000", "machine": "box"}),
] {
assert_eq!(code(fwd("forwards.add", bad.clone())), "invalid", "{bad}");
}
assert_eq!(fake.adds.borrow().len(), 3);
assert_eq!(code(fwd("forwards.add", json!({"dir": "/cfg", "instance": "nope", "spec": "3000"}))), "not-found");
assert_eq!(
fwd("forwards.rm", json!({"id": 1})).unwrap(),
json!({"ok": true, "local": "127.0.0.1:3000", "configured": true})
);
assert_eq!(code(fwd("forwards.rm", json!({"id": 9}))), "not-found");
assert_eq!(code(fwd("forwards.rm", json!({}))), "invalid");
assert_eq!(code(run(&path, "forwards.list", json!({}))), "internal");
}
fn held_ask(scope: &str, route: &str) -> asks::Ask {
asks::Ask {
key: asks::AskKey {
instance_id: "web-1-id".into(),
credential: "github-work".into(),
scope: scope.into(),
repo: Some("o/r\u{1b}[2J".into()),
presence: None,
},
instance: "web-1".into(),
sandbox: "web".into(),
kind: "github".into(),
method: "POST".into(),
route: route.into(),
hold: Duration::from_secs(30),
}
}
#[test]
fn access_methods_list_and_answer_the_requests() {
use crate::credentials::{answers, home};
let path = store_path("access");
let data = path.parent().unwrap().join("data");
let registry = Registry::new(data.clone());
home::update(&home::path(&data), |h| Ok(h.insert("github-work".into(), home::Entry::new("github", None)))).unwrap();
let access = |method: &str, params: Value| {
call(method, params, &Ctx { inbox: &path, client: "api:test", bridges: None, forwards: None, access: Some(®istry), host: None })
};
assert_eq!(access("access.pending", Value::Null).unwrap(), json!({"requests": []}));
let ids: Vec<String> = ["once", "instance", "always"]
.iter()
.map(|s| registry.ask(&held_ask(s, "/repos/o/r/pulls\n\u{7}")).unwrap().id().to_string())
.collect();
registry.ask(&held_ask("once", "/again")).unwrap();
let listed = access("access.pending", json!({})).unwrap();
let rows = listed["requests"].as_array().unwrap();
assert_eq!(rows.iter().map(|r| r["id"].as_str().unwrap()).collect::<Vec<_>>(), ids);
let first = &rows[0];
assert_eq!(first["route"], "/repos/o/r/pulls\\n\\u{7}");
assert_eq!(first["repo"], "o/r\\u{1b}[2J");
assert_eq!((first["held"].as_bool(), first["waiting"].as_u64()), (Some(true), Some(2)), "the second call joined");
assert_eq!(
(&first["instance"], &first["instance_id"], &first["sandbox"], &first["credential"], &first["scope"], &first["kind"], &first["method"]),
(&json!("web-1"), &json!("web-1-id"), &json!("web"), &json!("github-work"), &json!("once"), &json!("github"), &json!("POST"))
);
assert!(first["opened_at"].as_u64().unwrap() > 1_700_000_000);
crate::serve::dts::assert_matches("AccessPending", &listed);
crate::serve::dts::assert_matches("AccessRequest", first);
for (id, answer) in ids.iter().zip(["once", "instance", "always"]) {
let decided = access("access.decide", json!({"request": id, "answer": answer})).unwrap();
assert_eq!(decided["request"]["id"], id.as_str(), "{answer}");
crate::serve::dts::assert_matches("AccessDecided", &decided);
}
let markers: Vec<String> =
[asks::Answer::Once, asks::Answer::Instance, asks::Answer::Always, asks::Answer::Deny].iter().map(|a| format!("'{}'", a.marker())).collect();
assert_eq!(crate::serve::dts::union_members("AccessAnswer"), markers);
assert_eq!(access("access.pending", json!({})).unwrap(), json!({"requests": []}));
let kept = answers::load(&answers::path(&data)).unwrap();
assert_eq!(answers::lookup(&kept, &held_ask("instance", "/").key).map(|a| a.answer), Some(answers::Kind::Instance));
assert_eq!(home::load(&home::path(&data)).unwrap()["github-work"].rules[0].id.as_deref(), Some(ids[2].as_str()));
let deny = registry.ask(&held_ask("deny", "/")).unwrap().id().to_string();
assert_eq!(code(access("access.decide", json!({"request": deny, "answer": "yes"}))), "invalid");
assert_eq!(code(access("access.decide", json!({"request": deny}))), "invalid");
access("access.decide", json!({"request": deny, "answer": "deny"})).unwrap();
let kept = answers::load(&answers::path(&data)).unwrap();
assert_eq!(answers::lookup(&kept, &held_ask("deny", "/").key).map(|a| a.answer), Some(answers::Kind::Deny));
assert_eq!(code(access("access.decide", json!({"request": deny, "answer": "once"}))), "not-found");
assert_eq!(code(access("access.decide", json!({"request": "R-0000000000AB", "answer": "once"}))), "not-found");
let mut tag = held_ask("git.push", "/repos/o/r/git/refs/tags/v1");
tag.key.presence = Some(asks::PresenceAt { route: "DELETE /repos/o/r/git/refs/tags/v1".into(), target: "v1\u{1b}".into() });
let id = registry.ask(&tag).unwrap().id().to_string();
let listed = access("access.pending", json!({})).unwrap();
assert_eq!(listed["requests"][0]["presence"], "v1\\u{1b}");
crate::serve::dts::assert_matches("AccessRequest", &listed["requests"][0]);
let e = access("access.decide", json!({"request": id, "answer": "always"})).unwrap_err();
assert_eq!(e.code, "invalid");
assert!(e.message.contains("once or for this instance, never always"), "{}", e.message);
assert_eq!(access("access.pending", json!({})).unwrap()["requests"][0]["id"], id.as_str(), "still pending");
access("access.decide", json!({"request": id, "answer": "instance"})).unwrap();
assert_eq!(code(run(&path, "access.pending", json!({}))), "internal");
let _ = std::fs::remove_dir_all(path.parent().unwrap());
}
#[test]
fn npm_typings_match_the_wire_structs() {
use crate::serve::dts::{assert_matches, assert_variant, union_members};
use crate::serve::proto::{ErrorBody, HelloParams, HelloResult};
fn v(x: &impl Serialize) -> Value {
serde_json::to_value(x).unwrap()
}
let summary = || ThreadSummary {
id: 1,
owner: "o-id".into(),
owner_name: "o".into(),
key: Some("k".into()),
kind: "thread",
state: Some("active"),
status: Some("s".into()),
title: "t".into(),
level: None,
unread: true,
archived: false,
needs_you: false,
changed_at: 1,
};
let detail = ThreadDetail {
summary: summary(),
link: None,
child: None,
compose: Some(ComposeView { placeholder: None, hint: None }),
actions: vec![],
feed: vec![],
notes: vec![],
events_pending: 0,
};
let action = ActionView { id: "go".into(), label: "Go".into(), done: false, host: None, sends_event: true };
let note = NoteView { id: 1, level: "info", msg: "m".into(), link: None, at: 1 };
let row = ForwardRow {
id: 1,
dir: "/cfg".into(),
local: "127.0.0.1:3000".into(),
target: "web:3000".into(),
process: None,
state: "active".into(),
conns: 0,
configured: false,
open: false,
machine: Some("box".into()),
};
let added = Added { id: 1, local: "127.0.0.1:3000".into(), target: "web:3000".into() };
let removed = ForwardRemoved { ok: true, local: "127.0.0.1:3000".into(), configured: false };
let hello = HelloParams { version: "0.6.0".into(), build: 1, client: "api:x".into(), force: false };
let hello_result = HelloResult { version: "0.6.0".into(), build: 1, protocol: 1, handoff: true };
let error = ErrorBody { code: "failed".into(), message: "m".into(), data: Some(json!({"exit": 1})) };
let root = RootCandidate {
root: "/cfg".into(),
sandboxes: vec![SandboxEntry::named("web".into())],
error: None,
fleet: false,
copy: Some("cfg".into()),
home: true,
};
let cases: [(&str, Value); 13] = [
("ThreadSummary", v(&summary())),
("ThreadDetail", v(&detail)),
("ThreadCompose", v(&ComposeView { placeholder: None, hint: None })),
("ThreadAction", v(&action)),
("ThreadNote", v(¬e)),
("ForwardRow", v(&row)),
("ForwardAdded", v(&added)),
("ForwardRemoved", v(&removed)),
("HelloParams", v(&hello)),
("HelloResult", v(&hello_result)),
("ApiErrorBody", v(&error)),
("OkResult", ok().unwrap()),
("RootCandidate", v(&root)),
];
for (iface, value) in &cases {
assert_matches(iface, value);
}
assert_matches("MessageField", &v(&FieldView { label: "Head".into(), value: "36b1".into() }));
let blocks = vec![BlockView::Markdown { text: "t".into() }];
let variants: [(&str, Value); 6] = [
("FeedMessage", v(&FeedItemView::Message { seq: 1, at: 1, id: "m".into(), blocks, edited: false, withdrawn: false })),
("FeedReply", v(&FeedItemView::Reply { seq: 1, at: 1, text: "t".into() })),
("FeedAction", v(&FeedItemView::Action { seq: 1, at: 1, action: "go".into(), label: "Go".into() })),
("FeedMarker", v(&FeedItemView::Marker { seq: 1, at: 1, marker: "done", from: None, to: None })),
("MarkdownBlock", v(&BlockView::Markdown { text: "t".into() })),
("FieldsBlock", v(&BlockView::Fields { items: vec![FieldView { label: "l".into(), value: "v".into() }] })),
];
for (iface, value) in &variants {
assert_variant(iface, value);
}
let mixed = form::tests::mixed();
let open = FormRecord::open("f");
let submitted = FormRecord {
state: form::FormState::Submitted { at: 1, answers: Default::default(), client: "tui".into() },
..open.clone()
};
let example = form::tests::example();
let questions: Vec<Value> = example.questions.iter().chain(&mixed.questions).map(|q| v(&QuestionView::of(q))).collect();
let forms: Vec<(&str, Value)> = [
("FormBlock", v(&BlockView::of(&Block::Form(mixed.clone()), Some(&open)))),
("FormBlock", v(&BlockView::of(&Block::Form(mixed.clone()), Some(&submitted)))),
("FeedSubmission", v(&FeedItemView::Submission { seq: 1, at: 1, message: "m".into(), form: "f".into(), answers: json!({}) })),
]
.into_iter()
.chain(questions.into_iter().map(|q| {
let iface = match q["type"].as_str() {
Some("choice") => "ChoiceQuestion",
Some("text") => "TextQuestion",
_ => "ConfirmQuestion",
};
(iface, q)
}))
.collect();
for (iface, value) in &forms {
assert_variant(iface, value);
}
assert_matches("ChoiceOption", &v(&OptionView { id: "a".into(), label: "A".into(), description: None }));
assert_eq!(union_members("FeedItem"), ["FeedMessage", "FeedReply", "FeedAction", "FeedSubmission", "FeedMarker"]);
assert_eq!(union_members("MessageBlock"), ["MarkdownBlock", "FieldsBlock", "FormBlock"]);
assert_eq!(union_members("FormQuestion"), ["ChoiceQuestion", "TextQuestion", "ConfirmQuestion"]);
assert_eq!(crate::serve::dts::prop_type("FormBlock", "state").as_deref(), Some("'open' | 'submitted' | 'withdrawn'"));
assert_eq!(union_members("FormAnswer"), ["string", "string[]", "boolean"]);
assert_eq!(
crate::serve::dts::prop_type("FeedMarker", "marker").as_deref(),
Some("'done' | 'reopen' | 'state' | 'status'")
);
}
}