holochain_p2p 0.7.0-dev.21

holochain specific wrapper around more generic p2p module
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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
use bytes::Bytes;
use futures::future::BoxFuture;
use holo_hash::{DhtOpHash, DnaHash, OpBasis};
use holochain_serialized_bytes::prelude::decode;
use holochain_sqlite::db::{DbKindCache, DbKindDht, DbWrite, ReadAccess};
use holochain_sqlite::rusqlite::types::Value;
use holochain_sqlite::sql::sql_dht::{
    CHECK_OP_IDS_PRESENT, EARLIEST_TIMESTAMP, OPS_BY_ID, OP_HASHES_IN_TIME_SLICE,
    OP_HASHES_SINCE_TIME_BATCH, TOTAL_OP_COUNT,
};
use holochain_state::prelude::{named_params, StateMutationResult};
use holochain_types::dht_op::DhtOpHashed;
use holochain_types::prelude::DhtOp;
use kitsune2_api::*;
use std::collections::HashSet;
use std::fmt::{Debug, Formatter};
use std::rc::Rc;
use std::sync::Arc;

/// Holochain implementation of the Kitsune2 [OpStoreFactory].
pub struct HolochainOpStoreFactory {
    /// The database connection getter.
    pub getter: crate::GetDbOpStore,
    /// The cache database connection getter.
    pub cache_getter: crate::GetDbCache,
    /// The event handler.
    pub handler: Arc<std::sync::OnceLock<crate::spawn::WrapEvtSender>>,
}

impl std::fmt::Debug for HolochainOpStoreFactory {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("HolochainOpStoreFactory").finish()
    }
}

impl kitsune2_api::OpStoreFactory for HolochainOpStoreFactory {
    fn default_config(&self, _config: &mut kitsune2_api::Config) -> kitsune2_api::K2Result<()> {
        Ok(())
    }

    fn validate_config(&self, _config: &kitsune2_api::Config) -> kitsune2_api::K2Result<()> {
        Ok(())
    }

    fn create(
        &self,
        _builder: Arc<kitsune2_api::Builder>,
        space: kitsune2_api::SpaceId,
    ) -> BoxFut<'static, kitsune2_api::K2Result<kitsune2_api::DynOpStore>> {
        let getter = self.getter.clone();
        let cache_getter = self.cache_getter.clone();
        let handler = self.handler.clone();
        Box::pin(async move {
            let dna_hash = DnaHash::from_k2_space(&space);
            let db = getter(dna_hash.clone()).await.map_err(|err| {
                kitsune2_api::K2Error::other_src("failed to get op_store db", err)
            })?;
            let cache_db = cache_getter(dna_hash.clone())
                .await
                .map_err(|err| kitsune2_api::K2Error::other_src("failed to get cache db", err))?;
            let op_store: kitsune2_api::DynOpStore =
                Arc::new(HolochainOpStore::new(db, cache_db, dna_hash, handler));

            Ok(op_store)
        })
    }
}

/// Holochain implementation of the Kitsune2 [OpStore].
pub struct HolochainOpStore {
    db: DbWrite<DbKindDht>,
    cache_db: DbWrite<DbKindCache>,
    dna_hash: DnaHash,
    sender: Arc<std::sync::OnceLock<crate::spawn::WrapEvtSender>>,
}

impl Debug for HolochainOpStore {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("HolochainOpStore")
            .field("db", &self.db)
            .field("cache_db", &self.cache_db)
            .finish()
    }
}

impl HolochainOpStore {
    /// Create a new [HolochainOpStore].
    pub fn new(
        db: DbWrite<DbKindDht>,
        cache_db: DbWrite<DbKindCache>,
        dna_hash: DnaHash,
        sender: Arc<std::sync::OnceLock<crate::spawn::WrapEvtSender>>,
    ) -> HolochainOpStore {
        Self {
            db,
            cache_db,
            dna_hash,
            sender,
        }
    }
}

