Files
orch/src/adapter.rs
T

271 lines
9.2 KiB
Rust

//! Task sources and result sinks. Host-agnostic: built-ins are `dir` and `local-branch`; everything else
//! (Gitea, GitHub, Jira, ...) is an external `cmd` adapter speaking JSON, see docs/cmd-protocol.md.
use crate::state::Run;
use anyhow::{Context, Result, bail};
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value, json};
use std::io::{Read, Write};
use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::sync::mpsc;
use std::time::Duration;
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct Task {
/// Stable, unique per source; used for branch and run names (sanitized by orch).
pub id: String,
pub title: String,
pub body: String,
/// Local clone to work in; falls back to the profile's `repo`.
#[serde(default)]
pub repo: Option<PathBuf>,
/// Adapter-private fields (issue number, URL, ...): echoed back verbatim on claim/report/publish.
#[serde(flatten)]
pub extra: Map<String, Value>,
}
pub trait Source: Send + Sync {
fn list(&self) -> Result<Vec<Task>>;
/// false = somebody else got it; skip silently.
fn claim(&self, t: &Task) -> Result<bool>;
fn report(&self, t: &Task, r: &Run) -> Result<()>;
}
pub trait Sink: Send + Sync {
/// Called for runs that ended `done`. Returns a URL or note to store on the run.
fn publish(&self, t: &Task, r: &Run) -> Result<Option<String>>;
}
/// `[source]` / `[sink]` profile section.
#[derive(Deserialize, Debug, Clone)]
#[serde(deny_unknown_fields)]
pub struct Adapter {
/// source: dir | cmd. sink: local-branch | cmd.
pub kind: String,
/// dir: folder with `*.md` tasks.
pub path: Option<PathBuf>,
/// cmd: program and fixed args (whitespace-split); orch appends the operation name.
pub command: Option<String>,
}
pub fn source(a: &Adapter) -> Result<Box<dyn Source>> {
Ok(match a.kind.as_str() {
"dir" => Box::new(DirSource(
a.path.clone().context("source dir needs `path`")?,
)),
"cmd" => Box::new(Cmd(a
.command
.clone()
.context("source cmd needs `command`")?)),
k => bail!("unknown source kind {k:?} (dir | cmd)"),
})
}
pub fn sink(a: Option<&Adapter>) -> Result<Box<dyn Sink>> {
Ok(match a.map(|a| (a.kind.as_str(), a)) {
None | Some(("local-branch", _)) => Box::new(LocalBranch),
Some(("cmd", a)) => Box::new(Cmd(a
.command
.clone()
.context("sink cmd needs `command`")?)),
Some((k, _)) => bail!("unknown sink kind {k:?} (local-branch | cmd)"),
})
}
/// Markdown task: first `#` heading = title, rest = prompt. Shared with `orch run FILE`.
pub fn parse_task_md(id: &str, s: &str) -> Task {
let title = s
.lines()
.find(|l| l.starts_with('#'))
.map(|l| l.trim_start_matches('#').trim().to_string());
let body: String = s
.lines()
.filter(|l| !l.starts_with('#'))
.collect::<Vec<_>>()
.join("\n");
let title = title.unwrap_or_else(|| id.to_string());
let body = if body.trim().is_empty() {
title.clone()
} else {
body.trim().to_string()
};
Task {
id: id.into(),
title,
body,
repo: None,
extra: Map::new(),
}
}
// ---- dir -------------------------------------------------------------------------------------
/// `*.md` files in a folder. Claim = atomic rename into `.running/`; report moves to `.done/` or `.failed/`.
pub struct DirSource(PathBuf);
impl DirSource {
fn mv(&self, id: &str, from: &str, to: &str) -> Result<bool> {
let dest = self.0.join(to);
std::fs::create_dir_all(&dest)?;
let src = if from.is_empty() {
self.0.clone()
} else {
self.0.join(from)
};
match std::fs::rename(src.join(format!("{id}.md")), dest.join(format!("{id}.md"))) {
Ok(()) => Ok(true),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false), // lost the race
Err(e) => Err(e.into()),
}
}
}
impl DirSource {
/// Quota requeue: the task goes back into the queue for the next pull.
fn mv_back(&self, id: &str) -> Result<bool> {
let name = format!("{id}.md");
match std::fs::rename(self.0.join(".running").join(&name), self.0.join(&name)) {
Ok(()) => Ok(true),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
Err(e) => Err(e.into()),
}
}
}
impl Source for DirSource {
fn list(&self) -> Result<Vec<Task>> {
let mut v = vec![];
for e in std::fs::read_dir(&self.0)
.with_context(|| format!("source dir {}", self.0.display()))?
.flatten()
{
let p = e.path();
if p.extension().is_some_and(|x| x == "md") && p.is_file() {
let id = p.file_stem().and_then(|s| s.to_str()).unwrap_or("task");
v.push(parse_task_md(id, &std::fs::read_to_string(&p)?));
}
}
v.sort_by(|a, b| a.id.cmp(&b.id));
Ok(v)
}
fn claim(&self, t: &Task) -> Result<bool> {
self.mv(&t.id, "", ".running")
}
fn report(&self, t: &Task, r: &Run) -> Result<()> {
use crate::state::Status;
match r.status {
Status::Done => self.mv(&t.id, ".running", ".done")?,
Status::Requeued => self.mv_back(&t.id)?,
_ => self.mv(&t.id, ".running", ".failed")?,
};
Ok(())
}
}
// ---- local branch ----------------------------------------------------------------------------
/// Fallback sink: the work already sits on the local branch `orch/ID`; nothing to push.
pub struct LocalBranch;
impl Sink for LocalBranch {
fn publish(&self, _t: &Task, r: &Run) -> Result<Option<String>> {
Ok(Some(format!("branch {} in {}", r.branch, r.repo.display())))
}
}
// ---- cmd -------------------------------------------------------------------------------------
/// External adapter: `COMMAND OP` with a JSON object on stdin, a JSON object on stdout, exit 0.
pub struct Cmd(String);
const CMD_TIMEOUT: Duration = Duration::from_secs(120);
pub fn call(command: &str, op: &str, input: &Value) -> Result<Value> {
let mut parts = command.split_whitespace();
let mut child = Command::new(parts.next().context("empty adapter command")?)
.args(parts)
.arg(op)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()
.with_context(|| format!("adapter {command}"))?;
child
.stdin
.take()
.unwrap()
.write_all(input.to_string().as_bytes())?; // dropped = EOF
let mut out = child.stdout.take().unwrap();
let (tx, rx) = mpsc::channel();
std::thread::spawn(move || {
let mut s = String::new();
let _ = tx.send(out.read_to_string(&mut s).map(|_| s));
});
let Ok(res) = rx.recv_timeout(CMD_TIMEOUT) else {
let _ = child.kill();
bail!(
"adapter {command} {op}: timed out after {}s",
CMD_TIMEOUT.as_secs()
);
};
let st = child.wait()?;
if !st.success() {
bail!("adapter {command} {op}: exit {}", st.code().unwrap_or(-1));
}
serde_json::from_str(res?.trim()).with_context(|| format!("adapter {op}: stdout is not JSON"))
}
fn run_json(t: &Task, r: &Run) -> Value {
json!({"task": t, "run": {
"id": r.id, "status": r.status, "reason": r.reason, "branch": r.branch, "repo": r.repo,
"worktree": r.worktree, "attempts": r.attempts, "input_tokens": r.input_tokens,
"output_tokens": r.output_tokens, "cache_read_tokens": r.cache_read_tokens,
"cache_write_tokens": r.cache_write_tokens, "published": r.published,
}})
}
impl Source for Cmd {
fn list(&self) -> Result<Vec<Task>> {
let v = call(&self.0, "list", &json!({}))?;
serde_json::from_value(v["tasks"].clone())
.context("list: `tasks` must be an array of tasks")
}
fn claim(&self, t: &Task) -> Result<bool> {
let v = call(&self.0, "claim", &json!({"task": t}))?;
v["claimed"]
.as_bool()
.context("claim: `claimed` must be a bool")
}
fn report(&self, t: &Task, r: &Run) -> Result<()> {
call(&self.0, "report", &run_json(t, r)).map(|_| ())
}
}
impl Sink for Cmd {
fn publish(&self, t: &Task, r: &Run) -> Result<Option<String>> {
let v = call(&self.0, "publish", &run_json(t, r))?;
Ok(v["url"].as_str().map(String::from))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn task_md_and_wire_format() {
let t = parse_task_md("fix-it", "# Fix it\n\nDo the thing\nplease\n");
assert_eq!(
(t.title.as_str(), t.body.as_str()),
("Fix it", "Do the thing\nplease")
);
assert_eq!(parse_task_md("x", "just text").title, "x");
assert_eq!(parse_task_md("x", "# Only title").body, "Only title");
// unknown fields survive a round trip (adapters stay stateless)
let t: Task =
serde_json::from_str(r#"{"id":"a","title":"t","body":"b","number":7,"url":"u"}"#)
.unwrap();
assert_eq!(serde_json::to_value(&t).unwrap()["number"], 7);
assert!(serde_json::from_str::<Task>(r#"{"id":"a"}"#).is_err());
}
}