Skip to main content

stackless_core/state/
resource.rs

1//! Durable resource inventory. Intent precedes creation; absence ends ownership.
2
3use serde::{Deserialize, Serialize};
4
5use super::row::Row;
6use super::{Checkpoint, StateError, Store};
7
8/// Instance-scoped resources outlive every step resource.
9pub const INSTANCE_RESOURCE_STEP: &str = "";
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
12#[serde(rename_all = "snake_case")]
13pub enum Ownership {
14    Owned,
15    Borrowed,
16    Shared,
17}
18
19impl Ownership {
20    fn as_str(self) -> &'static str {
21        match self {
22            Self::Owned => "owned",
23            Self::Borrowed => "borrowed",
24            Self::Shared => "shared",
25        }
26    }
27}
28
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
30#[serde(rename_all = "snake_case")]
31pub enum ResourcePhase {
32    Intent,
33    Created,
34    Ready,
35    Absent,
36}
37
38#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
39pub struct ResourceRecord {
40    pub owner_id: String,
41    pub key: String,
42    pub step_id: String,
43    pub provider: String,
44    pub ownership: Ownership,
45    pub phase: ResourcePhase,
46    pub resource_kind: String,
47    pub resource_id: String,
48    /// Provider recovery context. Contains credentials; never a public result.
49    #[serde(skip_serializing)]
50    pub payload: String,
51    pub created_at: i64,
52    pub updated_at: i64,
53    pub dependencies: Vec<String>,
54}
55
56impl ResourceRecord {
57    pub fn checkpoint(&self, instance: &str) -> Checkpoint {
58        Checkpoint {
59            instance: instance.into(),
60            step_id: self.step_id.clone(),
61            resource_kind: self.resource_kind.clone(),
62            resource_id: self.resource_id.clone(),
63            payload: self.payload.clone(),
64            recorded_at: self.updated_at,
65        }
66    }
67
68    fn from_row(row: &Row) -> Result<Self, StateError> {
69        let ownership = match row.get_string(4)?.as_str() {
70            "owned" => Ownership::Owned,
71            "borrowed" => Ownership::Borrowed,
72            "shared" => Ownership::Shared,
73            other => {
74                return Err(StateError::ResourceInvariant {
75                    detail: format!("unknown ownership {other:?}"),
76                });
77            }
78        };
79        let phase = match row.get_string(5)?.as_str() {
80            "intent" => ResourcePhase::Intent,
81            "created" => ResourcePhase::Created,
82            "ready" => ResourcePhase::Ready,
83            "absent" => ResourcePhase::Absent,
84            other => {
85                return Err(StateError::ResourceInvariant {
86                    detail: format!("unknown resource phase {other:?}"),
87                });
88            }
89        };
90        Ok(Self {
91            owner_id: row.get_string(0)?,
92            key: row.get_string(1)?,
93            step_id: row.get_string(2)?,
94            provider: row.get_string(3)?,
95            ownership,
96            phase,
97            resource_kind: row.get_string(6)?,
98            resource_id: row.get_string(7)?,
99            payload: row.get_string(8)?,
100            created_at: row.get_i64(9)?,
101            updated_at: row.get_i64(10)?,
102            dependencies: serde_json::from_str(&row.get_string(11)?).map_err(|_| {
103                StateError::ResourceInvariant {
104                    detail: "unreadable resource dependencies".into(),
105                }
106            })?,
107        })
108    }
109}
110
111#[derive(Debug)]
112pub struct ResourceIntent<'a> {
113    pub owner_id: &'a str,
114    pub key: &'a str,
115    pub step_id: &'a str,
116    pub provider: &'a str,
117    pub ownership: Ownership,
118    pub resource_kind: &'a str,
119    /// Exact provider lookup key or idempotency key, known before creation.
120    pub resource_id: &'a str,
121    pub payload: &'a str,
122    pub dependencies: &'a [&'a str],
123}
124
125impl Store {
126    /// Persist before creating anything. A retry returns the original recovery
127    /// context, so a changed request cannot hide an unfinished creation.
128    pub fn resource_intent(
129        &self,
130        intent: ResourceIntent<'_>,
131    ) -> Result<ResourceRecord, StateError> {
132        for parent in intent.dependencies {
133            if *parent == intent.key || self.resource(intent.owner_id, parent)?.is_none() {
134                return Err(StateError::ResourceInvariant {
135                    detail: format!(
136                        "resource {:?} requires a prior parent intent {:?}",
137                        intent.key, parent
138                    ),
139                });
140            }
141        }
142        self.execute(
143            "INSERT INTO resources (owner_id, resource_key, step_id, provider, ownership, phase,
144             resource_kind, resource_id, payload, created_at, updated_at, dependencies)
145             SELECT ?1, ?2, ?3, ?4, ?5, 'intent', ?6, ?7, ?8, ?9, ?9, ?10
146             WHERE EXISTS (SELECT 1 FROM instances WHERE instance_id = ?1 AND status = 'active')
147             ON CONFLICT(owner_id, resource_key) DO NOTHING",
148            &[
149                intent.owner_id.into(),
150                intent.key.into(),
151                intent.step_id.into(),
152                intent.provider.into(),
153                intent.ownership.as_str().into(),
154                intent.resource_kind.into(),
155                intent.resource_id.into(),
156                intent.payload.into(),
157                Self::now().into(),
158                serde_json::to_string(intent.dependencies)
159                    .map_err(|_| StateError::ResourceInvariant {
160                        detail: "cannot encode resource dependencies".into(),
161                    })?
162                    .into(),
163            ],
164        )?;
165        let record = self.resource(intent.owner_id, intent.key)?.ok_or_else(|| {
166            StateError::ResourceInvariant {
167                detail: format!("owner {} is not active", intent.owner_id),
168            }
169        })?;
170        if record.dependencies != intent.dependencies
171            || record.provider != intent.provider
172            || record.ownership != intent.ownership
173            || record.step_id != intent.step_id
174            || record.resource_kind != intent.resource_kind
175        {
176            return Err(StateError::ResourceInvariant {
177                detail: format!(
178                    "resource key {:?} already has a different owner contract",
179                    intent.key
180                ),
181            });
182        }
183        Ok(record)
184    }
185
186    /// Persist submission state while the create result is still unknown.
187    pub fn resource_intent_payload(
188        &self,
189        owner: &str,
190        key: &str,
191        payload: &str,
192    ) -> Result<(), StateError> {
193        self.remember_payload_secrets(owner, payload)?;
194        self.resource_transition(
195            "UPDATE resources SET payload = ?3, updated_at = ?4 WHERE owner_id = ?1 AND resource_key = ?2 AND phase = 'intent'",
196            &[owner.into(), key.into(), payload.into(), Self::now().into()], key,
197        )
198    }
199
200    /// Save the returned handle before configuring, deploying, or waiting.
201    pub fn resource_created(
202        &self,
203        owner: &str,
204        key: &str,
205        id: &str,
206        payload: &str,
207    ) -> Result<(), StateError> {
208        self.remember_payload_secrets(owner, payload)?;
209        self.resource_transition(
210            "UPDATE resources SET phase = 'created', resource_id = ?3, payload = ?4, updated_at = ?5
211             WHERE owner_id = ?1 AND resource_key = ?2 AND (phase = 'intent' OR (phase = 'created' AND resource_id = ?3))",
212            &[owner.into(), key.into(), id.into(), payload.into(), Self::now().into()], key,
213        )
214    }
215
216    /// Refresh credentials or recovery handles without changing the resource's phase.
217    pub fn resource_refresh_payload(
218        &self,
219        owner: &str,
220        key: &str,
221        id: &str,
222        payload: &str,
223    ) -> Result<(), StateError> {
224        self.remember_payload_secrets(owner, payload)?;
225        self.resource_transition(
226            "UPDATE resources SET payload = ?4, updated_at = ?5 WHERE owner_id = ?1 AND resource_key = ?2 AND resource_id = ?3 AND phase IN ('created', 'ready')",
227            &[owner.into(), key.into(), id.into(), payload.into(), Self::now().into()], key,
228        )
229    }
230
231    /// Recreate only after the previous resource was independently observed absent.
232    pub fn resource_rearm(
233        &self,
234        owner: &str,
235        key: &str,
236        id: &str,
237        payload: &str,
238    ) -> Result<(), StateError> {
239        self.resource_transition(
240            "UPDATE resources SET phase = 'intent', resource_id = ?3, payload = ?4, updated_at = ?5
241             WHERE owner_id = ?1 AND resource_key = ?2 AND phase = 'absent'",
242            &[
243                owner.into(),
244                key.into(),
245                id.into(),
246                payload.into(),
247                Self::now().into(),
248            ],
249            key,
250        )
251    }
252
253    pub fn resource_ready(&self, owner: &str, key: &str) -> Result<(), StateError> {
254        self.resource_transition(
255            "UPDATE resources SET phase = 'ready', updated_at = ?3 WHERE owner_id = ?1 AND resource_key = ?2
256             AND phase IN ('created', 'ready')",
257            &[owner.into(), key.into(), Self::now().into()], key,
258        )
259    }
260
261    /// Only call after verified absence or release of a borrowed/shared reference.
262    pub fn resource_absent(&self, owner: &str, key: &str) -> Result<(), StateError> {
263        self.resource_transition(
264            "UPDATE resources SET phase = 'absent', updated_at = ?3 WHERE owner_id = ?1 AND resource_key = ?2",
265            &[owner.into(), key.into(), Self::now().into()], key,
266        )
267    }
268
269    fn resource_transition(
270        &self,
271        sql: &str,
272        params: &[super::value::Value],
273        key: &str,
274    ) -> Result<(), StateError> {
275        if self.execute(sql, params)? != 1 {
276            return Err(StateError::ResourceInvariant {
277                detail: format!("invalid transition for resource {key:?}"),
278            });
279        }
280        Ok(())
281    }
282
283    pub fn resources(&self, owner: &str) -> Result<Vec<ResourceRecord>, StateError> {
284        self.query_map(
285            "SELECT owner_id, resource_key, step_id, provider, ownership, phase,
286            resource_kind, resource_id, payload, created_at, updated_at, dependencies
287            FROM resources WHERE owner_id = ?1 ORDER BY rowid",
288            &[owner.into()],
289            ResourceRecord::from_row,
290        )
291    }
292
293    pub fn resource(&self, owner: &str, key: &str) -> Result<Option<ResourceRecord>, StateError> {
294        self.query_row(
295            "SELECT owner_id, resource_key, step_id, provider, ownership, phase,
296            resource_kind, resource_id, payload, created_at, updated_at, dependencies
297            FROM resources WHERE owner_id = ?1 AND resource_key = ?2",
298            &[owner.into(), key.into()],
299            ResourceRecord::from_row,
300        )
301    }
302}