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
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
// SPDX-License-Identifier: MIT OR Apache-2.0

use std::collections::HashSet;
use std::fmt::Display;
use std::str::FromStr;
use std::time::Duration;

use p2panda_core::cbor::{decode_cbor, encode_cbor};
use p2panda_core::{Topic, VerifyingKey};
use serde::{Deserialize, Serialize};
use sqlx::{query, query_as, query_scalar};

use crate::address_book::{AddressBookStore, NodeInfo};
use crate::sqlite::{SqliteError, SqliteStore};

impl<N> AddressBookStore<VerifyingKey, N> for SqliteStore
where
    N: NodeInfo<VerifyingKey> + Serialize + for<'de> Deserialize<'de>,
{
    type Error = SqliteError;

    async fn insert_node_info(&self, info: N) -> Result<bool, Self::Error> {
        let is_upsert = {
            let row = self
                .tx(async |tx| {
                    query_as::<_, (i32,)>("SELECT COUNT(*) FROM node_infos_v1 WHERE node_id = ?")
                        .bind(info.id().to_hex())
                        .fetch_one(&mut **tx)
                        .await
                        .map_err(SqliteError::Sqlite)
                })
                .await?;

            row.0 == 1
        };

        self.tx(async |tx| {
            query(
                "
                INSERT
                INTO
                    node_infos_v1 (
                        node_id,
                        node_info,
                        bootstrap
                    )
                VALUES
                    (?, ?, ?)
                ON CONFLICT(node_id)
                DO UPDATE
                    SET
                        node_info = EXCLUDED.node_info,
                        bootstrap = EXCLUDED.bootstrap
                ",
            )
            .bind(info.id().to_hex())
            .bind(
                encode_cbor(&info)
                    .map_err(|err| SqliteError::Encode("node_info".to_string(), err))?,
            )
            .bind(info.is_bootstrap())
            .execute(&mut **tx)
            .await
            .map_err(SqliteError::Sqlite)
        })
        .await?;

        Ok(!is_upsert)
    }

    async fn remove_node_info(&self, id: &VerifyingKey) -> Result<bool, Self::Error> {
        // Remove node's info.
        let result = self
            .tx(async |tx| {
                query(
                    "
                    DELETE FROM
                        node_infos_v1
                    WHERE
                        node_id = ?
                    ",
                )
                .bind(id.to_hex())
                .execute(&mut **tx)
                .await
                .map_err(SqliteError::Sqlite)
            })
            .await?;

        // Remove associated topics for this node.
        self.tx(async |tx| {
            query(
                "
                DELETE FROM
                    topics2node_infos_v1
                WHERE
                    node_id = ?
                ",
            )
            .bind(id.to_hex())
            .execute(&mut **tx)
            .await
            .map_err(SqliteError::Sqlite)
        })
        .await?;

        Ok(result.rows_affected() > 0)
    }

    async fn remove_older_than(&self, duration: Duration) -> Result<usize, Self::Error> {
        let result = self
            .tx(async |tx| {
                query_as::<_, (String,)>(
                    "
                    DELETE FROM
                        node_infos_v1
                    WHERE
                        updated_at < UNIXEPOCH() - ?
                    RETURNING
                        node_id
                    ",
                )
                .bind(duration.as_secs() as i64)
                .fetch_all(&mut **tx)
                .await
                .map_err(SqliteError::Sqlite)
            })
            .await?;

        let node_ids: Vec<&String> = result.iter().map(|item| &item.0).collect();

        // Remove associated topics for removed nodes.
        self.tx(async |tx| {
            query(&format!(
                "
                DELETE FROM
                    topics2node_infos_v1
                WHERE
                    node_id IN ({})
                ",
                in_op_str(&node_ids)
            ))
            .execute(&mut **tx)
            .await
            .map_err(SqliteError::Sqlite)
        })
        .await?;

        Ok(node_ids.len())
    }

    async fn node_info(&self, id: &VerifyingKey) -> Result<Option<N>, Self::Error> {
        let result = self
            .execute(async |pool| {
                query_as::<_, (Vec<u8>,)>(
                    "
                    SELECT
                        node_info
                    FROM
                        node_infos_v1
                    WHERE
                        node_id = ?
                    ",
                )
                .bind(id.to_hex())
                .fetch_optional(pool)
                .await
                .map_err(SqliteError::Sqlite)
            })
            .await?;

        decode_node_info(result)
    }

    async fn node_topics(&self, id: &VerifyingKey) -> Result<HashSet<Topic>, Self::Error> {
        let result = self
            .execute(async |pool| {
                query_as::<_, (String,)>(
                    "
                    SELECT
                        topic_id
                    FROM
                        topics2node_infos_v1
                    WHERE
                        node_id = ?
                    ",
                )
                .bind(id.to_hex())
                .fetch_all(pool)
                .await
                .map_err(SqliteError::Sqlite)
            })
            .await?;

        result
            .iter()
            .map(|item| {
                Topic::from_str(&item.0)
                    .map_err(|err| SqliteError::Decode("topic_id".to_string(), err.into()))
            })
            .collect()
    }

    async fn all_node_infos(&self) -> Result<Vec<N>, Self::Error> {
        let result = self
            .execute(async |pool| {
                query_as::<_, (Vec<u8>,)>(
                    "
                    SELECT
                        node_info
                    FROM
                        node_infos_v1
                    ",
                )
                .fetch_all(pool)
                .await
                .map_err(SqliteError::Sqlite)
            })
            .await?;

        decode_node_infos(result)
    }

    async fn all_nodes_len(&self) -> Result<usize, Self::Error> {
        let count: i64 = self
            .execute(async |pool| {
                query_scalar(
                    "
                    SELECT
                        COUNT(node_id)
                    FROM
                        node_infos_v1
                    ",
                )
                .fetch_one(pool)
                .await
                .map_err(SqliteError::Sqlite)
            })
            .await?;

        Ok(count as usize)
    }

    async fn all_bootstrap_nodes_len(&self) -> Result<usize, Self::Error> {
        let count: i64 = self
            .execute(async |pool| {
                query_scalar(
                    "
                    SELECT
                        COUNT(node_id)
                    FROM
                        node_infos_v1
                    WHERE
                        bootstrap = TRUE
                    ",
                )
                .fetch_one(pool)
                .await
                .map_err(SqliteError::Sqlite)
            })
            .await?;

        Ok(count as usize)
    }

    async fn selected_node_infos(&self, ids: &[VerifyingKey]) -> Result<Vec<N>, Self::Error> {
        let result = self
            .execute(async |pool| {
                query_as::<_, (Vec<u8>,)>(&format!(
                    "
                    SELECT
                        node_info
                    FROM
                        node_infos_v1
                    WHERE
                        node_id IN ({})
                    ",
                    in_op_str(ids)
                ))
                .fetch_all(pool)
                .await
                .map_err(SqliteError::Sqlite)
            })
            .await?;

        decode_node_infos(result)
    }

    async fn set_topics(
        &self,
        id: VerifyingKey,
        topics: HashSet<Topic>,
    ) -> Result<(), Self::Error> {
        // Remove all previous topics set for this node id and replace it with new values. Both
        // updates will be executed inside the same atomic transaction.
        self.tx(async |tx| {
            query(
                "
                DELETE FROM
                    topics2node_infos_v1
                WHERE
                    node_id = ?
                ",
            )
            .bind(id.to_hex())
            .execute(&mut **tx)
            .await
            .map_err(SqliteError::Sqlite)
        })
        .await?;

        for topic in topics {
            self.tx(async |tx| {
                query(
                    "
                    INSERT OR IGNORE
                    INTO
                        topics2node_infos_v1 (
                            node_id,
                            topic_id
                        )
                    VALUES
                        (?, ?)
                    ",
                )
                .bind(id.to_hex())
                .bind(topic.to_string())
                .execute(&mut **tx)
                .await
                .map_err(SqliteError::Sqlite)
            })
            .await?;
        }

        Ok(())
    }

    async fn node_infos_by_topics(&self, topics: &[Topic]) -> Result<Vec<N>, Self::Error> {
        let result = self
            .execute(async |pool| {
                query_as::<_, (Vec<u8>,)>(&format!(
                    "
                    SELECT
                        node_infos_v1.node_info
                    FROM
                        node_infos_v1
                    LEFT JOIN topics2node_infos_v1
                        ON node_infos_v1.node_id = topics2node_infos_v1.node_id
                    WHERE
                        topics2node_infos_v1.topic_id IN ({})
                    GROUP BY
                        node_infos_v1.node_id
                    ",
                    in_op_str(topics)
                ))
                .fetch_all(pool)
                .await
                .map_err(SqliteError::Sqlite)
            })
            .await?;

        decode_node_infos(result)
    }

    async fn random_node(&self) -> Result<Option<N>, Self::Error> {
        let result = self
            .execute(async |pool| {
                query_as::<_, (Vec<u8>,)>(
                    "
                    SELECT
                        node_info
                    FROM
                        node_infos_v1
                    ORDER BY RANDOM()
                    LIMIT 1
                    ",
                )
                .fetch_optional(pool)
                .await
                .map_err(SqliteError::Sqlite)
            })
            .await?;

        decode_node_info(result)
    }

    async fn random_bootstrap_node(&self) -> Result<Option<N>, Self::Error> {
        let result = self
            .execute(async |pool| {
                query_as::<_, (Vec<u8>,)>(
                    "
                    SELECT
                        node_info
                    FROM
                        node_infos_v1
                    WHERE
                        bootstrap = TRUE
                    ORDER BY RANDOM()
                    LIMIT 1
                    ",
                )
                .fetch_optional(pool)
                .await
                .map_err(SqliteError::Sqlite)
            })
            .await?;

        decode_node_info(result)
    }
}

