summaryrefslogtreecommitdiff
path: root/crates/common/src/manager/restore.rs
blob: 0f5cf44c32bfd3e3d12416382dad59734b167c89 (plain)
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
/*
 * SPDX-FileCopyrightText: 2020 Stalwart Labs Ltd <hello@stalw.art>
 *
 * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
 */

use std::{
    io::ErrorKind,
    path::{Path, PathBuf},
};

use crate::Core;
use jmap_proto::types::{collection::Collection, property::Property};
use store::{
    roaring::RoaringBitmap,
    write::{
        key::DeserializeBigEndian, BatchBuilder, BitmapClass, BitmapHash, BlobOp, DirectoryClass,
        FtsQueueClass, LookupClass, MaybeDynamicId, MaybeDynamicValue, Operation, TagValue,
        ValueClass,
    },
    BlobStore, Serialize, Store, U32_LEN,
};
use store::{
    write::{QueueClass, QueueEvent},
    Deserialize, U64_LEN,
};
use tokio::{
    fs::File,
    io::{AsyncReadExt, BufReader},
};
use utils::{failed, BlobHash, UnwrapFailure};

use super::backup::{DeserializeBytes, Family, Op, FILE_VERSION, MAGIC_MARKER};

impl Core {
    pub async fn restore(&self, src: PathBuf) {
        // Backup the core
        if src.is_dir() {
            // Iterate directory and spawn a task for each file
            let mut tasks = Vec::new();
            for entry in std::fs::read_dir(&src).failed("Failed to read directory") {
                let entry = entry.failed("Failed to read entry");
                let path = entry.path();
                if path.is_file() {
                    let storage = self.storage.clone();
                    let blob_store = self.storage.blob.clone();
                    tasks.push(tokio::spawn(async move {
                        restore_file(storage.data, blob_store, &path).await;
                    }));
                }
            }

            for task in tasks {
                task.await.failed("Failed to wait for task");
            }
        } else {
            restore_file(self.storage.data.clone(), self.storage.blob.clone(), &src).await;
        }
    }
}

