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
//! Shared tests for keyvaluedb functionality, to be executed against actual implementations.

#![deny(clippy::all)]

use keyvaluedb::{DBKey, DBKeyRef, DBKeyValue, DBKeyValueRef, IoStatsKind, KeyValueDB};
use std::io;

/// A test for `KeyValueDB::get`.
pub async fn test_put_and_get<DB: KeyValueDB>(db: DB) -> io::Result<()> {
    let key1 = b"key1";

    let mut transaction = db.transaction();
    transaction.put(0, key1.to_vec(), b"horse");
    db.write(transaction).await.map_err(|e| e.error)?;
    assert_eq!(db.get(0, key1).await?.unwrap(), b"horse");
    Ok(())
}

/// A test for `KeyValueDB::get` and delete with transaction.
pub async fn test_delete_and_get<DB: KeyValueDB>(db: DB) -> io::Result<()> {
    let key1 = b"key1";

    let mut transaction = db.transaction();
    transaction.put(0, key1, b"horse");
    db.write(transaction).await.map_err(|e| e.error)?;
    assert_eq!(db.get(0, key1).await?.unwrap(), b"horse");

    let mut transaction = db.transaction();
    transaction.delete(0, key1);
    db.write(transaction).await.map_err(|e| e.error)?;
    assert!(db.get(0, key1).await?.is_none());
    Ok(())
}

/// A test for `KeyValueDB::get` and delete without transaction.
pub async fn test_delete_and_get_single<DB: KeyValueDB>(db: DB) -> io::Result<()> {
    let key1 = b"key1";

    let mut transaction = db.transaction();
    transaction.put(0, key1, b"horse");
    db.write(transaction).await.map_err(|e| e.error)?;
    assert_eq!(db.get(0, key1).await?.unwrap(), b"horse");

    assert_eq!(db.delete(0, key1).await?, Some(b"horse".to_vec()));
    assert!(db.get(0, key1).await?.is_none());
    assert_eq!(db.delete(0, key1).await?, None);

    Ok(())
}

/// A test for `KeyValueDB::get`.
/// Assumes the `db` has only 1 column.
pub async fn test_get_fails_with_non_existing_column<DB: KeyValueDB>(db: DB) -> io::Result<()> {
    assert!(db.get(1, b"").await.is_err());
    Ok(())
}

/// A test for `KeyValueDB::write`.
pub async fn test_write_clears_buffered_ops<DB: KeyValueDB>(db: DB) -> io::Result<()> {
    let mut batch = db.transaction();
    batch.put(0, b"foo", b"bar");
    db.write(batch).await.map_err(|e| e.error)?;

    assert_eq!(db.get(0, b"foo").await?.unwrap(), b"bar");

    let mut batch = db.transaction();
    batch.put(0, b"foo", b"baz");
    db.write(batch).await.map_err(|e| e.error)?;

    assert_eq!(db.get(0, b"foo").await?.unwrap(), b"baz");
    Ok(())
}

/// A test for `KeyValueDB::iter`.
pub async fn test_iter<DB: KeyValueDB>(db: DB) -> io::Result<()> {
    let key1 = b"key1";
    let key2 = b"key2";

    let mut transaction = db.transaction();
    transaction.put(0, key1, key1);
    transaction.put(0, key2, key2);
    db.write(transaction).await.map_err(|e| e.error)?;

    let mut contents: Vec<DBKeyValue> = Vec::new();
    let out = db
        .iter(0, None, |kv: DBKeyValueRef| {
            contents.push((kv.0.clone(), kv.1.clone()));
            Ok(Option::<()>::None)
        })
        .await?;
    assert!(out.is_none());
    assert_eq!(contents.len(), 2);
    assert_eq!(contents[0].0, key1);
    assert_eq!(contents[0].1, key1);
    assert_eq!(contents[1].0, key2);
    assert_eq!(contents[1].1, key2);

    // test iter with early return
    let mut contents: Vec<DBKeyValue> = Vec::new();
    let out = db
        .iter(0, None, |kv: DBKeyValueRef| {
            contents.push((kv.0.clone(), kv.1.clone()));
            Ok(Option::<()>::Some(()))
        })
        .await?;
    assert!(out.is_some());
    assert_eq!(contents.len(), 1);
    assert_eq!(contents[0].0, key1);
    assert_eq!(contents[0].1, key1);
    Ok(())
}

