1#[cfg(any(windows, test))]
21mod acl;
22mod db;
23mod fs;
24mod lock;
25
26use std::path::{Path, PathBuf};
27use std::sync::Arc;
28
29use serde::{Deserialize, Serialize};
30
31#[cfg(test)]
32pub(crate) use db::dead_pid;
33pub use db::{
34 CopyName, Ended, EventCursor, EventPage, Lease, LeaseOutcome, Lifetime, MIRROR_FILE, NewResource, NotPerCopy, OperationId, OperationRow, Outcome, Owner,
35 PortReservation, Recovered, Reserver, ResourceId, ResourceKind, ResourceRow, ResourceState, RunRow, Scope, Store, Tx,
36};
37pub(crate) use fs::{create_private, if_there, private_dir, remove_path, write_private};
38
39pub(crate) fn create_dir(dir: &Path) -> Result<()> {
42 private_dir(dir).map_err(Error::io(dir, "created"))
43}
44
45pub(crate) fn write(path: &Path, contents: &[u8]) -> Result<()> {
48 write_private(path, contents).map_err(Error::io(path, "written"))
49}
50
51pub(crate) fn remove(path: &Path) -> Result<()> {
54 remove_path(path).map_err(Error::io(path, "removed"))
55}
56
57pub(crate) fn read_json<T: serde::de::DeserializeOwned + Default>(path: &Path) -> Result<T> {
60 match if_there(std::fs::read_to_string(path)).map_err(Error::io(path, "read"))? {
61 Some(text) => serde_json::from_str(&text).map_err(|e| Error::io(path, "read")(std::io::Error::new(std::io::ErrorKind::InvalidData, e))),
62 None => Ok(T::default()),
63 }
64}
65
66pub(crate) fn write_json<T: Serialize>(path: &Path, value: &T) -> Result<()> {
68 if let Some(dir) = path.parent() {
69 create_dir(dir)?;
70 }
71 let json = serde_json::to_string(value).map_err(|e| Error::io(path, "written")(std::io::Error::other(e)))?;
72 write(path, json.as_bytes())
73}
74pub(crate) use lock::{RunLocks, hold};
75
76use crate::Result;
77use crate::error::{Error, ErrorCode};
78use crate::events::EventLog;
79use crate::name::RunName;
80use crate::project::Format;
81use crate::project::platform::{Cloud, Provider};
82use crate::state::{Desired, Op, Park, RunState};
83use crate::status::MachineStatus;
84
85const RECORD_VERSION: u32 = 0;
87
88const LOCK_FILE: &str = "lock";
90
91pub(crate) const EVENTS_KEPT: usize = 4000;
93
94#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
96#[non_exhaustive]
97pub struct LastOp {
98 pub op: Op,
100 pub ok: bool,
102 #[serde(default, skip_serializing_if = "Option::is_none")]
104 pub code: Option<ErrorCode>,
105 pub at: String,
107}
108
109impl LastOp {
110 pub(crate) fn ended(op: Op, code: Option<ErrorCode>, at: String) -> LastOp {
113 LastOp {
114 op,
115 ok: code.is_none(),
116 code,
117 at,
118 }
119 }
120}
121
122#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
124#[non_exhaustive]
125pub struct RunRecord {
126 pub version: u32,
128 pub name: RunName,
130 #[serde(alias = "manifest")]
133 pub project: PathBuf,
134 #[serde(alias = "driver")]
136 pub format: Format,
137 #[serde(default, skip_serializing_if = "Option::is_none")]
139 pub cloud: Option<Cloud>,
140 #[serde(default, skip_serializing_if = "Option::is_none")]
142 pub provider: Option<Provider>,
143 #[serde(default, skip_serializing_if = "Option::is_none")]
145 pub docker_context: Option<String>,
146 #[serde(default, skip_serializing_if = "Option::is_none")]
148 pub host_label: Option<String>,
149 pub state: RunState,
151 #[serde(default, skip_serializing_if = "Option::is_none")]
154 pub parked: Option<Park>,
155 #[serde(default, skip_serializing_if = "Option::is_none")]
157 pub started_at: Option<String>,
158 #[serde(default, skip_serializing_if = "Option::is_none")]
161 pub expires_at: Option<u64>,
162 #[serde(default, skip_serializing_if = "Option::is_none")]
164 pub last: Option<LastOp>,
165 #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
170 pub env: std::collections::BTreeMap<String, String>,
171}
172
173impl RunRecord {
174 #[must_use]
178 pub fn expired(&self, now: std::time::SystemTime) -> bool {
179 let now = crate::clock::unix_seconds(now);
180 self.state != RunState::Absent && self.expires_at.is_some_and(|at| at <= now)
181 }
182
183 pub(crate) fn fresh(name: RunName, project: PathBuf, format: Format) -> RunRecord {
185 RunRecord {
186 version: RECORD_VERSION,
187 name,
188 project,
189 format,
190 cloud: None,
191 provider: None,
192 docker_context: None,
193 host_label: None,
194 state: RunState::Absent,
195 parked: None,
196 started_at: None,
197 expires_at: None,
198 last: None,
199 env: std::collections::BTreeMap::new(),
200 }
201 }
202}
203
204#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
208#[non_exhaustive]
209pub struct LastObserved {
210 pub machines: Vec<MachineStatus>,
212}
213
214#[derive(Debug, Clone)]
216pub(crate) struct Home {
217 runs: PathBuf,
218 db: Arc<Store>,
220}
221
222impl Home {
223 pub(crate) fn open(home: &Path, profile: Option<&Path>) -> Result<Home> {
226 fs::private_home(home, profile).map_err(Error::io(home, "made owner-only"))?;
227 let runs = home.join("runs");
228 create_dir(&runs)?;
229 let db = Arc::new(Store::open(home)?);
230 Ok(Home { runs, db })
231 }
232
233 pub(crate) fn run_dir(&self, name: &RunName) -> Result<PathBuf> {
235 let dir = self.run_dir_path(name);
236 create_dir(&dir)?;
237 Ok(dir)
238 }
239
240 pub(crate) fn run_dir_path(&self, name: &RunName) -> PathBuf {
242 self.runs.join(name.as_str())
243 }
244
245 pub(crate) fn lock_path(&self, name: &RunName) -> PathBuf {
247 self.run_dir_path(name).join(LOCK_FILE)
248 }
249
250 pub(crate) fn db(&self) -> &Arc<Store> {
252 &self.db
253 }
254
255 pub(crate) fn record(&self, name: &RunName) -> Result<Option<RunRecord>> {
257 Ok(self.db.read(|tx| tx.run(name))?.map(|r| r.record))
258 }
259
260 pub(crate) fn save(&self, record: &RunRecord) -> Result<()> {
263 self.run_dir(&record.name)?;
264 self.db.write(|tx| tx.save_record(record, Desired::Running))
265 }
266
267 pub(crate) fn save_adopted(&self, record: &RunRecord) -> Result<()> {
270 self.run_dir(&record.name)?;
271 self.db.write(|tx| {
272 tx.save_record(record, Desired::Running)?;
273 if let Some(row) = tx.run(&record.name)?
274 && row.state != RunState::Ready
275 {
276 tx.apply(&record.name, crate::state::Transition::adopted(row.state)?)?;
277 }
278 Ok(())
279 })
280 }
281
282 pub(crate) fn records(&self) -> Result<Vec<RunRecord>> {
284 self.db.read(|tx| tx.runs().map(|rows| rows.into_iter().map(|r| r.record).collect()))
285 }
286
287 pub(crate) fn trim_event_log(&self, name: &RunName) -> Result<()> {
289 self.db.write(|tx| {
290 let (events, unreadable) = tx.events_after(EventCursor::default(), Some(name), EVENTS_KEPT + 1)?;
291 if events.len() + unreadable > EVENTS_KEPT {
292 tx.trim_events(name, EVENTS_KEPT / 2)?;
293 }
294 Ok(())
295 })
296 }
297
298 pub(crate) fn events(&self, name: &RunName) -> Result<EventLog> {
301 let (events, unreadable) = self.db.read(|tx| tx.events_after(EventCursor::default(), Some(name), usize::MAX))?;
302 Ok(EventLog {
303 events: events.into_iter().map(|(_, e)| e).collect(),
304 unreadable,
305 })
306 }
307}
308
309#[cfg(test)]
310mod tests {
311 use super::*;
312
313 fn record(name: &str) -> RunRecord {
314 RunRecord::fresh(RunName::new(name).unwrap(), "/work/x".into(), Format::Compose)
315 }
316
317 #[test]
318 fn records_are_kept_per_run_and_listed_by_name() {
319 let home = tempfile::tempdir().unwrap();
320 let store = Home::open(home.path(), None).unwrap();
321 assert_eq!(store.record(&RunName::new("b").unwrap()).unwrap(), None);
322 let mut b = record("b");
323 b.host_label = Some("server".into());
324 store.save(&b).unwrap();
325 store.save(&record("a")).unwrap();
326 let names: Vec<String> = store.records().unwrap().iter().map(|r| r.name.to_string()).collect();
327 assert_eq!(names, ["a", "b"]);
328 assert_eq!(store.record(&b.name).unwrap(), Some(b));
329 }
330}