Skip to main content

isothrum_runner/store/db/
rows.rs

1//! What the store's tables hold, as the store hands them out.
2
3use std::fmt;
4use std::path::PathBuf;
5
6use crate::project::platform::Protocol;
7use serde::{Deserialize, Serialize};
8
9use super::owner::Owner;
10use crate::error::ErrorCode;
11use crate::name::RunName;
12use crate::state::{Desired, Op, RunState};
13use crate::store::{LastObserved, RunRecord};
14
15/// An operation's id: the journal's key, increasing in a home and never reused.
16#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, schemars::JsonSchema)]
17#[serde(transparent)]
18pub struct OperationId(pub i64);
19
20/// A resource row's id.
21#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, schemars::JsonSchema)]
22#[serde(transparent)]
23pub struct ResourceId(pub i64);
24
25/// An event's place in the home's event table, increasing across every run: a subscriber resumes
26/// after the last one it saw.
27#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, schemars::JsonSchema)]
28#[serde(transparent)]
29pub struct EventCursor(pub u64);
30
31impl fmt::Display for OperationId {
32    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33        write!(f, "#{}", self.0)
34    }
35}
36
37/// A page of the event table ([`super::Tx::events_page`]).
38#[derive(Debug, Clone, PartialEq)]
39#[non_exhaustive]
40pub struct EventPage {
41    /// The events it read, oldest first, each with its cursor.
42    pub events: Vec<(EventCursor, crate::events::Event)>,
43    /// How many of its rows weren't an event this runner reads (another version's kind).
44    pub unreadable: usize,
45    /// The cursor of the last row it scanned, read or not: where the next page starts.
46    pub last: EventCursor,
47}
48
49/// A run, as the store keeps it.
50#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
51#[non_exhaustive]
52pub struct RunRow {
53    /// The run's name.
54    pub name: RunName,
55    /// The project folder it was last brought up or updated from.
56    pub project: PathBuf,
57    /// The digest of that project's files ([`crate::Project::digest`]); empty when it wasn't
58    /// read (an import, a run that never set it).
59    pub source_digest: String,
60    /// What the user wants of it.
61    pub desired: Desired,
62    /// Where it stands.
63    pub state: RunState,
64    /// Why it failed, when `state` is `failed`.
65    pub failed_cause: Option<ErrorCode>,
66    /// The operation whose transition put it there; none after an observation or an import.
67    pub state_op: Option<OperationId>,
68    /// When it got there.
69    pub state_at: String,
70    /// The rest the runner keeps about it (its `state` is this row's).
71    pub record: RunRecord,
72    /// What the runner last saw of it, when it read it.
73    pub observed: Option<LastObserved>,
74    /// When it last saw it.
75    pub observed_at: Option<String>,
76}
77
78impl RunRow {
79    /// Whether the run stands where the user wants it.
80    #[must_use]
81    pub fn converged(&self) -> bool {
82        self.desired.met_by() == self.state
83    }
84}
85
86/// How an operation ended.
87#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
88#[serde(rename_all = "snake_case")]
89#[non_exhaustive]
90pub enum Outcome {
91    /// It reached its end without an error.
92    Succeeded,
93    /// It failed.
94    Failed,
95    /// It was cut short (an embedder's cancel, Ctrl-C).
96    Cancelled,
97    /// Its process died before it ended: a later operation found it and closed it.
98    Abandoned,
99}
100
101/// An operation's end.
102#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
103#[non_exhaustive]
104pub struct Ended {
105    /// When.
106    pub at: String,
107    /// How.
108    pub outcome: Outcome,
109    /// Its error's code, when it failed.
110    pub code: Option<ErrorCode>,
111}
112
113/// An operation of the journal.
114#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
115#[non_exhaustive]
116pub struct OperationRow {
117    /// Its id.
118    pub id: OperationId,
119    /// Its run.
120    pub run: RunName,
121    /// What it is.
122    pub op: Op,
123    /// When it was queued (journaled).
124    pub queued_at: String,
125    /// When it started; none while it waits in a queue.
126    pub started_at: Option<String>,
127    /// Its end; none while it runs, or when its process died before it ended.
128    pub ended: Option<Ended>,
129    /// Whether a cancel was asked for.
130    pub cancel_requested: bool,
131    /// The process that runs it.
132    pub owner: Owner,
133    /// The operation this one recovered, when it found one unfinished.
134    pub resumed_from: Option<OperationId>,
135}
136
137/// Whose a resource is: the provider's (made by a manifest step) or the runner's own, on this
138/// computer.
139#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
140#[serde(rename_all = "snake_case")]
141#[non_exhaustive]
142pub enum Scope {
143    /// Made by a manifest step: a VM, a container, a network, a volume, a module's resource.
144    Provider,
145    /// A file or process the runner keeps for the run on this computer.
146    Local,
147}
148
149/// What a resource is. The provider kinds are manifest v2's `resources[].kind`; the local ones
150/// the runner's own.
151#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
152#[serde(rename_all = "snake_case")]
153#[non_exhaustive]
154pub enum ResourceKind {
155    /// A virtual machine.
156    Vm,
157    /// A container.
158    Container,
159    /// A network.
160    Network,
161    /// A volume.
162    Volume,
163    /// A hub (a Docker host VM several runs share).
164    Hub,
165    /// A process a step leaves running.
166    Process,
167    /// A Terraform module's resources, as one.
168    Module,
169    /// The machines' SSH host keys this computer trusts.
170    HostKeys,
171    /// The files the run's tools keep in its state folder.
172    StateFiles,
173    /// The run's outputs archive.
174    Archive,
175    /// The graphical consoles the runner chose.
176    Consoles,
177    /// A tool process an operation runs.
178    ToolProcess,
179}
180
181impl ResourceKind {
182    /// Whose a resource of this kind is.
183    #[must_use]
184    pub fn scope(self) -> Scope {
185        match self {
186            ResourceKind::Vm
187            | ResourceKind::Container
188            | ResourceKind::Network
189            | ResourceKind::Volume
190            | ResourceKind::Hub
191            | ResourceKind::Process
192            | ResourceKind::Module => Scope::Provider,
193            ResourceKind::HostKeys | ResourceKind::StateFiles | ResourceKind::Archive | ResourceKind::Consoles | ResourceKind::ToolProcess => Scope::Local,
194        }
195    }
196
197    /// The lifetime a local kind always has (host keys go with the machines that made them,
198    /// the rest with the run); none for a provider kind, whose manifest says.
199    #[must_use]
200    pub fn lifetime(self) -> Option<Lifetime> {
201        match self.scope() {
202            Scope::Provider => None,
203            Scope::Local if self == ResourceKind::HostKeys => Some(Lifetime::Machines),
204            Scope::Local => Some(Lifetime::Run),
205        }
206    }
207}
208
209/// Where a resource stands, written ahead of the provider's call.
210#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
211#[serde(rename_all = "snake_case")]
212#[non_exhaustive]
213pub enum ResourceState {
214    /// Written before the call that makes it: it may or may not exist.
215    Creating,
216    /// The provider made it, with this id.
217    Created,
218    /// Written before the call that removes it.
219    Destroying,
220    /// Removed, or found missing.
221    Gone,
222}
223
224/// What a resource's life is tied to.
225#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
226#[serde(rename_all = "snake_case")]
227#[non_exhaustive]
228pub enum Lifetime {
229    /// The run's machines: a machine made again makes it stale (a cleared start forgets it).
230    Machines,
231    /// The run: only its `down` removes it.
232    Run,
233}
234
235/// A provider resource's name on the host, rendered with the run's per-copy key (`${run.key}`):
236/// the only name a recovery looks a resource up by, so it never matches another copy's.
237#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, schemars::JsonSchema)]
238#[serde(transparent)]
239pub struct CopyName(String);
240
241impl CopyName {
242    /// `rendered`, a name the manifest's template gave with the run's key `key` filled in.
243    ///
244    /// # Errors
245    ///
246    /// `rendered` doesn't hold `key` (a bare manifest name, shared by every copy), or `key` is
247    /// empty.
248    pub fn rendered(rendered: impl Into<String>, key: &str) -> Result<CopyName, NotPerCopy> {
249        let rendered = rendered.into();
250        if key.is_empty() || !rendered.contains(key) {
251            return Err(NotPerCopy { name: rendered });
252        }
253        Ok(CopyName(rendered))
254    }
255
256    /// A name the store wrote, checked when it was.
257    pub(crate) fn stored(name: String) -> CopyName {
258        CopyName(name)
259    }
260
261    /// The name.
262    #[must_use]
263    pub fn as_str(&self) -> &str {
264        &self.0
265    }
266}
267
268/// A name with no per-copy key in it: another copy of the run could have it.
269#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
270#[error("`{name}` doesn't hold the run's key: another copy could have it")]
271pub struct NotPerCopy {
272    /// The name.
273    pub name: String,
274}
275
276/// A resource the run made or keeps.
277#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
278#[non_exhaustive]
279pub struct ResourceRow {
280    /// Its id.
281    pub id: ResourceId,
282    /// Its run.
283    pub run: RunName,
284    /// The manifest resource's key, or the local thing's.
285    pub key: String,
286    /// What it is.
287    pub kind: ResourceKind,
288    /// Whose it is.
289    pub scope: Scope,
290    /// Its name on the host, for a provider resource: what a recovery finds a `creating` one by.
291    pub copy_name: Option<CopyName>,
292    /// The provider's id for it (for a local one, its path); none while `creating`.
293    pub native_id: Option<String>,
294    /// Where it stands.
295    pub state: ResourceState,
296    /// What its life is tied to.
297    pub lifetime: Lifetime,
298    /// The operation that made it.
299    pub created_by: OperationId,
300    /// The operation that removes or removed it.
301    pub destroyed_by: Option<OperationId>,
302    /// What removing it needs besides its id.
303    pub detail: Option<serde_json::Value>,
304}
305
306/// A resource about to be made: written, as `creating`, before the call that makes it.
307#[derive(Debug, Clone)]
308#[non_exhaustive]
309pub struct NewResource<'a> {
310    /// Its run.
311    pub run: &'a RunName,
312    /// Its key.
313    pub key: &'a str,
314    /// What it is.
315    pub kind: ResourceKind,
316    /// Its name on the host (provider resources).
317    pub copy_name: Option<CopyName>,
318    /// Its lifetime, for a provider kind (a local kind's is its own: [`ResourceKind::lifetime`]).
319    pub lifetime: Option<Lifetime>,
320    /// The operation making it.
321    pub by: OperationId,
322    /// What removing it will need besides its id.
323    pub detail: Option<serde_json::Value>,
324}
325
326impl<'a> NewResource<'a> {
327    /// A resource of `kind`, keyed `key`, of `run`, made by `by`.
328    #[must_use]
329    pub fn new(run: &'a RunName, key: &'a str, kind: ResourceKind, by: OperationId) -> NewResource<'a> {
330        NewResource {
331            run,
332            key,
333            kind,
334            copy_name: None,
335            lifetime: None,
336            by,
337            detail: None,
338        }
339    }
340
341    /// Named `name` on the host.
342    #[must_use]
343    pub fn named(mut self, name: CopyName) -> NewResource<'a> {
344        self.copy_name = Some(name);
345        self
346    }
347
348    /// With lifetime `lifetime` (a provider kind's, from its manifest).
349    #[must_use]
350    pub fn living(mut self, lifetime: Lifetime) -> NewResource<'a> {
351        self.lifetime = Some(lifetime);
352        self
353    }
354
355    /// With `detail`.
356    #[must_use]
357    pub fn with_detail(mut self, detail: serde_json::Value) -> NewResource<'a> {
358        self.detail = Some(detail);
359        self
360    }
361}
362
363/// A scope held by a process for a while.
364#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
365#[non_exhaustive]
366pub struct Lease {
367    /// What it holds (`run:<name>`, `home:slots`, `home:service`).
368    pub scope: String,
369    /// Who holds it.
370    pub owner: Owner,
371    /// Since when.
372    pub acquired_at: String,
373    /// Until when, in seconds since the Unix epoch, unless renewed.
374    pub expires_at: u64,
375}
376
377/// What asking for a lease gave.
378#[derive(Debug, Clone, PartialEq, Eq)]
379#[non_exhaustive]
380pub enum LeaseOutcome {
381    /// Taken; `took_over` is the lease a dead or expired holder left.
382    Acquired {
383        /// The lease taken over, if one was.
384        took_over: Option<Lease>,
385    },
386    /// A live owner holds it.
387    Held(Lease),
388}
389
390/// A host port a run's operation holds while it starts.
391#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
392#[non_exhaustive]
393pub struct PortReservation {
394    /// The port, on the host.
395    pub port: crate::port::HostPort,
396    /// Its protocol.
397    pub protocol: Protocol,
398    /// The run.
399    pub run: RunName,
400    /// The operation holding it, when it was journaled.
401    pub operation: Option<OperationId>,
402}