holochain_data 0.7.0-rc.0

Database abstraction layer for Holochain using sqlx
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
//! Free-standing operations against the `ScheduledFunction` table.

use holo_hash::AgentPubKey;
use holochain_timestamp::Timestamp;
use sqlx::{Executor, Sqlite};

/// Parameters for inserting (or upserting) a row into `ScheduledFunction`.
pub struct InsertScheduledFunction<'a> {
    /// Agent that owns this scheduled function.
    pub author: &'a AgentPubKey,
    /// Name of the zome containing the scheduled function.
    pub zome_name: &'a str,
    /// Name of the scheduled function within the zome.
    pub scheduled_fn: &'a str,
    /// Serialized `Option<Schedule>` blob for `maybe_schedule`.
    pub maybe_schedule: &'a [u8],
    /// Microsecond timestamp at which the function becomes live.
    pub start_at: Timestamp,
    /// Microsecond timestamp at which the function expires.
    pub end_at: Timestamp,
    /// `true` if the row is removed once the function fires.
    pub ephemeral: bool,
}

/// Upsert a scheduled-function row, updating existing fields when the
/// `(author, zome_name, scheduled_fn)` primary key already exists.
/// Returns the number of rows written (1 on insert or update, 0 on no-op).
pub(crate) async fn upsert_scheduled_function<'a, 'e, E>(
    executor: E,
    f: InsertScheduledFunction<'a>,
) -> sqlx::Result<u64>
where
    E: Executor<'e, Database = Sqlite>,
{
    let result = sqlx::query(
        "INSERT INTO ScheduledFunction
            (author, zome_name, scheduled_fn, maybe_schedule, start_at, end_at, ephemeral)
         VALUES (?, ?, ?, ?, ?, ?, ?)
         ON CONFLICT(author, zome_name, scheduled_fn) DO UPDATE SET
             maybe_schedule = excluded.maybe_schedule,
             start_at       = excluded.start_at,
             end_at         = excluded.end_at,
             ephemeral      = excluded.ephemeral",
    )
    .bind(f.author.get_raw_36())
    .bind(f.zome_name)
    .bind(f.scheduled_fn)
    .bind(f.maybe_schedule)
    .bind(f.start_at.as_micros())
    .bind(f.end_at.as_micros())
    .bind(f.ephemeral as i64)
    .execute(executor)
    .await?;
    Ok(result.rows_affected())
}

/// Delete the scheduled-function row for the given `(author, zome_name, scheduled_fn)` tuple.
///
/// Returns the number of rows deleted (0 if the row did not exist).
pub(crate) async fn delete_scheduled_function<'e, E>(
    executor: E,
    author: &AgentPubKey,
    zome_name: &str,
    scheduled_fn: &str,
) -> sqlx::Result<u64>
where
    E: Executor<'e, Database = Sqlite>,
{
    let result = sqlx::query(
        "DELETE FROM ScheduledFunction
         WHERE author = ? AND zome_name = ? AND scheduled_fn = ?",
    )
    .bind(author.get_raw_36())
    .bind(zome_name)
    .bind(scheduled_fn)
    .execute(executor)
    .await?;
    Ok(result.rows_affected())
}

/// Return persisted (non-ephemeral) scheduled-function rows for `author` whose
/// `end_at` is before `now`, as `(zome_name, scheduled_fn, maybe_schedule_blob)` tuples.
pub(crate) async fn get_expired_persisted_scheduled_functions<'e, E>(
    executor: E,
    author: &AgentPubKey,
    now: Timestamp,
) -> sqlx::Result<Vec<(String, String, Vec<u8>)>>
where
    E: Executor<'e, Database = Sqlite>,
{
    #[derive(sqlx::FromRow)]
    struct Row {
        zome_name: String,
        scheduled_fn: String,
        maybe_schedule: Vec<u8>,
    }

    let rows: Vec<Row> = sqlx::query_as(
        "SELECT zome_name, scheduled_fn, maybe_schedule
         FROM ScheduledFunction
         WHERE ephemeral = 0 AND author = ? AND end_at < ?",
    )
    .bind(author.get_raw_36())
    .bind(now.as_micros())
    .fetch_all(executor)
    .await?;

    Ok(rows
        .into_iter()
        .map(|r| (r.zome_name, r.scheduled_fn, r.maybe_schedule))
        .collect())
}

