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
// Copyright 2019 Conflux Foundation. All rights reserved.
// Conflux is free software and distributed under GNU General Public License.
// See http://www.gnu.org/licenses/

/// One of the elementary value type supported by db.
pub trait DbValueType {
    type Type: ?Sized;
}

pub trait KeyValueDbTypes {
    type ValueType: DbValueType;
}

pub trait KeyValueDbTraitRead: KeyValueDbTypes {
    fn get(&self, key: &[u8]) -> Result<Option<Self::ValueType>>;

    fn get_with_number_key(&self, key: i64) -> Result<Option<Self::ValueType>> {
        self.get(key.to_string().as_bytes())
    }
}

/// The difference between this trait and KeyValueDbTraitRead is that, the type
/// which implements KeyValueDbTraitRead may use lock to serialize the reads,
/// which is not necessarily a multi reader.
pub trait KeyValueDbTraitMultiReader: KeyValueDbTraitRead {}

/// These special get methods are provided for db like sqlite, where concurrency
/// can only be achieved by opening a separate connection, otherwise
/// lock is required for concurrent read.
pub trait KeyValueDbTraitOwnedRead: KeyValueDbTypes {
    fn get_mut(&mut self, key: &[u8]) -> Result<Option<Self::ValueType>>;

    fn get_mut_with_number_key(
        &mut self, key: i64,
    ) -> Result<Option<Self::ValueType>> {
        trace!(
            "KeyValue:get: key={:?} {:?}",
            key,
            key.to_string().as_bytes()
        );
        self.get_mut(key.to_string().as_bytes())
    }
}

enable_impl_transmute_for_element_satisfy! {
    generic Item;
    trait 'static + FallibleIterator<Item = Item, Error = Error>;
}

pub struct KvdbIterIterator<Item, KeyType: ?Sized, T: ?Sized> {
    __i_m: std::marker::PhantomData<Item>,
    __k_m: std::marker::PhantomData<KeyType>,
    __t_m: std::marker::PhantomData<T>,
}

pub trait KeyValueDbIterableTrait<Item, KeyType: ?Sized, Tag: ?Sized>
where KvdbIterIterator<Item, KeyType, Tag>:
        WrappedTrait<dyn FallibleIterator<Item = Item, Error = Error>>
{
    fn iter_range(
        &mut self, lower_bound_incl: &KeyType,
        upper_bound_excl: Option<&KeyType>,
    ) -> Result<
        Wrap<
            KvdbIterIterator<Item, KeyType, Tag>,
            dyn FallibleIterator<Item = Item, Error = Error>,
        >,
    >;
    fn iter_range_excl(
        &mut self, lower_bound_excl: &KeyType, upper_bound_excl: &KeyType,
    ) -> Result<
        Wrap<
            KvdbIterIterator<Item, KeyType, Tag>,
            dyn FallibleIterator<Item = Item, Error = Error>,
        >,
    >;
}

pub trait KeyValueDbTraitSingleWriter: KeyValueDbTraitOwnedRead {
    /// Return Some(maybe_old_value) or None if the db don't support reading the
    /// old value at deletion.
    fn delete(&mut self, key: &[u8])
        -> Result<Option<Option<Self::ValueType>>>;
    fn delete_with_number_key(
        &mut self, key: i64,
    ) -> Result<Option<Option<Self::ValueType>>> {
        self.delete(key.to_string().as_bytes())
    }
    fn put(
        &mut self, key: &[u8], value: &<Self::ValueType as DbValueType>::Type,
    ) -> Result<Option<Option<Self::ValueType>>>;
    fn put_with_number_key(
        &mut self, key: i64, value: &<Self::ValueType as DbValueType>::Type,
    ) -> Result<Option<Option<Self::ValueType>>> {
        trace!(
            "KeyValue:put: key={:?} {:?}",
            key,
            key.to_string().as_bytes()
        );
        self.put(key.to_string().as_bytes(), value)
    }
}

pub trait KeyValueDbTraitSingleWriterMultiReader:
    KeyValueDbTraitMultiReader + KeyValueDbTraitSingleWriter
{
}