async fn restore_file(store: Store, blob_store: BlobStore, path: &Path) {
    println!("Importing database dump from {}.", path.to_str().unwrap());

    let mut reader = OpReader::new(path).await;
    let mut account_id = u32::MAX;
    let mut document_id = u32::MAX;
    let mut collection = u8::MAX;
    let mut family = Family::None;
    let email_collection = u8::from(Collection::Email);
    let mut seq = 0;

    let mut batch_size = 0;
    let mut batch = BatchBuilder::new();

    while let Some(op) = reader.next().await {
        match op {
            Op::Family(f) => family = f,
            Op::AccountId(a) => {
                account_id = a;
                batch.with_account_id(account_id);
            }
            Op::Collection(c) => {
                collection = c;
                batch.with_collection(collection);
            }
            Op::DocumentId(d) => {
                document_id = d;
                batch.update_document(document_id);
            }
            Op::KeyValue((key, value)) => {
                batch_size += key.len() + value.len() + U32_LEN * 2;

                match family {
                    Family::Property => {
                        let field = key
                            .as_slice()
                            .deserialize_u8(0)
                            .expect("Failed to deserialize field");
                        if collection == u8::from(Collection::Mailbox)
                            && u8::from(Property::EmailIds) == field
                        {
                            batch.add(
                                ValueClass::Property(field),
                                i64::deserialize(&value)
                                    .expect("Failed to deserialize mailbox uidnext"),
                            );
                        } else {
                            batch.set(ValueClass::Property(field), value);
                        }
                    }
                    Family::FtsIndex => {
                        if reader.version > 1 {
                            let mut hash = [0u8; 8];
                            let (hash, len) = match key.len() {
                                9 => {
                                    hash[..8].copy_from_slice(&key[..8]);
                                    (hash, key[key.len() - 1])
                                }
                                len @ (1..=7) => {
                                    hash[..len].copy_from_slice(&key[..len]);
                                    (hash, len as u8)
                                }
                                invalid => {
                                    panic!("Invalid text bitmap key length {invalid}");
                                }
                            };

                            batch.set(ValueClass::FtsIndex(BitmapHash { hash, len }), value);
                        }
                    }
                    Family::Acl => {
                        batch.set(
                            ValueClass::Acl(
                                key.as_slice()
                                    .deserialize_be_u32(0)
                                    .expect("Failed to deserialize acl"),
                            ),
                            value,
                        );
                    }
                    Family::Blob => {
                        let hash = BlobHash::try_from_hash_slice(&key).expect("Invalid blob hash");

                        if account_id != u32::MAX && document_id != u32::MAX {
                            if reader.version == 1 && collection == email_collection {
                                batch.set(
                                    ValueClass::FtsQueue(FtsQueueClass {
                                        seq,
                                        hash: hash.clone(),
                                    }),
                                    0u64.serialize(),
                                );
                                seq += 1;
                            }
                            batch.set(ValueClass::Blob(BlobOp::Link { hash }), vec![]);
                        } else {
                            batch_size -= value.len();
                            blob_store
                                .put_blob(&key, &value)
                                .await
                                .expect("Failed to write blob");
                            batch.set(ValueClass::Blob(BlobOp::Commit { hash }), vec![]);
                        }
                    }
                    Family::Config => {
                        batch.set(ValueClass::Config(key), value);
                    }
                    Family::LookupValue => {
                        batch.set(ValueClass::Lookup(LookupClass::Key(key)), value);
                    }
                    Family::LookupCounter => {
                        batch.add(
                            ValueClass::Lookup(LookupClass::Counter(key)),
                            i64::deserialize(&value).expect("Failed to deserialize counter"),
                        );
                    }
                    Family::Directory => {
                        let key = key.as_slice();
                        let class: DirectoryClass<MaybeDynamicId> =
                            match key.first().expect("Failed to read directory key type") {
                                0 => DirectoryClass::NameToId(
                                    key.get(1..)
                                        .expect("Failed to read directory string")
                                        .to_vec(),
                                ),
                                1 => DirectoryClass::EmailToId(
                                    key.get(1..)
                                        .expect("Failed to read directory string")
                                        .to_vec(),
                                ),
                                2 => DirectoryClass::Principal(MaybeDynamicId::Static(
                                    key.get(1..)
                                        .expect("Failed to read range for principal id")
                                        .deserialize_leb128::<u32>()
                                        .expect("Failed to deserialize principal id"),
                                )),
                                3 => DirectoryClass::Domain(
                                    key.get(1..)
                                        .expect("Failed to read directory string")
                                        .to_vec(),
                                ),
                                4 => {
                                    batch.add(
                                        ValueClass::Directory(DirectoryClass::UsedQuota(
                                            key.get(1..)
                                                .expect("Failed to read principal id")
                                                .deserialize_leb128()
                                                .expect("Failed to read principal id"),
                                        )),
                                        i64::deserialize(&value)
                                            .expect("Failed to deserialize quota"),
                                    );

                                    continue;
                                }
                                5 => DirectoryClass::MemberOf {
                                    principal_id: MaybeDynamicId::Static(
                                        key.deserialize_be_u32(1)
                                            .expect("Failed to read principal id"),
                                    ),
                                    member_of: MaybeDynamicId::Static(
                                        key.deserialize_be_u32(1 + U32_LEN)
                                            .expect("Failed to read principal id"),
                                    ),
                                },
                                6 => DirectoryClass::Members {
                                    principal_id: MaybeDynamicId::Static(
                                        key.deserialize_be_u32(1)
                                            .expect("Failed to read principal id"),
                                    ),
                                    has_member: MaybeDynamicId::Static(
                                        key.deserialize_be_u32(1 + U32_LEN)
                                            .expect("Failed to read principal id"),
                                    ),
                                },

                                _ => failed("Invalid directory key"),
                            };
                        batch.set(ValueClass::Directory(class), value);
                    }
                    Family::Queue => {
                        let key = key.as_slice();

                        match key.first().expect("Failed to read queue key type") {
                            0 => {
                                batch.set(
                                    ValueClass::Queue(QueueClass::Message(
                                        key.deserialize_be_u64(1)
                                            .expect("Failed to deserialize queue message id"),
                                    )),
                                    value,
                                );
                            }
                            1 => {
                                batch.set(
                                    ValueClass::Queue(QueueClass::MessageEvent(QueueEvent {
                                        due: key
                                            .deserialize_be_u64(1)
                                            .expect("Failed to deserialize queue message id"),
                                        queue_id: key
                                            .deserialize_be_u64(1 + U64_LEN)
                                            .expect("Failed to deserialize queue message id"),
                                    })),
                                    value,
                                );
                            }
                            _ => failed("Invalid queue key"),
                        }
                    }
                    Family::Index => batch.ops.push(Operation::Index {
                        field: key.first().copied().expect("Failed to read index field"),
                        key: key.get(1..).expect("Failed to read index key").to_vec(),
                        set: true,
                    }),
                    Family::Bitmap => {
                        let key = key.as_slice();
                        let class: BitmapClass<MaybeDynamicId> =
                            match key.first().expect("Failed to read bitmap class") {
                                0 => BitmapClass::DocumentIds,
                                1 => BitmapClass::Tag {
                                    field: key.get(1).copied().expect("Failed to read field"),
                                    value: TagValue::Id(MaybeDynamicId::Static(
                                        key.deserialize_be_u32(2).expect("Failed to read tag id"),
                                    )),
                                },
                                2 => BitmapClass::Tag {
                                    field: key.get(1).copied().expect("Failed to read field"),
                                    value: TagValue::Text(
                                        key.get(2..).expect("Failed to read tag text").to_vec(),
                                    ),
                                },
                                3 => BitmapClass::Tag {
                                    field: key.get(1).copied().expect("Failed to read field"),
                                    value: TagValue::Id(MaybeDynamicId::Static(
                                        key.get(2)
                                            .copied()
                                            .expect("Failed to read tag static id")
                                            .into(),
                                    )),
                                },
                                4 => {
                                    if reader.version == 1 && collection == email_collection {
                                        continue;
                                    }

                                    BitmapClass::Text {
                                        field: key.get(1).copied().expect("Failed to read field"),
                                        token: BitmapHash {
                                            len: key
                                                .get(2)
                                                .copied()
                                                .expect("Failed to read tag static id"),
                                            hash: key
                                                .get(3..11)
                                                .expect("Failed to read tag static id")
                                                .try_into()
                                                .unwrap(),
                                        },
                                    }
                                }
                                _ => failed("Invalid bitmap class"),
                            };
                        let document_ids = RoaringBitmap::deserialize_from(&value[..])
                            .expect("Failed to deserialize bitmap");

                        for document_id in document_ids {
                            batch.ops.push(Operation::DocumentId { document_id });
                            batch.ops.push(Operation::Bitmap {
                                class: class.clone(),
                                set: true,
                            });

                            if batch.ops.len() >= 1000 {
                                store
                                    .write(batch.build())
                                    .await
                                    .failed("Failed to write batch");
                                batch = BatchBuilder::new();
                                batch
                                    .with_account_id(account_id)
                                    .with_collection(collection);
                            }
                        }
                    }
                    Family::Log => {
                        batch.ops.push(Operation::ChangeId {
                            change_id: key
                                .as_slice()
                                .deserialize_be_u64(0)
                                .expect("Failed to deserialize change id"),
                        });
                        batch.ops.push(Operation::Log {
                            set: MaybeDynamicValue::Static(value),
                        });
                    }
                    Family::None => failed("No family specified in file"),
                }
            }
        }

        if batch.ops.len() >= 1000 || batch_size >= 5_000_000 {
            store
                .write(batch.build())
                .await
                .failed("Failed to write batch");
            batch = BatchBuilder::new();
            batch
                .with_account_id(account_id)
                .with_collection(collection)
                .update_document(document_id);
            batch_size = 0;
        }
    }

    if !batch.is_empty() {
        store
            .write(batch.build())
            .await
            .failed("Failed to write batch");
    }
}