/// Return live scheduled-function rows for `author` where `now` falls between
/// `start_at` and `end_at` (inclusive on both sides): `start <= now AND now <= end`.
///
/// Returns `(zome_name, scheduled_fn, maybe_schedule_blob, ephemeral)` tuples,
/// ordered by `start_at ASC`.
pub(crate) async fn get_live_scheduled_functions<'e, E>(
    executor: E,
    author: &AgentPubKey,
    now: Timestamp,
) -> sqlx::Result<Vec<(String, String, Vec<u8>, bool)>>
where
    E: Executor<'e, Database = Sqlite>,
{
    #[derive(sqlx::FromRow)]
    struct Row {
        zome_name: String,
        scheduled_fn: String,
        maybe_schedule: Vec<u8>,
        ephemeral: i64,
    }

    let rows: Vec<Row> = sqlx::query_as(
        "SELECT zome_name, scheduled_fn, maybe_schedule, ephemeral
         FROM ScheduledFunction
         WHERE author = ? AND start_at <= ? AND ? <= end_at
         ORDER BY start_at ASC",
    )
    .bind(author.get_raw_36())
    .bind(now.as_micros())
    .bind(now.as_micros())
    .fetch_all(executor)
    .await?;

    Ok(rows
        .into_iter()
        .map(|r| {
            (
                r.zome_name,
                r.scheduled_fn,
                r.maybe_schedule,
                r.ephemeral != 0,
            )
        })
        .collect())
}

/// Delete all live ephemeral scheduled-function rows for `author` whose
/// `start_at` is at or before `now`. Returns the number of rows deleted.
pub(crate) async fn delete_live_ephemeral_scheduled_functions<'e, E>(
    executor: E,
    author: &AgentPubKey,
    now: Timestamp,
) -> sqlx::Result<u64>
where
    E: Executor<'e, Database = Sqlite>,
{
    let result = sqlx::query(
        "DELETE FROM ScheduledFunction
         WHERE ephemeral = 1 AND author = ? AND start_at <= ?",
    )
    .bind(author.get_raw_36())
    .bind(now.as_micros())
    .execute(executor)
    .await?;
    Ok(result.rows_affected())
}

/// Delete every ephemeral scheduled-function row in the store, regardless of
/// author or liveness. Returns the number of rows deleted.
///
/// Used at conductor startup to clear ephemeral schedules left over from a
/// previous run — ephemeral schedules do not survive a reboot.
pub(crate) async fn delete_all_ephemeral_scheduled_functions<'e, E>(
    executor: E,
) -> sqlx::Result<u64>
where
    E: Executor<'e, Database = Sqlite>,
{
    let result = sqlx::query("DELETE FROM ScheduledFunction WHERE ephemeral = 1")
        .execute(executor)
        .await?;
    Ok(result.rows_affected())
}