/// A test for `KeyValueDB::iter_keys`.
pub async fn test_iter_keys<DB: KeyValueDB>(db: DB) -> io::Result<()> {
    let key1 = b"key1";
    let key2 = b"key2";

    let mut transaction = db.transaction();
    transaction.put(0, key1, key1);
    transaction.put(0, key2, key2);
    db.write(transaction).await.map_err(|e| e.error)?;

    let mut contents: Vec<DBKey> = Vec::new();
    let out = db
        .iter_keys(0, None, |k: DBKeyRef| {
            contents.push(k.clone());
            Ok(Option::<()>::None)
        })
        .await?;
    assert!(out.is_none());
    assert_eq!(contents.len(), 2);
    assert_eq!(contents[0], key1);
    assert_eq!(contents[1], key2);

    // test iter keys with early return
    let mut contents: Vec<DBKey> = Vec::new();
    let out = db
        .iter_keys(0, None, |k: DBKeyRef| {
            contents.push(k.clone());
            Ok(Option::<()>::Some(()))
        })
        .await?;
    assert!(out.is_some());
    assert_eq!(contents.len(), 1);
    assert_eq!(contents[0], key1);

    Ok(())
}

/// A test for `KeyValueDB::iter` with a prefix.
pub async fn test_iter_with_prefix<DB: KeyValueDB>(db: DB) -> io::Result<()> {
    let key1 = b"0";
    let key2 = b"ab";
    let key3 = b"abc";
    let key4 = b"abcd";

    let mut batch = db.transaction();
    batch.put(0, key1, key1);
    batch.put(0, key2, key2);
    batch.put(0, key3, key3);
    batch.put(0, key4, key4);
    db.write(batch).await.map_err(|e| e.error)?;

    // empty prefix
    let mut contents: Vec<DBKeyValue> = Vec::new();
    let out = db
        .iter(0, Some(b""), |kv: DBKeyValueRef| {
            contents.push((kv.0.clone(), kv.1.clone()));
            Ok(Option::<()>::None)
        })
        .await?;
    assert!(out.is_none());
    assert_eq!(contents.len(), 4);
    assert_eq!(contents[0].0, key1);
    assert_eq!(contents[1].0, key2);
    assert_eq!(contents[2].0, key3);
    assert_eq!(contents[3].0, key4);

    // empty prefix with early return
    let mut contents: Vec<DBKeyValue> = Vec::new();
    let out = db
        .iter(0, Some(b""), |kv: DBKeyValueRef| {
            contents.push((kv.0.clone(), kv.1.clone()));
            Ok(Option::<()>::Some(()))
        })
        .await?;
    assert!(out.is_some());
    assert_eq!(contents.len(), 1);
    assert_eq!(contents[0].0, key1);

    // prefix a
    let mut contents: Vec<DBKeyValue> = Vec::new();
    db.iter(0, Some(b"a"), |kv: DBKeyValueRef| {
        contents.push((kv.0.clone(), kv.1.clone()));
        Ok(Option::<()>::None)
    })
    .await?;
    assert_eq!(contents.len(), 3);
    assert_eq!(contents[0].0, key2);
    assert_eq!(contents[1].0, key3);
    assert_eq!(contents[2].0, key4);

    // prefix abc
    let mut contents: Vec<DBKeyValue> = Vec::new();
    db.iter(0, Some(b"abc"), |kv: DBKeyValueRef| {
        contents.push((kv.0.clone(), kv.1.clone()));
        Ok(Option::<()>::None)
    })
    .await?;
    assert_eq!(contents.len(), 2);
    assert_eq!(contents[0].0, key3);
    assert_eq!(contents[1].0, key4);

    // prefix abcde
    let mut contents: Vec<DBKeyValue> = Vec::new();
    db.iter(0, Some(b"abcde"), |kv: DBKeyValueRef| {
        contents.push((kv.0.clone(), kv.1.clone()));
        Ok(Option::<()>::None)
    })
    .await?;
    assert_eq!(contents.len(), 0);

    // prefix 0
    let mut contents: Vec<DBKeyValue> = Vec::new();
    db.iter(0, Some(b"0"), |kv: DBKeyValueRef| {
        contents.push((kv.0.clone(), kv.1.clone()));
        Ok(Option::<()>::None)
    })
    .await?;
    assert_eq!(contents.len(), 1);
    assert_eq!(contents[0].0, key1);
    Ok(())
}

