Skip to main content

mlua_swarm/store/task/
mod.rs

1//! `TaskStore` — persistence for `Task` records.
2//!
3//! Part of the issue #13 ID-hierarchy reconciliation: Blueprint -> Task ->
4//! Run -> Step -> Attempt. A `Task` is the **work-item identity**: one row
5//! per unit of work ("resolve issue #10" + a Blueprint ref snapshot + an
6//! input ctx), created once when the work is submitted (e.g.
7//! `POST /v1/tasks`). A single Task can be kicked N times; each kick mints
8//! a [`RunId`](crate::types::RunId) and is tracked by the sibling
9//! [`crate::store::run`] store — this module owns only the 1-row-per-Task
10//! identity and its coarse lifecycle status.
11//!
12//! Current scope:
13//!
14//! - [`InMemoryTaskStore`] — process-volatile default.
15//! - [`SqliteTaskStore`] — file-backed persistence via `rusqlite-isle`
16//!   (thread-isolated `Connection`, single-writer FIFO discipline; same
17//!   shape as [`crate::store::issue::sqlite::SqliteIssueStore`]).
18//! - Other persistent backends (Git / mini-app / …) are future carries.
19
20use crate::types::TaskId;
21use async_trait::async_trait;
22use serde::{Deserialize, Serialize};
23use std::collections::HashMap;
24use std::sync::Mutex;
25use thiserror::Error;
26
27pub mod inmemory;
28pub mod sqlite;
29pub use inmemory::InMemoryTaskStore;
30pub use sqlite::SqliteTaskStore;
31
32// ──────────────────────────────────────────────────────────────────────────
33// TaskRecordStatus / TaskRecord
34// ──────────────────────────────────────────────────────────────────────────
35
36/// Lifecycle status of a [`TaskRecord`].
37///
38/// Coarser than [`crate::store::run::RunStatus`]: a Task's status tracks
39/// "is there work in flight / did the most recent kick finish", while a
40/// Run's status tracks one specific kick's own outcome.
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
42#[serde(rename_all = "snake_case")]
43pub enum TaskRecordStatus {
44    /// Created, no [`crate::store::run::RunRecord`] started yet.
45    Pending,
46    /// A Run is currently in flight for this Task.
47    Running,
48    /// The Task's most recent Run completed successfully.
49    Done,
50    /// The Task's most recent Run failed.
51    Failed,
52}
53
54/// One persisted `Task` row — the work-item identity.
55#[derive(Debug, Clone, Serialize, Deserialize)]
56pub struct TaskRecord {
57    /// Task identifier.
58    pub id: TaskId,
59    /// Human-facing goal / description (e.g. "resolve issue #10").
60    pub goal: String,
61    /// Snapshot of the Blueprint selector supplied at creation (the
62    /// `POST /v1/tasks` body's `BlueprintSelector`). Kept as a bare
63    /// `serde_json::Value` so the store layer does not depend on the
64    /// selector's Rust type — callers decode/encode at the API boundary.
65    pub blueprint_ref: serde_json::Value,
66    /// Input context supplied at task creation.
67    pub input_ctx: serde_json::Value,
68    /// Current lifecycle status.
69    pub status: TaskRecordStatus,
70    /// Unix epoch seconds — creation time.
71    pub created_at: u64,
72    /// Unix epoch seconds — last update time.
73    pub updated_at: u64,
74}
75
76/// Errors surfaced by a [`TaskStore`] implementation.
77#[derive(Debug, Error)]
78pub enum TaskStoreError {
79    /// No Task exists for the given id.
80    #[error("task not found: {0}")]
81    NotFound(TaskId),
82
83    /// `create` was called with an id that is already stored.
84    #[error("task already exists: {0}")]
85    Duplicate(TaskId),
86
87    /// Backend-specific failure not covered by the other variants.
88    #[error("other: {0}")]
89    Other(String),
90}
91
92// ──────────────────────────────────────────────────────────────────────────
93// TaskStore trait
94// ──────────────────────────────────────────────────────────────────────────
95
96/// Persistence interface for `Task` records — the work-item identity
97/// layer of the issue #13 ID hierarchy.
98#[async_trait]
99pub trait TaskStore: Send + Sync {
100    /// Backend name — for diagnostics/logging.
101    fn name(&self) -> &str;
102
103    /// Create a new Task row. Returns `Duplicate` if `record.id` is
104    /// already stored.
105    async fn create(&self, record: TaskRecord) -> Result<(), TaskStoreError>;
106
107    /// Fetch a Task by id.
108    async fn get(&self, id: &TaskId) -> Result<TaskRecord, TaskStoreError>;
109
110    /// List every Task, newest first (descending `created_at`).
111    async fn list(&self) -> Result<Vec<TaskRecord>, TaskStoreError>;
112
113    /// Update a Task's status, bumping `updated_at` to now.
114    async fn update_status(
115        &self,
116        id: &TaskId,
117        status: TaskRecordStatus,
118    ) -> Result<(), TaskStoreError>;
119}
120
121// ──────────────────────────────────────────────────────────────────────────
122// Shared inner state used by the InMemory backend.
123// ──────────────────────────────────────────────────────────────────────────
124
125#[derive(Default)]
126pub(crate) struct Inner {
127    /// Insertion order — used as a stable tie-break under `list()`.
128    pub(crate) order: Vec<TaskId>,
129    pub(crate) records: HashMap<TaskId, TaskRecord>,
130}
131
132pub(crate) type SharedInner = Mutex<Inner>;