vtcode_core/scheduler/
store.rs1use anyhow::{Context, Result, bail};
2use chrono::{DateTime, Local, Utc};
3use std::fs;
4use std::io::Write;
5use std::path::{Path, PathBuf};
6use std::time::Duration;
7
8use super::session::ScheduleCreateInput;
9use super::spec::{ScheduledTaskDefinition, ScheduledTaskRecord, ScheduledTaskRuntimeState, ScheduledTaskSummary};
10use super::{MAX_SCHEDULED_TASKS, atomic_write, initialize_runtime_state};
11use vtcode_commons::VtCodePaths;
12
13const CLAIM_STALE_SECS: u64 = 15 * 60;
14const DURABLE_STORE_DIR: &str = "scheduled_tasks";
15
16#[derive(Debug, Clone)]
17pub struct SchedulerPaths {
18 pub config_root: PathBuf,
19 pub data_root: PathBuf,
20}
21
22impl SchedulerPaths {
23 pub fn new_default() -> Result<Self> {
24 let paths = VtCodePaths::resolve().context("Failed to resolve VT Code paths")?;
25 let config_root = paths.config_path(DURABLE_STORE_DIR)?;
26 let data_root = paths.state_path(DURABLE_STORE_DIR)?;
27 Ok(Self { config_root, data_root })
28 }
29
30 #[must_use]
31 pub fn tasks_dir(&self) -> PathBuf {
32 self.config_root.join("tasks")
33 }
34
35 #[must_use]
36 pub fn state_dir(&self) -> PathBuf {
37 self.data_root.join("state")
38 }
39
40 #[must_use]
41 pub fn claims_dir(&self) -> PathBuf {
42 self.data_root.join("claims")
43 }
44
45 #[must_use]
46 pub fn runs_dir(&self) -> PathBuf {
47 self.data_root.join("runs")
48 }
49
50 pub fn ensure_dirs(&self) -> Result<()> {
51 for dir in [
52 &self.config_root,
53 &self.data_root,
54 &self.tasks_dir(),
55 &self.state_dir(),
56 &self.claims_dir(),
57 &self.runs_dir(),
58 ] {
59 VtCodePaths::ensure_user_dir(dir)
60 .with_context(|| format!("Failed to create scheduler directory {}", dir.display()))?;
61 }
62 Ok(())
63 }
64
65 #[must_use]
66 pub fn definition_path(&self, id: &str) -> PathBuf {
67 self.tasks_dir().join(format!("{id}.toml"))
68 }
69
70 #[must_use]
71 pub fn runtime_path(&self, id: &str) -> PathBuf {
72 self.state_dir().join(format!("{id}.json"))
73 }
74
75 #[must_use]
76 pub fn claim_path(&self, id: &str) -> PathBuf {
77 self.claims_dir().join(format!("{id}.claim"))
78 }
79
80 #[must_use]
81 pub fn artifact_dir(&self, id: &str, run_at: DateTime<Utc>) -> PathBuf {
82 self.runs_dir().join(id).join(run_at.format("%Y%m%dT%H%M%SZ").to_string())
83 }
84}
85
86#[derive(Debug, Clone)]
87pub struct DurableTaskStore {
88 paths: SchedulerPaths,
89}
90
91impl DurableTaskStore {
92 #[must_use]
93 pub fn with_paths(paths: SchedulerPaths) -> Self {
94 Self { paths }
95 }
96
97 pub fn new_default() -> Result<Self> {
98 Ok(Self { paths: SchedulerPaths::new_default()? })
99 }
100
101 #[must_use]
102 pub fn paths(&self) -> &SchedulerPaths {
103 &self.paths
104 }
105
106 pub fn create(&self, definition: ScheduledTaskDefinition) -> Result<ScheduledTaskSummary> {
107 self.paths.ensure_dirs()?;
108 let current_count = self.definition_paths()?.len();
109 if current_count >= MAX_SCHEDULED_TASKS {
110 bail!("VT Code supports at most {MAX_SCHEDULED_TASKS} durable scheduled tasks");
111 }
112
113 let runtime = initialize_runtime_state(&definition)?;
114 self.write_definition(&definition)?;
115 self.write_runtime(&definition.id, &runtime)?;
116 Ok(ScheduledTaskRecord { definition, runtime }.summary())
117 }
118
119 pub fn create_from_input(
120 &self,
121 input: ScheduleCreateInput,
122 now: DateTime<Local>,
123 default_workspace: Option<PathBuf>,
124 ) -> Result<ScheduledTaskSummary> {
125 let definition = input.build_definition(now, default_workspace)?;
126 self.create(definition)
127 }
128
129 pub fn list(&self) -> Result<Vec<ScheduledTaskSummary>> {
130 let mut records = self.load_records()?;
131 records.sort_by_key(|record| record.runtime.next_run_at);
132 Ok(records.into_iter().map(|record| record.summary()).collect())
133 }
134
135 pub fn delete(&self, id: &str) -> Result<Option<ScheduledTaskSummary>> {
136 validate_task_id(id)?;
137 let Some(record) = self.load_record(id)? else {
138 return Ok(None);
139 };
140 let _ = fs::remove_file(self.paths.definition_path(id));
141 let _ = fs::remove_file(self.paths.runtime_path(id));
142 let _ = fs::remove_file(self.paths.claim_path(id));
143 Ok(Some(record.summary()))
144 }
145
146 pub fn load_record(&self, id: &str) -> Result<Option<ScheduledTaskRecord>> {
147 validate_task_id(id)?;
148 let definition_path = self.paths.definition_path(id);
149 if !definition_path.exists() {
150 return Ok(None);
151 }
152 let definition = read_definition(&definition_path)?;
153 let runtime = match self.read_runtime(&definition.id)? {
154 Some(runtime) => runtime,
155 None => initialize_runtime_state(&definition)?,
156 };
157 Ok(Some(ScheduledTaskRecord { definition, runtime }))
158 }
159
160 pub fn update_runtime(&self, record: &ScheduledTaskRecord) -> Result<()> {
161 self.write_runtime(&record.definition.id, &record.runtime)
162 }
163
164 pub(crate) async fn load_records_async(&self) -> Result<Vec<ScheduledTaskRecord>> {
165 let store = self.clone();
166 tokio::task::spawn_blocking(move || store.load_records())
167 .await
168 .context("Scheduled task loading task panicked")?
169 }
170
171 pub(crate) async fn update_runtime_async(&self, record: ScheduledTaskRecord) -> Result<()> {
172 let store = self.clone();
173 tokio::task::spawn_blocking(move || store.update_runtime(&record))
174 .await
175 .context("Scheduled task runtime update task panicked")?
176 }
177
178 fn load_records(&self) -> Result<Vec<ScheduledTaskRecord>> {
179 self.paths.ensure_dirs()?;
180 let mut records = Vec::new();
181 for definition_path in self.definition_paths()? {
182 let definition = match read_definition(&definition_path) {
185 Ok(definition) => definition,
186 Err(error) => {
187 tracing::warn!(
188 path = %definition_path.display(),
189 error = %error,
190 "Skipping unreadable scheduled task definition"
191 );
192 continue;
193 }
194 };
195 let runtime = self
196 .read_runtime(&definition.id)?
197 .unwrap_or(initialize_runtime_state(&definition)?);
198 records.push(ScheduledTaskRecord { definition, runtime });
199 }
200 Ok(records)
201 }
202
203 fn definition_paths(&self) -> Result<Vec<PathBuf>> {
204 self.paths.ensure_dirs()?;
205 let mut paths = Vec::new();
206 for entry in fs::read_dir(self.paths.tasks_dir())
207 .with_context(|| format!("Failed to read {}", self.paths.tasks_dir().display()))?
208 {
209 let entry = entry?;
210 let path = entry.path();
211 if path.extension().and_then(|value| value.to_str()) == Some("toml") {
212 paths.push(path);
213 }
214 }
215 paths.sort();
216 Ok(paths)
217 }
218
219 fn write_definition(&self, definition: &ScheduledTaskDefinition) -> Result<()> {
220 let serialized = toml::to_string_pretty(definition).context("Failed to serialize task definition")?;
221 atomic_write(&self.paths.definition_path(&definition.id), serialized.as_bytes())
222 }
223
224 fn read_runtime(&self, id: &str) -> Result<Option<ScheduledTaskRuntimeState>> {
225 let path = self.paths.runtime_path(id);
226 if !path.exists() {
227 return Ok(None);
228 }
229 let raw = fs::read_to_string(&path).with_context(|| format!("Failed to read {}", path.display()))?;
230 let runtime = serde_json::from_str(&raw).with_context(|| format!("Failed to parse {}", path.display()))?;
231 Ok(Some(runtime))
232 }
233
234 fn write_runtime(&self, id: &str, runtime: &ScheduledTaskRuntimeState) -> Result<()> {
235 let serialized = serde_json::to_vec_pretty(runtime).context("Failed to serialize runtime state")?;
236 atomic_write(&self.paths.runtime_path(id), &serialized)
237 }
238}
239
240fn read_definition(path: &Path) -> Result<ScheduledTaskDefinition> {
241 let raw = fs::read_to_string(path).with_context(|| format!("Failed to read {}", path.display()))?;
242 let definition: ScheduledTaskDefinition =
243 toml::from_str(&raw).with_context(|| format!("Failed to parse {}", path.display()))?;
244 validate_task_id(&definition.id)?;
245 Ok(definition)
246}
247
248fn validate_task_id(id: &str) -> Result<()> {
252 if id.is_empty()
253 || id.contains(['/', '\\'])
254 || Path::new(id)
255 .components()
256 .any(|component| !matches!(component, std::path::Component::Normal(_)))
257 {
258 bail!("Invalid scheduled task id: {id:?}");
259 }
260 Ok(())
261}
262
263fn try_acquire_claim(paths: &SchedulerPaths, id: &str) -> Result<bool> {
264 paths.ensure_dirs()?;
265 let path = paths.claim_path(id);
266 match VtCodePaths::create_private_file(&path) {
267 Ok(mut file) => {
268 let timestamp = Utc::now().to_rfc3339();
269 file.write_all(timestamp.as_bytes())
270 .with_context(|| format!("Failed to write {}", path.display()))?;
271 Ok(true)
272 }
273 Err(error)
274 if error.chain().any(|cause| {
275 cause
276 .downcast_ref::<std::io::Error>()
277 .is_some_and(|io_error| io_error.kind() == std::io::ErrorKind::AlreadyExists)
278 }) =>
279 {
280 if claim_is_stale(&path)? {
281 let _ = fs::remove_file(&path);
282 return try_acquire_claim(paths, id);
283 }
284 Ok(false)
285 }
286 Err(error) => Err(error).with_context(|| format!("Failed to create {}", path.display())),
287 }
288}
289
290pub(crate) async fn try_acquire_claim_async(paths: SchedulerPaths, id: String) -> Result<bool> {
291 tokio::task::spawn_blocking(move || try_acquire_claim(&paths, &id))
292 .await
293 .context("Scheduled task claim acquisition task panicked")?
294}
295
296fn claim_is_stale(path: &Path) -> Result<bool> {
297 let metadata = fs::metadata(path).with_context(|| format!("Failed to stat {}", path.display()))?;
298 let modified = metadata
299 .modified()
300 .with_context(|| format!("Failed to read modification time for {}", path.display()))?;
301 let elapsed = modified.elapsed().unwrap_or_default();
302 Ok(elapsed >= Duration::from_secs(CLAIM_STALE_SECS))
303}
304
305fn release_claim(paths: &SchedulerPaths, id: &str) -> Result<()> {
306 let path = paths.claim_path(id);
307 if path.exists() {
308 fs::remove_file(&path).with_context(|| format!("Failed to remove {}", path.display()))?;
309 }
310 Ok(())
311}
312
313pub(crate) async fn release_claim_async(paths: SchedulerPaths, id: String) -> Result<()> {
314 tokio::task::spawn_blocking(move || release_claim(&paths, &id))
315 .await
316 .context("Scheduled task claim release task panicked")?
317}