pub trait KeyValueDbTrait:
    KeyValueDbTraitMultiReader + Send + Sync + MallocSizeOf
{
    /// Return Some(maybe_old_value) or None if the db don't support reading the
    /// old value at deletion.
    fn delete(&self, key: &[u8]) -> Result<Option<Option<Self::ValueType>>>;
    fn delete_with_number_key(
        &self, key: i64,
    ) -> Result<Option<Option<Self::ValueType>>> {
        self.delete(key.to_string().as_bytes())
    }
    fn put(
        &self, key: &[u8], value: &<Self::ValueType as DbValueType>::Type,
    ) -> Result<Option<Option<Self::ValueType>>>;
    fn put_with_number_key(
        &self, key: i64, value: &<Self::ValueType as DbValueType>::Type,
    ) -> Result<Option<Option<Self::ValueType>>> {
        self.put(key.to_string().as_bytes(), value)
    }
}

// FIXME: Is it possible to detach SingleWriter from it, so that the
// implementation doesn't look so ugly on KvdbSqliteTransaction?
#[allow(drop_bounds)]
pub trait KeyValueDbTransactionTrait:
    KeyValueDbTraitSingleWriter + Drop
{
    /// Commit may be retried upon failure.
    fn commit(&mut self, db: &dyn Any) -> Result<()>;
    fn revert(&mut self) -> Result<()>;
    /// When error occured within a transaction before commit, user may have to
    /// revert the transaction and restart a new transaction.
    ///
    /// When restart fails, user may retry with no_revert set to true.
    fn restart(&mut self, immediate_write: bool, no_revert: bool)
        -> Result<()>;
}

/// This trait is to help with the committing of the transaction for which
/// the db object should be provided for serialization.
pub trait KeyValueDbAsAnyTrait: KeyValueDbTypes {
    fn as_any(&self) -> &dyn Any;
}

impl<T: KeyValueDbTypes + Any> KeyValueDbAsAnyTrait for T {
    fn as_any(&self) -> &dyn Any { self }
}

pub trait KeyValueDbTraitTransactional: KeyValueDbAsAnyTrait {
    type TransactionType: KeyValueDbTransactionTrait<
        ValueType = Self::ValueType,
    >;

    /// Immediate_write indicates whether the transaction should acquire a
    /// write-lock immediately if any.
    fn start_transaction(
        &self, immediate_write: bool,
    ) -> Result<Self::TransactionType>;
}

pub trait KeyValueDbTraitTransactionalDyn: KeyValueDbAsAnyTrait {
    fn start_transaction_dyn(
        &self, immediate_write: bool,
    ) -> Result<Box<dyn KeyValueDbTransactionTrait<ValueType = Self::ValueType>>>;
}

impl<T: KeyValueDbTraitTransactional> KeyValueDbTraitTransactionalDyn for T
where T::TransactionType: 'static
{
    fn start_transaction_dyn(
        &self, immediate_write: bool,
    ) -> Result<Box<dyn KeyValueDbTransactionTrait<ValueType = Self::ValueType>>>
    {
        Ok(Box::new(self.start_transaction(immediate_write)?))
    }
}

pub trait KeyValueDbToOwnedReadTrait: KeyValueDbTypes {
    fn to_owned_read(
        &self,
    ) -> Result<
        Box<dyn '_ + KeyValueDbTraitOwnedRead<ValueType = Self::ValueType>>,
    >;
}

impl<T: 'static + KeyValueDbTraitMultiReader> KeyValueDbToOwnedReadTrait for T
where for<'a> &'a T: KeyValueDbTraitOwnedRead<ValueType = Self::ValueType>
{
    fn to_owned_read(
        &self,
    ) -> Result<
        Box<dyn '_ + KeyValueDbTraitOwnedRead<ValueType = Self::ValueType>>,
    > {
        Ok(Box::new(self))
    }
}

macro_rules! mark_kvdb_multi_reader {
    ($type:ty) => {
        impl KeyValueDbTraitMultiReader for $type {}
        // Family dispatching
        impl OwnedReadImplFamily for &$type {
            type FamilyRepresentative = dyn KeyValueDbTraitMultiReader<
                ValueType = <$type as KeyValueDbTypes>::ValueType,
            >;
        }
    };
}

