p2panda-store 0.6.1

Database traits and SQLite implementations for p2panda
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
// SPDX-License-Identifier: MIT OR Apache-2.0

use std::collections::HashSet;
use std::fmt::Display;
use std::hash::Hash as StdHash;
use std::str::FromStr;

use p2panda_core::Hash;
use sqlx::{query, query_as};

use crate::orderer::OrdererStore;
#[cfg(any(test, feature = "test_utils"))]
use crate::orderer::OrdererTestExt;
use crate::sqlite::{DecodeError, SqliteError, SqliteStore};

impl<ID> OrdererStore<ID> for SqliteStore
where
    ID: Eq + Ord + StdHash + Display + FromStr,
{
    type Error = SqliteError;

    async fn mark_ready(&self, id: ID) -> Result<bool, Self::Error> {
        self.tx(async |tx| {
            let queue_index = {
                let last_index: (i64,) = query_as(
                    "
                    SELECT
                        MAX(queue_index)
                    FROM
                        orderer_ready_v1
                    ",
                )
                .fetch_one(&mut **tx)
                .await?;

                // This returns "0" (default) if no rows are in the database.
                last_index.0 + 1
            };

            let in_queue = true;

            // Ignore insertion when hash already exists (UNIQUE constraint).
            let result = query(
                "
                INSERT OR IGNORE
                INTO
                    orderer_ready_v1 (
                        id,
                        queue_index,
                        in_queue
                    )
                VALUES
                    (?, ?, ?)
                ",
            )
            .bind(id.to_string())
            .bind(queue_index)
            .bind(in_queue)
            .execute(&mut **tx)
            .await?;

            // If no rows have been affected by this INSERT we know the item already exists in the
            // "ready" table.
            //
            // This means that we've tried to mark an already existing item as ready _again_ and
            // can happen when an item got re-processed by the orderer.
            //
            // Since we want the system to always behave the same and allow idempotency (and not
            // "swallow" items when they got re-processed), we check if this "ready" item is still
            // in the queue. If not, we re-queue it.
            if result.rows_affected() == 0 {
                let was_in_queue: (bool,) = query_as(
                    "
                    SELECT
                        in_queue
                    FROM
                        orderer_ready_v1
                    WHERE
                        id = ?
                    ",
                )
                .bind(id.to_string())
                .fetch_one(&mut **tx)
                .await?;

                // Do nothing when item is still in queue (waiting to be picked up).
                if was_in_queue.0 {
                    return Ok(false);
                }

                // Re-queue item otherwise with new queue index.
                query(
                    "
                    UPDATE
                        orderer_ready_v1
                    SET
                        queue_index = ?,
                        in_queue = ?
                    WHERE
                        id = ?
                    ",
                )
                .bind(queue_index)
                .bind(in_queue)
                .bind(id.to_string())
                .execute(&mut **tx)
                .await?;

                Ok(true)
            } else {
                Ok(result.rows_affected() > 0)
            }
        })
        .await
    }

    async fn mark_pending(
        &self,
        child_id: ID,
        mut parent_ids: Vec<ID>,
    ) -> Result<bool, Self::Error> {
        self.tx(async |tx| {
            let child_id = child_id.to_string();

            // Make hashing digest deterministic by sorting array first.
            parent_ids.sort();

            // Derive a hash from id (child) and all it's dependencies (parents).
            let set_digest = Hash::digest({
                let mut buf: Vec<u8> = Vec::new();
                buf.extend_from_slice(child_id.as_bytes());
                for id in &parent_ids {
                    buf.extend_from_slice(id.to_string().as_bytes());
                }
                buf
            })
            .to_string();

            let mut insertion_occured = false;

            for id in &parent_ids {
                // Ignore items which are already marked as "ready".
                let is_ready = query(
                    "
                    SELECT
                        1
                    FROM
                        orderer_ready_v1
                    WHERE
                        id = ?
                    ",
                )
                .bind(id.to_string())
                .fetch_optional(&mut **tx)
                .await?
                .is_some();

                if is_ready {
                    continue;
                }

                let id = id.to_string();

                // Insert all dependencies for this non-ready dependency key with a set digest.
                for parent_id in &parent_ids {
                    let parent_id = parent_id.to_string();

                    let result = query(
                        "
                        INSERT OR IGNORE
                        INTO
                            orderer_pending_v1 (
                                id,
                                child_id,
                                parent_id,
                                set_digest
                            )
                        VALUES
                            (?, ?, ?, ?)
                        ",
                    )
                    .bind(&id)
                    .bind(&child_id)
                    .bind(&parent_id)
                    .bind(&set_digest)
                    .execute(&mut **tx)
                    .await?;

                    if result.rows_affected() > 0 {
                        insertion_occured = true;
                    }
                }
            }

            Ok(insertion_occured)
        })
        .await
    }

    async fn get_next_pending(
        &self,
        id: ID,
    ) -> Result<Option<HashSet<(ID, Vec<ID>)>>, Self::Error> {
        self.tx(async |tx| {
            // Find all unique (child_id, set_digest) combinations that depend on the given id.
            let sets: Vec<(String, String)> = query_as(
                "
                SELECT
                    DISTINCT child_id,
                    set_digest
                FROM
                    orderer_pending_v1
                WHERE
                    id = ?
                ",
            )
            .bind(id.to_string())
            .fetch_all(&mut **tx)
            .await?;

            if sets.is_empty() {
                return Ok(None);
            }

            let mut result = HashSet::new();

            // For each set, get the complete original dependency list.
            for (child_id, set_digest) in sets {
                let parent_ids: Vec<(String,)> = query_as(
                    "
                    SELECT
                        parent_id
                    FROM
                        orderer_pending_v1
                    WHERE
                        child_id = ?
                        AND set_digest = ?
                    ORDER BY
                        parent_id
                    ",
                )
                .bind(&child_id)
                .bind(&set_digest)
                .fetch_all(&mut **tx)
                .await?;

                let child_id = ID::from_str(&child_id)
                    .map_err(|_| SqliteError::Decode("child_id".into(), DecodeError::FromStr))?;

                let mut dependencies = Vec::new();
                for (parent_id,) in parent_ids {
                    let parent_id = ID::from_str(&parent_id).map_err(|_| {
                        SqliteError::Decode("parent_id".into(), DecodeError::FromStr)
                    })?;
                    dependencies.push(parent_id);
                }

                result.insert((child_id, dependencies));
            }

            Ok(Some(result))
        })
        .await
    }

    async fn take_next_ready(&self) -> Result<Option<ID>, Self::Error> {
        self.tx(async |tx| {
            let row: Option<(String,)> = query_as(
                "
                SELECT
                    id
                FROM
                    orderer_ready_v1
                WHERE
                    in_queue = TRUE
                ORDER BY
                    queue_index ASC
                LIMIT
                    1
                ",
            )
            .fetch_optional(&mut **tx)
            .await?;

            let Some((id_str,)) = row else {
                return Ok(None);
            };

            let id = ID::from_str(&id_str)
                .map_err(|_| SqliteError::Decode("id".into(), DecodeError::FromStr))?;

            query(
                "
                UPDATE
                    orderer_ready_v1
                SET
                    in_queue = FALSE
                WHERE
                    id = ?
                ",
            )
            .bind(&id_str)
            .execute(&mut **tx)
            .await?;

            Ok(Some(id))
        })
        .await
    }

    async fn remove_pending(&self, id: ID) -> Result<bool, Self::Error> {
        self.tx(async |tx| {
            let result = query(
                "
                DELETE FROM
                    orderer_pending_v1
                WHERE
                    id = ?
                ",
            )
            .bind(id.to_string())
            .execute(&mut **tx)
            .await?;

            Ok(result.rows_affected() > 0)
        })
        .await
    }

    async fn ready(&self, dependencies: &[ID]) -> Result<bool, Self::Error> {
        self.tx(async |tx| {
            let sql = format!(
                "
                SELECT
                    COUNT(id)
                FROM
                    orderer_ready_v1
                WHERE id IN ({})
                ",
                dependencies
                    .iter()
                    .map(|dep| format!("'{dep}'"))
                    .collect::<Vec<String>>()
                    .join(",")
            );

            let result: (i64,) = query_as(&sql).fetch_one(&mut **tx).await?;
            Ok(result.0 as usize == dependencies.len())
        })
        .await
    }
}

#[cfg(any(test, feature = "test_utils"))]
impl OrdererTestExt for SqliteStore {
    async fn ready_len(&self) -> usize {
        self.tx(async |tx| {
            let row: (i64,) = query_as(
                "
                SELECT
                    COUNT(id)
                FROM
                    orderer_ready_v1
                ",
            )
            .fetch_one(&mut **tx)
            .await?;
            Ok(row.0 as usize)
        })
        .await
        .unwrap()
    }

    async fn ready_queue_len(&self) -> usize {
        self.tx(async |tx| {
            let row: (i64,) = query_as(
                "
                SELECT
                    COUNT(id)
                FROM
                    orderer_ready_v1
                WHERE
                    in_queue = TRUE
                ",
            )
            .fetch_one(&mut **tx)
            .await?;
            Ok(row.0 as usize)
        })
        .await
        .unwrap()
    }

    async fn pending_len(&self) -> usize {
        self.tx(async |tx| {
            let row: (i64,) = query_as(
                "
                SELECT
                    COUNT(DISTINCT id)
                FROM
                    orderer_pending_v1
                ",
            )
            .fetch_one(&mut **tx)
            .await?;
            Ok(row.0 as usize)
        })
        .await
        .unwrap()
    }
}