forked from jl777/SuperNET
-
Notifications
You must be signed in to change notification settings - Fork 100
/
Copy pathindexed_db.rs
1569 lines (1396 loc) · 57.6 KB
/
indexed_db.rs
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
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! The representation of [Indexed DB](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API)
//! based on low-level interface described in `db_driver.rs`.
//!
//! # Implementation
//!
//! Since the wrappers represented in `db_driver.rs` are not `Send`,
//! the implementation below initializes and spawns a `IdbDatabaseImpl` database instance locally
//! and communicate with it through the `mpsc` channel.
use async_trait::async_trait;
use common::executor::spawn_local;
use common::log::debug;
use common::stringify_js_error;
use derive_more::Display;
use futures::channel::{mpsc, oneshot};
use futures::StreamExt;
use mm2_core::DbNamespaceId;
use mm2_err_handle::prelude::*;
use primitives::hash::H160;
use serde::de::DeserializeOwned;
use serde::Serialize;
use serde_json::{self as json, Value as Json};
use std::collections::HashMap;
use std::marker::PhantomData;
use std::sync::Mutex;
use wasm_bindgen::JsCast;
use web_sys::{Window, WorkerGlobalScope};
macro_rules! try_serialize_index_value {
($exp:expr, $index:expr) => {{
match $exp {
Ok(res) => res,
Err(ser_err) => {
return MmError::err(DbTransactionError::ErrorSerializingIndex {
index: $index.to_owned(),
description: ser_err.to_string(),
});
},
}
}};
}
mod be_big_uint;
mod db_driver;
mod db_lock;
mod indexed_cursor;
pub use be_big_uint::BeBigUint;
pub use db_driver::{DbTransactionError, DbTransactionResult, DbUpgrader, InitDbError, InitDbResult, ItemId,
OnUpgradeError, OnUpgradeResult};
pub use db_lock::{ConstructibleDb, DbLocked, SharedDb, WeakDb};
use db_driver::{IdbDatabaseBuilder, IdbDatabaseImpl, IdbObjectStoreImpl, IdbTransactionImpl, OnUpgradeNeededCb};
use indexed_cursor::{cursor_event_loop, CursorBuilder, CursorDriver, CursorError, CursorFilters, CursorFiltersExt,
CursorResult, DbCursorEventTx};
type DbEventTx = mpsc::UnboundedSender<internal::DbEvent>;
type DbTransactionEventTx = mpsc::UnboundedSender<internal::DbTransactionEvent>;
type DbTableEventTx = mpsc::UnboundedSender<internal::DbTableEvent>;
pub mod cursor_prelude {
pub use crate::indexed_db::indexed_cursor::{CursorError, CursorResult};
}
pub trait TableSignature: DeserializeOwned + Serialize + 'static {
const TABLE_NAME: &'static str;
fn on_upgrade_needed(upgrader: &DbUpgrader, old_version: u32, new_version: u32) -> OnUpgradeResult<()>;
}
/// Essential operations for initializing an IndexedDb instance.
#[async_trait]
pub trait DbInstance: Sized {
/// Returns the static name of the database.
const DB_NAME: &'static str;
/// Initialize the database with the provided identifier.
/// This method ensures that the database is properly set up with the correct version
/// and has the required tables.
async fn init(db_id: DbIdentifier) -> InitDbResult<Self>;
}
#[derive(Clone, Display)]
#[display(fmt = "{}::{}::{}", namespace_id, "self.display_rmd160()", db_name)]
pub struct DbIdentifier {
namespace_id: DbNamespaceId,
/// The `RIPEMD160(SHA256(x))` where x is secp256k1 pubkey derived from passphrase.
/// This value is used to distinguish different databases corresponding to user's different seed phrases.
wallet_rmd160: Option<H160>,
db_name: &'static str,
}
impl DbIdentifier {
pub fn db_name(&self) -> &'static str { self.db_name }
pub fn new<Db: DbInstance>(namespace_id: DbNamespaceId, wallet_rmd160: Option<H160>) -> DbIdentifier {
DbIdentifier {
namespace_id,
wallet_rmd160,
db_name: Db::DB_NAME,
}
}
pub fn for_test(db_name: &'static str) -> DbIdentifier {
DbIdentifier {
namespace_id: DbNamespaceId::for_test(),
wallet_rmd160: Some(H160::default()),
db_name,
}
}
pub fn display_rmd160(&self) -> String {
self.wallet_rmd160
.map(hex::encode)
.unwrap_or_else(|| "KOMODEFI".to_string())
}
}
pub struct IndexedDbBuilder {
pub db_name: String,
pub db_version: u32,
pub tables: HashMap<String, OnUpgradeNeededCb>,
}
impl IndexedDbBuilder {
pub fn new(db_id: DbIdentifier) -> IndexedDbBuilder {
IndexedDbBuilder {
db_name: db_id.to_string(),
db_version: 1,
tables: HashMap::new(),
}
}
pub fn with_version(mut self, db_version: u32) -> IndexedDbBuilder {
self.db_version = db_version;
self
}
pub fn with_table<Table: TableSignature>(mut self) -> IndexedDbBuilder {
let on_upgrade_needed_cb = Box::new(Table::on_upgrade_needed);
self.tables.insert(Table::TABLE_NAME.to_owned(), on_upgrade_needed_cb);
self
}
pub async fn build(self) -> InitDbResult<IndexedDb> {
let (init_tx, init_rx) = oneshot::channel();
let (event_tx, event_rx) = mpsc::unbounded();
self.init_and_spawn(init_tx, event_rx);
init_rx.await.expect("The init channel must not be closed")?;
Ok(IndexedDb { event_tx })
}
fn init_and_spawn(
self,
init_tx: oneshot::Sender<InitDbResult<()>>,
event_rx: mpsc::UnboundedReceiver<internal::DbEvent>,
) {
let fut = async move {
let db = match IdbDatabaseBuilder::new(&self.db_name)
.with_version(self.db_version)
.with_tables(self.tables.into_iter())
.build()
.await
{
Ok(db) => db,
Err(e) => {
// ignore if the receiver is closed
let _res = init_tx.send(Err(e));
return;
},
};
// ignore if the receiver is closed
let _res = init_tx.send(Ok(()));
// run the event loop
IndexedDb::event_loop(event_rx, db).await;
};
// `IndexedDb::event_loop` will finish almost immediately once the opposite `event_tx` is dropped.
spawn_local(fut);
}
}
pub struct IndexedDb {
event_tx: DbEventTx,
}
async fn send_event_recv_response<Event, Item, Error>(
event_tx: &mpsc::UnboundedSender<Event>,
event: Event,
result_rx: oneshot::Receiver<MmResult<Item, Error>>,
) -> MmResult<Item, Error>
where
Error: WithInternal + NotMmError,
{
if let Err(e) = event_tx.unbounded_send(event) {
return MmError::err(Error::internal(format!("Error sending event: {}", e)));
}
match result_rx.await {
Ok(result) => result,
Err(e) => MmError::err(Error::internal(format!("Error receiving result: {}", e))),
}
}
impl IndexedDb {
pub async fn transaction(&self) -> DbTransactionResult<DbTransaction<'_>> {
let (result_tx, result_rx) = oneshot::channel();
let event = internal::DbEvent::CreateTransaction { result_tx };
let transaction_event_tx = send_event_recv_response(&self.event_tx, event, result_rx).await?;
Ok(DbTransaction {
event_tx: transaction_event_tx,
phantom: PhantomData,
})
}
async fn event_loop(mut rx: mpsc::UnboundedReceiver<internal::DbEvent>, db: IdbDatabaseImpl) {
while let Some(event) = rx.next().await {
match event {
internal::DbEvent::CreateTransaction { result_tx } => Self::create_transaction(&db, result_tx),
}
}
}
fn create_transaction(db: &IdbDatabaseImpl, result_tx: oneshot::Sender<DbTransactionResult<DbTransactionEventTx>>) {
let transaction = match db.transaction() {
Ok(transaction) => transaction,
Err(e) => {
// ignore if the receiver is closed
result_tx.send(Err(e)).ok();
return;
},
};
let (transaction_event_tx, transaction_event_rx) = mpsc::unbounded();
// Spawn the event loop.
let fut = async move { DbTransaction::event_loop(transaction_event_rx, transaction).await };
// `DbTransaction::event_loop` will finish almost immediately once `transaction_event_rx` is dropped.
spawn_local(fut);
// ignore if the receiver is closed
result_tx.send(Ok(transaction_event_tx)).ok();
}
}
pub struct DbTransaction<'transaction> {
event_tx: DbTransactionEventTx,
phantom: PhantomData<&'transaction ()>,
}
impl DbTransaction<'_> {
pub async fn table<Table: TableSignature>(&self) -> DbTransactionResult<DbTable<'_, Table>> {
let (result_tx, result_rx) = oneshot::channel();
let event = internal::DbTransactionEvent::OpenTable {
table_name: Table::TABLE_NAME.to_owned(),
result_tx,
};
let transaction_event_tx = send_event_recv_response(&self.event_tx, event, result_rx).await?;
Ok(DbTable {
event_tx: transaction_event_tx,
phantom: PhantomData,
})
}
pub async fn aborted(&self) -> DbTransactionResult<bool> {
let (result_tx, result_rx) = oneshot::channel();
let event = internal::DbTransactionEvent::IsAborted { result_tx };
send_event_recv_response(&self.event_tx, event, result_rx).await
}
async fn event_loop(
mut rx: mpsc::UnboundedReceiver<internal::DbTransactionEvent>,
transaction: IdbTransactionImpl,
) {
while let Some(event) = rx.next().await {
match event {
internal::DbTransactionEvent::OpenTable { table_name, result_tx } => {
Self::open_table(&transaction, table_name, result_tx)
},
internal::DbTransactionEvent::IsAborted { result_tx } => {
result_tx.send(Ok(transaction.aborted())).ok();
},
}
}
}
fn open_table(
transaction: &IdbTransactionImpl,
table_name: String,
result_tx: oneshot::Sender<DbTransactionResult<mpsc::UnboundedSender<internal::DbTableEvent>>>,
) {
let table = match transaction.open_table(&table_name) {
Ok(table) => table,
Err(e) => {
// ignore if the receiver is closed
result_tx.send(Err(e)).ok();
return;
},
};
let (table_event_tx, table_event_rx) = mpsc::unbounded();
let fut = async move { table_event_loop(table_event_rx, table).await };
// `table_event_loop` will finish almost immediately once `table_event_tx` is dropped.
spawn_local(fut);
// ignore if the receiver is closed
result_tx.send(Ok(table_event_tx)).ok();
}
}
pub struct DbTable<'transaction, Table: TableSignature> {
event_tx: DbTableEventTx,
phantom: PhantomData<&'transaction Table>,
}
pub enum AddOrIgnoreResult {
Added(ItemId),
ExistAlready(ItemId),
}
impl AddOrIgnoreResult {
pub fn get_id(&self) -> ItemId {
match self {
AddOrIgnoreResult::Added(id) => *id,
AddOrIgnoreResult::ExistAlready(id) => *id,
}
}
}
impl<'transaction, Table: TableSignature> DbTable<'transaction, Table> {
/// Adds the given item to the table.
/// https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/add
pub async fn add_item(&self, item: &Table) -> DbTransactionResult<ItemId> {
let item = json::to_value(item).map_to_mm(|e| DbTransactionError::ErrorSerializingItem(e.to_string()))?;
let (result_tx, result_rx) = oneshot::channel();
let event = internal::DbTableEvent::AddItem { item, result_tx };
send_event_recv_response(&self.event_tx, event, result_rx).await
}
/// Adds the given `item` if there are no items with the same `index`.
/// https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/add
///
/// * `index` - the name of a corresponding `Table`'s field by which records will be searched.
/// * `index_value` - the value of the `index`, therefore the value of a corresponding `Table`'s field.
pub async fn add_item_or_ignore_by_unique_index<Value>(
&self,
index: &str,
index_value: Value,
item: &Table,
) -> DbTransactionResult<AddOrIgnoreResult>
where
Value: Serialize,
{
let ids = self.get_item_ids(index, index_value).await?;
match ids.len() {
0 => self.add_item(item).await.map(AddOrIgnoreResult::Added),
1 => Ok(AddOrIgnoreResult::ExistAlready(ids[0])),
got_items => MmError::err(DbTransactionError::MultipleItemsByUniqueIndex {
index: index.to_owned(),
got_items,
}),
}
}
/// Adds the given `item` if there are no items with the same multiple indexes.
/// https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/add
///
/// For more details on multiple indexes see [`TableUpgrader::create_multi_index`].
pub async fn add_item_or_ignore_by_unique_multi_index(
&self,
multi_index: MultiIndex,
item: &Table,
) -> DbTransactionResult<AddOrIgnoreResult> {
self.add_item_or_ignore_by_unique_index(&multi_index.index, multi_index.values, item)
.await
}
/// Queries items from the store matching the specified `index`.
/// https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/getAllKeys
///
/// * `index` - the name of a corresponding `Table`'s field by which records will be searched.
/// * `index_value` - the value of the `index`, therefore the value of a corresponding `Table`'s field.
pub async fn get_items<Value>(&self, index: &str, index_value: Value) -> DbTransactionResult<Vec<(ItemId, Table)>>
where
Value: Serialize,
{
let (result_tx, result_rx) = oneshot::channel();
let index_value = try_serialize_index_value!(json::to_value(index_value), index);
let event = internal::DbTableEvent::GetItems {
index: index.to_owned(),
index_value,
result_tx,
};
send_event_recv_response(&self.event_tx, event, result_rx)
.await
.and_then(|items| Self::deserialize_items(items))
}
/// Queries items from the store matching the specified multiple indexes.
/// https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/getAllKeys
///
/// For more details on multiple indexes see [`TableUpgrader::create_multi_index`].
pub async fn get_items_by_multi_index(&self, multi_index: MultiIndex) -> DbTransactionResult<Vec<(ItemId, Table)>> {
self.get_items(&multi_index.index, multi_index.values).await
}
/// Queries an item from the store matching the specified **unique** `index`.
/// https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/getAllKeys
///
/// * `index` - the name of a corresponding `Table`'s field by which records will be searched.
/// * `index_value` - the value of the `index`, therefore the value of a corresponding `Table`'s field.
///
pub async fn get_item_by_unique_index<Value>(
&self,
index: &str,
index_value: Value,
) -> DbTransactionResult<Option<(ItemId, Table)>>
where
Value: Serialize,
{
let items = self.get_items(index, index_value).await?;
if items.len() > 1 {
return MmError::err(DbTransactionError::MultipleItemsByUniqueIndex {
index: index.to_owned(),
got_items: items.len(),
});
}
Ok(items.into_iter().next())
}
/// Queries an item from the store matching the specified **unique** multiple indexes.
/// https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/getAllKeys
///
/// For more details on multiple indexes see [`TableUpgrader::create_multi_index`].
pub async fn get_item_by_unique_multi_index(
&self,
multi_index: MultiIndex,
) -> DbTransactionResult<Option<(ItemId, Table)>> {
self.get_item_by_unique_index(&multi_index.index, multi_index.values)
.await
}
/// Queries IDs of items from the store matching the specified `index`.
/// Such IDs can be used to delete, replace items.
/// https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/getAllKeys
///
/// * `index` - the name of a corresponding `Table`'s field by which records will be searched.
/// * `index_value` - the value of the `index`, therefore the value of a corresponding `Table`'s field.
pub async fn get_item_ids<Value>(&self, index: &str, index_value: Value) -> DbTransactionResult<Vec<ItemId>>
where
Value: Serialize,
{
let (result_tx, result_rx) = oneshot::channel();
let index_value = try_serialize_index_value!(json::to_value(index_value), index);
let event = internal::DbTableEvent::GetItemIds {
index: index.to_owned(),
index_value,
result_tx,
};
send_event_recv_response(&self.event_tx, event, result_rx).await
}
/// Queries IDs of items from the store matching the specified multiple indexes.
/// Such IDs can be used to delete, replace items.
/// https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/getAllKeys
///
/// For more details on multiple indexes see [`TableUpgrader::create_multi_index`].
pub async fn get_item_ids_by_multi_index(&self, multi_index: MultiIndex) -> DbTransactionResult<Vec<ItemId>> {
self.get_item_ids(&multi_index.index, multi_index.values).await
}
/// Queries all items from the store.
/// https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/getAll
pub async fn get_all_items(&self) -> DbTransactionResult<Vec<(ItemId, Table)>> {
let (result_tx, result_rx) = oneshot::channel();
let event = internal::DbTableEvent::GetAllItems { result_tx };
send_event_recv_response(&self.event_tx, event, result_rx)
.await
.and_then(|items| Self::deserialize_items(items))
}
/// Returns the number of items matching the specified `index`.
/// https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/count
///
/// * `index` - the name of a corresponding `Table`'s field by which records will be searched.
/// * `index_value` - the value of the `index`, therefore the value of a corresponding `Table`'s field.
pub async fn count<Value: Serialize>(&self, index: &str, index_value: Value) -> DbTransactionResult<usize> {
let (result_tx, result_rx) = oneshot::channel();
let index_value = try_serialize_index_value!(json::to_value(index_value), index);
let event = internal::DbTableEvent::Count {
index: index.to_owned(),
index_value,
result_tx,
};
send_event_recv_response(&self.event_tx, event, result_rx).await
}
/// Returns the number of items matching the specified multiple indexes.
/// https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/count
///
/// For more details on multiple indexes see [`TableUpgrader::create_multi_index`].
pub async fn count_by_multi_index(&self, multi_index: MultiIndex) -> DbTransactionResult<usize> {
self.count(&multi_index.index, multi_index.values).await
}
/// Returns the number of items in the store.
/// https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/count
pub async fn count_all(&self) -> DbTransactionResult<usize> {
let (result_tx, result_rx) = oneshot::channel();
let event = internal::DbTableEvent::CountAll { result_tx };
send_event_recv_response(&self.event_tx, event, result_rx).await
}
/// Adds the given `item` or replace the previous one.
/// https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/put
pub async fn replace_item(&self, item_id: ItemId, item: &Table) -> DbTransactionResult<ItemId> {
let item = json::to_value(item).map_to_mm(|e| DbTransactionError::ErrorSerializingItem(e.to_string()))?;
let (result_tx, result_rx) = oneshot::channel();
let event = internal::DbTableEvent::ReplaceItem {
item_id,
item,
result_tx,
};
send_event_recv_response(&self.event_tx, event, result_rx).await
}
/// Adds the given `item` or replace the previous one if such item with the specified `index` exists already.
/// https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/put
///
/// * `index` - the name of a corresponding `Table`'s field by which records will be searched.
/// * `index_value` - the value of the `index`, therefore the value of a corresponding `Table`'s field.
pub async fn replace_item_by_unique_index<Value>(
&self,
index: &str,
index_value: Value,
item: &Table,
) -> DbTransactionResult<ItemId>
where
Value: Serialize,
{
let ids = self.get_item_ids(index, index_value).await?;
match ids.len() {
0 => self.add_item(item).await,
1 => {
let item_id = ids[0];
self.replace_item(item_id, item).await
},
got_items => MmError::err(DbTransactionError::MultipleItemsByUniqueIndex {
index: index.to_owned(),
got_items,
}),
}
}
/// Adds the given `item` or replace the previous one if such item with the specified multiple indexes exists already.
/// https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/put
///
/// For more details on multiple indexes see [`TableUpgrader::create_multi_index`].
pub async fn replace_item_by_unique_multi_index(
&self,
multi_index: MultiIndex,
item: &Table,
) -> DbTransactionResult<ItemId> {
self.replace_item_by_unique_index(&multi_index.index, multi_index.values, item)
.await
}
/// Deletes an item from the store by the specified `item_id`.
/// https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/delete
pub async fn delete_item(&self, item_id: ItemId) -> DbTransactionResult<()> {
let (result_tx, result_rx) = oneshot::channel();
let event = internal::DbTableEvent::DeleteItem { item_id, result_tx };
send_event_recv_response(&self.event_tx, event, result_rx).await
}
/// Tries to find an item by the **unique** `index` and removes it if it exists.
/// Returns `Ok(None)` if there is no an item with the given `index`.
/// https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/delete
///
/// * `index` - the name of a corresponding `Table`'s field by which records will be searched.
/// * `index_value` - the value of the `index`, therefore the value of a corresponding `Table`'s field.
pub async fn delete_item_by_unique_index<Value>(
&self,
index: &str,
index_value: Value,
) -> DbTransactionResult<Option<ItemId>>
where
Value: Serialize,
{
let ids = self.get_item_ids(index, index_value).await?;
match ids.len() {
0 => Ok(None),
1 => {
let item_id = ids[0];
self.delete_item(item_id).await?;
Ok(Some(item_id))
},
got_items => MmError::err(DbTransactionError::MultipleItemsByUniqueIndex {
index: index.to_owned(),
got_items,
}),
}
}
/// Tries to find an item matching the specified **unique** multiple indexes and removes the item if it exists.
/// Returns `Ok(None)` if there is no an item with the given keys.
/// https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/delete
///
/// For more details on multiple indexes see [`TableUpgrader::create_multi_index`].
pub async fn delete_item_by_unique_multi_index(
&self,
multi_index: MultiIndex,
) -> DbTransactionResult<Option<ItemId>> {
self.delete_item_by_unique_index(&multi_index.index, multi_index.values)
.await
}
/// Tries to find items matching the given `index` and removes them from the store.
/// Returns IDs of removed items.
/// https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/delete
pub async fn delete_items_by_index<Value>(
&self,
index: &str,
index_value: Value,
) -> DbTransactionResult<Vec<ItemId>>
where
Value: Serialize,
{
let ids = self.get_item_ids(index, index_value).await?;
for item_id in ids.iter() {
self.delete_item(*item_id).await?;
}
Ok(ids)
}
/// Tries to find items matching the given multiple indexes and removes them from the store.
/// Returns IDs of removed items.
/// https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/delete
///
/// For more details on multiple indexes see [`TableUpgrader::create_multi_index`].
pub async fn delete_items_by_multi_index(&self, multi_index: MultiIndex) -> DbTransactionResult<Vec<ItemId>> {
self.delete_items_by_index(&multi_index.index, multi_index.values).await
}
/// Deletes all items from the store.
/// https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/clear
pub async fn clear(&self) -> DbTransactionResult<()> {
let (result_tx, result_rx) = oneshot::channel();
let event = internal::DbTableEvent::Clear { result_tx };
send_event_recv_response(&self.event_tx, event, result_rx).await
}
/// Returns a `CursorBuilder` builder. It can be used to open a cursor at the specified with specific key bounds.
/// See [`CursorBuilder::open_cursor`].
pub fn cursor_builder<'reference>(&'reference self) -> CursorBuilder<'transaction, 'reference, Table> {
CursorBuilder::new(self)
}
/// Whether the transaction is aborted.
pub async fn aborted(&self) -> DbTransactionResult<bool> {
let (result_tx, result_rx) = oneshot::channel();
let event = internal::DbTableEvent::IsAborted { result_tx };
send_event_recv_response(&self.event_tx, event, result_rx).await
}
/// Opens a cursor by the specified `index`.
/// https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/openCursor
async fn open_cursor(
&self,
index: &str,
filters: CursorFilters,
filters_ext: CursorFiltersExt,
) -> CursorResult<DbCursorEventTx> {
let (result_tx, result_rx) = oneshot::channel();
let event = internal::DbTableEvent::OpenCursor {
index: index.to_owned(),
filters,
filters_ext,
result_tx,
};
let cursor_event_tx = send_event_recv_response(&self.event_tx, event, result_rx)
.await
.mm_err(|e| CursorError::UnexpectedState(e.to_string()))?;
Ok(cursor_event_tx)
}
fn deserialize_items(items: Vec<(ItemId, Json)>) -> DbTransactionResult<Vec<(ItemId, Table)>> {
items
.into_iter()
.map(|(item_id, item)| {
let item: Table =
json::from_value(item).map_to_mm(|e| DbTransactionError::ErrorDeserializingItem(e.to_string()))?;
Ok((item_id, item))
})
.collect()
}
}
/// This event loop cannot be part of the `DbTable`, because the `Table` type parameter is not known when this function is called.
async fn table_event_loop(mut rx: mpsc::UnboundedReceiver<internal::DbTableEvent>, table: IdbObjectStoreImpl) {
while let Some(event) = rx.next().await {
match event {
internal::DbTableEvent::AddItem { item, result_tx } => {
let res = table.add_item(&item).await;
result_tx.send(res).ok();
},
internal::DbTableEvent::GetItems {
index,
index_value,
result_tx,
} => {
let res = table.get_items(&index, index_value).await;
result_tx.send(res).ok();
},
internal::DbTableEvent::GetItemIds {
index,
index_value,
result_tx,
} => {
let res = table.get_item_ids(&index, index_value).await;
result_tx.send(res).ok();
},
internal::DbTableEvent::GetAllItems { result_tx } => {
let res = table.get_all_items().await;
result_tx.send(res).ok();
},
internal::DbTableEvent::Count {
index,
index_value,
result_tx,
} => {
let res = table.count(&index, index_value).await;
result_tx.send(res).ok();
},
internal::DbTableEvent::CountAll { result_tx } => {
let res = table.count_all().await;
result_tx.send(res).ok();
},
internal::DbTableEvent::ReplaceItem {
item_id,
item,
result_tx,
} => {
let res = table.replace_item(item_id, item).await;
result_tx.send(res).ok();
},
internal::DbTableEvent::DeleteItem { item_id, result_tx } => {
let res = table.delete_item(item_id).await;
result_tx.send(res).ok();
},
internal::DbTableEvent::Clear { result_tx } => {
let res = table.clear().await;
result_tx.send(res).ok();
},
internal::DbTableEvent::IsAborted { result_tx } => {
result_tx.send(Ok(table.aborted())).ok();
},
internal::DbTableEvent::OpenCursor {
index,
filters,
filters_ext,
result_tx,
} => {
open_cursor(&table, index, filters, filters_ext, result_tx);
},
}
}
}
pub struct MultiIndex {
index: String,
values: Vec<Json>,
}
impl MultiIndex {
pub fn new(index: &str) -> MultiIndex {
MultiIndex {
index: index.to_owned(),
values: Vec::new(),
}
}
pub fn push<Value: Serialize>(&mut self, value: Value) -> DbTransactionResult<&mut Self> {
let index_value = try_serialize_index_value!(json::to_value(value), self.index);
self.values.push(index_value);
Ok(self)
}
pub fn with_value<Value: Serialize>(mut self, value: Value) -> DbTransactionResult<Self> {
self.push(value)?;
Ok(self)
}
}
fn open_cursor(
table: &IdbObjectStoreImpl,
index: String,
filters: CursorFilters,
filter_ext: CursorFiltersExt,
result_tx: oneshot::Sender<CursorResult<DbCursorEventTx>>,
) {
let db_index = match table.open_index(&index) {
Ok(db_index) => db_index,
Err(tr_err) => {
let cursor_err = tr_err.map(|tr_err| CursorError::ErrorOpeningCursor {
description: tr_err.to_string(),
});
result_tx.send(Err(cursor_err)).ok();
return;
},
};
let cursor = match CursorDriver::init_cursor(db_index, filters, filter_ext) {
Ok(cursor) => cursor,
Err(e) => {
result_tx.send(Err(e)).ok();
return;
},
};
let (event_tx, event_rx) = mpsc::unbounded();
let fut = async move { cursor_event_loop(event_rx, cursor).await };
// `cursor_event_loop` will finish almost immediately once `event_tx` is dropped.
spawn_local(fut);
// ignore if the receiver is closed
result_tx.send(Ok(event_tx)).ok();
}
/// Detects the current execution environment (window or worker) and follows the appropriate way
/// of getting `web_sys::IdbFactory` instance.
pub(crate) fn get_idb_factory() -> Result<web_sys::IdbFactory, InitDbError> {
// try getting global with type safety and explicit type conversion.
let global = js_sys::global()
.dyn_into::<js_sys::Object>()
.map_err(|err| InitDbError::NotSupported(format!("{err:?}")))?;
let idb_factory = if let Some(window) = global.dyn_ref::<Window>() {
window.indexed_db()
} else if let Some(worker) = global.dyn_ref::<WorkerGlobalScope>() {
worker.indexed_db()
} else {
return Err(InitDbError::NotSupported("Unknown WASM environment.".to_string()));
};
match idb_factory {
Ok(Some(db)) => Ok(db),
Ok(None) => Err(InitDbError::NotSupported(
if global.dyn_ref::<Window>().is_some() {
"IndexedDB not supported in window context"
} else {
"IndexedDB not supported in worker context"
}
.to_string(),
)),
Err(e) => Err(InitDbError::NotSupported(stringify_js_error(&e))),
}
}
/// Internal events.
mod internal {
use super::*;
pub(super) enum DbEvent {
CreateTransaction {
result_tx: oneshot::Sender<DbTransactionResult<DbTransactionEventTx>>,
},
}
pub(super) enum DbTransactionEvent {
OpenTable {
table_name: String,
result_tx: oneshot::Sender<DbTransactionResult<mpsc::UnboundedSender<DbTableEvent>>>,
},
IsAborted {
result_tx: oneshot::Sender<DbTransactionResult<bool>>,
},
}
pub(super) enum DbTableEvent {
AddItem {
item: Json,
result_tx: oneshot::Sender<DbTransactionResult<ItemId>>,
},
GetItems {
index: String,
index_value: Json,
result_tx: oneshot::Sender<DbTransactionResult<Vec<(ItemId, Json)>>>,
},
GetItemIds {
index: String,
index_value: Json,
result_tx: oneshot::Sender<DbTransactionResult<Vec<ItemId>>>,
},
GetAllItems {
result_tx: oneshot::Sender<DbTransactionResult<Vec<(ItemId, Json)>>>,
},
Count {
index: String,
index_value: Json,
result_tx: oneshot::Sender<DbTransactionResult<usize>>,
},
CountAll {
result_tx: oneshot::Sender<DbTransactionResult<usize>>,
},
ReplaceItem {
item_id: ItemId,
item: Json,
result_tx: oneshot::Sender<DbTransactionResult<ItemId>>,
},
DeleteItem {
item_id: ItemId,
result_tx: oneshot::Sender<DbTransactionResult<()>>,
},
Clear {
result_tx: oneshot::Sender<DbTransactionResult<()>>,
},
IsAborted {
result_tx: oneshot::Sender<DbTransactionResult<bool>>,
},
OpenCursor {
index: String,
filters: CursorFilters,
filters_ext: CursorFiltersExt,
result_tx: oneshot::Sender<CursorResult<DbCursorEventTx>>,
},
}
}
mod tests {
use super::*;
use common::log::wasm_log::register_wasm_log;
use lazy_static::lazy_static;
use serde::{Deserialize, Serialize};
use wasm_bindgen_test::*;
wasm_bindgen_test_configure!(run_in_browser);
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
struct TxTable {
ticker: String,
tx_hash: String,
block_height: u64,
}
impl TableSignature for TxTable {
const TABLE_NAME: &'static str = "tx_table";
fn on_upgrade_needed(upgrader: &DbUpgrader, old_version: u32, _new_version: u32) -> OnUpgradeResult<()> {
if old_version > 0 {
// the table is initialized already
return Ok(());
}
let table_upgrader = upgrader.create_table("tx_table")?;
table_upgrader.create_index("ticker", false)?;
table_upgrader.create_index("tx_hash", true)
}
}
#[wasm_bindgen_test]
async fn test_add_get_item() {
const DB_NAME: &str = "TEST_ADD_GET_ITEM";
const DB_VERSION: u32 = 1;
let rick_tx_1 = TxTable {
ticker: "RICK".to_owned(),
tx_hash: "0a0fda88364b960000f445351fe7678317a1e0c80584de0413377ede00ba696f".to_owned(),
block_height: 10000,
};
let rick_tx_2 = TxTable {
ticker: "RICK".to_owned(),
tx_hash: "ba881ecca15b5d4593f14f25debbcdfe25f101fd2e9cf8d0b5d92d19813d4424".to_owned(),
block_height: 10000,
};
let morty_tx_1 = TxTable {
ticker: "MORTY".to_owned(),
tx_hash: "1fc789133239260ed16361190a026a88cab2243935f02f1ccd794f1d06a22246".to_owned(),
block_height: 20000,
};
register_wasm_log();
let db = IndexedDbBuilder::new(DbIdentifier::for_test(DB_NAME))
.with_version(DB_VERSION)
.with_table::<TxTable>()
.build()
.await
.expect("!IndexedDb::init");
let transaction = db.transaction().await.expect("!IndexedDb::transaction()");
let table = transaction
.table::<TxTable>()
.await
.expect("!DbTransaction::open_table");
let rick_tx_1_id = table
.add_item(&rick_tx_1)
.await
.expect("!Couldn't add a 'RICK' transaction");