lash-sqlite-store 0.1.0-alpha.60

SQLite-backed session store for the lash agent runtime.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
//! SQLite-backed runtime trigger store.
//!
//! This is the durable peer of [`SqliteProcessRegistry`]: it stores trigger
//! subscriptions and append-only trigger occurrences at deployment scope,
//! outside any session database.

use super::*;

pub struct SqliteTriggerStore {
    conn: SqliteConnection,
}

impl SqliteTriggerStore {
    pub async fn open(path: &Path) -> tokio_rusqlite::Result<Self> {
        let conn = SqliteConnection::open(path).await?;
        ensure_trigger_schema(&conn).await?;
        apply_pragmas(&conn, StoreBacking::File).await?;
        Ok(Self { conn })
    }

    pub async fn memory() -> tokio_rusqlite::Result<Self> {
        let conn = SqliteConnection::open_in_memory().await?;
        ensure_trigger_schema(&conn).await?;
        apply_pragmas(&conn, StoreBacking::Memory).await?;
        Ok(Self { conn })
    }

    fn encode_json<T: serde::Serialize>(value: &T) -> Result<String, lash_core::PluginError> {
        serde_json::to_string(value).map_err(|err| {
            lash_core::PluginError::Session(format!("failed to encode trigger row: {err}"))
        })
    }

    fn decode_subscription(
        json: String,
    ) -> Result<lash_core::TriggerSubscriptionRecord, lash_core::PluginError> {
        serde_json::from_str(&json).map_err(|err| {
            lash_core::PluginError::Session(format!(
                "failed to decode trigger subscription row: {err}"
            ))
        })
    }

    fn decode_occurrence(
        json: String,
    ) -> Result<lash_core::TriggerOccurrenceRecord, lash_core::PluginError> {
        serde_json::from_str(&json).map_err(|err| {
            lash_core::PluginError::Session(format!(
                "failed to decode trigger occurrence row: {err}"
            ))
        })
    }
}

fn trigger_tx_outcome<T>(
    result: Result<T, lash_core::PluginError>,
) -> TxOutcome<Result<T, lash_core::PluginError>> {
    match result {
        Ok(value) => TxOutcome::Commit(Ok(value)),
        Err(err) => TxOutcome::Rollback(Err(err)),
    }
}

#[async_trait::async_trait]
impl lash_core::TriggerStore for SqliteTriggerStore {
    fn durability_tier(&self) -> DurabilityTier {
        DurabilityTier::Durable
    }