struct OpReader {
    version: u8,
    file: BufReader<File>,
}

impl OpReader {
    async fn new(path: &Path) -> Self {
        let mut file = BufReader::new(File::open(&path).await.failed("Failed to open file"));

        if file
            .read_u8()
            .await
            .failed(&format!("Failed to read magic marker from {path:?}"))
            != MAGIC_MARKER
        {
            failed(&format!("Invalid magic marker in {path:?}"));
        }

        let version = file
            .read_u8()
            .await
            .failed(&format!("Failed to read version from {path:?}"));

        if version > FILE_VERSION {
            failed(&format!("Invalid file version in {path:?}"));
        }

        Self { file, version }
    }

    async fn next(&mut self) -> Option<Op> {
        match self.file.read_u8().await {
            Ok(byte) => match byte {
                0 => Op::Family(
                    Family::try_from(self.expect_u8().await).failed("Failed to read family"),
                ),
                1 => Op::KeyValue((
                    self.expect_sized_bytes().await,
                    self.expect_sized_bytes().await,
                )),
                2 => Op::KeyValue((self.expect_sized_bytes().await, vec![])),
                3 => Op::AccountId(self.expect_u32_be().await),
                4 => Op::Collection(self.expect_u8().await),
                5 => Op::DocumentId(self.expect_u32_be().await),
                unknown => {
                    failed(&format!("Unknown op type {unknown}"));
                }
            }
            .into(),
            Err(err) if err.kind() == ErrorKind::UnexpectedEof => None,
            Err(err) => failed(&format!("Failed to read file: {err:?}")),
        }
    }

    async fn expect_u8(&mut self) -> u8 {
        self.file.read_u8().await.failed("Failed to read u8")
    }

    async fn expect_u32_be(&mut self) -> u32 {
        self.file.read_u32().await.failed("Failed to read u32")
    }

    async fn expect_sized_bytes(&mut self) -> Vec<u8> {
        let len = self.expect_u32_be().await as usize;
        let mut bytes = vec![0; len];
        self.file
            .read_exact(&mut bytes)
            .await
            .failed("Failed to read bytes");
        bytes
    }
}

impl TryFrom<u8> for Family {
    type Error = String;

    fn try_from(value: u8) -> Result<Self, Self::Error> {
        match value {
            0 => Ok(Self::Property),
            1 => Ok(Self::FtsIndex),
            2 => Ok(Self::Acl),
            3 => Ok(Self::Blob),
            4 => Ok(Self::Config),
            5 => Ok(Self::LookupValue),
            6 => Ok(Self::LookupCounter),
            7 => Ok(Self::Directory),
            8 => Ok(Self::Queue),
            9 => Ok(Self::Index),
            10 => Ok(Self::Bitmap),
            11 => Ok(Self::Log),
            other => Err(format!("Unknown family type {other}")),
        }
    }
}