-
Notifications
You must be signed in to change notification settings - Fork 76
Expand file tree
/
Copy pathdb.rs
More file actions
2959 lines (2636 loc) · 116 KB
/
Copy pathdb.rs
File metadata and controls
2959 lines (2636 loc) · 116 KB
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
//! Persistent, ACID compliant, threadsafe to-disk store.
//! Powered by Sled - an embedded database.
pub mod btreemap_store;
mod encoding;
pub mod kv_store;
#[cfg(feature = "db-sled")]
mod migrations;
#[cfg(all(feature = "db-redb", target_arch = "wasm32"))]
pub mod opfs_backend;
pub mod plugin_meta;
mod prop_val_sub_index;
mod query_index;
#[cfg(feature = "db-redb")]
pub mod redb_store;
pub use query_index::{drive_prefix_from_subject, QueryFilter};
#[cfg(feature = "db-sled")]
pub mod sled_store;
#[cfg(test)]
pub mod test;
pub mod trees;
#[cfg(feature = "db-sled")]
mod v1_types;
#[cfg(feature = "db-sled")]
mod v2_types;
mod val_prop_sub_index;
use std::{
collections::{HashMap, HashSet},
sync::{Arc, Mutex, RwLock},
vec,
};
use crate::{
agents::ForAgent,
atoms::IndexAtom,
class_extender::{
ClassExtender, ClassExtenderScope, CommitExtenderContext, GetExtenderContext,
},
commit::{CommitOpts, CommitResponse},
db::{
encoding::{decode_propvals, encode_propvals},
plugin_meta::{PluginMeta, PluginMetaKey},
query_index::{requires_query_index, NO_VALUE},
val_prop_sub_index::find_in_val_prop_sub_index,
},
endpoints::{Endpoint, HandleGetContext},
errors::{AtomicError, AtomicResult},
resources::PropVals,
storelike::{Query, QueryResult, ResourceResponse, Storelike},
urls,
values::SortableValue,
Atom, Commit, Resource, Subject, Value,
};
use async_trait::async_trait;
use tracing::{info, instrument};
use trees::{Method, Operation, Transaction, Tree};
use self::{
kv_store::KvStore,
prop_val_sub_index::{add_atom_to_prop_val_sub_index, find_in_prop_val_sub_index},
query_index::{
check_if_atom_matches_watched_query_filters, query_sorted_indexed, should_include_resource,
update_indexed_member, IndexIterator,
},
val_prop_sub_index::add_atom_to_valpropsub_index,
};
// A function called by the Store when a Commit is accepted
type HandleCommit = Box<dyn Fn(&CommitResponse) + Send + Sync>;
/// Event emitted when a resource is created, updated, or deleted.
#[derive(Debug, Clone)]
pub enum DbEvent {
/// Resource changed. Carries the subject (pure_id) and the Loro delta if available.
Changed {
subject: Subject,
/// The Loro delta (from the commit's loro_update). None for non-Loro changes.
delta: Option<Vec<u8>>,
/// Optional transport/source identity for echo suppression.
source_id: Option<String>,
/// True when this change created the resource (no prior version).
is_new: bool,
/// Whether an applied commit produced this change.
///
/// A commit also runs `handle_commit`, which is how `atomic-server`
/// tells subscribed WebSocket clients that something moved. Writes that
/// arrive as raw CRDT state — a peer's live `UPDATE` frame, a bulk
/// `SYNC_PUSH` import — have no commit, so nothing announces them and
/// the local UI renders a store it no longer matches. Listeners use
/// this to fan out exactly the changes the commit hook won't.
from_commit: bool,
},
/// Resource destroyed.
Destroyed {
subject: Subject,
/// Optional transport/source identity for echo suppression.
source_id: Option<String>,
/// See [`DbEvent::Changed::from_commit`].
from_commit: bool,
},
/// A resource entered or left the result set of a watched query. Emitted
/// from `apply_transaction` after a successful write that touches
/// `Tree::QueryMembers`. `filter_bytes` is the encoded `QueryFilter`
/// (the same key used in `Tree::WatchedQueries`).
///
/// Note: a sort-key change on an already-matching resource produces a
/// (Removed, Added) pair for the same `(filter_bytes, subject)` within a
/// single commit. Consumers that want true add/remove semantics should
/// dedup; consumers that want every membership-touching event (the
/// current text `QUERY_UPDATE` model) can pass them through.
QueryMembershipChanged {
filter_bytes: Vec<u8>,
subject: String,
added: bool,
/// Optional transport/source identity for echo suppression.
source_id: Option<String>,
},
}
/// A drive with its subject and display name.
#[derive(Debug, Clone, serde::Serialize)]
pub struct DriveInfo {
pub subject: String,
pub name: String,
}
/// Per-drive storage usage. A managed node reports these to its control plane
/// (`POST /api/node-usage`) for quota tracking; field names match that wire
/// contract. See [`Db::per_drive_usage`].
#[derive(Debug, Clone, serde::Serialize)]
pub struct DriveUsage {
pub drive_subject: String,
pub name: Option<String>,
pub resource_count: u64,
pub blob_bytes: u64,
pub loro_bytes: u64,
}
/// Result of loading an agent from a secret.
pub struct AgentLoadResult {
pub agent: crate::agents::Agent,
/// If true, the drive DID from the secret doesn't exist locally.
/// The caller must sync with another device to obtain the genesis commit.
pub drive_needs_sync: bool,
}
/// Result of mapping an incoming request target to a canonical subject.
pub struct ResolvedTarget {
pub subject: Subject,
pub alias_subject: Option<String>,
}
/// Inside the reference_index, each value is mapped to this type.
/// The String on the left represents a Property URL, and the second one is the set of subjects.
pub type PropSubjectMap = HashMap<String, HashSet<String>>;
/// A remote Atomic Server that a drive is replicated to.
///
/// Deliberately server-local: see [`Db::get_replication_targets`] for why this
/// must never be stored inside the drive it describes.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ReplicationTarget {
/// WebSocket URL of the remote server, e.g. `wss://example.com/ws`.
pub url: String,
/// The agent that asked for this replication. Its *read* rights bound what
/// gets exported, so a later boot-time re-run stays scoped to what the
/// person who authorized it could actually see.
pub authorized_by: String,
}
const REPLICATION_PREFIX: &str = "replication:";
fn replication_key(drive: &str) -> String {
format!("{REPLICATION_PREFIX}{drive}")
}
/// The Db is a persistent on-disk Atomic Data store.
/// It's an implementation of [Storelike].
/// It uses a [KvStore] backend for key-value storage (sled, BTreeMap, etc.).
/// It stores [Resource]s as [PropVals]s by their subject as key.
/// It builds a value index for performant [Query]s.
/// It keeps track of Queries and updates their index when [crate::Commit]s are applied.
/// You can pass a custom `on_commit` function to run at Commit time.
/// `Db` should be easily, cheaply clone-able, as users of this library could have one `Db` per connection.
#[derive(Clone)]
pub struct Db {
/// The key-value store backend. Abstracted behind a trait so different
/// backends (sled, BTreeMap, etc.) can be used interchangeably.
pub kv: Arc<dyn KvStore>,
default_agent: Arc<Mutex<Option<crate::agents::Agent>>>,
/// Endpoints are checked whenever a resource is requested. They calculate (some properties of) the resource and return it.
endpoints: Vec<Endpoint>,
/// List of class extenders.
class_extenders: Arc<RwLock<Vec<ClassExtender>>>,
/// Function called whenever a Commit is applied.
on_commit: Option<Arc<HandleCommit>>,
/// Broadcast channel for all resource mutations.
db_events: tokio::sync::broadcast::Sender<DbEvent>,
/// In-memory authoritative map of watched query filters, keyed by drive
/// prefix (e.g. `"https://example.com"` for HTTP drives, the DID for
/// DID-form drives). The KV `Tree::WatchedQueries` is the persistence
/// layer; this map is the runtime lookup. Populated from the KV at Db
/// open, kept in sync by `Db::register_watched_query`. The hot path in
/// `check_if_atom_matches_watched_query_filters` reads from here and
/// never touches msgpack on a commit.
watched_queries_by_drive: Arc<RwLock<HashMap<String, Vec<Arc<query_index::QueryFilter>>>>>,
/// Where the DB is stored on disk.
#[allow(dead_code)]
path: std::path::PathBuf,
/// The base domain of the store.
pub base_domain: Option<String>,
/// Sync admission/quota policy consulted before importing a `SYNC_PUSH`.
/// Defaults to the permissive [`crate::sync::policy::OpenPolicy`] so
/// self-hosted / local-first nodes are unrestricted; a managed node
/// installs a concrete policy via [`Db::set_sync_policy`].
sync_policy: Arc<RwLock<Arc<dyn crate::sync::policy::SyncPolicy>>>,
/// Short-lived hash → (drive-subject, requested-at) map for blob hashes
/// the server has asked a peer for (via `BLOB_REQUEST`, emitted from
/// `import_sync_push` for an already-admitted drive). Consulted when
/// the matching `BLOB_RESPONSE` arrives — a frame with no matching
/// entry here was never requested and is rejected outright; one with a
/// match is gated through `sync_policy().admit_drive_write` before the
/// bytes are stored (planning/unified-sync.md F4). Node-wide rather
/// than per-connection: cloning `Db` shares the same `Arc`, so it
/// works uniformly whether the response arrives over the WS or Iroh
/// transport. Entries are normally consumed (removed) on first use; a
/// peer that never responds would otherwise leak one entry per missing
/// blob forever, so `note_pending_blob_request` also lazily prunes
/// anything older than `PENDING_BLOB_REQUEST_TTL`.
pending_blob_requests: Arc<RwLock<HashMap<[u8; 32], (String, std::time::Instant)>>>,
}
/// How long an unanswered `BLOB_REQUEST` stays in `pending_blob_requests`
/// before lazy pruning drops it. Generous relative to a realistic peer
/// round trip (seconds) — this bounds a slow leak from peers that vanish
/// mid-sync, not a normal-latency budget.
const PENDING_BLOB_REQUEST_TTL: std::time::Duration = std::time::Duration::from_secs(300);
/// The default (permissive) sync policy reference used by every `Db` until a
/// managed node installs one.
fn default_sync_policy() -> Arc<RwLock<Arc<dyn crate::sync::policy::SyncPolicy>>> {
Arc::new(RwLock::new(Arc::new(crate::sync::policy::OpenPolicy)))
}
impl Db {
/// Install a sync admission/quota policy (managed nodes). The default is
/// [`crate::sync::policy::OpenPolicy`] (allow everything, no quotas).
pub fn set_sync_policy(&self, policy: Arc<dyn crate::sync::policy::SyncPolicy>) {
if let Ok(mut guard) = self.sync_policy.write() {
*guard = policy;
}
}
/// The currently-installed sync policy.
pub fn sync_policy(&self) -> Arc<dyn crate::sync::policy::SyncPolicy> {
self.sync_policy
.read()
.map(|guard| guard.clone())
.unwrap_or_else(|_| Arc::new(crate::sync::policy::OpenPolicy))
}
/// Record that the server asked a peer for `hash` while importing a
/// `SYNC_PUSH` for `drive` (already admission-checked at that point).
/// Consulted by the `BLOB_RESPONSE` handler (planning/unified-sync.md
/// F4) so it can gate the write against that same drive instead of
/// accepting arbitrary blob bytes unconditionally.
pub fn note_pending_blob_request(&self, hash: [u8; 32], drive: String) {
if let Ok(mut guard) = self.pending_blob_requests.write() {
let now = std::time::Instant::now();
guard.retain(|_, (_, requested_at)| {
now.duration_since(*requested_at) < PENDING_BLOB_REQUEST_TTL
});
guard.insert(hash, (drive, now));
}
}
/// Consume (remove) the drive a pending `BLOB_REQUEST` for `hash` was
/// issued for, if any. `None` means this hash was never requested by
/// this node (or the request expired — see `PENDING_BLOB_REQUEST_TTL`)
/// — the caller should reject the response outright.
pub fn take_pending_blob_request(&self, hash: &[u8; 32]) -> Option<String> {
let (drive, requested_at) = self
.pending_blob_requests
.write()
.ok()
.and_then(|mut guard| guard.remove(hash))?;
if requested_at.elapsed() < PENDING_BLOB_REQUEST_TTL {
Some(drive)
} else {
None
}
}
/// Creates a new store at the specified path, or opens the store if it already exists.
/// Uses sled as the storage backend.
#[cfg(feature = "db-sled")]
pub async fn init(path: &std::path::Path, base_domain: Option<String>) -> AtomicResult<Db> {
tracing::info!("Opening database at {:?}", path);
let sled_store = sled_store::SledStore::open(path)?;
// Run migrations before wrapping in Arc (migrations need direct sled access)
migrations::migrate_maybe(&sled_store)
.map(|e| format!("Error during migration of database: {:?}", e))?;
let store = Db {
path: path.into(),
kv: Arc::new(sled_store),
default_agent: Arc::new(Mutex::new(None)),
endpoints: vec![],
class_extenders: Arc::new(RwLock::new(vec![])),
on_commit: None,
db_events: tokio::sync::broadcast::channel(64).0,
watched_queries_by_drive: Arc::new(RwLock::new(HashMap::new())),
base_domain,
sync_policy: default_sync_policy(),
pending_blob_requests: Arc::new(RwLock::new(HashMap::new())),
};
store.add_class_extender(crate::collections::get_collection_class_extender())?;
// Load persisted watched-queries (if any) into the in-memory map
// before bootstrap, so any filter-matching commits during bootstrap
// see the right state.
store.populate_watched_queries_cache()?;
// Re-run on every startup so new vocabulary (properties, classes) added
// to default_store.json is available without a manual `populate` command.
crate::populate::bootstrap(&store)
.await
.map_err(|e| format!("Failed to populate base models. {}", e))?;
Ok(store)
}
/// Creates a Db backed by an in-memory BTreeMap store.
/// Useful for tests and WASM targets.
pub async fn init_memory(base_domain: Option<String>) -> AtomicResult<Db> {
let store = Db {
path: std::path::PathBuf::new(),
kv: Arc::new(btreemap_store::BTreeMapStore::new()),
default_agent: Arc::new(Mutex::new(None)),
endpoints: vec![],
class_extenders: Arc::new(RwLock::new(vec![])),
on_commit: None,
db_events: tokio::sync::broadcast::channel(64).0,
watched_queries_by_drive: Arc::new(RwLock::new(HashMap::new())),
base_domain,
sync_policy: default_sync_policy(),
pending_blob_requests: Arc::new(RwLock::new(HashMap::new())),
};
store.add_class_extender(crate::collections::get_collection_class_extender())?;
store.populate_watched_queries_cache()?;
crate::populate::bootstrap(&store)
.await
.map_err(|e| format!("Failed to populate base models. {}", e))?;
Ok(store)
}
/// Creates a Db backed by redb with an in-memory backend.
/// Useful for WASM targets where redb provides proper B-tree indexing.
/// Can be upgraded to OPFS persistence in the future.
#[cfg(feature = "db-redb")]
pub async fn init_redb(base_domain: Option<String>) -> AtomicResult<Db> {
let redb_store = redb_store::RedbStore::new_memory()?;
let store = Db {
path: std::path::PathBuf::new(),
kv: Arc::new(redb_store),
default_agent: Arc::new(Mutex::new(None)),
endpoints: vec![],
class_extenders: Arc::new(RwLock::new(vec![])),
on_commit: None,
db_events: tokio::sync::broadcast::channel(64).0,
watched_queries_by_drive: Arc::new(RwLock::new(HashMap::new())),
base_domain,
sync_policy: default_sync_policy(),
pending_blob_requests: Arc::new(RwLock::new(HashMap::new())),
};
store.add_class_extender(crate::collections::get_collection_class_extender())?;
store.populate_watched_queries_cache()?;
crate::populate::bootstrap(&store)
.await
.map_err(|e| format!("Failed to populate base models. {}", e))?;
Ok(store)
}
/// Creates a Db backed by redb with file-based persistent storage.
/// Works on all native targets (not WASM — use init_redb_opfs for that).
#[cfg(all(feature = "db-redb", not(target_arch = "wasm32")))]
pub async fn init_redb_file(
path: &std::path::Path,
base_domain: Option<String>,
uploads_path: &std::path::Path,
) -> AtomicResult<Db> {
tracing::info!("Opening ReDB database at {:?}", path);
std::fs::create_dir_all(path).map_err(|e| {
format!(
"Failed to create database directory {}: {e}",
path.display()
)
})?;
let redb_path = path.join("atomic.redb");
// Migration logic: if a sled store exists but redb doesn't, migrate it.
#[cfg(feature = "db-sled")]
if !redb_path.exists() {
let sled_path = path.join("sled");
// Pre-redb servers stored the sled DB directly in the store dir
// (`store/db`, `store/conf`), NOT in a `sled/` subdir. Detect that
// legacy layout and relocate the sled files into `sled/` first.
// Without this the auto-migration never fires on a real in-place
// upgrade, and `migrate_from_sled`'s rename-to-`.bak` would try to
// rename the whole store dir — clobbering the redb we just wrote.
let legacy_root_sled =
!sled_path.exists() && path.join("db").exists() && path.join("conf").exists();
if legacy_root_sled {
tracing::warn!(
"Detected a legacy sled store at the store root; relocating it into `sled/` before migration."
);
std::fs::create_dir_all(&sled_path)?;
// Collect first, then move — don't mutate the dir mid-iteration.
// Everything in the store dir is sled's (uploads live elsewhere);
// skip the `sled/` dir we just created.
let names: Vec<std::ffi::OsString> = std::fs::read_dir(path)?
.filter_map(|e| e.ok())
.map(|e| e.file_name())
.filter(|name| name.as_os_str() != "sled")
.collect();
for name in names {
std::fs::rename(path.join(&name), sled_path.join(&name))?;
}
}
if sled_path.exists() {
Self::migrate_from_sled(
&sled_path,
&redb_path,
uploads_path,
base_domain.as_deref(),
)
.await?;
}
} else {
let _ = uploads_path;
}
#[cfg(not(feature = "db-sled"))]
let _ = uploads_path;
let redb_store = redb_store::RedbStore::new_file(&redb_path)?;
let store = Db {
path: path.to_path_buf(),
kv: Arc::new(redb_store),
default_agent: Arc::new(Mutex::new(None)),
endpoints: vec![],
class_extenders: Arc::new(RwLock::new(vec![])),
on_commit: None,
db_events: tokio::sync::broadcast::channel(64).0,
watched_queries_by_drive: Arc::new(RwLock::new(HashMap::new())),
base_domain,
sync_policy: default_sync_policy(),
pending_blob_requests: Arc::new(RwLock::new(HashMap::new())),
};
store.add_class_extender(crate::collections::get_collection_class_extender())?;
store.populate_watched_queries_cache()?;
crate::populate::bootstrap(&store)
.await
.map_err(|e| format!("Failed to populate base models. {}", e))?;
Ok(store)
}
#[cfg(all(feature = "db-redb", feature = "db-sled", not(target_arch = "wasm32")))]
async fn migrate_from_sled(
sled_path: &std::path::Path,
redb_path: &std::path::Path,
uploads_path: &std::path::Path,
base_domain: Option<&str>,
) -> AtomicResult<()> {
tracing::warn!("Migrating data from Sled to ReDB and files to CAS...");
let sled_store = sled_store::SledStore::open(sled_path)?;
// Bring the sled schema fully up to date BEFORE reading Tree::Resources.
// A pre-v3 backup keeps its data in `resources_v2` (or `resources_v1`);
// without this, the loop below reads the empty `resources_v3` tree and
// silently migrates ZERO user resources — then renames the source dir to
// `.bak`. `migrate_maybe` chains v0→v1→v2→v3 in place so the read sees
// every resource. (Verified against a real v2 backup: 61,804 resources
// were invisible without this call.)
migrations::migrate_maybe(&sled_store)?;
let redb_store = redb_store::RedbStore::new_file(redb_path)?;
let mut count_resources = 0;
let mut count_snapshots = 0;
let mut count_blobs = 0;
// Migrate Resources
for item in sled_store.iter_tree(Tree::Resources) {
let (subject_bytes, propvals_bin) = item?;
let subject_str = String::from_utf8_lossy(&subject_bytes).to_string();
// Try to decode with various versions
let mut propvals = if let Ok(pv) = rmp_serde::from_slice::<PropVals>(&propvals_bin) {
pv
} else if let Ok(pv_v2) = rmp_serde::from_slice::<v2_types::PropValsV2>(&propvals_bin) {
v2_types::propvals_v2_to_v3(pv_v2, base_domain.unwrap_or("localhost"))
} else if let Ok(pv_v1) = bincode1::deserialize::<v1_types::PropValsV1>(&propvals_bin) {
v1_types::propvals_v1_to_v2(pv_v1)
} else {
tracing::error!("Failed to migrate resource: {}", subject_str);
continue;
};
// Migrate File resources to CAS
let is_file = propvals
.get(urls::IS_A)
.map(|v| v.to_string().contains(urls::FILE))
.unwrap_or(false);
if is_file && !propvals.contains_key(urls::BLOB) {
if let Some(internal_id) = propvals.get(urls::INTERNAL_ID).map(|v| v.to_string()) {
let file_path = uploads_path.join(&internal_id);
if file_path.exists() {
if let Ok(bytes) = std::fs::read(&file_path) {
let hash = blake3::hash(&bytes);
let hash_hex = hash.to_hex().to_string();
let hash_bytes = hash.as_bytes();
redb_store.insert(Tree::Blobs, hash_bytes, &bytes)?;
propvals.insert(
urls::BLOB.to_string(),
Value::AtomicUrl(
format!("did:ad:blob:{}", hash_hex.clone()).into(),
),
);
propvals.insert(urls::INTERNAL_ID.to_string(), Value::String(hash_hex));
count_blobs += 1;
}
}
}
}
redb_store.insert(
Tree::Resources,
&subject_bytes,
&rmp_serde::to_vec(&propvals).unwrap(),
)?;
count_resources += 1;
}
// Migrate LoroSnapshots
for item in sled_store.iter_tree(Tree::LoroSnapshots) {
let (key, val) = item?;
redb_store.insert(Tree::LoroSnapshots, &key, &val)?;
count_snapshots += 1;
}
// Migrate other metadata trees
for tree in [Tree::PluginMeta, Tree::DriveMapping, Tree::DidMapping] {
for item in sled_store.iter_tree(tree.clone()) {
let (key, val) = item?;
redb_store.insert(tree.clone(), &key, &val)?;
}
}
tracing::info!(
"Migration complete: {} resources, {} snapshots, {} blobs migrated.",
count_resources,
count_snapshots,
count_blobs
);
// Optionally rename old sled dir
let mut backup_path = sled_path.to_path_buf();
backup_path.set_extension("bak");
let _ = std::fs::rename(sled_path, backup_path);
Ok(())
}
/// Creates a Db backed by redb with OPFS persistent storage.
/// Only available in WASM Workers. Data survives page reloads.
#[cfg(all(feature = "db-redb", target_arch = "wasm32"))]
pub async fn init_redb_opfs(base_domain: Option<String>, filename: &str) -> AtomicResult<Db> {
let redb_store = redb_store::RedbStore::new_opfs(filename).await?;
let store = Db {
path: std::path::PathBuf::new(),
kv: Arc::new(redb_store),
default_agent: Arc::new(Mutex::new(None)),
endpoints: vec![],
class_extenders: Arc::new(RwLock::new(vec![])),
on_commit: None,
db_events: tokio::sync::broadcast::channel(64).0,
watched_queries_by_drive: Arc::new(RwLock::new(HashMap::new())),
base_domain,
sync_policy: default_sync_policy(),
pending_blob_requests: Arc::new(RwLock::new(HashMap::new())),
};
store.add_class_extender(crate::collections::get_collection_class_extender())?;
store.populate_watched_queries_cache()?;
crate::populate::bootstrap(&store)
.await
.map_err(|e| format!("Failed to populate base models. {}", e))?;
Ok(store)
}
/// Creates a clone of the store with a different base_domain.
/// This is useful for multi-tenant applications.
/// Cloning is very cheap, as it only clones Arc pointers.
pub fn clone_with_url(&self, base_domain: String) -> Db {
let mut clone = self.clone();
clone.base_domain = Some(base_domain);
clone
}
/// Create a temporary in-memory Db. Useful for testing.
/// Populates the database, creates a default agent, and sets the server_url to "http://localhost/".
/// This variant covers `db` builds without a disk backend (e.g. `ws`
/// alone) by running on the same BTreeMap store WASM targets use.
#[cfg(all(not(feature = "db-sled"), not(feature = "db-redb")))]
pub async fn init_temp(_id: &str) -> AtomicResult<Db> {
let store = Db::init_memory(Some("https://localhost".into())).await?;
let agent = store.create_agent(None).await?;
store.set_default_agent(agent);
store.populate().await?;
Ok(store)
}
/// Create a temporary Db in `.temp/db/{id}`. Useful for testing.
/// Populates the database, creates a default agent, and sets the server_url to "http://localhost/".
#[cfg(all(feature = "db-sled", not(feature = "db-redb")))]
pub async fn init_temp(id: &str) -> AtomicResult<Db> {
let tmp_dir_path = format!(".temp/db/{}", id);
let _try_remove_existing = std::fs::remove_dir_all(&tmp_dir_path);
let store = Db::init(
std::path::Path::new(&tmp_dir_path),
Some("https://localhost".into()),
)
.await?;
let agent = store.create_agent(None).await?;
store.set_default_agent(agent);
store.populate().await?;
Ok(store)
}
/// Create a temporary Db backed by ReDB. Useful for testing.
#[cfg(all(feature = "db-redb", not(target_arch = "wasm32")))]
pub async fn init_temp(id: &str) -> AtomicResult<Db> {
let tmp_dir_path = format!(".temp/db/{}", id);
let uploads_path = format!(".temp/db/{}/uploads", id);
let _try_remove_existing = std::fs::remove_dir_all(&tmp_dir_path);
std::fs::create_dir_all(&uploads_path)
.map_err(|e| format!("Failed to create temp dir: {e}"))?;
let store = Db::init_redb_file(
std::path::Path::new(&tmp_dir_path),
Some("https://localhost".into()),
std::path::Path::new(&uploads_path),
)
.await?;
let agent = store.create_agent(None).await?;
store.set_default_agent(agent);
store.populate().await?;
Ok(store)
}
// ── High-level SDK helpers ──────────────────────────────────────────────────
/// Get the active drive subject, if one is set.
pub fn get_active_drive(&self) -> Option<String> {
self.kv
.get(trees::Tree::PluginMeta, b"active_drive")
.ok()
.flatten()
.and_then(|v| String::from_utf8(v).ok())
}
/// Set the active drive subject. Persisted in the database.
pub fn set_active_drive(&self, drive: &str) -> AtomicResult<()> {
self.kv
.insert(trees::Tree::PluginMeta, b"active_drive", drive.as_bytes())
}
/// Clear the default agent.
pub fn clear_default_agent(&self) {
self.default_agent.lock().unwrap().take();
}
/// Create a new drive owned by the current agent.
/// Signs a genesis commit to produce a `did:ad:` subject.
/// Sets it as the active drive. Returns the drive DID.
pub async fn create_drive(&self, name: &str) -> AtomicResult<String> {
let agent = self.get_default_agent()?;
let mut builder = crate::commit::CommitBuilder::new("placeholder".into());
builder.set(
urls::IS_A.into(),
Value::ResourceArray(vec![urls::DRIVE.into()]),
);
builder.set(urls::NAME.into(), Value::String(name.into()));
builder.set(
urls::WRITE.into(),
Value::ResourceArray(vec![agent.subject.to_string().into()]),
);
builder.set(
urls::READ.into(),
Value::ResourceArray(vec![urls::PUBLIC_AGENT.into()]),
);
let commit = crate::commit::Commit::create_did(builder, &agent, self).await?;
let did = commit.subject.to_string();
let opts = crate::commit::CommitOpts {
validate_signature: true,
validate_timestamp: false,
validate_previous_commit: false,
validate_rights: false,
update_index: true,
..crate::commit::CommitOpts::no_validations_no_index()
};
self.apply_commit(commit, &opts).await?;
self.set_active_drive(&did)?;
// Add the new drive to the agent's `drives` array and persist.
let agent = self.get_default_agent()?;
let mut agent_resource = self.get_resource(&agent.subject).await?;
let mut drives: Vec<crate::values::SubResource> = agent_resource
.get(urls::DRIVES)
.ok()
.and_then(|v| match v {
Value::ResourceArray(arr) => Some(arr.clone()),
_ => None,
})
.unwrap_or_default();
if !drives.iter().any(|d| d.to_string() == did) {
drives.push(did.clone().into());
agent_resource.set_unsafe(urls::DRIVES.into(), Value::ResourceArray(drives))?;
self.add_resource_opts(&agent_resource, false, true, true)
.await?;
}
Ok(did)
}
/// Create a new resource with a `did:ad:` subject via genesis commit.
pub async fn create_resource(
&self,
class: &str,
parent: &str,
name: &str,
props: Option<Vec<(&str, Value)>>,
) -> AtomicResult<String> {
let agent = self.get_default_agent()?;
let mut builder = crate::commit::CommitBuilder::new("placeholder".into());
builder.set(urls::IS_A.into(), Value::ResourceArray(vec![class.into()]));
builder.set(urls::NAME.into(), Value::String(name.into()));
builder.set(urls::PARENT.into(), Value::AtomicUrl(parent.into()));
if let Some(extra) = props {
for (prop, val) in extra {
builder.set(prop.into(), val);
}
}
let commit = crate::commit::Commit::create_did(builder, &agent, self).await?;
let did = commit.subject.to_string();
let opts = crate::commit::CommitOpts {
validate_signature: true,
validate_timestamp: false,
validate_previous_commit: false,
validate_rights: false,
update_index: true,
..crate::commit::CommitOpts::no_validations_no_index()
};
self.apply_commit(commit, &opts).await?;
Ok(did)
}
/// Load an agent from a secret and set it as the default agent.
/// Persists the agent resource so its `drives` property is queryable.
/// If the secret contains a drive DID, sets it as the active drive.
///
/// Returns `AgentLoadResult` which indicates whether the drive exists locally.
/// If `drive_needs_sync` is true, the caller must sync with another device
/// before the user can create resources — the drive's genesis commit is missing.
pub async fn load_agent_from_secret(&self, secret: &str) -> AtomicResult<AgentLoadResult> {
let agent = crate::agents::Agent::from_secret(secret)?;
self.set_default_agent(agent.clone());
// Persist so list_drives() can read the agent's `drives` property
let agent_resource = agent.to_resource()?;
self.add_resource_opts(&agent_resource, false, false, true)
.await?;
let mut drive_needs_sync = false;
if let Some(drive) = &agent.initial_drive {
let drive_str = drive.to_string();
let _ = self.set_active_drive(&drive_str);
// Check if the drive resource actually exists locally.
// Without the genesis commit, the DID is just a string — the device
// can't create resources under it.
//
// `has_stored_resource`, not `get_resource`: the latter falls back to
// fetching the subject over the network, so asking whether a drive is
// *here* would go looking for it *there* — a DID resolution that can
// hang for half a minute while it holds up everything waiting on this
// call. Signing in on a device that doesn't have the drive yet is the
// normal case, not the exception.
let drive_subject = Subject::from_raw(&drive_str, self.get_base_domain().as_deref());
if !self.has_stored_resource(&drive_subject) {
tracing::warn!(
"Drive {} from secret does not exist locally — needs sync from another device",
&drive_str[..drive_str.len().min(30)]
);
drive_needs_sync = true;
}
}
Ok(AgentLoadResult {
agent,
drive_needs_sync,
})
}
/// List drives belonging to the current agent.
/// Falls back to the active drive if the agent resource has no `drives` property.
pub async fn list_drives(&self) -> AtomicResult<Vec<DriveInfo>> {
let agent = self.get_default_agent()?;
let agent_resource = self.get_resource(&agent.subject).await?;
let subjects = match agent_resource.get(urls::DRIVES) {
Ok(Value::ResourceArray(arr)) => arr.iter().map(|s| s.to_string()).collect::<Vec<_>>(),
_ => vec![],
};
// Fallback: active drive not in agent resource
let subjects = if subjects.is_empty() {
match self.get_active_drive() {
Some(active) => vec![active],
None => vec![],
}
} else {
subjects
};
let mut drives = Vec::with_capacity(subjects.len());
for subject in subjects {
let name = match self.get_resource(&subject.as_str().into()).await {
Ok(r) => r.get(urls::NAME).map(|v| v.to_string()).unwrap_or_default(),
Err(_) => String::new(),
};
drives.push(DriveInfo { subject, name });
}
Ok(drives)
}
/// Cheap local-presence check (no network fetch): is this subject's resource
/// already stored locally? Used by managed-node replication to skip drives it
/// already hosts before resolving/pulling them from a peer.
pub fn has_resource_locally(&self, subject: &str) -> bool {
self.kv
.contains_key(Tree::Resources, subject.as_bytes())
.unwrap_or(false)
}
/// Per-drive storage usage (resource count, Loro snapshot bytes, blob
/// bytes) for the given `drive_subjects`, for a managed node's control-plane
/// usage report. A managed node passes its allowlisted (hosted) drives —
/// these belong to enrolled users, not the node's own agent. Walks the Loro
/// and resource trees once each. Blobs are content-addressed and counted
/// once — a blob shared across drives is attributed to whichever drive's
/// resource is visited first.
pub async fn per_drive_usage(
&self,
drive_subjects: &[String],
) -> AtomicResult<Vec<DriveUsage>> {
use std::collections::{HashMap, HashSet};
if drive_subjects.is_empty() {
return Ok(vec![]);
}
// Map every resource subject (pure id) → its drive, and seed a row per drive.
let mut subject_to_drive: HashMap<String, String> = HashMap::new();
let mut usage: HashMap<String, DriveUsage> = HashMap::new();
for drive_subject in drive_subjects {
// Best-effort display name from the drive resource.
let name = match self.get_resource(&drive_subject.as_str().into()).await {
Ok(r) => r.get(urls::NAME).ok().map(|v| v.to_string()),
Err(_) => None,
};
usage.insert(
drive_subject.clone(),
DriveUsage {
drive_subject: drive_subject.clone(),
name,
resource_count: 0,
blob_bytes: 0,
loro_bytes: 0,
},
);
let ds: crate::Subject = drive_subject.as_str().into();
// The drive root resource itself is part of the drive;
// collect_drive_subjects only walks its children.
subject_to_drive.insert(ds.pure_id(), drive_subject.clone());
for subject in crate::sync::engine::collect_drive_subjects(self, &ds).await {
subject_to_drive.insert(subject, drive_subject.clone());
}
}
// Loro snapshot bytes — one pass over the snapshots tree (subject-keyed).
for item in self.kv.iter_tree(Tree::LoroSnapshots) {
let Ok((key, val)) = item else { continue };
let subject = String::from_utf8_lossy(&key);
if let Some(drive) = subject_to_drive.get(subject.as_ref()) {
if let Some(row) = usage.get_mut(drive) {
row.loro_bytes += val.len() as u64;
}
}
}
// Resource counts + blob bytes — one pass over resources.
let mut seen_blobs: HashSet<[u8; 32]> = HashSet::new();
for resource in self.all_resources(false) {
let subject = resource.get_subject().pure_id();
let Some(drive) = subject_to_drive.get(&subject).cloned() else {
continue;
};
if let Some(row) = usage.get_mut(&drive) {
row.resource_count += 1;
}
let Ok(blob_val) = resource.get(urls::BLOB) else {
continue;
};
let blob_did = blob_val.to_string();
let blob_subject = crate::Subject::from_raw(&blob_did, None);
let Some(hash_hex) = blob_subject.blob_hash_hex() else {
continue;
};
let Ok(hash_bytes) = hex::decode(hash_hex) else {
continue;
};
if hash_bytes.len() != 32 {
continue;
}
let mut hash = [0u8; 32];
hash.copy_from_slice(&hash_bytes);
if !seen_blobs.insert(hash) {
continue;
}
if let Ok(Some(bytes)) = self.kv.get(Tree::Blobs, &hash) {
if let Some(row) = usage.get_mut(&drive) {
row.blob_bytes += bytes.len() as u64;
}
}
}
Ok(usage.into_values().collect())
}
/// Get children of a resource, optionally filtered by class.
pub async fn get_children(
&self,
parent: &str,
class_filter: Option<&str>,
) -> AtomicResult<Vec<Resource>> {
let mut result = Vec::new();
for resource in self.all_resources(false) {
if let Ok(p) = resource.get(urls::PARENT) {
if p.to_string() != parent {
continue;
}