impl DbValueType for () {
    type Type = ();
}

impl DbValueType for Box<[u8]> {
    type Type = [u8];
}

impl DbValueType for i64 {
    type Type = i64;
}

/// We implement the family dispatching for types which implements
/// KeyValueDbTraitOwnedRead by different reasons:
///
/// a) Any type which implements KvdbSqliteAsReadOnlyAndIterableTrait can issue
/// sql queries to load db; The feature is required by SnapshotDbSqlite where
/// the sqlite connection is shared for MPT table and for KV table.
///
/// b) similar requirement may hold for any different database engine;
///
/// c) For a db engine which is by default KeyValueDbTraitMultiReader,
/// KeyValueDbTraitOwnedRead is naturally read without explicit locking.
impl<
        T: OwnedReadImplFamily
            + OwnedReadImplByFamily<
                <T as OwnedReadImplFamily>::FamilyRepresentative,
            >,
    > KeyValueDbTraitOwnedRead for T
{
    fn get_mut(&mut self, key: &[u8]) -> Result<Option<Self::ValueType>> {
        self.get_mut_impl(key)
    }

    fn get_mut_with_number_key(
        &mut self, key: i64,
    ) -> Result<Option<Self::ValueType>> {
        trace!(
            "KeyValue:get_impl: key={:?} {:?}",
            key,
            key.to_string().as_bytes()
        );
        self.get_mut_with_number_key_impl(key)
    }
}

pub trait OwnedReadImplFamily {
    type FamilyRepresentative: ?Sized;
}

pub trait OwnedReadImplByFamily<FamilyRepresentative: ?Sized>:
    KeyValueDbTypes
{
    fn get_mut_impl(&mut self, key: &[u8]) -> Result<Option<Self::ValueType>>;
    fn get_mut_with_number_key_impl(
        &mut self, key: i64,
    ) -> Result<Option<Self::ValueType>>;
}

impl<
        T: SingleWriterImplFamily
            + SingleWriterImplByFamily<
                <T as SingleWriterImplFamily>::FamilyRepresentative,
            > + KeyValueDbTraitOwnedRead,
    > KeyValueDbTraitSingleWriter for T
{
    fn delete(
        &mut self, key: &[u8],
    ) -> Result<Option<Option<Self::ValueType>>> {
        self.delete_impl(key)
    }

    fn delete_with_number_key(
        &mut self, key: i64,
    ) -> Result<Option<Option<Self::ValueType>>> {
        self.delete_with_number_key_impl(key)
    }

    fn put(
        &mut self, key: &[u8], value: &<Self::ValueType as DbValueType>::Type,
    ) -> Result<Option<Option<Self::ValueType>>> {
        self.put_impl(key, value)
    }

    fn put_with_number_key(
        &mut self, key: i64, value: &<Self::ValueType as DbValueType>::Type,
    ) -> Result<Option<Option<Self::ValueType>>> {
        self.put_with_number_key_impl(key, value)
    }
}

pub trait SingleWriterImplFamily {
    type FamilyRepresentative: ?Sized;
}

pub trait SingleWriterImplByFamily<FamilyRepresentative: ?Sized>:
    KeyValueDbTypes
{
    fn delete_impl(
        &mut self, key: &[u8],
    ) -> Result<Option<Option<Self::ValueType>>>;

    fn delete_with_number_key_impl(
        &mut self, key: i64,
    ) -> Result<Option<Option<Self::ValueType>>>;

    fn put_impl(
        &mut self, key: &[u8], value: &<Self::ValueType as DbValueType>::Type,
    ) -> Result<Option<Option<Self::ValueType>>>;

    fn put_with_number_key_impl(
        &mut self, key: i64, value: &<Self::ValueType as DbValueType>::Type,
    ) -> Result<Option<Option<Self::ValueType>>>;
}