/// The number of columns required to run `test_io_stats`.
pub const IO_STATS_NUM_COLUMNS: u32 = 3;

/// A test for `KeyValueDB::io_stats`.
/// Assumes that the `db` has at least 3 columns.
pub async fn test_io_stats<DB: KeyValueDB>(db: DB) -> io::Result<()> {
    let key1 = b"kkk";
    let mut batch = db.transaction();
    batch.put(0, key1, key1);
    batch.put(1, key1, key1);
    batch.put(2, key1, key1);

    for _ in 0..10 {
        db.get(0, key1).await?;
    }

    db.write(batch).await.map_err(|e| e.error)?;

    let io_stats = db.io_stats(IoStatsKind::SincePrevious);
    assert_eq!(io_stats.transactions, 1);
    assert_eq!(io_stats.writes, 3);
    assert_eq!(io_stats.bytes_written, 18);
    assert_eq!(io_stats.reads, 10);
    assert_eq!(io_stats.bytes_read, 30);

    let new_io_stats = db.io_stats(IoStatsKind::SincePrevious);
    // Since we taken previous statistic period,
    // this is expected to be totally empty.
    assert_eq!(new_io_stats.transactions, 0);

    // but the overall should be there
    let new_io_stats = db.io_stats(IoStatsKind::Overall);
    assert_eq!(new_io_stats.bytes_written, 18);

    let mut batch = db.transaction();
    batch.delete(0, key1);
    batch.delete(1, key1);
    batch.delete(2, key1);

    // transaction is not commited yet
    assert_eq!(db.io_stats(IoStatsKind::SincePrevious).writes, 0);

    db.write(batch).await.map_err(|e| e.error)?;
    // now it is, and delete is counted as write
    assert_eq!(db.io_stats(IoStatsKind::SincePrevious).writes, 3);
    Ok(())
}

/// The number of columns required to run `test_delete_prefix`.
pub const DELETE_PREFIX_NUM_COLUMNS: u32 = 7;

/// A test for `KeyValueDB::delete_prefix`.
pub async fn test_delete_prefix<DB: KeyValueDB + 'static>(db: DB) -> io::Result<()> {
    let keys = [
        &[][..],
        &[0u8][..],
        &[0, 1][..],
        &[1][..],
        &[1, 0][..],
        &[1, 255][..],
        &[1, 255, 255][..],
        &[2][..],
        &[2, 0][..],
        &[2, 255][..],
        &[255; 16][..],
    ];
    let tests: [_; DELETE_PREFIX_NUM_COLUMNS as usize] = [
        // standard
        (
            &[1u8][..],
            [
                true, true, true, false, false, false, false, true, true, true, true,
            ],
        ),
        // edge
        (
            &[1u8, 255, 255][..],
            [
                true, true, true, true, true, true, false, true, true, true, true,
            ],
        ),
        // none 1
        (
            &[1, 2][..],
            [
                true, true, true, true, true, true, true, true, true, true, true,
            ],
        ),
        // none 2
        (
            &[8][..],
            [
                true, true, true, true, true, true, true, true, true, true, true,
            ],
        ),
        // last value
        (
            &[255, 255][..],
            [
                true, true, true, true, true, true, true, true, true, true, false,
            ],
        ),
        // last value, limit prefix
        (
            &[255][..],
            [
                true, true, true, true, true, true, true, true, true, true, false,
            ],
        ),
        // all
        (
            &[][..],
            [
                false, false, false, false, false, false, false, false, false, false, false,
            ],
        ),
    ];
    for (ix, test) in tests.iter().enumerate() {
        let ix = ix as u32;

        // Init Transaction
        let mut batch = db.transaction();
        for (i, key) in keys.iter().enumerate() {
            batch.put(ix, key, &[i as u8]);
        }
        db.write(batch).await.map_err(|e| e.error)?;

        // Delete Transaction
        let mut batch = db.transaction();
        batch.delete_prefix(ix, test.0);
        db.write(batch).await.map_err(|e| e.error)?;

        // Check Test
        let mut state = [true; 11];
        for (c, key) in keys.iter().enumerate() {
            state[c] = db.get(ix, key).await?.is_some();
        }
        assert_eq!(state, test.1, "at {}", ix);
    }

    Ok(())
}