/// Return `true` if a scheduled-function row exists for the given
/// `(author, zome_name, scheduled_fn)` tuple, regardless of liveness — i.e.
/// whether `now` falls within the row's `[start_at, end_at]` window.
pub(crate) async fn is_function_scheduled<'e, E>(
    executor: E,
    author: &AgentPubKey,
    zome_name: &str,
    scheduled_fn: &str,
) -> sqlx::Result<bool>
where
    E: Executor<'e, Database = Sqlite>,
{
    let row: (i64,) = sqlx::query_as(
        "SELECT EXISTS (
            SELECT 1 FROM ScheduledFunction
            WHERE author = ? AND zome_name = ? AND scheduled_fn = ?
         )",
    )
    .bind(author.get_raw_36())
    .bind(zome_name)
    .bind(scheduled_fn)
    .fetch_one(executor)
    .await?;
    Ok(row.0 != 0)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::kind::Dht;
    use crate::test_open_db;
    use holo_hash::DnaHash;
    use std::sync::Arc;

    fn dht_id() -> Dht {
        Dht::new(Arc::new(DnaHash::from_raw_36(vec![0u8; 36])))
    }

    fn agent(seed: u8) -> AgentPubKey {
        AgentPubKey::from_raw_36(vec![seed; 36])
    }

    #[tokio::test]
    async fn insert_upsert_delete_scheduled_function() {
        let db = test_open_db(dht_id()).await.unwrap();
        let author = agent(1);
        let payload = b"schedule-blob";

        // Initial insert.
        db.upsert_scheduled_function(InsertScheduledFunction {
            author: &author,
            zome_name: "z",
            scheduled_fn: "f",
            maybe_schedule: payload,
            start_at: Timestamp::from_micros(100),
            end_at: Timestamp::from_micros(200),
            ephemeral: true,
        })
        .await
        .unwrap();

        // Same key — the upsert clause should replace the row, not error
        // with a PK conflict.
        db.upsert_scheduled_function(InsertScheduledFunction {
            author: &author,
            zome_name: "z",
            scheduled_fn: "f",
            maybe_schedule: payload,
            start_at: Timestamp::from_micros(150),
            end_at: Timestamp::from_micros(250),
            ephemeral: false,
        })
        .await
        .unwrap();

        db.delete_scheduled_function(&author, "z", "f")
            .await
            .unwrap();

        // Re-insert succeeds, confirming delete removed the row.
        db.upsert_scheduled_function(InsertScheduledFunction {
            author: &author,
            zome_name: "z",
            scheduled_fn: "f",
            maybe_schedule: payload,
            start_at: Timestamp::from_micros(100),
            end_at: Timestamp::from_micros(200),
            ephemeral: true,
        })
        .await
        .unwrap();
    }

    #[tokio::test]
    async fn expired_persisted_scoped_to_author() {
        let db = test_open_db(dht_id()).await.unwrap();
        let alice = agent(1);
        let bob = agent(2);
        let payload = b"";

        let now_time = Timestamp::from_micros(200);

        // Alice: persisted, expired (end_at=100, now=200).
        db.upsert_scheduled_function(InsertScheduledFunction {
            author: &alice,
            zome_name: "z",
            scheduled_fn: "f",
            maybe_schedule: payload,
            start_at: Timestamp::from_micros(50),
            end_at: Timestamp::from_micros(100),
            ephemeral: false,
        })
        .await
        .unwrap();

        // Alice: persisted, not yet expired (end_at=300, now=200).
        db.upsert_scheduled_function(InsertScheduledFunction {
            author: &alice,
            zome_name: "z",
            scheduled_fn: "g",
            maybe_schedule: payload,
            start_at: Timestamp::from_micros(50),
            end_at: Timestamp::from_micros(300),
            ephemeral: false,
        })
        .await
        .unwrap();

        // Alice: ephemeral, "expired" (must NOT be returned — query is non-ephemeral only).
        db.upsert_scheduled_function(InsertScheduledFunction {
            author: &alice,
            zome_name: "z",
            scheduled_fn: "e",
            maybe_schedule: payload,
            start_at: Timestamp::from_micros(50),
            end_at: Timestamp::from_micros(100),
            ephemeral: true,
        })
        .await
        .unwrap();

        // Bob: persisted, expired but different author (must NOT be returned).
        db.upsert_scheduled_function(InsertScheduledFunction {
            author: &bob,
            zome_name: "z",
            scheduled_fn: "f",
            maybe_schedule: payload,
            start_at: Timestamp::from_micros(50),
            end_at: Timestamp::from_micros(100),
            ephemeral: false,
        })
        .await
        .unwrap();

        let result = db
            .as_ref()
            .get_expired_persisted_scheduled_functions(&alice, now_time)
            .await
            .unwrap();
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].0, "z");
        assert_eq!(result[0].1, "f");
    }

    #[tokio::test]
    async fn delete_live_ephemeral_scoped_to_author_and_now() {
        let db = test_open_db(dht_id()).await.unwrap();
        let alice = agent(1);
        let bob = agent(2);
        let payload = b"";

        // Alice: ephemeral start_at=100 (eligible at now=150).
        db.upsert_scheduled_function(InsertScheduledFunction {
            author: &alice,
            zome_name: "z",
            scheduled_fn: "f",
            maybe_schedule: payload,
            start_at: Timestamp::from_micros(100),
            end_at: Timestamp::from_micros(300),
            ephemeral: true,
        })
        .await
        .unwrap();
        // Alice: non-ephemeral (must NOT be deleted).
        db.upsert_scheduled_function(InsertScheduledFunction {
            author: &alice,
            zome_name: "z",
            scheduled_fn: "g",
            maybe_schedule: payload,
            start_at: Timestamp::from_micros(100),
            end_at: Timestamp::from_micros(300),
            ephemeral: false,
        })
        .await
        .unwrap();
        // Bob: ephemeral but different author (must NOT be deleted).
        db.upsert_scheduled_function(InsertScheduledFunction {
            author: &bob,
            zome_name: "z",
            scheduled_fn: "f",
            maybe_schedule: payload,
            start_at: Timestamp::from_micros(100),
            end_at: Timestamp::from_micros(300),
            ephemeral: true,
        })
        .await
        .unwrap();

        db.delete_live_ephemeral_scheduled_functions(&alice, Timestamp::from_micros(150))
            .await
            .unwrap();

        // Spot-check by re-inserting Alice's ephemeral row to confirm it was
        // gone (otherwise PK conflict would error).
        db.upsert_scheduled_function(InsertScheduledFunction {
            author: &alice,
            zome_name: "z",
            scheduled_fn: "f",
            maybe_schedule: payload,
            start_at: Timestamp::from_micros(100),
            end_at: Timestamp::from_micros(300),
            ephemeral: true,
        })
        .await
        .unwrap();
    }
}