#[cfg(any(test, feature = "test_utils"))]
#[doc(hidden)]
impl SqliteStore {
    pub async fn set_last_changed(
        &self,
        id: &VerifyingKey,
        timestamp: u64,
    ) -> Result<(), SqliteError> {
        self.tx(async |tx| {
            query(
                "
                UPDATE
                    node_infos_v1
                SET
                    updated_at = ?
                WHERE
                    node_id = ?
                ",
            )
            .bind(timestamp as i64)
            .bind(id.to_hex())
            .execute(&mut **tx)
            .await
            .map_err(SqliteError::Sqlite)
        })
        .await?;

        Ok(())
    }
}

/// Takes a list of items implementing `Display` to turn it into an SQL "IN" operator where each
/// item is represented as a string.
///
/// ```text
/// SELECT * FROM users
/// WHERE
///     id IN ('1a', '2b', '3c');
/// ```
fn in_op_str<T: Display>(list: &[T]) -> String {
    list.iter()
        .map(|item| format!("'{item}'"))
        .collect::<Vec<String>>()
        .join(",")
}

/// Deserialize multiple rows containing encoded node info.
fn decode_node_infos<N>(result: Vec<(Vec<u8>,)>) -> Result<Vec<N>, SqliteError>
where
    N: NodeInfo<VerifyingKey> + Serialize + for<'a> Deserialize<'a>,
{
    result
        .iter()
        .map(|item| {
            decode_cbor(&item.0[..])
                .map_err(|err| SqliteError::Decode("node_info".to_string(), err.into()))
        })
        .collect()
}

/// Deserialize single row maybe containing encoded node info.
fn decode_node_info<N>(result: Option<(Vec<u8>,)>) -> Result<Option<N>, SqliteError>
where
    N: NodeInfo<VerifyingKey> + Serialize + for<'a> Deserialize<'a>,
{
    match result {
        Some((bytes,)) => {
            Ok(Some(decode_cbor(&bytes[..]).map_err(|err| {
                SqliteError::Decode("node_info".to_string(), err.into())
            })?))
        }
        None => Ok(None),
    }
}