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
use holochain_keystore::MetaLairClient;
use holochain_sqlite::prelude::*;
use holochain_sqlite::rusqlite::Statement;
use holochain_sqlite::rusqlite::Transaction;
use holochain_types::prelude::*;
use holochain_zome_types::test_utils::fake_cell_id;
use kitsune_p2p::KitsuneSpace;
use shrinkwraprs::Shrinkwrap;
use std::collections::HashMap;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use tempfile::TempDir;
use crate::prelude::Store;
use crate::prelude::Txn;
pub mod mutations_helpers;
pub fn test_authored_db() -> TestDb<DbKindAuthored> {
test_authored_db_with_id(1)
}
pub fn test_authored_db_with_id(id: u8) -> TestDb<DbKindAuthored> {
test_db(DbKindAuthored(Arc::new(fake_dna_hash(id))))
}
pub fn test_authored_db_with_dna_hash(hash: DnaHash) -> TestDb<DbKindAuthored> {
test_db(DbKindAuthored(Arc::new(hash)))
}
pub fn test_dht_db() -> TestDb<DbKindDht> {
test_dht_db_with_id(1)
}
pub fn test_dht_db_with_id(id: u8) -> TestDb<DbKindDht> {
test_db(DbKindDht(Arc::new(fake_dna_hash(id))))
}
pub fn test_dht_db_with_dna_hash(hash: DnaHash) -> TestDb<DbKindDht> {
test_db(DbKindDht(Arc::new(hash)))
}
pub fn test_cache_db() -> TestDb<DbKindCache> {
test_cache_db_with_id(1)
}
pub fn test_cache_db_with_id(id: u8) -> TestDb<DbKindCache> {
test_db(DbKindCache(Arc::new(fake_cell_id(id).dna_hash().clone())))
}
pub fn test_cache_db_with_dna_hash(hash: DnaHash) -> TestDb<DbKindCache> {
test_db(DbKindCache(Arc::new(hash)))
}
pub fn test_conductor_db() -> TestDb<DbKindConductor> {
test_db(DbKindConductor)
}
pub fn test_wasm_db() -> TestDb<DbKindWasm> {
test_db(DbKindWasm)
}
pub fn test_p2p_agents_db() -> TestDb<DbKindP2pAgents> {
test_db(DbKindP2pAgents(Arc::new(KitsuneSpace(vec![0; 36]))))
}
pub fn test_p2p_metrics_db() -> TestDb<DbKindP2pMetrics> {
test_db(DbKindP2pMetrics(Arc::new(KitsuneSpace(vec![0; 36]))))
}
fn test_db<Kind: DbKindT>(kind: Kind) -> TestDb<Kind> {
let tmpdir = tempfile::Builder::new()
.prefix("holochain-test-environments-")
.suffix(&nanoid::nanoid!())
.tempdir()
.unwrap();
TestDb {
db: DbWrite::test(tmpdir.path(), kind).expect("Couldn't create test database"),
tmpdir,
}
}
pub fn test_in_mem_db<Kind: DbKindT>(kind: Kind) -> DbWrite<Kind> {
DbWrite::test_in_mem(kind).expect("Couldn't create test database")
}
pub fn test_db_dir() -> TempDir {
tempfile::Builder::new()
.prefix("holochain-test-environments")
.suffix(&nanoid::nanoid!())
.tempdir()
.unwrap()
}
pub fn test_dbs_in(path: impl AsRef<Path>) -> TestDbs {
let tempdir = tempfile::Builder::new()
.prefix("holochain-test-environments")
.suffix(&nanoid::nanoid!())
.tempdir_in(path)
.unwrap();
TestDbs::new(tempdir)
}
pub fn test_keystore() -> holochain_keystore::MetaLairClient {
tokio_helper::block_on(
async move {
let keystore = holochain_keystore::test_keystore::spawn_test_keystore()
.await
.unwrap();
keystore
},
std::time::Duration::from_secs(1),
)
.expect("timeout elapsed")
}
#[derive(Shrinkwrap)]
pub struct TestDb<Kind: DbKindT> {
#[shrinkwrap(main_field)]
db: DbWrite<Kind>,
tmpdir: TempDir,
}
impl<Kind: DbKindT> TestDb<Kind> {
pub fn to_db(&self) -> DbWrite<Kind> {
self.db.clone()
}
pub fn into_tempdir(self) -> TempDir {
self.tmpdir
}
pub fn dump(&self, out: &Path) -> std::io::Result<()> {
std::fs::create_dir(&out).ok();
for entry in std::fs::read_dir(self.tmpdir.path())? {
let entry = entry?;
let path = entry.path();
if path.is_file() {
let mut out = out.to_owned();
out.push(format!(
"backup.{}",
path.extension().unwrap().to_string_lossy()
));
std::fs::copy(path, out)?;
}
}
Ok(())
}
pub fn dump_tmp(&self) {
dump_tmp(&self.db);
}
pub fn dna_hash(&self) -> Option<Arc<DnaHash>> {
match self.db.kind().kind() {
DbKind::Authored(hash) | DbKind::Cache(hash) | DbKind::Dht(hash) => Some(hash),
_ => None,
}
}
}
pub fn dump_tmp<Kind: DbKindT>(env: &DbWrite<Kind>) {
let mut tmp = std::env::temp_dir();
tmp.push("test_dbs");
std::fs::create_dir(&tmp).ok();
tmp.push("backup.sqlite");
println!("dumping db to {}", tmp.display());
std::fs::write(&tmp, b"").unwrap();
env.conn()
.unwrap()
.execute("VACUUM main into ?", [tmp.to_string_lossy()])
.unwrap();
}
pub struct TestDbs {
conductor: DbWrite<DbKindConductor>,
wasm: DbWrite<DbKindWasm>,
p2p: Arc<parking_lot::Mutex<HashMap<Arc<KitsuneSpace>, DbWrite<DbKindP2pAgents>>>>,
p2p_metrics: Arc<parking_lot::Mutex<HashMap<Arc<KitsuneSpace>, DbWrite<DbKindP2pMetrics>>>>,
dir: TestDir,
keystore: MetaLairClient,
}
#[derive(Debug)]
pub enum TestDir {
Temp(TempDir),
Perm(PathBuf),
Blank,
}
impl AsRef<Path> for TestDir {
fn as_ref(&self) -> &Path {
match self {
Self::Temp(d) => d.path(),
Self::Perm(d) => d.as_path(),
Self::Blank => unreachable!(),
}
}
}
impl std::ops::Deref for TestDir {
type Target = Path;
fn deref(&self) -> &Path {
match self {
Self::Temp(d) => d.path(),
Self::Perm(d) => d.as_path(),
Self::Blank => unreachable!(),
}
}
}
impl From<TempDir> for TestDir {
fn from(d: TempDir) -> Self {
Self::new(d)
}
}
impl TestDir {
pub fn new(d: TempDir) -> Self {
Self::Temp(d)
}
pub fn persist(&mut self) {
let old = std::mem::replace(self, Self::Blank);
match old {
Self::Temp(d) => {
tracing::info!("Made temp dir permanent at {:?}", d);
*self = Self::Perm(d.into_path());
}
old => *self = old,
}
}
}
#[allow(missing_docs)]
impl TestDbs {
pub fn with_keystore(tempdir: TempDir, keystore: MetaLairClient) -> Self {
let conductor = DbWrite::test(tempdir.path(), DbKindConductor).unwrap();
let wasm = DbWrite::test(tempdir.path(), DbKindWasm).unwrap();
let p2p = Arc::new(parking_lot::Mutex::new(HashMap::new()));
let p2p_metrics = Arc::new(parking_lot::Mutex::new(HashMap::new()));
Self {
conductor,
wasm,
p2p,
p2p_metrics,
dir: TestDir::new(tempdir),
keystore,
}
}
pub fn new(tempdir: TempDir) -> Self {
Self::with_keystore(tempdir, test_keystore())
}
pub fn conductor(&self) -> DbWrite<DbKindConductor> {
self.conductor.clone()
}
pub fn wasm(&self) -> DbWrite<DbKindWasm> {
self.wasm.clone()
}
pub fn p2p(
&self,
) -> Arc<parking_lot::Mutex<HashMap<Arc<KitsuneSpace>, DbWrite<DbKindP2pAgents>>>> {
self.p2p.clone()
}
pub fn p2p_metrics(
&self,
) -> Arc<parking_lot::Mutex<HashMap<Arc<KitsuneSpace>, DbWrite<DbKindP2pMetrics>>>> {
self.p2p_metrics.clone()
}
#[deprecated = "persist() should only be used during debugging"]
pub fn persist(&mut self) {
self.dir.persist();
}
pub fn path(&self) -> &Path {
&self.dir
}
pub fn keystore(&self) -> &MetaLairClient {
&self.keystore
}
}
#[macro_export]
macro_rules! here {
($test: expr) => {
concat!($test, " !!!_LOOK HERE:---> ", file!(), ":", line!())
};
}
pub fn fresh_store_test<F, R, K>(env: &DbRead<K>, f: F) -> R
where
F: FnOnce(&dyn Store) -> R,
K: DbKindT,
{
fresh_reader_test!(env, |txn| {
let store = Txn::from(&txn);
f(&store)
})
}
pub fn fresh_reader_test<E, F, R, K>(env: E, f: F) -> R
where
E: Into<DbRead<K>>,
F: FnOnce(Transaction) -> R,
K: DbKindT,
{
fresh_reader_test!(&env.into(), f)
}
pub fn print_stmts_test<E, F, R, K>(env: E, f: F) -> R
where
E: Into<DbRead<K>>,
F: FnOnce(Transaction) -> R,
K: DbKindT,
{
holochain_sqlite::print_stmts_test!(&env.into(), f)
}
#[tracing::instrument(skip(txn))]
pub fn dump_db(txn: &Transaction) {
let dump = |mut stmt: Statement| {
let mut rows = stmt.query([]).unwrap();
while let Some(row) = rows.next().unwrap() {
for column in row.as_ref().column_names() {
let row = row.get_ref_unwrap(column);
match row {
holochain_sqlite::rusqlite::types::ValueRef::Null
| holochain_sqlite::rusqlite::types::ValueRef::Integer(_)
| holochain_sqlite::rusqlite::types::ValueRef::Real(_) => {
tracing::debug!(?column, ?row);
}
holochain_sqlite::rusqlite::types::ValueRef::Text(text) => {
tracing::debug!(?column, row = ?String::from_utf8_lossy(text));
}
holochain_sqlite::rusqlite::types::ValueRef::Blob(blob) => {
let blob = base64::encode_config(blob, base64::URL_SAFE_NO_PAD);
tracing::debug!("column: {:?} row:{}", column, blob);
}
}
}
}
};
tracing::debug!("Actions:");
let stmt = txn.prepare("SELECT * FROM Action").unwrap();
dump(stmt);
tracing::debug!("Entries:");
let stmt = txn.prepare("SELECT * FROM Entry").unwrap();
dump(stmt);
tracing::debug!("DhtOps:");
let stmt = txn.prepare("SELECT * FROM DhtOp").unwrap();
dump(stmt);
}