use std::io::{Read, Write};
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use anyhow::{Context, Result};
use oxdock_fs::{EntryKind, GuardedPath};
use oxdock_parser::{
KEYWORD_ENV, KEYWORD_LET, Step, render_dsl_literal, render_quoted, render_structural,
};
use oxdock_pipe::PipeInner;
use oxdock_process::ProcessManager;
use super::io::write_stdout;
use super::steps::StepCtx;
const MAX_TRANSFER_ENTRIES: usize = 100_000;
type FetchedEntries = (Vec<(String, GuardedPath)>, Vec<String>);
pub(super) fn copy_transfer<P: ProcessManager>(
cx: &mut StepCtx<'_, P>,
from_host: bool,
to_host: bool,
from: &oxdock_parser::Arg,
to: &oxdock_parser::Arg,
) -> Result<()> {
if !cx.state.io.is_remote_guest() {
return Err(anyhow::Error::new(
super::diagnostics::eval_remote_copy_outside_guest(),
));
}
if to_host {
let guest_src = super::args::resolve_arg(from, cx)?;
let host_dst = super::args::resolve_arg(to, cx)?;
cx.state
.push_manifest
.push((guest_src.clone(), host_dst.clone()));
if let Some(sink) = cx.state.io.push_manifest_sink()
&& let Ok(mut guard) = sink.lock()
{
guard.push((guest_src, host_dst));
}
}
let _ = from_host;
Ok(())
}
struct TransferDecl {
from_host: bool,
unconditional: bool,
from: oxdock_parser::Arg,
to: oxdock_parser::Arg,
from_workspace: Option<oxdock_parser::WorkspaceTarget>,
}
pub enum TransferStage {
Mem(std::io::Cursor<Vec<u8>>),
#[cfg(not(miri))]
File(oxdock_fs::SpillFile),
}
impl TransferStage {
pub fn new_mem() -> Self {
Self::Mem(std::io::Cursor::new(Vec::new()))
}
#[cfg(not(miri))]
pub fn new_spill(
resolver: &oxdock_fs::PathResolver,
dir: &GuardedPath,
name: &str,
) -> Result<Self> {
let path = dir.join(name)?;
Ok(Self::File(resolver.create_spill_file(&path)?))
}
pub fn rewind(&mut self) -> Result<()> {
let result: std::io::Result<()> = match self {
Self::Mem(cursor) => {
cursor.set_position(0);
Ok(())
}
#[cfg(not(miri))]
Self::File(file) => {
use std::io::Seek;
file.seek(std::io::SeekFrom::Start(0)).map(|_| ())
}
};
result
.map_err(|err| anyhow::Error::new(super::diagnostics::eval_remote_rewind_failed(&err)))
}
}
impl std::io::Read for TransferStage {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
match self {
Self::Mem(cursor) => cursor.read(buf),
#[cfg(not(miri))]
Self::File(file) => file.read(buf),
}
}
}
impl std::io::Write for TransferStage {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
match self {
Self::Mem(cursor) => cursor.write(buf),
#[cfg(not(miri))]
Self::File(file) => file.write(buf),
}
}
fn flush(&mut self) -> std::io::Result<()> {
match self {
Self::Mem(cursor) => cursor.flush(),
#[cfg(not(miri))]
Self::File(file) => file.flush(),
}
}
}
fn collect_transfer_decls(body: &[Step]) -> Vec<TransferDecl> {
let mut out = Vec::new();
fn visit(
kind: &oxdock_parser::StepKind,
guarded: bool,
dead: bool,
out: &mut Vec<TransferDecl>,
) {
if dead {
return;
}
if let oxdock_parser::StepKind::Copy {
from_workspace,
from_host,
to_host,
from,
to,
} = kind
&& (*from_host || *to_host)
{
out.push(TransferDecl {
from_host: *from_host,
unconditional: !guarded,
from: from.clone(),
to: to.clone(),
from_workspace: from_workspace.clone(),
});
}
match kind {
oxdock_parser::StepKind::If {
cond,
then_body,
else_ifs,
else_body,
..
} => {
let cond_dead = matches!(
cond.as_ref(),
oxdock_parser::Expr::Literal(value) if value.as_bool() == Some(false)
);
for step in then_body {
visit_step(step, true, dead || cond_dead, out);
}
for (cond, body) in else_ifs {
let branch_dead = matches!(
cond.as_ref(),
oxdock_parser::Expr::Literal(value) if value.as_bool() == Some(false)
);
for step in body {
visit_step(step, true, dead || branch_dead, out);
}
}
if let Some(body) = else_body {
for step in body {
visit_step(step, true, dead, out);
}
}
}
_ => kind.walk_child_kinds(&mut |child| {
visit(child, true, dead, out);
}),
}
}
fn visit_step(step: &Step, guarded: bool, dead: bool, out: &mut Vec<TransferDecl>) {
visit(
&step.kind,
guarded || step.guard.is_some() || statically_false_guard(step.guard.as_ref()),
dead,
out,
);
}
for step in body {
visit_step(step, false, false, &mut out);
}
out
}
fn statically_false_guard(guard: Option<&oxdock_parser::GuardExpr>) -> bool {
use oxdock_parser::{Guard, GuardExpr};
fn is_false(expr: &GuardExpr) -> bool {
match expr {
GuardExpr::Predicate(Guard::Attr {
ns: oxdock_parser::Ns::Bool,
val: Some(value),
..
}) => !value.parse::<bool>().unwrap_or(true),
GuardExpr::Predicate(_) => false,
GuardExpr::All(children) => children.iter().any(is_false),
GuardExpr::Or(_) => false,
GuardExpr::Not(_) => false,
}
}
guard.is_some_and(is_false)
}
pub struct RemoteRequest {
pub target: String,
pub script_text: String,
pub fetch_files: Vec<(String, GuardedPath)>,
pub fetch_dirs: Vec<String>,
pub push_decls: Vec<(String, String)>,
pub stdin: Option<Arc<PipeInner>>,
pub stdout: Option<Arc<PipeInner>>,
pub stderr_sink: Option<oxdock_process::SharedOutput>,
pub cancelled: Arc<AtomicBool>,
pub envs: Vec<(String, String)>,
}
pub struct RemoteResponse {
pub stdout_bytes: Vec<u8>,
pub stderr_bytes: Vec<u8>,
}
pub trait RemoteRunner: Send + Sync {
fn run_remote(
&self,
request: RemoteRequest,
fs: &dyn oxdock_fs::WorkspaceFs,
) -> Result<RemoteResponse>;
}
fn resolve_header<P: ProcessManager>(
cx: &mut StepCtx<'_, P>,
target: &str,
vars: &[String],
env_names: &[String],
) -> Result<Vec<String>> {
let mut lines = Vec::new();
for name in vars {
let Some((decl_type, value)) = cx.state.get_var_typed(name) else {
return Err(anyhow::Error::new(
super::diagnostics::eval_remote_unknown_var(target, name),
));
};
let literal = render_dsl_literal(&value).with_context(|| {
super::diagnostics::eval_remote_unrenderable_var(name, value.type_name(), target)
})?;
lines.push(format!(
"{KEYWORD_LET} ${name}: {} = {literal}",
render_structural(&decl_type)
));
}
for name in env_names {
let Some(value) = cx.get_env(name) else {
return Err(anyhow::Error::new(
super::diagnostics::eval_remote_unknown_env(target, name),
));
};
lines.push(format!("{KEYWORD_ENV} {name}={}", render_quoted(&value)));
}
Ok(lines)
}
struct ResolvedFetch {
host_rel: String,
guest_rel: String,
from_workspace: Option<oxdock_parser::WorkspaceTarget>,
unconditional: bool,
}
fn resolve_fetch_entries<P: ProcessManager>(
cx: &mut StepCtx<'_, P>,
decls: &[ResolvedFetch],
) -> Result<FetchedEntries> {
let mut files = Vec::new();
let mut dirs = Vec::new();
for decl in decls {
resolve_one_fetch(cx, decl, &mut files, &mut dirs)?;
}
Ok((files, dirs))
}
fn resolve_one_fetch<P: ProcessManager>(
cx: &mut StepCtx<'_, P>,
decl: &ResolvedFetch,
files: &mut Vec<(String, GuardedPath)>,
dirs: &mut Vec<String>,
) -> Result<()> {
let source = match &decl.from_workspace {
Some(target) => cx.state.fs.resolve_copy_source_from_target(
super::handlers::copy_source_root(target.clone()),
&decl.host_rel,
),
None => cx.state.fs.resolve_copy_source(&decl.host_rel),
};
let source = match source {
Ok(source) => source,
Err(_) if !decl.unconditional => return Ok(()),
Err(_) => {
return Err(anyhow::Error::new(
super::diagnostics::eval_remote_fetch_missing(&decl.host_rel, None),
));
}
};
let dest_base = decl.guest_rel.clone();
match cx.state.fs.entry_kind(&source) {
Ok(EntryKind::Dir) => {
dirs.push(dest_base.clone());
let mut stack = vec![(source, dest_base)];
while let Some((dir, rel)) = stack.pop() {
let mut entries = cx.state.fs.read_dir_entries(&dir)?;
entries.sort_by_key(|entry| entry.file_name());
for entry in entries {
let name = entry.file_name().to_string_lossy().to_string();
let child = dir.join(&name)?;
let child_rel = format!("{rel}/{name}");
match cx.state.fs.entry_kind(&child)? {
EntryKind::Dir => {
dirs.push(child_rel.clone());
stack.push((child, child_rel));
}
_ => {
files.push((child_rel, child));
}
}
if files.len() + dirs.len() > MAX_TRANSFER_ENTRIES {
return Err(anyhow::Error::new(
super::diagnostics::eval_remote_fetch_entry_cap(
&decl.host_rel,
MAX_TRANSFER_ENTRIES,
),
));
}
}
}
}
Ok(_) => {
let dest = if dest_base.ends_with('/') || dest_base.ends_with('\\') {
let base = source
.as_path()
.file_name()
.map(|s| s.to_string_lossy().into_owned())
.ok_or_else(|| {
anyhow::Error::new(super::diagnostics::eval_remote_fetch_no_file_name(
&decl.host_rel,
))
})?;
format!("{dest_base}{base}")
} else {
dest_base
};
files.push((dest, source));
}
Err(err) => {
return Err(anyhow::Error::new(
super::diagnostics::eval_remote_fetch_missing(&decl.host_rel, Some(&err)),
));
}
}
Ok(())
}
pub fn apply_push_file(
fs: &dyn oxdock_fs::WorkspaceFs,
root: &GuardedPath,
rel: &str,
reader: &mut dyn Read,
) -> Result<()> {
let path = root.join(rel)?;
if let Some(parent) = parent_rel(rel) {
let dir = root.join(&parent)?;
fs.create_dir_all(&dir)?;
}
let mut writer = fs.open_write(&path)?;
let mut buf = [0u8; 65536];
loop {
let n = reader.read(&mut buf)?;
if n == 0 {
break;
}
writer.write_all(&buf[..n])?;
}
writer.flush()?;
Ok(())
}
pub fn apply_push_dir(
fs: &dyn oxdock_fs::WorkspaceFs,
root: &GuardedPath,
rel: &str,
) -> Result<()> {
if rel.is_empty() {
return Ok(());
}
let path = root.join(rel)?;
fs.create_dir_all(&path)?;
Ok(())
}
fn parent_rel(rel: &str) -> Option<String> {
rel.rfind('/').map(|idx| rel[..idx].to_string())
}
fn route_stdio<P: ProcessManager>(
cx: &mut StepCtx<'_, P>,
stdout_backend: Option<Arc<PipeInner>>,
stdout_bytes: &[u8],
stderr_bytes: &[u8],
) -> Result<()> {
if let Some(backend) = stdout_backend {
if !stdout_bytes.is_empty() {
let writer = backend.writer_handle();
if let Ok(mut guard) = writer.lock() {
guard.write_all(stdout_bytes)?;
guard.flush()?;
}
}
} else if !stdout_bytes.is_empty() {
let owned = stdout_bytes.to_vec();
write_stdout(cx.out.clone(), |writer| {
writer.write_all(&owned)?;
writer.flush()?;
Ok(())
})?;
}
if !stderr_bytes.is_empty() {
let owned = stderr_bytes.to_vec();
write_stdout(cx.err.clone(), |writer| {
writer.write_all(&owned)?;
writer.flush()?;
Ok(())
})?;
}
Ok(())
}
pub(super) fn run_remote_block<P: ProcessManager>(
cx: &mut StepCtx<'_, P>,
target: &str,
vars: &[String],
env_names: &[String],
body: &[Step],
) -> Result<()> {
if cx.state.io.is_remote_guest() {
return super::steps::execute_scoped_remote_body(
cx.state,
cx.process,
body,
cx.stdin.clone(),
cx.expose_stdin,
cx.out.clone(),
cx.err.clone(),
cx.out_pipe.clone(),
cx.stdin_pipe.clone(),
);
}
let runner =
cx.state.io.remote_runner(target).ok_or_else(|| {
anyhow::Error::new(super::diagnostics::eval_remote_no_session(target))
})?;
let mut script_text = resolve_header(cx, target, vars, env_names)?.join("\n");
if !script_text.is_empty() {
script_text.push('\n');
}
let wrapped = oxdock_parser::StepKind::RemoteBlock {
target: target.to_string(),
vars: vars.to_vec(),
env: env_names.to_vec(),
body: body.to_vec(),
};
script_text.push_str(&wrapped.to_string());
script_text.push('\n');
let raw_decls = collect_transfer_decls(body);
let mut fetch_decls = Vec::new();
let mut push_decls = Vec::new();
for decl in &raw_decls {
let from_resolved = super::args::resolve_arg(&decl.from, cx)?;
let to_resolved = super::args::resolve_arg(&decl.to, cx)?;
if decl.from_host {
fetch_decls.push(ResolvedFetch {
host_rel: from_resolved,
guest_rel: to_resolved,
from_workspace: decl.from_workspace.clone(),
unconditional: decl.unconditional,
});
} else {
push_decls.push((from_resolved, to_resolved));
}
}
let (fetch_files, fetch_dirs) = resolve_fetch_entries(cx, &fetch_decls)?;
let stderr_sink = cx.err_shared();
let mut transport_env: Vec<(String, String)> = cx
.env_snapshot()
.into_iter()
.filter(|(key, value)| oxdock_process::seed_differs(&cx.state.seed, key, value))
.collect();
transport_env.sort();
let request = RemoteRequest {
target: target.to_string(),
script_text,
fetch_files,
fetch_dirs,
push_decls,
stdin: cx.stdin_pipe.clone(),
stdout: cx.out_pipe.clone(),
stderr_sink,
cancelled: Arc::clone(&cx.state.cancel_token),
envs: transport_env,
};
let fs = cx.state.fs.as_ref();
let response = match runner.run_remote(request, fs) {
Ok(response) => response,
Err(err) => match super::exit::exit_code_of(&err) {
Some(code) => {
return Err(err.context(super::diagnostics::eval_remote_exit_status(target, code)));
}
None => {
return Err(err.context(super::diagnostics::eval_remote_transport_failed(target)));
}
},
};
route_stdio(
cx,
cx.out_pipe.clone(),
&response.stdout_bytes,
&response.stderr_bytes,
)?;
Ok(())
}
pub fn apply_push_symlink(
fs: &dyn oxdock_fs::WorkspaceFs,
root: &GuardedPath,
rel: &str,
target: &str,
) -> Result<()> {
let dst = root.join(rel).map_err(|err| {
anyhow::Error::new(super::diagnostics::eval_remote_push_destination_escapes(
rel, &err,
))
})?;
let src = if target.starts_with('/') {
root.join(target).map_err(|err| {
anyhow::Error::new(super::diagnostics::eval_remote_push_target_outside(
rel, &err,
))
})?
} else if let Some(parent) = rel.rfind('/') {
root.join(&format!("{}/{target}", &rel[..parent]))
.map_err(|err| {
anyhow::Error::new(super::diagnostics::eval_remote_push_target_outside(
rel, &err,
))
})?
} else {
root.join(target).map_err(|err| {
anyhow::Error::new(super::diagnostics::eval_remote_push_target_outside(
rel, &err,
))
})?
};
match fs.entry_kind_no_follow(&dst) {
Ok(EntryKind::Dir) => {
return Err(anyhow::Error::new(
super::diagnostics::eval_remote_push_symlink_over_dir(rel),
));
}
Ok(_) => {
fs.remove_file(&dst)?;
}
Err(_) => {}
}
if let Some(parent) = parent_rel(rel) {
let dir = root.join(&parent)?;
fs.create_dir_all(&dir)?;
}
fs.symlink(&src, &dst)?;
Ok(())
}