Skip to main content

stackless_core/state/
instance.rs

1//! Instance records: one name, one truth (invariant 1).
2
3use std::collections::BTreeMap;
4
5use super::error::StateError;
6use super::row::Row;
7use super::store::Store;
8use crate::types::DnsName;
9
10#[derive(Debug, Clone, PartialEq, Eq)]
11pub enum InstanceStatus {
12    Active,
13    Tombstoned,
14}
15
16impl InstanceStatus {
17    pub(super) fn from_sql(s: &str) -> Result<Self, StateError> {
18        match s {
19            "active" => Ok(Self::Active),
20            "tombstoned" => Ok(Self::Tombstoned),
21            other => Err(StateError::RowDecode {
22                column: 2,
23                detail: format!("unknown instance status {other:?}"),
24            }),
25        }
26    }
27}
28
29#[derive(Debug, Clone)]
30pub struct InstanceRecord {
31    pub name: DnsName,
32    /// Immutable for one birth; display names can be reused after teardown.
33    pub instance_id: String,
34    /// Provider namespace. Legacy instances retain their recorded name.
35    pub resource_namespace: String,
36    pub substrate: DnsName,
37    pub status: InstanceStatus,
38    /// The definition snapshot taken at creation (raw stackless.toml).
39    pub definition: String,
40    /// Recorded per-invocation `--source` pins (service โ†’ path).
41    pub source_overrides: BTreeMap<String, String>,
42    /// Whether `--dirty` was passed: snapshot source pins instead of using
43    /// them in place.
44    pub dirty: bool,
45    /// The directory the definition file came from at creation; the
46    /// sibling secrets env file resolves from here on resume.
47    pub definition_dir: String,
48    pub created_at: i64,
49    pub tombstoned_at: Option<i64>,
50}
51
52const SELECT_COLUMNS: &str = "name, substrate, status, definition, source_overrides, created_at, tombstoned_at, definition_dir, dirty, instance_id, resource_namespace";
53
54impl TryFrom<&Row> for InstanceRecord {
55    type Error = StateError;
56
57    fn try_from(row: &Row) -> Result<Self, Self::Error> {
58        let status = row.get_string(2)?;
59        let overrides_json = row.get_string(4)?;
60        let name = row.get_string(0)?;
61        let substrate = row.get_string(1)?;
62        Ok(Self {
63            name: DnsName::try_new(&name).map_err(|err| StateError::RowDecode {
64                column: 0,
65                detail: err.to_string(),
66            })?,
67            substrate: DnsName::try_new(&substrate).map_err(|err| StateError::RowDecode {
68                column: 1,
69                detail: err.to_string(),
70            })?,
71            instance_id: row.get_string(9)?,
72            resource_namespace: row.get_string(10)?,
73            status: InstanceStatus::from_sql(&status)?,
74            definition: row.get_string(3)?,
75            source_overrides: serde_json::from_str(&overrides_json).map_err(|err| {
76                StateError::RowDecode {
77                    column: 4,
78                    detail: err.to_string(),
79                }
80            })?,
81            created_at: row.get_i64(5)?,
82            tombstoned_at: row.get_opt_i64(6)?,
83            definition_dir: row.get_string(7)?,
84            dirty: row.get_i64(8)? != 0,
85        })
86    }
87}
88
89impl Store {
90    /// Create an instance record. Names are unique across substrates:
91    /// a clash is an error naming the existing substrate, not a sibling.
92    /// The UNIQUE PRIMARY KEY enforces this on both backends โ€” fleet-wide
93    /// when the remote plane is configured.
94    pub fn create_instance(
95        &self,
96        name: &str,
97        substrate: &str,
98        definition: &str,
99        source_overrides: &BTreeMap<String, String>,
100        definition_dir: &str,
101        dirty: bool,
102    ) -> Result<InstanceRecord, StateError> {
103        let overrides_json =
104            serde_json::to_string(source_overrides).unwrap_or_else(|_| "{}".into());
105        let instance_id = uuid::Uuid::new_v4().simple().to_string();
106        let namespace = format!("sl-{instance_id}");
107        let result = self.execute(
108            "INSERT INTO instances (name, substrate, status, definition, source_overrides, created_at, definition_dir, dirty, instance_id, resource_namespace)
109             VALUES (?1, ?2, 'active', ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
110            &[
111                name.into(),
112                substrate.into(),
113                definition.into(),
114                overrides_json.into(),
115                Self::now().into(),
116                definition_dir.into(),
117                i64::from(dirty).into(),
118                instance_id.into(),
119                namespace.into(),
120            ],
121        );
122        match result {
123            Ok(_) => self
124                .instance(name)?
125                .ok_or_else(|| StateError::InstanceNotFound { name: name.into() }),
126            Err(err) => {
127                // A failed insert under an existing name is the
128                // uniqueness conflict (driver-agnostic: the PRIMARY KEY
129                // rejected it on either backend). Distinguish it from a
130                // real error by re-reading.
131                if let Some(existing) = self.instance(name)? {
132                    Err(StateError::InstanceExists {
133                        name: name.into(),
134                        existing_substrate: existing.substrate.as_str().to_owned(),
135                    })
136                } else {
137                    Err(err)
138                }
139            }
140        }
141    }
142
143    pub fn instance(&self, name: &str) -> Result<Option<InstanceRecord>, StateError> {
144        self.query_row(
145            &format!("SELECT {SELECT_COLUMNS} FROM instances WHERE name = ?1"),
146            &[name.into()],
147            |row| InstanceRecord::try_from(row),
148        )
149    }
150
151    pub fn instances(&self) -> Result<Vec<InstanceRecord>, StateError> {
152        self.query_map(
153            &format!("SELECT {SELECT_COLUMNS} FROM instances ORDER BY name"),
154            &[],
155            |row| InstanceRecord::try_from(row),
156        )
157    }
158
159    /// Teardown leaves a tombstone, not amnesia (ยง2).
160    pub fn tombstone_instance(&self, name: &str) -> Result<(), StateError> {
161        let changed = self.execute(
162            "UPDATE instances SET status = 'tombstoned', tombstoned_at = ?2 WHERE name = ?1
163             AND NOT EXISTS (SELECT 1 FROM checkpoints WHERE instance = ?1)
164             AND NOT EXISTS (SELECT 1 FROM resources WHERE owner_id = instances.instance_id AND phase != 'absent')",
165            &[name.into(), Self::now().into()],
166        )?;
167        if changed == 0 {
168            return Err(if self.instance(name)?.is_none() {
169                StateError::InstanceNotFound { name: name.into() }
170            } else {
171                StateError::ResourceInvariant {
172                    detail: format!(
173                        "instance {name:?} still has teardown evidence or is not eligible for this transition"
174                    ),
175                }
176            });
177        }
178        Ok(())
179    }
180
181    /// `up` on a tombstone is a fresh birth under the old name: new
182    /// definition snapshot, active status, empty journal.
183    pub fn revive_instance(
184        &self,
185        name: &str,
186        definition: &str,
187        source_overrides: &BTreeMap<String, String>,
188        dirty: bool,
189    ) -> Result<(), StateError> {
190        let overrides_json =
191            serde_json::to_string(source_overrides).unwrap_or_else(|_| "{}".into());
192        let instance_id = uuid::Uuid::new_v4().simple().to_string();
193        let namespace = format!("sl-{instance_id}");
194        let changed = self.execute(
195            "UPDATE instances SET status = 'active', definition = ?2, source_overrides = ?3,
196             created_at = ?4, tombstoned_at = NULL, dirty = ?5, instance_id = ?6, resource_namespace = ?7 WHERE name = ?1 AND status = 'tombstoned'
197             AND NOT EXISTS (SELECT 1 FROM checkpoints WHERE instance = ?1)
198             AND NOT EXISTS (SELECT 1 FROM resources WHERE owner_id = instances.instance_id AND phase != 'absent')",
199            &[
200                name.into(),
201                definition.into(),
202                overrides_json.into(),
203                Self::now().into(),
204                i64::from(dirty).into(),
205                instance_id.into(),
206                namespace.into(),
207            ],
208        )?;
209        if changed == 0 {
210            return Err(if self.instance(name)?.is_none() {
211                StateError::InstanceNotFound { name: name.into() }
212            } else {
213                StateError::ResourceInvariant {
214                    detail: format!(
215                        "instance {name:?} still has teardown evidence or is not eligible for this transition"
216                    ),
217                }
218            });
219        }
220        Ok(())
221    }
222
223    /// Record per-invocation overrides on resume (an explicit, recorded
224    /// choice โ€” never ambient discovery).
225    pub fn update_source_overrides(
226        &self,
227        name: &str,
228        source_overrides: &BTreeMap<String, String>,
229    ) -> Result<(), StateError> {
230        let overrides_json =
231            serde_json::to_string(source_overrides).unwrap_or_else(|_| "{}".into());
232        self.execute(
233            "UPDATE instances SET source_overrides = ?2 WHERE name = ?1",
234            &[name.into(), overrides_json.into()],
235        )?;
236        Ok(())
237    }
238
239    /// Record per-invocation dirty mode on resume.
240    pub fn update_dirty(&self, name: &str, dirty: bool) -> Result<(), StateError> {
241        self.execute(
242            "UPDATE instances SET dirty = ?2 WHERE name = ?1",
243            &[name.into(), i64::from(dirty).into()],
244        )?;
245        Ok(())
246    }
247}