    async fn register_subscription(
        &self,
        draft: lash_core::TriggerSubscriptionDraft,
    ) -> Result<lash_core::TriggerSubscriptionRecord, lash_core::PluginError> {
        draft.validate()?;
        self.conn
            .write_flow(move |tx| {
                Ok(trigger_tx_outcome((|| {
                    tx.execute("INSERT INTO trigger_subscription_seq DEFAULT VALUES", [])
                        .map_err(process_sqlite_error)?;
                    let seq = tx.last_insert_rowid();
                    let handle = format!("trigger:{seq}");
                    let subscription_id = format!("subscription:{seq}");
                    let now = current_epoch_ms();
                    let record = lash_core::TriggerSubscriptionRecord {
                        subscription_id: subscription_id.clone(),
                        registrant: draft.registrant,
                        env_ref: draft.env_ref,
                        wake_target: draft.wake_target,
                        handle,
                        name: draft.name,
                        source_type: draft.source_type,
                        source_key: draft.source_key,
                        source: draft.source,
                        payload_schema: draft.payload_schema,
                        target: draft.target,
                        target_identity: draft.target_identity,
                        event_types: draft.event_types,
                        input_template: draft.input_template,
                        target_label: draft.target_label,
                        enabled: true,
                        created_at_ms: now,
                        updated_at_ms: now,
                    };
                    tx.execute(
                        "INSERT INTO trigger_subscriptions (
                            subscription_id, registrant_scope_id, handle, source_type, source_key,
                            enabled, created_at_ms, updated_at_ms, record_json
                         )
                         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
                        params![
                            record.subscription_id.as_str(),
                            record.registrant_scope_id().as_str(),
                            record.handle.as_str(),
                            record.source_type.as_str(),
                            record.source_key.as_str(),
                            i64::from(record.enabled),
                            record.created_at_ms as i64,
                            record.updated_at_ms as i64,
                            Self::encode_json(&record)?,
                        ],
                    )
                    .map_err(process_sqlite_error)?;
                    Ok(record)
                })()))
            })
            .await
            .map_err(process_sqlite_error)?
    }

    async fn list_subscriptions(
        &self,
        filter: lash_core::TriggerSubscriptionFilter,
    ) -> Result<Vec<lash_core::TriggerSubscriptionRecord>, lash_core::PluginError> {
        self.conn
            .call(move |conn| {
                Ok((|| {
                    let mut sql =
                        "SELECT subscription_id, record_json FROM trigger_subscriptions WHERE 1 = 1"
                            .to_string();
                    let mut values = Vec::<rusqlite::types::Value>::new();
                    if let Some(handle) = filter.handle.as_ref() {
                        sql.push_str(" AND handle = ?");
                        values.push(handle.clone().into());
                    }
                    if let Some(source_type) = filter.source_type.as_ref() {
                        sql.push_str(" AND source_type = ?");
                        values.push(source_type.clone().into());
                    }
                    if let Some(source_key) = filter.source_key.as_ref() {
                        sql.push_str(" AND source_key = ?");
                        values.push(source_key.clone().into());
                    }
                    if let Some(enabled) = filter.enabled {
                        sql.push_str(" AND enabled = ?");
                        values.push(i64::from(enabled).into());
                    }
                    sql.push_str(" ORDER BY registrant_scope_id ASC, handle ASC");
                    let mut stmt = conn.prepare(&sql).map_err(process_sqlite_error)?;
                    let rows = stmt
                        .query_map(rusqlite::params_from_iter(values.iter()), |row| {
                            Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
                        })
                        .map_err(process_sqlite_error)?;
                    let mut records = Vec::new();
                    for row in rows {
                        let (subscription_id, json) = row.map_err(process_sqlite_error)?;
                        let record = match Self::decode_subscription(json) {
                            Ok(record) => record,
                            Err(err) => {
                                tracing::warn!(
                                    error = %err,
                                    subscription_id,
                                    "skipping malformed trigger subscription during listing"
                                );
                                continue;
                            }
                        };
                        if filter.matches(&record) {
                            records.push(record);
                        }
                    }
                    Ok(records)
                })())
            })
            .await
            .map_err(process_sqlite_error)?
    }

    async fn cancel_subscription(
        &self,
        session_id: &str,
        handle: &str,
    ) -> Result<bool, lash_core::PluginError> {
        let session_id = session_id.to_string();
        let handle = handle.to_string();
        self.conn
            .write_flow(move |tx| {
                Ok(trigger_tx_outcome((|| {
                    let mut stmt = tx
                        .prepare(
                            "SELECT subscription_id, enabled, record_json
                             FROM trigger_subscriptions
                             WHERE handle = ?1",
                        )
                        .map_err(process_sqlite_error)?;
                    let rows = stmt
                        .query_map(params![handle.as_str()], |row| {
                            Ok((
                                row.get::<_, String>(0)?,
                                row.get::<_, i64>(1)?,
                                row.get::<_, String>(2)?,
                            ))
                        })
                        .map_err(process_sqlite_error)?;
                    let mut selected = None;
                    for row in rows {
                        let (subscription_id, enabled, json) = row.map_err(process_sqlite_error)?;
                        let record = match Self::decode_subscription(json.clone()) {
                            Ok(record) => record,
                            Err(err) => {
                                tracing::warn!(
                                    error = %err,
                                    subscription_id,
                                    handle,
                                    "skipping malformed trigger subscription during cancel"
                                );
                                continue;
                            }
                        };
                        if record.registrant_session_id() == Some(session_id.as_str()) {
                            selected = Some((subscription_id, enabled, json));
                            break;
                        }
                    }
                    let Some((subscription_id, enabled, json)) = selected else {
                        return Ok(false);
                    };
                    let changed = enabled != 0;
                    let updated_at_ms = current_epoch_ms();
                    match Self::decode_subscription(json) {
                        Ok(mut record) => {
                            record.enabled = false;
                            record.updated_at_ms = updated_at_ms;
                            tx.execute(
                                "UPDATE trigger_subscriptions
                                 SET enabled = ?3, updated_at_ms = ?4, record_json = ?5
                                 WHERE subscription_id = ?1 AND handle = ?2",
                                params![
                                    subscription_id.as_str(),
                                    handle.as_str(),
                                    i64::from(record.enabled),
                                    record.updated_at_ms as i64,
                                    Self::encode_json(&record)?,
                                ],
                            )
                            .map_err(process_sqlite_error)?;
                        }
                        Err(err) => {
                            tracing::warn!(
                                error = %err,
                                subscription_id,
                                handle,
                                "disabling malformed trigger subscription without rewriting record JSON"
                            );
                            tx.execute(
                                "UPDATE trigger_subscriptions
                                 SET enabled = ?3, updated_at_ms = ?4
                                 WHERE subscription_id = ?1 AND handle = ?2",
                                params![
                                    subscription_id.as_str(),
                                    handle.as_str(),
                                    0i64,
                                    updated_at_ms as i64,
                                ],
                            )
                            .map_err(process_sqlite_error)?;
                        }
                    }
                    Ok(changed)
                })()))
            })
            .await
            .map_err(process_sqlite_error)?
    }

    async fn delete_session_subscriptions(
        &self,
        session_id: &str,
    ) -> Result<usize, lash_core::PluginError> {
        let session_id = session_id.to_string();
        self.conn
            .write_flow(move |tx| {
                Ok(trigger_tx_outcome((|| {
                    let mut stmt = tx
                        .prepare("SELECT subscription_id, record_json FROM trigger_subscriptions")
                        .map_err(process_sqlite_error)?;
                    let rows = stmt
                        .query_map([], |row| {
                            Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
                        })
                        .map_err(process_sqlite_error)?;
                    let mut subscription_ids = Vec::new();
                    for row in rows {
                        let (subscription_id, json) = row.map_err(process_sqlite_error)?;
                        let record = match Self::decode_subscription(json) {
                            Ok(record) => record,
                            Err(err) => {
                                tracing::warn!(
                                    error = %err,
                                    subscription_id,
                                    "skipping malformed trigger subscription during session delete"
                                );
                                continue;
                            }
                        };
                        if record.registrant_session_id() == Some(session_id.as_str()) {
                            subscription_ids.push(subscription_id);
                        }
                    }
                    drop(stmt);
                    let mut deleted = 0usize;
                    for subscription_id in subscription_ids {
                        deleted = deleted.saturating_add(
                            tx.execute(
                                "DELETE FROM trigger_subscriptions WHERE subscription_id = ?1",
                                params![subscription_id.as_str()],
                            )
                            .map_err(process_sqlite_error)?,
                        );
                    }
                    Ok(deleted)
                })()))
            })
            .await
            .map_err(process_sqlite_error)?
    }

    async fn record_occurrence(
        &self,
        request: lash_core::TriggerOccurrenceRequest,
    ) -> Result<lash_core::TriggerOccurrenceRecord, lash_core::PluginError> {
        lash_core::validate_trigger_occurrence_request(&request)?;
        let request_hash = lash_core::trigger_occurrence_request_hash(&request)?;
        let occurrence_id = lash_core::deterministic_occurrence_id(&request)?;
        self.conn
            .write_flow(move |tx| {
                Ok(trigger_tx_outcome((|| {
                    let existing: Option<(String, String)> = tx
                        .query_row(
                            "SELECT request_hash, record_json
                             FROM trigger_occurrences
                             WHERE idempotency_key = ?1",
                            params![request.idempotency_key.as_str()],
                            |row| Ok((row.get(0)?, row.get(1)?)),
                        )
                        .optional()
                        .map_err(process_sqlite_error)?;
                    if let Some((existing_hash, existing_json)) = existing {
                        if existing_hash != request_hash {
                            return Err(lash_core::PluginError::Session(format!(
                                "trigger occurrence idempotency conflict for `{}`",
                                request.idempotency_key
                            )));
                        }
                        return Self::decode_occurrence(existing_json);
                    }
                    let record = lash_core::TriggerOccurrenceRecord {
                        occurrence_id: occurrence_id.clone(),
                        source_type: request.source_type,
                        source_key: request.source_key,
                        payload: request.payload,
                        idempotency_key: request.idempotency_key,
                        source: request.source,
                        occurred_at_ms: current_epoch_ms(),
                    };
                    tx.execute(
                        "INSERT INTO trigger_occurrences (
                            occurrence_id, idempotency_key, request_hash, source_type,
                            source_key, occurred_at_ms, record_json
                         )
                         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
                        params![
                            record.occurrence_id.as_str(),
                            record.idempotency_key.as_str(),
                            request_hash.as_str(),
                            record.source_type.as_str(),
                            record.source_key.as_str(),
                            record.occurred_at_ms as i64,
                            Self::encode_json(&record)?,
                        ],
                    )
                    .map_err(process_sqlite_error)?;
                    Ok(record)
                })()))
            })
            .await
            .map_err(process_sqlite_error)?
    }

    async fn reserve_matching_deliveries(
        &self,
        occurrence_id: &str,
    ) -> Result<Vec<lash_core::TriggerDeliveryReservation>, lash_core::PluginError> {
        let occurrence_id = occurrence_id.to_string();
        self.conn
            .write_flow(move |tx| {
                Ok(trigger_tx_outcome((|| {
                    let occurrence_json: Option<String> = tx
                        .query_row(
                            "SELECT record_json
                             FROM trigger_occurrences
                             WHERE occurrence_id = ?1",
                            params![occurrence_id.as_str()],
                            |row| row.get(0),
                        )
                        .optional()
                        .map_err(process_sqlite_error)?;
                    let Some(occurrence_json) = occurrence_json else {
                        return Err(lash_core::PluginError::Session(format!(
                            "unknown trigger occurrence `{occurrence_id}`"
                        )));
                    };
                    let occurrence = Self::decode_occurrence(occurrence_json)?;
                    let subscriptions = {
                        let mut stmt = tx
                            .prepare(
                                "SELECT subscription_id, record_json
                                 FROM trigger_subscriptions
                                 WHERE enabled = 1 AND source_type = ?1 AND source_key = ?2
                                 ORDER BY registrant_scope_id ASC, handle ASC",
                            )
                            .map_err(process_sqlite_error)?;
                        let rows = stmt
                            .query_map(
                                params![
                                    occurrence.source_type.as_str(),
                                    occurrence.source_key.as_str()
                                ],
                                |row| {
                                    Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
                                },
                            )
                            .map_err(process_sqlite_error)?;
                        let mut subscriptions = Vec::new();
                        for row in rows {
                            let (subscription_id, json) = row.map_err(process_sqlite_error)?;
                            match Self::decode_subscription(json) {
                                Ok(subscription) => subscriptions.push(subscription),
                                Err(err) => tracing::warn!(
                                    error = %err,
                                    subscription_id,
                                    occurrence_id = %occurrence.occurrence_id,
                                    "skipping malformed trigger subscription during delivery reservation"
                                ),
                            }
                        }
                        subscriptions
                    };
                    let mut reservations = Vec::new();
                    for subscription in subscriptions {
                        let process_id = lash_core::deterministic_delivery_process_id(
                            &occurrence.occurrence_id,
                            &subscription.subscription_id,
                        )?;
                        let inserted = tx
                            .execute(
                                "INSERT OR IGNORE INTO trigger_deliveries (
                                    occurrence_id, subscription_id, process_id, created_at_ms
                                 )
                                 VALUES (?1, ?2, ?3, ?4)",
                                params![
                                    occurrence.occurrence_id.as_str(),
                                    subscription.subscription_id.as_str(),
                                    process_id.as_str(),
                                    current_epoch_ms() as i64,
                                ],
                            )
                            .map_err(process_sqlite_error)?;
                        if inserted == 0 {
                            continue;
                        }
                        reservations.push(lash_core::TriggerDeliveryReservation {
                            occurrence: occurrence.clone(),
                            subscription,
                            process_id,
                        });
                    }
                    Ok(reservations)
                })()))
            })
            .await
            .map_err(process_sqlite_error)?
    }
}