/// A complex test.
pub async fn test_complex<DB: KeyValueDB>(db: DB) -> io::Result<()> {
    let key1 = b"02c69be41d0b7e40352fc85be1cd65eb03d40ef8427a0ca4596b1ead9a00e9fc";
    let key2 = b"03c69be41d0b7e40352fc85be1cd65eb03d40ef8427a0ca4596b1ead9a00e9fc";
    let key3 = b"04c00000000b7e40352fc85be1cd65eb03d40ef8427a0ca4596b1ead9a00e9fc";
    let key4 = b"04c01111110b7e40352fc85be1cd65eb03d40ef8427a0ca4596b1ead9a00e9fc";
    let key5 = b"04c02222220b7e40352fc85be1cd65eb03d40ef8427a0ca4596b1ead9a00e9fc";

    let mut batch = db.transaction();
    batch.put(0, key1, b"cat");
    batch.put(0, key2, b"dog");
    batch.put(0, key3, b"caterpillar");
    batch.put(0, key4, b"beef");
    batch.put(0, key5, b"fish");
    db.write(batch).await.map_err(|e| e.error)?;

    assert_eq!(db.get(0, key1).await?.unwrap(), b"cat");

    let mut contents: Vec<DBKeyValue> = Vec::new();
    db.iter(0, None, |kv: DBKeyValueRef| {
        contents.push((kv.0.clone(), kv.1.clone()));
        Ok(Option::<()>::None)
    })
    .await?;
    assert_eq!(contents.len(), 5);
    assert_eq!(contents[0].0, key1.to_vec());
    assert_eq!(contents[0].1, b"cat");
    assert_eq!(contents[1].0, key2.to_vec());
    assert_eq!(contents[1].1, b"dog");

    let mut contents: Vec<DBKeyValue> = Vec::new();
    db.iter(0, Some(b"04c0"), |kv: DBKeyValueRef| {
        contents.push((kv.0.clone(), kv.1.clone()));
        Ok(Option::<()>::None)
    })
    .await?;
    assert_eq!(contents[0].1, b"caterpillar");
    assert_eq!(contents[1].1, b"beef");
    assert_eq!(contents[2].1, b"fish");

    let mut batch = db.transaction();
    batch.delete(0, key1);
    db.write(batch).await.map_err(|e| e.error)?;

    assert!(db.get(0, key1).await?.is_none());

    let mut batch = db.transaction();
    batch.put(0, key1, b"cat");
    db.write(batch).await.map_err(|e| e.error)?;

    let mut transaction = db.transaction();
    transaction.put(0, key3, b"elephant");
    transaction.delete(0, key1);
    db.write(transaction).await.map_err(|e| e.error)?;
    assert!(db.get(0, key1).await?.is_none());
    assert_eq!(db.get(0, key3).await?.unwrap(), b"elephant");

    assert_eq!(
        db.first_with_prefix(0, key3).await?.unwrap(),
        (key3.to_vec(), b"elephant".to_vec())
    );
    assert_eq!(
        db.first_with_prefix(0, key2).await?.unwrap(),
        (key2.to_vec(), b"dog".to_vec())
    );

    let mut transaction = db.transaction();
    transaction.put(0, key1, b"horse");
    transaction.delete(0, key3);
    db.write(transaction).await.map_err(|e| e.error)?;
    assert!(db.get(0, key3).await?.is_none());
    assert_eq!(db.get(0, key1).await?.unwrap(), b"horse");

    assert!(db.get(0, key3).await?.is_none());
    assert_eq!(db.get(0, key1).await?.unwrap(), b"horse");
    Ok(())
}