返回 CodeWhale
registry.rs
根目录 / crates / lane / src / registry.rs
1 //! Durable lane registry under `$CODEWHALE_HOME/lanes/`.
2
3 use std::fs::{self, OpenOptions};
4 use std::path::{Path, PathBuf};
5
6 use anyhow::{Context, Result, bail};
7 use chrono::{SecondsFormat, Utc};
8 use serde::{Deserialize, Serialize};
9
10 use crate::runtime::RuntimeBackendKind;
11
12 const LANES_SUBDIR: &str = "lanes";
13 const LOGS_SUBDIR: &str = "logs";
14
15 /// Lifecycle status for a running workflow instance.
16 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
17 #[serde(rename_all = "snake_case")]
18 pub enum LaneStatus {
19 Pending,
20 Running,
21 Stopped,
22 Failed,
23 Completed,
24 }
25
26 impl LaneStatus {
27 pub fn as_str(self) -> &'static str {
28 match self {
29 Self::Pending => "pending",
30 Self::Running => "running",
31 Self::Stopped => "stopped",
32 Self::Failed => "failed",
33 Self::Completed => "completed",
34 }
35 }
36
37 pub fn is_active(self) -> bool {
38 matches!(self, Self::Pending | Self::Running)
39 }
40 }
41
42 /// Result of an attempted terminal transition.
43 ///
44 /// The caller needs all three cases distinguished to report a truthful
45 /// receipt: "I stopped it", "it was already terminal", and "it moved on since
46 /// you read it, so I refused". Collapsing them into a bool made a concurrent
47 /// stop by another process indistinguishable from our own transition.
48 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
49 pub enum TerminalTransition {
50 /// This call performed the active -> terminal transition.
51 Transitioned,
52 /// The record was already terminal; nothing changed.
53 AlreadyTerminal,
54 /// The caller pinned a lifecycle generation and the record has moved on.
55 /// Nothing was changed and no backend teardown ran.
56 FenceMismatch { observed: u64 },
57 }
58
59 impl TerminalTransition {
60 #[must_use]
61 pub const fn transitioned(self) -> bool {
62 matches!(self, Self::Transitioned)
63 }
64 }
65
66 /// One lane record: a running (or completed) workflow instance.
67 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
68 pub struct LaneRecord {
69 pub id: String,
70 #[serde(default, skip_serializing_if = "Option::is_none")]
71 pub workflow: Option<String>,
72 #[serde(default, skip_serializing_if = "Option::is_none")]
73 pub fleet: Option<String>,
74 #[serde(default, skip_serializing_if = "Option::is_none")]
75 pub issue: Option<String>,
76 #[serde(default, skip_serializing_if = "Option::is_none")]
77 pub goal: Option<String>,
78 pub runtime: RuntimeBackendKind,
79 pub status: LaneStatus,
80 /// Monotonic durable lifecycle sequence used by Work Graph reconciliation.
81 #[serde(default)]
82 pub lifecycle_seq: u64,
83 #[serde(default, skip_serializing_if = "Option::is_none")]
84 pub worktree_path: Option<PathBuf>,
85 #[serde(default, skip_serializing_if = "Option::is_none")]
86 pub branch: Option<String>,
87 /// tmux session name when `runtime == tmux`.
88 #[serde(default, skip_serializing_if = "Option::is_none")]
89 pub tmux_session: Option<String>,
90 /// Explicit tmux server socket used for this Lane. Pinning the socket keeps
91 /// start/attach/stop/reconcile in the same server namespace even when
92 /// `TMUX_TMPDIR` or the caller environment changes between commands.
93 #[serde(default, skip_serializing_if = "Option::is_none")]
94 pub tmux_socket: Option<PathBuf>,
95 /// Absolute path to the stream-json / NDJSON journal for this lane.
96 pub log_path: PathBuf,
97 pub started_at: String,
98 #[serde(default, skip_serializing_if = "Option::is_none")]
99 pub stopped_at: Option<String>,
100 /// Optional human-readable attach target (e.g. `tmux attach -t …`).
101 #[serde(default, skip_serializing_if = "Option::is_none")]
102 pub attach_target: Option<String>,
103 /// Worktree cleanup TTL in seconds (None = no auto-cleanup).
104 #[serde(default, skip_serializing_if = "Option::is_none")]
105 pub worktree_ttl_secs: Option<u64>,
106 }
107
108 impl LaneRecord {
109 pub fn new_id() -> String {
110 let short = uuid::Uuid::new_v4().to_string();
111 format!("lane-{}", &short[..8])
112 }
113
114 pub fn now_rfc3339() -> String {
115 Utc::now().to_rfc3339_opts(SecondsFormat::Secs, true)
116 }
117 }
118
119 /// Registry root: `$CODEWHALE_HOME/lanes`.
120 pub fn lanes_dir() -> Result<PathBuf> {
121 codewhale_config::ensure_state_dir(LANES_SUBDIR)
122 }
123
124 /// Where the Lane registry *would* live, without creating it.
125 ///
126 /// [`lanes_dir`] creates the directory as a side effect, which makes it
127 /// useless for answering "is there a durable Lane registry?" — a read-only
128 /// status surface must not conjure the store it is reporting on. Availability
129 /// probing goes through this instead (see [`crate::control::ControlContext`]).
130 pub fn lane_registry_root() -> Result<PathBuf> {
131 Ok(codewhale_config::codewhale_home()?.join(LANES_SUBDIR))
132 }
133
134 /// A lane id names files under the registry root, so it must be a plain
135 /// name: ASCII letters, digits, `-` and `_` only.
136 fn checked_lane_id(id: &str) -> Result<()> {
137 let plain = !id.is_empty()
138 && id.len() <= 128
139 && id
140 .bytes()
141 .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_');
142 anyhow::ensure!(plain, "invalid lane id {id:?}");
143 Ok(())
144 }
145
146 /// Persist and load lane records.
147 #[derive(Debug, Clone)]
148 pub struct LaneRegistry {
149 root: PathBuf,
150 }
151
152 impl LaneRegistry {
153 /// Open the default registry under `$CODEWHALE_HOME/lanes`.
154 pub fn open_default() -> Result<Self> {
155 Self::open(lanes_dir()?)
156 }
157
158 /// Open a registry at an explicit root (tests / custom homes).
159 pub fn open(root: impl Into<PathBuf>) -> Result<Self> {
160 let root = root.into();
161 fs::create_dir_all(&root)
162 .with_context(|| format!("create lane registry {}", root.display()))?;
163 fs::create_dir_all(root.join(LOGS_SUBDIR))
164 .with_context(|| format!("create lane logs under {}", root.display()))?;
165 Ok(Self { root })
166 }
167
168 pub fn root(&self) -> &Path {
169 &self.root
170 }
171
172 pub fn logs_dir(&self) -> PathBuf {
173 self.root.join(LOGS_SUBDIR)
174 }
175
176 pub fn record_path(&self, id: &str) -> PathBuf {
177 self.root.join(format!("{id}.json"))
178 }
179
180 pub fn log_path_for(&self, id: &str) -> PathBuf {
181 self.logs_dir().join(format!("{id}.ndjson"))
182 }
183
184 pub fn save(&self, record: &LaneRecord) -> Result<()> {
185 checked_lane_id(&record.id)?;
186 let path = self.record_path(&record.id);
187 let json = serde_json::to_string_pretty(record).context("serialize lane record")?;
188 // A fresh, exclusively created temporary: a predictable name could be
189 // pre-placed as a link and written through.
190 let tmp = self.root.join(format!(
191 ".{}.{}.{}.tmp",
192 record.id,
193 std::process::id(),
194 uuid::Uuid::new_v4().simple()
195 ));
196 let written = (|| -> std::io::Result<()> {
197 use std::io::Write as _;
198 let mut options = fs::OpenOptions::new();
199 options.write(true).create_new(true);
200 #[cfg(unix)]
201 {
202 use std::os::unix::fs::OpenOptionsExt;
203 options.mode(0o600);
204 }
205 let mut file = options.open(&tmp)?;
206 file.write_all(json.as_bytes())?;
207 file.sync_all()
208 })();
209 if let Err(error) = written {
210 let _ = fs::remove_file(&tmp);
211 return Err(error).with_context(|| format!("write {}", tmp.display()));
212 }
213 if let Err(error) = fs::rename(&tmp, &path) {
214 let _ = fs::remove_file(&tmp);
215 return Err(error).with_context(|| format!("rename {}", path.display()));
216 }
217 Ok(())
218 }
219
220 pub fn load(&self, id: &str) -> Result<LaneRecord> {
221 checked_lane_id(id)?;
222 let path = self.record_path(id);
223 let text = fs::read_to_string(&path)
224 .with_context(|| format!("read lane record {}", path.display()))?;
225 serde_json::from_str(&text).with_context(|| format!("parse lane record {}", path.display()))
226 }
227
228 pub fn list(&self) -> Result<Vec<LaneRecord>> {
229 let mut records = Vec::new();
230 for entry in fs::read_dir(&self.root)
231 .with_context(|| format!("read lane registry {}", self.root.display()))?
232 {
233 let entry = entry?;
234 let path = entry.path();
235 if path.extension().and_then(|e| e.to_str()) != Some("json") {
236 continue;
237 }
238 let text =
239 fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
240 match serde_json::from_str::<LaneRecord>(&text) {
241 Ok(record) => records.push(record),
242 Err(err) => {
243 // Skip corrupt records rather than failing the whole list.
244 eprintln!(
245 "warning: skip corrupt lane record {}: {err}",
246 path.display()
247 );
248 }
249 }
250 }
251 records.sort_by(|a, b| b.started_at.cmp(&a.started_at));
252 Ok(records)
253 }
254
255 /// Create a pending lane with log file reserved.
256 pub fn create_pending(
257 &self,
258 workflow: Option<String>,
259 fleet: Option<String>,
260 issue: Option<String>,
261 goal: Option<String>,
262 runtime: RuntimeBackendKind,
263 worktree_ttl_secs: Option<u64>,
264 ) -> Result<LaneRecord> {
265 let id = LaneRecord::new_id();
266 let log_path = self.log_path_for(&id);
267 // Touch the log so `lane logs` works immediately.
268 let mut options = OpenOptions::new();
269 options.write(true).create_new(true);
270 #[cfg(unix)]
271 {
272 use std::os::unix::fs::OpenOptionsExt;
273 options.mode(0o600);
274 }
275 options
276 .open(&log_path)
277 .with_context(|| format!("create log {}", log_path.display()))?;
278 let record = LaneRecord {
279 id,
280 workflow,
281 fleet,
282 issue,
283 goal,
284 runtime,
285 status: LaneStatus::Pending,
286 lifecycle_seq: 1,
287 worktree_path: None,
288 branch: None,
289 tmux_session: None,
290 tmux_socket: None,
291 log_path,
292 started_at: LaneRecord::now_rfc3339(),
293 stopped_at: None,
294 attach_target: None,
295 worktree_ttl_secs,
296 };
297 self.save(&record)?;
298 Ok(record)
299 }
300
301 /// Record a freshly provisioned worktree on the stored Lane.
302 ///
303 /// Runs under the per-Lane lock and changes only `worktree_path` and
304 /// `branch`, so whichever terminal record a failed start or a concurrent
305 /// stop leaves behind still references the worktree.
306 pub fn persist_worktree(&self, record: &LaneRecord) -> Result<()> {
307 let lock_path = self.root.join(format!("{}.lock", record.id));
308 let lock_file = OpenOptions::new()
309 .create(true)
310 .truncate(false)
311 .read(true)
312 .write(true)
313 .open(&lock_path)
314 .with_context(|| format!("open lane lock {}", lock_path.display()))?;
315 let mut lock = fd_lock::RwLock::new(lock_file);
316 let _guard = lock
317 .write()
318 .with_context(|| format!("lock lane record {}", record.id))?;
319
320 let mut current = self.load(&record.id)?;
321 current.worktree_path = record.worktree_path.clone();
322 current.branch = record.branch.clone();
323 self.save(&current)
324 }
325
326 /// Atomically promote a Pending Lane to Running.
327 ///
328 /// A concurrent `lane stop` is allowed to win while a backend is still
329 /// launching. In that case this returns `false`, reloads the terminal
330 /// record, and the backend must tear down any process it just created.
331 pub fn mark_running_if_pending(&self, record: &mut LaneRecord) -> Result<bool> {
332 self.mark_running_if_pending_with(record, || Ok(()), || Ok(()))
333 }
334
335 /// Atomically launch backend state and promote a Pending Lane to Running.
336 ///
337 /// The per-Lane lock spans the durable Pending check, `before_transition`,
338 /// and the Running save. A concurrent stop therefore either wins before
339 /// launch (and this returns `false` without calling the closure) or waits
340 /// until the Running record is visible. Backend metadata is first saved in
341 /// the Pending record so a failed final save still leaves enough data for
342 /// a later stop. `rollback` is attempted if that final save fails.
343 pub fn mark_running_if_pending_with<Start, Rollback>(
344 &self,
345 record: &mut LaneRecord,
346 before_transition: Start,
347 rollback: Rollback,
348 ) -> Result<bool>
349 where
350 Start: FnOnce() -> Result<()>,
351 Rollback: FnOnce() -> Result<()>,
352 {
353 let lock_path = self.root.join(format!("{}.lock", record.id));
354 let lock_file = OpenOptions::new()
355 .create(true)
356 .truncate(false)
357 .read(true)
358 .write(true)
359 .open(&lock_path)
360 .with_context(|| format!("open lane lock {}", lock_path.display()))?;
361 let mut lock = fd_lock::RwLock::new(lock_file);
362 let _guard = lock
363 .write()
364 .with_context(|| format!("lock lane record {}", record.id))?;
365
366 let current = self.load(&record.id)?;
367 if current.status != LaneStatus::Pending {
368 *record = current;
369 return Ok(false);
370 }
371 record.lifecycle_seq = current.lifecycle_seq.max(1);
372
373 // `record` carries backend metadata (tmux session, worktree, attach
374 // target) populated during launch. Persist it while still Pending so
375 // a failed launch/final save remains discoverable and stoppable.
376 record.status = LaneStatus::Pending;
377 record.stopped_at = None;
378 self.save(record)?;
379
380 before_transition()?;
381 record.status = LaneStatus::Running;
382 record.lifecycle_seq = record.lifecycle_seq.saturating_add(1);
383 record.stopped_at = None;
384 if let Err(save_error) = self.save(record) {
385 record.status = LaneStatus::Pending;
386 record.lifecycle_seq = current.lifecycle_seq.max(1);
387 if let Err(rollback_error) = rollback() {
388 return Err(save_error).context(format!(
389 "persist running Lane; backend rollback also failed: {rollback_error:#}"
390 ));
391 }
392 return Err(save_error).context("persist running Lane after backend launch");
393 }
394 Ok(true)
395 }
396
397 /// Atomically transition an active Lane to a terminal state.
398 ///
399 /// Detached tmux reconciliation, an explicit stop, and a second status
400 /// reader can race in separate CLI processes. Serialize those terminal
401 /// decisions on a per-Lane advisory lock, reload the live record under the
402 /// lock, and only let the first active -> terminal transition win.
403 pub fn mark_terminal_if_active(
404 &self,
405 record: &mut LaneRecord,
406 status: LaneStatus,
407 ) -> Result<bool> {
408 self.mark_terminal_if_active_with(record, status, |_| Ok(()))
409 }
410
411 /// Atomically perform backend teardown and transition an active Lane.
412 ///
413 /// `before_transition` runs while holding the per-Lane lifecycle lock.
414 /// If teardown fails, the record remains active. This keeps a failed tmux
415 /// kill from being persisted as Stopped and prevents cleanup racing a
416 /// concurrent reconciliation decision.
417 pub fn mark_terminal_if_active_with<F>(
418 &self,
419 record: &mut LaneRecord,
420 status: LaneStatus,
421 before_transition: F,
422 ) -> Result<bool>
423 where
424 F: FnOnce(&LaneRecord) -> Result<()>,
425 {
426 self.mark_terminal_if_active_fenced(record, status, None, before_transition)
427 .map(TerminalTransition::transitioned)
428 }
429
430 /// [`mark_terminal_if_active_with`] with an optional lifecycle fence.
431 ///
432 /// `expected_lifecycle_seq` is evaluated **after** the live record is
433 /// reloaded under the per-Lane advisory lock, not by the caller before it.
434 /// A pre-lock check is a TOCTOU: another process can transition the record
435 /// between the caller's read and this write, and the caller would then act
436 /// on a generation it never observed. Checking here means a stale fence
437 /// refuses without running `before_transition`, so no backend teardown
438 /// happens for a run the caller did not actually target.
439 ///
440 /// [`mark_terminal_if_active_with`]: Self::mark_terminal_if_active_with
441 pub fn mark_terminal_if_active_fenced<F>(
442 &self,
443 record: &mut LaneRecord,
444 status: LaneStatus,
445 expected_lifecycle_seq: Option<u64>,
446 before_transition: F,
447 ) -> Result<TerminalTransition>
448 where
449 F: FnOnce(&LaneRecord) -> Result<()>,
450 {
451 if status.is_active() {
452 bail!("terminal lane transition requires a terminal status");
453 }
454
455 let lock_path = self.root.join(format!("{}.lock", record.id));
456 let lock_file = OpenOptions::new()
457 .create(true)
458 .truncate(false)
459 .read(true)
460 .write(true)
461 .open(&lock_path)
462 .with_context(|| format!("open lane lock {}", lock_path.display()))?;
463 let mut lock = fd_lock::RwLock::new(lock_file);
464 let _guard = lock
465 .write()
466 .with_context(|| format!("lock lane record {}", record.id))?;
467
468 let mut current = self.load(&record.id)?;
469 // Fence first: a mismatched generation must not run backend teardown.
470 if let Some(expected) = expected_lifecycle_seq
471 && expected != current.lifecycle_seq
472 {
473 let observed = current.lifecycle_seq;
474 *record = current;
475 return Ok(TerminalTransition::FenceMismatch { observed });
476 }
477 if !current.status.is_active() {
478 *record = current;
479 return Ok(TerminalTransition::AlreadyTerminal);
480 }
481 before_transition(&current)?;
482 current.lifecycle_seq = current.lifecycle_seq.max(1).saturating_add(1);
483 current.status = status;
484 current.stopped_at = Some(LaneRecord::now_rfc3339());
485 current.attach_target = None;
486 self.save(&current)?;
487 *record = current;
488 Ok(TerminalTransition::Transitioned)
489 }
490 }
491
492 #[cfg(test)]
493 mod tests {
494 use super::*;
495 use std::sync::atomic::{AtomicUsize, Ordering};
496 use std::sync::{Arc, mpsc};
497 use tempfile::tempdir;
498
499 #[test]
500 fn registry_persists_across_open() {
501 let dir = tempdir().unwrap();
502 let reg = LaneRegistry::open(dir.path()).unwrap();
503 let record = reg
504 .create_pending(
505 Some("stopship".into()),
506 Some("stopship".into()),
507 Some("4375".into()),
508 None,
509 RuntimeBackendKind::Tmux,
510 Some(3600),
511 )
512 .unwrap();
513 let id = record.id.clone();
514
515 let reg2 = LaneRegistry::open(dir.path()).unwrap();
516 let loaded = reg2.load(&id).unwrap();
517 assert_eq!(loaded.workflow.as_deref(), Some("stopship"));
518 assert_eq!(loaded.fleet.as_deref(), Some("stopship"));
519 assert_eq!(loaded.issue.as_deref(), Some("4375"));
520 assert_eq!(loaded.runtime, RuntimeBackendKind::Tmux);
521 assert_eq!(loaded.status, LaneStatus::Pending);
522 assert_eq!(loaded.lifecycle_seq, 1);
523 assert!(loaded.log_path.is_file() || loaded.log_path.exists());
524
525 let listed = reg2.list().unwrap();
526 assert_eq!(listed.len(), 1);
527 assert_eq!(listed[0].id, id);
528 }
529
530 #[test]
531 fn terminal_lane_cannot_launch_after_stop_wins() {
532 let dir = tempdir().unwrap();
533 let reg = LaneRegistry::open(dir.path()).unwrap();
534 let mut record = reg
535 .create_pending(None, None, None, None, RuntimeBackendKind::Tmux, None)
536 .unwrap();
537 assert!(
538 reg.mark_terminal_if_active(&mut record, LaneStatus::Stopped)
539 .unwrap()
540 );
541 let starts = AtomicUsize::new(0);
542 assert!(
543 !reg.mark_running_if_pending_with(
544 &mut record,
545 || {
546 starts.fetch_add(1, Ordering::SeqCst);
547 Ok(())
548 },
549 || Ok(()),
550 )
551 .unwrap()
552 );
553 assert_eq!(starts.load(Ordering::SeqCst), 0);
554 assert_eq!(record.status, LaneStatus::Stopped);
555 assert_eq!(record.lifecycle_seq, 2);
556 let loaded = reg.load(&record.id).unwrap();
557 assert_eq!(loaded.status, LaneStatus::Stopped);
558 assert_eq!(loaded.lifecycle_seq, 2);
559 }
560
561 #[test]
562 fn start_and_stop_are_serialized_across_backend_launch() {
563 let dir = tempdir().unwrap();
564 let reg = LaneRegistry::open(dir.path()).unwrap();
565 let record = reg
566 .create_pending(None, None, None, None, RuntimeBackendKind::Tmux, None)
567 .unwrap();
568 let id = record.id.clone();
569 let starts = Arc::new(AtomicUsize::new(0));
570 let teardowns = Arc::new(AtomicUsize::new(0));
571 let (entered_tx, entered_rx) = mpsc::channel();
572 let (release_tx, release_rx) = mpsc::channel();
573
574 let start_reg = reg.clone();
575 let start_count = Arc::clone(&starts);
576 let start_thread = std::thread::spawn(move || {
577 let mut record = record;
578 let started = start_reg
579 .mark_running_if_pending_with(
580 &mut record,
581 || {
582 start_count.fetch_add(1, Ordering::SeqCst);
583 entered_tx.send(()).unwrap();
584 release_rx.recv().unwrap();
585 Ok(())
586 },
587 || Ok(()),
588 )
589 .unwrap();
590 assert!(started);
591 });
592 entered_rx.recv().unwrap();
593
594 let stop_reg = reg.clone();
595 let stop_id = id.clone();
596 let teardown_count = Arc::clone(&teardowns);
597 let (stopped_tx, stopped_rx) = mpsc::channel();
598 let stop_thread = std::thread::spawn(move || {
599 let mut record = stop_reg.load(&stop_id).unwrap();
600 let stopped = stop_reg
601 .mark_terminal_if_active_with(&mut record, LaneStatus::Stopped, |_| {
602 teardown_count.fetch_add(1, Ordering::SeqCst);
603 Ok(())
604 })
605 .unwrap();
606 stopped_tx.send(stopped).unwrap();
607 });
608 assert!(matches!(
609 stopped_rx.try_recv(),
610 Err(mpsc::TryRecvError::Empty)
611 ));
612 release_tx.send(()).unwrap();
613 start_thread.join().unwrap();
614 assert!(stopped_rx.recv().unwrap());
615 stop_thread.join().unwrap();
616
617 assert_eq!(starts.load(Ordering::SeqCst), 1);
618 assert_eq!(teardowns.load(Ordering::SeqCst), 1);
619 let loaded = reg.load(&id).unwrap();
620 assert_eq!(loaded.status, LaneStatus::Stopped);
621 assert_eq!(
622 loaded.lifecycle_seq, 3,
623 "pending, running, and stopped are three durable owner states"
624 );
625 }
626
627 #[test]
628 fn teardown_failure_keeps_durable_lane_active() {
629 let dir = tempdir().unwrap();
630 let reg = LaneRegistry::open(dir.path()).unwrap();
631 let mut record = reg
632 .create_pending(None, None, None, None, RuntimeBackendKind::Tmux, None)
633 .unwrap();
634 assert!(reg.mark_running_if_pending(&mut record).unwrap());
635 let error = reg
636 .mark_terminal_if_active_with(&mut record, LaneStatus::Stopped, |_| {
637 bail!("backend still alive")
638 })
639 .unwrap_err();
640 assert!(error.to_string().contains("backend still alive"));
641 assert_eq!(record.status, LaneStatus::Running);
642 assert_eq!(record.lifecycle_seq, 2);
643 let loaded = reg.load(&record.id).unwrap();
644 assert_eq!(loaded.status, LaneStatus::Running);
645 assert_eq!(loaded.lifecycle_seq, 2);
646 }
647
648 #[test]
649 fn ids_that_are_not_plain_names_are_refused() {
650 let dir = tempdir().unwrap();
651 let reg = LaneRegistry::open(dir.path().join("lanes")).unwrap();
652 std::fs::write(dir.path().join("outside.json"), "{}").unwrap();
653
654 for id in ["../outside", "a/b", "", "lane 1", "lane.json"] {
655 assert!(reg.load(id).is_err(), "{id:?} must be refused");
656 }
657 let mut record = reg
658 .create_pending(None, None, None, None, RuntimeBackendKind::Tmux, None)
659 .unwrap();
660 record.id = "../outside".into();
661 assert!(reg.save(&record).is_err());
662 assert_eq!(
663 std::fs::read_to_string(dir.path().join("outside.json")).unwrap(),
664 "{}"
665 );
666 }
667
668 #[cfg(unix)]
669 #[test]
670 fn save_does_not_write_through_a_planted_temporary_link() {
671 let dir = tempdir().unwrap();
672 let reg = LaneRegistry::open(dir.path().join("lanes")).unwrap();
673 let record = reg
674 .create_pending(None, None, None, None, RuntimeBackendKind::Tmux, None)
675 .unwrap();
676 let victim = dir.path().join("victim");
677 std::fs::write(&victim, "keep").unwrap();
678 std::os::unix::fs::symlink(
679 &victim,
680 reg.record_path(&record.id).with_extension("json.tmp"),
681 )
682 .unwrap();
683
684 reg.save(&record).unwrap();
685
686 assert_eq!(std::fs::read_to_string(&victim).unwrap(), "keep");
687 assert_eq!(reg.load(&record.id).unwrap().id, record.id);
688 }
689 }
690
690 lines RUST