impl OpStore for HolochainOpStore {
    fn process_incoming_ops(&self, op_list: Vec<Bytes>) -> BoxFut<'_, K2Result<Vec<OpId>>> {
        Box::pin(async move {
            let mut dht_ops = Vec::with_capacity(op_list.len());
            let mut ids = Vec::with_capacity(op_list.len());
            for op_bytes in op_list {
                let op = decode::<_, DhtOp>(&op_bytes)
                    .map_err(|e| K2Error::other_src("Could not decode op", e))?;
                let op_hashed = DhtOpHashed::from_content_sync(op.clone());
                ids.push(op_hashed.hash.to_located_k2_op_id(&op.dht_basis()));
                dht_ops.push(op);
            }

            use crate::types::event::HcP2pHandler;
            self.sender
                .get()
                .ok_or_else(|| K2Error::other("event handler not registered"))?
                .handle_publish(self.dna_hash.clone(), dht_ops)
                .await
                .map_err(|e| K2Error::other_src("Failed to publish incoming ops", e))?;

            Ok(ids)
        })
    }

    fn retrieve_op_hashes_in_time_slice(
        &self,
        arc: DhtArc,
        start: Timestamp,
        end: Timestamp,
    ) -> BoxFuture<'_, K2Result<(Vec<OpId>, u32)>> {
        let db = self.db.clone();

        let (arc_start, arc_end) = match arc {
            DhtArc::Empty => {
                return Box::pin(async move { Ok((vec![], 0)) });
            }
            DhtArc::Arc(start, end) => (start, end),
        };

        Box::pin(async move {
            let out = db
                .read_async(move |txn| -> StateMutationResult<(Vec<OpId>, u32)> {
                    let mut stmt = txn.prepare(OP_HASHES_IN_TIME_SLICE)?;

                    let mut rows = stmt.query(named_params! {
                        ":storage_start_loc": arc_start,
                        ":storage_end_loc": arc_end,
                        ":timestamp_min": start.as_micros(),
                        ":timestamp_max": end.as_micros(),
                    })?;

                    let mut out = Vec::new();
                    let mut out_size = 0;
                    while let Some(row) = rows.next()? {
                        let hash: DhtOpHash = row.get(0)?;
                        let op_basis: OpBasis = row.get(1)?;
                        let serialized_size: u32 = row.get(2)?;

                        let op_id = hash.to_located_k2_op_id(&op_basis);
                        out.push(op_id);
                        out_size += serialized_size;
                    }

                    Ok((out, out_size))
                })
                .await
                .map_err(|e| K2Error::other_src("Failed to retrieve op hashes in time slice", e))?;

            Ok(out)
        })
    }

    /// Retrieve a list of ops by their op ids.
    ///
    /// This should be used to get op data for ops.
    fn retrieve_ops(&self, op_ids: Vec<OpId>) -> BoxFuture<'_, K2Result<Vec<MetaOp>>> {
        let db = self.db.clone();

        Box::pin(async move {
            let out = db
                .read_async(move |txn| -> StateMutationResult<Vec<MetaOp>> {
                    let mut stmt = txn.prepare(OPS_BY_ID)?;

                    let mut rows = stmt.query([Rc::new(
                        op_ids
                            .iter()
                            .filter_map(|id| match DhtOpHash::try_from_k2_op(id) {
                                Ok(hash) => Some(Value::from(hash.into_inner())),
                                Err(e) => {
                                    tracing::warn!("Cannot retrieve op for invalid op id: {e}");
                                    None
                                }
                            })
                            .collect::<Vec<_>>(),
                    )])?;

                    let mut out = Vec::new();
                    while let Some(row) = rows.next()? {
                        let hash: DhtOpHash = row.get(0)?;
                        let op_basis: OpBasis = row.get(1)?;
                        let dht_op = holochain_state::query::map_sql_dht_op(false, "type", row)?;

                        out.push(MetaOp {
                            op_id: hash.to_located_k2_op_id(&op_basis),
                            op_data: holochain_serialized_bytes::prelude::encode(&dht_op)?.into(),
                        });
                    }

                    Ok(out)
                })
                .await
                .map_err(|e| K2Error::other_src("Failed to retrieve ops", e))?;

            Ok(out)
        })
    }

    fn filter_out_existing_ops(&self, op_ids: Vec<OpId>) -> BoxFuture<'_, K2Result<Vec<OpId>>> {
        let db = self.db.clone();

        Box::pin(async move {
            let out = db
                .read_async(move |txn| -> StateMutationResult<Vec<OpId>> {
                    let mut out = op_ids.clone().into_iter().collect::<HashSet<_>>();

                    let mut stmt = txn.prepare(CHECK_OP_IDS_PRESENT)?;

                    let mut rows = stmt.query([Rc::new(
                        op_ids
                            .iter()
                            .filter_map(|id| match DhtOpHash::try_from_k2_op(id) {
                                Ok(hash) => Some(Value::from(hash.into_inner())),
                                Err(e) => {
                                    tracing::warn!("Got invalid op id: {e}");
                                    out.remove(id);
                                    None
                                }
                            })
                            .collect::<Vec<_>>(),
                    )])?;

                    while let Some(row) = rows.next()? {
                        let op_hash: DhtOpHash = row.get(0)?;
                        let op_basis: OpBasis = row.get(1)?;
                        out.remove(&op_hash.to_located_k2_op_id(&op_basis));
                    }

                    Ok(out.into_iter().collect())
                })
                .await
                .map_err(|e| K2Error::other_src("Failed to filter out existing ops", e))?;

            Ok(out)
        })
    }

    fn retrieve_op_ids_bounded(
        &self,
        arc: DhtArc,
        start: Timestamp,
        limit_bytes: u32,
    ) -> BoxFuture<'_, K2Result<(Vec<OpId>, u32, Timestamp)>> {
        let db = self.db.clone();

        let (arc_start, arc_end) = match arc {
            DhtArc::Empty => {
                return Box::pin(async move { Ok((vec![], 0, start)) });
            }
            DhtArc::Arc(start, end) => (start, end),
        };

        Box::pin(async move {
            let out = db
                .read_async(
                    move |txn| -> StateMutationResult<(Vec<OpId>, u32, Timestamp)> {
                        let mut used_bytes = 0;
                        let mut latest_timestamp = start;
                        let mut out = HashSet::new();

                        'outer: loop {
                            let mut stmt = txn.prepare(OP_HASHES_SINCE_TIME_BATCH)?;
                            let mut rows = match stmt.query(named_params! {
                                ":storage_start_loc": arc_start,
                                ":storage_end_loc": arc_end,
                                ":timestamp_min": latest_timestamp.as_micros(),
                                // Fetch ops in batches of 500. This lets us observe the `limit_bytes`
                                // without going to the database too many times.
                                // Because the timestamp being queried is the integration timestamp,
                                // it shouldn't be possible for >500 ops authored at the same time
                                // to prevent this loop from proceeding.
                                ":limit": 500,
                            }) {
                                Ok(rows) => rows,
                                Err(e) => return Err(e.into()),
                            };

                            let ops_size = out.len();

                            while let Some(row) = rows.next()? {
                                let hash: DhtOpHash = row.get(0)?;
                                let op_basis: OpBasis = row.get(1)?;
                                let timestamp = Timestamp::from_micros(row.get::<_, i64>(2)?);
                                let serialized_size: u32 = row.get(3)?;

                                if used_bytes + serialized_size > limit_bytes {
                                    break 'outer;
                                }

                                let op_id = hash.to_located_k2_op_id(&op_basis);
                                if out.insert(op_id) {
                                    latest_timestamp = timestamp;
                                    used_bytes += serialized_size;
                                }
                            }

                            // If we didn't discover any new ops, break
                            if out.len() == ops_size {
                                break;
                            }
                        }

                        Ok((out.into_iter().collect(), used_bytes, latest_timestamp))
                    },
                )
                .await
                .map_err(|e| K2Error::other_src("Failed to retrieve op ids bounded", e))?;

            Ok(out)
        })
    }

    fn earliest_timestamp_in_arc(&self, arc: DhtArc) -> BoxFuture<'_, K2Result<Option<Timestamp>>> {
        let db = self.db.clone();

        let (arc_start, arc_end) = match arc {
            DhtArc::Empty => {
                return Box::pin(async move { Ok(None) });
            }
            DhtArc::Arc(start, end) => (start, end),
        };

        Box::pin(async move {
            db.read_async(move |txn| -> StateMutationResult<Option<Timestamp>> {
                let mut stmt = txn.prepare(EARLIEST_TIMESTAMP)?;

                Ok(stmt
                    .query_row(
                        named_params! {
                            ":storage_start_loc": arc_start,
                            ":storage_end_loc": arc_end,
                        },
                        |row| row.get::<_, Option<i64>>(0),
                    )?
                    .map(Timestamp::from_micros))
            })
            .await
            .map_err(|e| K2Error::other_src("Failed to retrieve earliest timestamp in arc", e))
        })
    }

    fn query_total_op_count(&self) -> BoxFuture<'_, K2Result<u64>> {
        let db = self.db.clone();
        let cache_db = self.cache_db.clone();

        Box::pin(async move {
            let dht_count = db
                .read_async(move |txn| -> StateMutationResult<u64> {
                    Ok(txn.query_row(TOTAL_OP_COUNT, [], |row| row.get(0))?)
                })
                .await
                .map_err(|e| K2Error::other_src("Failed to query total op count from dht", e))?;

            let cache_count = cache_db
                .read_async(move |txn| -> StateMutationResult<u64> {
                    Ok(txn.query_row(TOTAL_OP_COUNT, [], |row| row.get(0))?)
                })
                .await
                .map_err(|e| K2Error::other_src("Failed to query total op count from cache", e))?;

            Ok(dht_count + cache_count)
        })
    }

    fn store_slice_hash(
        &self,
        arc: DhtArc,
        slice_index: u64,
        slice_hash: Bytes,
    ) -> BoxFuture<'_, K2Result<()>> {
        let db = self.db.clone();

        let (arc_start, arc_end) = match arc {
            DhtArc::Empty => {
                return Box::pin(async move { Ok(()) });
            }
            DhtArc::Arc(start, end) => (start, end),
        };

        Box::pin(async move {
            db.write_async(move |txn| -> StateMutationResult<()> {
                let mut stmt = txn.prepare(
                    r#"INSERT INTO SliceHash
                (arc_start, arc_end, slice_index, hash)
                VALUES (:arc_start, :arc_end, :slice_index, :hash)"#,
                )?;

                stmt.execute(named_params! {
                    ":arc_start": arc_start,
                    ":arc_end": arc_end,
                    ":slice_index": slice_index,
                    ":hash": slice_hash.to_vec(),
                })?;

                Ok(())
            })
            .await
            .map_err(|e| K2Error::other_src("Failed to store slice hash", e))?;

            Ok(())
        })
    }

    fn slice_hash_count(&self, arc: DhtArc) -> BoxFuture<'_, K2Result<u64>> {
        let db = self.db.clone();

        let (arc_start, arc_end) = match arc {
            DhtArc::Empty => {
                return Box::pin(async move { Ok(0) });
            }
            DhtArc::Arc(start, end) => (start, end),
        };

        Box::pin(async move {
            let out = db
                .read_async(move |txn| -> StateMutationResult<u64> {
                    let mut stmt = txn.prepare(
                        r#"SELECT COALESCE(MAX(slice_index),0) FROM SliceHash
                    WHERE arc_start = :arc_start AND arc_end = :arc_end"#,
                    )?;

                    let count = match stmt.query_row(
                        named_params! {
                            ":arc_start": arc_start,
                            ":arc_end": arc_end,
                        },
                        |r| r.get(0),
                    ) {
                        Ok(count) => count,
                        Err(holochain_sqlite::rusqlite::Error::QueryReturnedNoRows) => 0,
                        Err(e) => return Err(e.into()),
                    };

                    Ok(count)
                })
                .await
                .map_err(|e| K2Error::other_src("Failed to count slice hashes", e))?;

            Ok(out)
        })
    }

    fn retrieve_slice_hash(
        &self,
        arc: DhtArc,
        slice_index: u64,
    ) -> BoxFuture<'_, K2Result<Option<Bytes>>> {
        let db = self.db.clone();

        let (arc_start, arc_end) = match arc {
            DhtArc::Empty => {
                return Box::pin(async move { Ok(None) });
            }
            DhtArc::Arc(start, end) => (start, end),
        };

        Box::pin(async move {
            let out = db
                .read_async(move |txn| -> StateMutationResult<Option<Bytes>> {
                    let mut stmt = txn.prepare(r#"SELECT hash FROM SliceHash
                    WHERE arc_start = :arc_start AND arc_end = :arc_end AND slice_index = :slice_index"#)?;

                    let hash = match stmt.query_row(named_params! {
                        ":arc_start": arc_start,
                        ":arc_end": arc_end,
                        ":slice_index": slice_index,
                    }, |r| r.get::<_, Vec<u8>>(0)) {
                        Ok(hash) => Some(Bytes::from(hash)),
                        Err(holochain_sqlite::rusqlite::Error::QueryReturnedNoRows) => None,
                        Err(e) => return Err(e.into()),
                    };

                    Ok(hash)
                })
                .await
                .map_err(|e| K2Error::other_src("Failed to retrieve slice hash", e))?;

            Ok(out)
        })
    }

    fn retrieve_slice_hashes(&self, arc: DhtArc) -> BoxFuture<'_, K2Result<Vec<(u64, Bytes)>>> {
        let db = self.db.clone();

        let (arc_start, arc_end) = match arc {
            DhtArc::Empty => {
                return Box::pin(async move { Ok(vec![]) });
            }
            DhtArc::Arc(start, end) => (start, end),
        };

        Box::pin(async move {
            let out = db
                .read_async(move |txn| -> StateMutationResult<Vec<(u64, Bytes)>> {
                    let mut stmt = txn.prepare(
                        r#"SELECT slice_index, hash FROM SliceHash
                    WHERE arc_start = :arc_start AND arc_end = :arc_end"#,
                    )?;

                    let hash = stmt
                        .query_map(
                            named_params! {
                                ":arc_start": arc_start,
                                ":arc_end": arc_end,
                            },
                            |r| Ok((r.get::<_, u64>(0)?, Bytes::from(r.get::<_, Vec<u8>>(1)?))),
                        )?
                        .collect::<holochain_sqlite::rusqlite::Result<Vec<_>>>()?;

                    Ok(hash)
                })
                .await
                .map_err(|e| K2Error::other_src("Failed to retrieve slice hashes", e))?;

            Ok(out)
        })
    }
}