impl<
        T: ReadImplFamily
            + ReadImplByFamily<<T as ReadImplFamily>::FamilyRepresentative>,
    > KeyValueDbTraitRead for T
{
    fn get(&self, key: &[u8]) -> Result<Option<Self::ValueType>> {
        self.get_impl(key)
    }

    fn get_with_number_key(&self, key: i64) -> Result<Option<Self::ValueType>> {
        self.get_with_number_key_impl(key)
    }
}

pub trait ReadImplFamily {
    type FamilyRepresentative: ?Sized;
}

pub trait ReadImplByFamily<FamilyRepresentative: ?Sized>:
    KeyValueDbTypes
{
    fn get_impl(&self, key: &[u8]) -> Result<Option<Self::ValueType>>;

    fn get_with_number_key_impl(
        &self, key: i64,
    ) -> Result<Option<Self::ValueType>>;
}

impl<
        T: DbImplFamily
            + DbImplByFamily<<T as DbImplFamily>::FamilyRepresentative>
            + KeyValueDbTraitMultiReader
            + Send
            + Sync
            + MallocSizeOf,
    > KeyValueDbTrait for T
{
    fn delete(&self, key: &[u8]) -> Result<Option<Option<Self::ValueType>>> {
        self.delete_impl(key)
    }

    fn delete_with_number_key(
        &self, key: i64,
    ) -> Result<Option<Option<Self::ValueType>>> {
        self.delete_with_number_key_impl(key)
    }

    fn put(
        &self, key: &[u8], value: &<Self::ValueType as DbValueType>::Type,
    ) -> Result<Option<Option<Self::ValueType>>> {
        self.put_impl(key, value)
    }

    fn put_with_number_key(
        &self, key: i64, value: &<Self::ValueType as DbValueType>::Type,
    ) -> Result<Option<Option<Self::ValueType>>> {
        self.put_with_number_key_impl(key, value)
    }
}

pub trait DbImplFamily {
    type FamilyRepresentative: ?Sized;
}

pub trait DbImplByFamily<FamilyRepresentative: ?Sized>:
    KeyValueDbTypes
{
    fn delete_impl(
        &self, key: &[u8],
    ) -> Result<Option<Option<Self::ValueType>>>;

    fn delete_with_number_key_impl(
        &self, key: i64,
    ) -> Result<Option<Option<Self::ValueType>>>;

    fn put_impl(
        &self, key: &[u8], value: &<Self::ValueType as DbValueType>::Type,
    ) -> Result<Option<Option<Self::ValueType>>>;

    fn put_with_number_key_impl(
        &self, key: i64, value: &<Self::ValueType as DbValueType>::Type,
    ) -> Result<Option<Option<Self::ValueType>>>;
}

impl<ValueType: DbValueType> OwnedReadImplFamily
    for dyn KeyValueDbTraitMultiReader<ValueType = ValueType>
{
    type FamilyRepresentative =
        dyn KeyValueDbTraitMultiReader<ValueType = ValueType>;
}

/// Implement KeyValueDbTraitOwnedRead automatically for database engine which
/// satisfies KeyValueDbTraitMultiReader.
impl<
        T: KeyValueDbTraitMultiReader<ValueType = ValueType>,
        ValueType: DbValueType,
    > KeyValueDbTypes for &T
{
    type ValueType = T::ValueType;
}

impl<
        T: KeyValueDbTraitMultiReader<ValueType = ValueType>,
        ValueType: DbValueType,
    >
    OwnedReadImplByFamily<dyn KeyValueDbTraitMultiReader<ValueType = ValueType>>
    for &T
{
    fn get_mut_impl(&mut self, key: &[u8]) -> Result<Option<Self::ValueType>> {
        self.get(key)
    }

    fn get_mut_with_number_key_impl(
        &mut self, key: i64,
    ) -> Result<Option<Self::ValueType>> {
        self.get_with_number_key(key)
    }
}

use crate::{
    impls::errors::*,
    utils::{
        tuple::ElementSatisfy,
        wrap::{Wrap, WrappedTrait},
    },
};
use fallible_iterator::FallibleIterator;
use malloc_size_of::MallocSizeOf;
use std::any::Any;