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
// ─── storage/mod.rs ──────────────────────────────────────────────────────────
// This is the root module for all storage backends. It does three things:
//
// 1. Declares and conditionally exposes the concrete backend modules
// (disk, encrypted, wasm) based on the compile target.
//
// 2. Defines the StorageBackend trait — the single interface that the rest
// of the engine uses to read/write data. Any type that implements this
// trait can be used as a storage backend, whether it writes to a disk
// file, an encrypted file, or a browser OPFS file.
//
// 3. Provides the startup replay functions (stream_into_state, apply_entry,
// replay_log_entries) that rebuild the in-memory database state from the
// persistent log on server/worker startup.
//
// The StorageBackend trait is the key abstraction that makes MoltenDB's
// "same engine, different storage" design possible. The engine (mod.rs,
// operations.rs, handlers.rs) never imports a concrete storage type — it
// only ever holds an Arc<dyn StorageBackend>. This means you can swap the
// storage backend without changing any engine code.
// ─────────────────────────────────────────────────────────────────────────────
// ── Conditional module declarations ──────────────────────────────────────────
// These cfg attributes mean "only compile this when NOT targeting wasm32".
// On native (server) builds we get disk.rs and encrypted.rs.
// On WASM (browser) builds we get wasm.rs.
// This prevents browser-incompatible code (file I/O, Tokio tasks) from being
// compiled into the WASM binary.
// tiered.rs provides MmapLogReader (memory-mapped cold log reads) and
// TieredStorage (hot + cold two-tier backend for large-scale deployments).
// Re-export the concrete types so callers can write `storage::AsyncDiskStorage`
// instead of `storage::disk::AsyncDiskStorage`.
pub use ;
pub use EncryptedStorage;
// Re-export TieredStorage so engine/mod.rs and main.rs can use it directly.
pub use TieredStorage;
// On WASM builds, expose the browser-side OPFS storage.
pub use OpfsStorage;
// ── Shared imports ────────────────────────────────────────────────────────────
// These are used by both the trait definition and the replay functions below.
use crate;
use Value;
use ControlFlow;
// DashMap is a concurrent hash map — like HashMap but safe to read/write from
// multiple threads simultaneously without a global lock.
// DashSet is the set equivalent.
use ;
// serde_json::Value is a dynamically-typed JSON value (can be object, array,
// string, number, bool, or null). All document data is stored as Value.
// ─── StorageBackend trait ─────────────────────────────────────────────────────
//
// This is the core abstraction of the storage layer. Any type that implements
// these three methods can serve as a MoltenDB storage backend.
//
// The trait requires Send + Sync because the backend is stored inside an
// Arc<dyn StorageBackend> and shared across multiple Tokio tasks/threads.
// • Send = the type can be moved to another thread
// • Sync = the type can be referenced from multiple threads simultaneously
// ─────────────────────────────────────────────────────────────────────────────
/// The core storage abstraction. Implement this trait to add a new storage backend.
///
/// All three methods operate on `LogEntry` — the atomic unit of data in MoltenDB.
/// The engine never writes raw bytes; it always goes through this interface.
// ─── Startup replay ───────────────────────────────────────────────────────────
//
// When the server starts (or the WASM worker initialises), we need to rebuild
// the in-memory state from the persistent log. These functions handle that.
//
// The process is:
// 1. Call storage.stream_log_into() — this either loads a binary snapshot
// + delta (fast path) or streams the full log line-by-line (slow path).
// 2. For each LogEntry, call apply_entry() to update the in-memory DashMaps.
// 3. After all entries are applied, the in-memory state matches the log.
// ─────────────────────────────────────────────────────────────────────────────
/// Drive startup by streaming all log entries from storage into the in-memory
/// state and index maps. Uses snapshot + delta replay when available.
///
/// `state` — the main data store: collection name → (key → document state)
/// `indexes` — the index store: "collection:field" → (field value → set of keys)
///
/// Returns the total number of log entries processed.
/// Apply a single log entry to the in-memory state and indexes.
///
/// If `pointer` is provided (during log replay), INSERT entries are stored
/// as `DocumentState::Cold(pointer)` to save memory. Live writes stay `Hot`.
// Replay a slice of already-decoded log entries into RAM state.
//
// This is an alternative to stream_into_state() used when the entries have
// already been loaded into memory (e.g. after decryption by EncryptedStorage).
// It applies the same logic as apply_entry() but iterates a pre-built slice.
// pub fn replay_log_entries(
// entries: &[LogEntry],
// state: &DashMap<String, DashMap<String, Value>>,
// indexes: &DashMap<String, DashMap<String, DashSet<String>>>,
// ) {
// for entry in entries {
// match entry.cmd.as_str() {
// "INSERT" => {
// // Get or create the collection, then insert the document.
// let col = state
// .entry(entry.collection.clone())
// .or_insert_with(DashMap::new);
// col.insert(entry.key.clone(), entry.value.clone());
// // Keep indexes in sync with the inserted document.
// crate::engine::indexing::index_doc(indexes, &entry.collection, &entry.key, &entry.value);
// }
// "DELETE" => {
// if let Some(col) = state.get(&entry.collection) {
// // Remove from indexes before removing from state.
// if let Some(old_val) = col.get(&entry.key) {
// crate::engine::indexing::unindex_doc(
// indexes,
// &entry.collection,
// &entry.key,
// old_val.value(),
// );
// }
// col.remove(&entry.key);
// }
// }
// "DROP" => {
// // Remove the collection and all its associated indexes.
// state.remove(&entry.collection);
// indexes.retain(|k, _| !k.starts_with(&format!("{}:", entry.collection)));
// }
// "INDEX" => {
// // Register an empty index slot.
// indexes.insert(
// format!("{}:{}", entry.collection, entry.key),
// DashMap::new(),
// );
// }
// _ => {}
// }
// }
// println!("✅ Database restored & Indexes rebuilt!");
// }