Skip to main content

orch/store/cluster/
progress.rs

1//! `orch progress` records: what an agent finished, what is left, and where the work is. The record
2//! goes through the log, the daemon's engine commits and pushes before it writes one
3
4use serde::{Deserialize, Serialize};
5
6use crate::store::TaskStore;
7
8/// Each text field is cut to this many characters, a record is a pointer and not a log
9const MAX_TEXT: usize = 500;
10/// Records kept per task, oldest dropped first
11const KEEP: usize = 5;
12
13/// What the CLI sends after it tried to commit in the worktree itself
14#[derive(Debug, Clone, Serialize, Deserialize)]
15pub struct Report {
16    pub worktree: String,
17    pub done: String,
18    pub left: String,
19    pub state: String,
20    pub cli_committed: bool,
21    #[serde(default)]
22    pub cli_error: Option<String>,
23}
24
25#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
26pub struct Record {
27    pub node: String,
28    pub ts: String,
29    pub branch: String,
30    pub commit: String,
31    /// `agent`, `cli`, `orch` or `none`
32    pub committed_by: String,
33    /// `agent`, `orch` or `none`
34    pub pushed_by: String,
35    #[serde(default)]
36    pub error: Option<String>,
37    pub done: String,
38    pub left: String,
39    pub state: String,
40}
41
42/// A text field cut to the length a record keeps
43pub fn cut(s: &str) -> String {
44    s.chars().take(MAX_TEXT).collect()
45}
46
47fn key(task_id: i64) -> String {
48    format!("progress:{task_id}")
49}
50
51pub async fn list(store: &TaskStore, task_id: i64) -> anyhow::Result<Vec<Record>> {
52    match store.kv_get(&key(task_id)).await? {
53        Some(json) => Ok(serde_json::from_str(&json)?),
54        None => Ok(Vec::new()),
55    }
56}
57
58/// Add `record` to the task's records, keeping the newest few
59pub async fn append(store: &TaskStore, task_id: i64, record: &Record) -> anyhow::Result<()> {
60    let mut records = list(store, task_id).await?;
61    records.push(record.clone());
62    let skip = records.len().saturating_sub(KEEP);
63    let records: Vec<Record> = records.into_iter().skip(skip).collect();
64    store
65        .kv_set(&key(task_id), &serde_json::to_string(&records)?)
66        .await?;
67    Ok(())
68}