Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
#![allow(unused)]
use std::{
    borrow::Cow,
    collections::HashMap,
    ffi::OsStr,
    fs::File,
    hash::{Hash, Hasher},
    io,
    path::{Path, PathBuf},
    sync::{atomic::AtomicU32, Arc, Mutex},
    time::Duration,
};

use fuser::{
    FileAttr, Filesystem, ReplyAttr, ReplyBmap, ReplyCreate, ReplyData, ReplyDirectory, ReplyEmpty,
    ReplyEntry, ReplyLock, ReplyOpen, ReplyStatfs, ReplyWrite, ReplyXattr, Request,
};
use indicatif::{ProgressBar, ProgressStyle};
use shared_buffer::OwnedBuffer;
use tokio::runtime::Handle;
use virtual_fs::{
    mem_fs::{self, OffloadBackingStore},
    AsyncReadExt, AsyncSeekExt, AsyncWriteExt, FileOpener, FileSystem, FsError,
};
use wasmer_wasix::{
    fs::WasiFdSeed,
    journal::{
        copy_journal, ArchivedJournalEntry, ArchivedJournalEntryFileDescriptorWriteV1, Journal,
        JournalEntry, JournalEntryFileDescriptorWriteV1, LogFileJournal, LogWriteResult,
        ReadableJournal, WritableJournal,
    },
    types::Oflags,
    wasmer_wasix_types::wasi,
    VIRTUAL_ROOT_FD,
};

#[derive(Debug)]
struct State {
    handle: tokio::runtime::Handle,
    mem_fs: mem_fs::FileSystem,
    inos: HashMap<u64, Cow<'static, str>>,
    lookup: HashMap<
        u32,
        Arc<tokio::sync::Mutex<Box<dyn virtual_fs::VirtualFile + Send + Sync + 'static>>>,
    >,
    seed: WasiFdSeed,
    fake_offset: u64,
}

#[derive(Debug)]
struct MutexState {
    inner: Mutex<State>,
}

#[derive(Debug)]
pub struct JournalFileSystemBuilder {
    path: PathBuf,
    fd_seed: WasiFdSeed,
    progress_bar: bool,
}

impl JournalFileSystemBuilder {
    pub fn new(path: &Path) -> Self {
        Self {
            path: path.to_path_buf(),
            fd_seed: WasiFdSeed::default(),
            progress_bar: false,
        }
    }

    pub fn with_fd_seed(mut self, fd_seed: WasiFdSeed) -> Self {
        self.fd_seed = fd_seed;
        self
    }

    pub fn with_progress_bar(mut self, val: bool) -> Self {
        self.progress_bar = val;
        self
    }

    // Opens the journal and copies all its contents into
    // and memory file system
    pub fn build(self) -> anyhow::Result<JournalFileSystem> {
        let journal = LogFileJournal::new(&self.path)?;
        let backing_store = journal.backing_store();
        let file_len = backing_store.owned_buffer().len();

        let mem_fs = mem_fs::FileSystem::default().with_backing_offload(backing_store)?;
        let state = MutexState {
            inner: Mutex::new(State {
                handle: tokio::runtime::Handle::current(),
                mem_fs,
                inos: Default::default(),
                seed: self.fd_seed,
                lookup: Default::default(),
                fake_offset: 0,
            }),
        };

        let progress = if self.progress_bar {
            let mut pb = ProgressBar::new(file_len as u64);
            pb.set_style(ProgressStyle::with_template("{msg}\n{spinner:.green} [{elapsed_precise}] [{wide_bar:.cyan/blue}] {bytes}/{total_bytes} ({bytes_per_sec}, {eta})")
                .unwrap()
                .progress_chars("#>-"));
            pb.set_message("Loading journal...");

            Some(pb)
        } else {
            None
        };

        tokio::task::block_in_place(|| {
            if let Some(progress) = progress {
                copy_journal_with_progress(&journal, &state, progress)
            } else {
                copy_journal(&journal, &state)
            }
        })?;

        let ret = JournalFileSystem {
            handle: tokio::runtime::Handle::current(),
            journal,
            state,
        };

        Ok(ret)
    }
}

pub fn copy_journal_with_progress<R: ReadableJournal, W: WritableJournal>(
    from: &R,
    to: &W,
    mut progress: ProgressBar,
) -> anyhow::Result<()> {
    while let Some(record) = from.read()? {
        progress.set_position(record.record_end);
        to.write(record.into_inner())?;
    }
    progress.finish_and_clear();
    println!("Journal is mounted");
    Ok(())
}

#[derive(Debug)]
pub struct JournalFileSystem {
    handle: tokio::runtime::Handle,
    journal: LogFileJournal,
    state: MutexState,
}

impl JournalFileSystem {
    fn reverse_ino(&self, ino: u64) -> Result<Cow<'static, str>, libc::c_int> {
        if ino == 1 {
            return Ok("/".into());
        }
        let path = {
            let mut state = self.state.inner.lock().unwrap();
            match state.inos.get(&ino).cloned() {
                Some(path) => path,
                None => {
                    return Err(libc::ENOENT);
                }
            }
        };
        Ok(path)
    }

    fn attr<'a>(&self, path: Cow<'a, str>) -> Result<FileAttr, libc::c_int> {
        let mut state = self.state.inner.lock().unwrap();

        let res = state.mem_fs.metadata(&Path::new(path.as_ref()));
        match res {
            Ok(meta) => {
                // The ino is just the hash of the name
                let mut hasher = std::collections::hash_map::DefaultHasher::new();
                path.hash(&mut hasher);
                let ino = hasher.finish();
                state
                    .inos
                    .entry(ino)
                    .or_insert_with(|| path.into_owned().into());

                // Build a file attr and return it
                Ok(FileAttr {
                    ino,
                    size: meta.len,
                    blocks: (1u64.max(meta.len) - 1 / 512) + 1,
                    atime: time01::Timespec::new(meta.accessed as i64, 0),
                    mtime: time01::Timespec::new(meta.modified as i64, 0),
                    ctime: time01::Timespec::new(meta.created as i64, 0),
                    crtime: time01::Timespec::new(meta.created as i64, 0),
                    kind: file_type_to_kind(meta.ft),
                    perm: 0o644,
                    nlink: 1,
                    uid: 0,
                    gid: 0,
                    rdev: 0,
                    flags: 0,
                })
            }
            Err(FsError::EntryNotFound) => Err(libc::ENOENT),
            Err(_) => Err(libc::EIO),
        }
    }
}

impl WritableJournal for MutexState {
    fn write<'a>(&'a self, entry: JournalEntry<'a>) -> anyhow::Result<LogWriteResult> {
        let mut state = self.inner.lock().unwrap();
        let ret = LogWriteResult {
            record_start: state.fake_offset,
            record_end: state.fake_offset + entry.estimate_size() as u64,
        };
        state.fake_offset += ret.record_size();
        match entry {
            JournalEntry::FileDescriptorWriteV1 {
                fd,
                offset,
                data,
                is_64bit,
            } => {
                let handle = state.handle.clone();
                if let Some(file) = state.lookup.get_mut(&fd) {
                    handle.block_on(async {
                        let mut file = file.lock().await;
                        file.seek(io::SeekFrom::Start(offset)).await;
                        file.write_all(&data).await
                    })?;
                }
            }
            JournalEntry::CloseFileDescriptorV1 { fd } => {
                state.lookup.remove(&fd);
            }
            JournalEntry::OpenFileDescriptorV1 {
                fd,
                dirfd,
                dirflags,
                path,
                o_flags,
                fs_rights_base,
                fs_rights_inheriting,
                fs_flags,
            } => {
                state.seed.clip_val(fd + 1);
                let file = state
                    .mem_fs
                    .new_open_options()
                    .create(o_flags.contains(Oflags::CREATE))
                    .truncate(o_flags.contains(Oflags::TRUNC))
                    .write(true)
                    .read(true)
                    .open(path.as_ref())?;
                state
                    .lookup
                    .insert(fd, Arc::new(tokio::sync::Mutex::new(file)));
            }
            JournalEntry::RenumberFileDescriptorV1 { old_fd, new_fd } => {
                state.seed.clip_val(new_fd + 1);
                if let Some(file) = state.lookup.remove(&old_fd) {
                    state.lookup.insert(new_fd, file);
                }
            }
            JournalEntry::DuplicateFileDescriptorV1 {
                original_fd,
                copied_fd,
            } => {
                state.seed.clip_val(copied_fd + 1);
                if let Some(file) = state.lookup.get(&original_fd).cloned() {
                    state.lookup.insert(copied_fd, file);
                }
            }
            JournalEntry::CreateDirectoryV1 { fd, path } => {
                state.mem_fs.create_dir(&Path::new(path.as_ref())).ok();
            }
            JournalEntry::RemoveDirectoryV1 { fd, path } => {
                state.mem_fs.remove_dir(&Path::new(path.as_ref()))?;
            }
            JournalEntry::FileDescriptorSetSizeV1 { fd, st_size } => {
                let handle = state.handle.clone();
                if let Some(file) = state.lookup.get(&fd) {
                    handle.block_on(async {
                        let mut file = file.lock().await;
                        file.set_len(st_size)
                    })?;
                }
            }
            JournalEntry::FileDescriptorAllocateV1 { fd, offset, len } => {
                let handle = state.handle.clone();
                if let Some(file) = state.lookup.get(&fd) {
                    handle.block_on(async {
                        let mut file = file.lock().await;
                        file.set_len(offset + len)
                    })?;
                }
            }
            JournalEntry::UnlinkFileV1 { fd, path } => {
                state.mem_fs.remove_file(&Path::new(path.as_ref()))?;
            }
            JournalEntry::PathRenameV1 {
                old_fd,
                old_path,
                new_fd,
                new_path,
            } => {
                let handle = state.handle.clone();
                handle.block_on(async {
                    state
                        .mem_fs
                        .rename(&Path::new(old_path.as_ref()), &Path::new(new_path.as_ref()))
                        .await
                })?;
            }
            JournalEntry::SocketOpenV1 { fd, .. } => {
                state.seed.clip_val(fd + 1);
            }
            JournalEntry::CreatePipeV1 { fd1, fd2 } => {
                state.seed.clip_val(fd1 + 1);
                state.seed.clip_val(fd2 + 1);
            }
            JournalEntry::CreateEventV1 { fd, .. } => {
                state.seed.clip_val(fd + 1);
            }
            JournalEntry::EpollCreateV1 { fd } => {
                state.seed.clip_val(fd + 1);
            }
            JournalEntry::EpollCtlV1 {
                epfd,
                op,
                fd,
                event,
            } => {
                state.seed.clip_val(fd + 1);
            }
            JournalEntry::SocketAcceptedV1 { fd, .. } => {
                state.seed.clip_val(fd + 1);
            }
            _ => {}
        }
        Ok(ret)
    }

    fn flush(&self) -> anyhow::Result<()> {
        let mut state = self.inner.lock().unwrap();
        state.mem_fs.flush()?;
        Ok(())
    }
}

impl JournalFileSystem {
    fn compute_path<'a>(&'a self, parent: u64, name: &'a OsStr) -> Result<Cow<'_, str>, i32> {
        // Get the path from the ino otherwise it is not a known
        // path (this means the other methods have to be hit first)
        let path = match self.reverse_ino(parent) {
            Ok(a) => a,
            Err(err) => {
                tracing::trace!("fs::compute_path reverse_ino({parent}) errno={err}");
                return Err(err);
            }
        };

        // Add the name as a postfix
        let name = name.to_string_lossy();
        let path = if path.ends_with("/") {
            path + name
        } else {
            path + "/" + name
        };
        Ok(path)
    }
}

impl Filesystem for JournalFileSystem {
    fn init(&mut self, _req: &Request) -> Result<(), libc::c_int> {
        Ok(())
    }

    fn destroy(&mut self, _req: &Request) {}

    fn lookup(&mut self, _req: &Request, parent: u64, name: &OsStr, reply: ReplyEntry) {
        let path = match self.compute_path(parent, name) {
            Ok(a) => a,
            Err(err) => {
                tracing::trace!("fs::lookup err={err}");
                return reply.error(err);
            }
        };

        match self.attr(path) {
            Ok(meta) => reply.entry(&time01::Timespec::new(1, 0), &meta, 0),
            Err(err) => {
                tracing::trace!("fs::lookup err={err}");
                reply.error(err)
            }
        }
    }

    fn getattr(&mut self, _req: &Request, ino: u64, reply: ReplyAttr) {
        let path = match self.reverse_ino(ino) {
            Ok(a) => a,
            Err(err) => {
                tracing::trace!("fs::getattr reverse_ino({ino}) errno={err}");
                reply.error(err);
                return;
            }
        };

        match self.attr(path) {
            Ok(meta) => reply.attr(&time01::Timespec::new(1, 0), &meta),
            Err(err) => reply.error(err),
        }
    }

    fn setattr(
        &mut self,
        _req: &Request,
        ino: u64,
        _mode: Option<u32>,
        _uid: Option<u32>,
        _gid: Option<u32>,
        size: Option<u64>,
        _atime: Option<time01::Timespec>,
        _mtime: Option<time01::Timespec>,
        fh: Option<u64>,
        _crtime: Option<time01::Timespec>,
        _chgtime: Option<time01::Timespec>,
        _bkuptime: Option<time01::Timespec>,
        _flags: Option<u32>,
        reply: ReplyAttr,
    ) {
        let mut entries = Vec::new();

        let attr = match fh {
            Some(fd) => {
                let fd = fd as u32;
                let mut state = self.state.inner.lock().unwrap();
                let file = match state.lookup.get_mut(&fd) {
                    Some(f) => f.clone(),
                    None => {
                        tracing::trace!("fs::getattr noent (fd={fd})");
                        reply.error(libc::ENOENT);
                        return;
                    }
                };

                self.handle.block_on(async {
                    let mut file = file.lock().await;

                    if let Some(size) = size {
                        entries.push(JournalEntry::FileDescriptorSetSizeV1 {
                            fd: fd as u32,
                            st_size: size,
                        })
                    }

                    FileAttr {
                        ino,
                        size: file.size(),
                        blocks: (1u64.max(file.size()) - 1 / 512) + 1,
                        atime: time01::Timespec::new(file.last_accessed() as i64, 0),
                        mtime: time01::Timespec::new(file.last_modified() as i64, 0),
                        ctime: time01::Timespec::new(file.created_time() as i64, 0),
                        crtime: time01::Timespec::new(file.created_time() as i64, 0),
                        kind: fuser::FileType::RegularFile,
                        perm: 0o644,
                        nlink: 1,
                        uid: 0,
                        gid: 0,
                        rdev: 0,
                        flags: 0,
                    }
                })
            }
            None => {
                let path = match self.reverse_ino(ino) {
                    Ok(a) => a,
                    Err(err) => {
                        tracing::trace!("fs::setattr reverse_ino({ino}) errno={err}");
                        reply.error(err);
                        return;
                    }
                };

                let fh;
                let mut state = self.state.inner.lock().unwrap();
                let file = state
                    .mem_fs
                    .new_open_options()
                    .read(true)
                    .write(true)
                    .open(&Path::new(path.as_ref()));
                match file {
                    Ok(file) => {
                        // Reserve a file descriptor and close the state
                        fh = state.seed.next_val();
                        drop(state);

                        entries.push(JournalEntry::OpenFileDescriptorV1 {
                            fd: fh,
                            dirfd: VIRTUAL_ROOT_FD,
                            dirflags: 0,
                            path,
                            o_flags: wasi::Oflags::empty(),
                            fs_rights_base: wasi::Rights::all(),
                            fs_rights_inheriting: wasi::Rights::all(),
                            fs_flags: wasi::Fdflags::empty(),
                        });
                        if let Some(size) = size {
                            entries.push(JournalEntry::FileDescriptorSetSizeV1 {
                                fd: fh as u32,
                                st_size: size,
                            })
                        }
                        entries.push(JournalEntry::CloseFileDescriptorV1 { fd: fh });

                        for entry in entries.iter() {
                            if self.state.write(entry.clone()).is_err() {
                                tracing::trace!("fs::open err=EIO");
                                reply.error(libc::EIO);
                                return;
                            }
                        }
                        for entry in entries.iter() {
                            if self.journal.write(entry.clone()).is_err() {
                                tracing::trace!("fs::open err=EIO");
                                reply.error(libc::EIO);
                                return;
                            }
                        }
                        FileAttr {
                            ino,
                            size: file.size(),
                            blocks: (1u64.max(file.size()) - 1 / 512) + 1,
                            atime: time01::Timespec::new(file.last_accessed() as i64, 0),
                            mtime: time01::Timespec::new(file.last_modified() as i64, 0),
                            ctime: time01::Timespec::new(file.created_time() as i64, 0),
                            crtime: time01::Timespec::new(file.created_time() as i64, 0),
                            kind: fuser::FileType::RegularFile,
                            perm: 0o644,
                            nlink: 1,
                            uid: 0,
                            gid: 0,
                            rdev: 0,
                            flags: 0,
                        }
                    }
                    Err(FsError::EntryNotFound) => {
                        // Maybe its a directory, in which case we are done
                        if let Ok(meta) = state.mem_fs.metadata(&Path::new(path.as_ref())) {
                            FileAttr {
                                ino,
                                size: meta.len,
                                blocks: (1u64.max(meta.len) - 1 / 512) + 1,
                                atime: time01::Timespec::new(meta.accessed as i64, 0),
                                mtime: time01::Timespec::new(meta.modified as i64, 0),
                                ctime: time01::Timespec::new(meta.created as i64, 0),
                                crtime: time01::Timespec::new(meta.created as i64, 0),
                                kind: file_type_to_kind(meta.ft),
                                perm: 0o644,
                                nlink: 1,
                                uid: 0,
                                gid: 0,
                                rdev: 0,
                                flags: 0,
                            }
                        } else {
                            tracing::trace!("fs::setattr open_file({path}) err=ENOENT");
                            reply.error(libc::ENOENT);
                            return;
                        }
                    }
                    Err(err) => {
                        tracing::trace!("fs::setattr open_file({path}) err={err}");
                        reply.error(libc::EIO);
                        return;
                    }
                }
            }
        };

        // Return the data
        reply.attr(&time01::Timespec::new(1, 0), &attr)
    }

    fn setxattr(
        &mut self,
        _req: &Request,
        _ino: u64,
        _name: &OsStr,
        _value: &[u8],
        _flags: u32,
        _position: u32,
        reply: ReplyEmpty,
    ) {
        tracing::trace!("fs::setxattr err=ENOSYS");
        reply.error(libc::ENOSYS);
    }

    fn getxattr(
        &mut self,
        _req: &Request,
        _ino: u64,
        _name: &OsStr,
        _size: u32,
        reply: ReplyXattr,
    ) {
        tracing::trace!("fs::getxattr size(0)");
        reply.size(0)
    }

    fn open(&mut self, _req: &Request, ino: u64, flags: u32, reply: ReplyOpen) {
        let path = match self.reverse_ino(ino) {
            Ok(a) => a,
            Err(err) => {
                tracing::trace!("fs::open reverse_ino({ino}) errno={err}");
                reply.error(err);
                return;
            }
        };

        // Reserve a file descriptor
        let fh = {
            let mut state = self.state.inner.lock().unwrap();
            state.seed.next_val()
        };

        // Write the journals
        let entry = JournalEntry::OpenFileDescriptorV1 {
            fd: fh,
            dirfd: VIRTUAL_ROOT_FD,
            dirflags: 0,
            path,
            o_flags: wasi::Oflags::empty(),
            fs_rights_base: wasi::Rights::all(),
            fs_rights_inheriting: wasi::Rights::all(),
            fs_flags: wasi::Fdflags::empty(),
        };
        if self.state.write(entry.clone()).is_err() {
            tracing::trace!("fs::open err=EIO");
            reply.error(libc::EIO);
            return;
        }
        if self.journal.write(entry).is_err() {
            tracing::trace!("fs::open err=EIO");
            reply.error(libc::EIO);
            return;
        }

        tracing::trace!("fs::open opened fh={fh}");
        reply.opened(fh as u64, flags);
    }

    fn release(
        &mut self,
        _req: &Request,
        _ino: u64,
        fh: u64,
        _flags: u32,
        _lock_owner: u64,
        _flush: bool,
        reply: ReplyEmpty,
    ) {
        let fh = fh as u32;

        {
            // Check that the file handle exists
            let mut state = self.state.inner.lock().unwrap();
            if !state.lookup.contains_key(&fh) {
                tracing::trace!("fs::release err=ENOENT (fd={fh})");
                reply.error(libc::ENOENT);
                return;
            }
        }

        // Write the journals
        let entry = JournalEntry::CloseFileDescriptorV1 { fd: fh };
        if self.state.write(entry.clone()).is_err() {
            tracing::trace!("fs::release err=EIO");
            reply.error(libc::EIO);
            return;
        }
        if self.journal.write(entry).is_err() {
            tracing::trace!("fs::release err=EIO");
            reply.error(libc::EIO);
            return;
        }

        tracing::trace!("fs::release ok");
        reply.ok();
    }

    fn create(
        &mut self,
        _req: &Request,
        parent: u64,
        name: &OsStr,
        mode: u32,
        flags: u32,
        reply: ReplyCreate,
    ) {
        let path = match self.compute_path(parent, name) {
            Ok(a) => a,
            Err(err) => return reply.error(err),
        };

        // The ino is just the hash of the name
        let mut hasher = std::collections::hash_map::DefaultHasher::new();
        path.hash(&mut hasher);
        let ino = hasher.finish();

        // Reserve a file descriptor
        let fh = {
            let mut state = self.state.inner.lock().unwrap();
            state.seed.next_val()
        };

        // Write the journals
        let entry = JournalEntry::OpenFileDescriptorV1 {
            fd: fh,
            dirfd: VIRTUAL_ROOT_FD,
            dirflags: 0,
            path,
            o_flags: wasi::Oflags::CREATE,
            fs_rights_base: wasi::Rights::all(),
            fs_rights_inheriting: wasi::Rights::all(),
            fs_flags: wasi::Fdflags::empty(),
        };
        if let Err(err) = self.state.write(entry.clone()) {
            tracing::trace!("fs::create (j1) err=EIO - {err}");
            reply.error(libc::EIO);
            return;
        }
        if let Err(err) = self.journal.write(entry) {
            tracing::trace!("fs::create (j2) err=EIO - {err}");
            reply.error(libc::EIO);
            return;
        }

        let now = time01::get_time();
        reply.created(
            &time01::Timespec::new(1, 0),
            &FileAttr {
                ino,
                size: 0,
                blocks: 0,
                atime: now,
                mtime: now,
                ctime: now,
                crtime: now,
                kind: fuser::FileType::RegularFile,
                perm: 0o644,
                nlink: 1,
                uid: 0,
                gid: 0,
                rdev: 0,
                flags: 0,
            },
            0,
            fh as u64,
            flags,
        );
    }

    fn read(
        &mut self,
        _req: &Request,
        ino: u64,
        fh: u64,
        offset: i64,
        size: u32,
        reply: ReplyData,
    ) {
        let fh = fh as u32;

        // Grab the file from the file handle
        let mut state = self.state.inner.lock().unwrap();
        let file = match state.lookup.get_mut(&fh) {
            Some(a) => a,
            None => {
                tracing::trace!("fs::read lookup(fh={fh}) noent err=EIO");
                reply.error(libc::ENOENT);
                return;
            }
        };

        // Read the data from the file and return it
        let data: Result<_, io::Error> = self.handle.block_on(async {
            let mut file = file.lock().await;

            let mut buf = Vec::with_capacity(size as usize);
            unsafe { buf.set_len(size as usize) };
            file.seek(io::SeekFrom::Start(offset as u64)).await?;
            let amt = file.read(&mut buf).await?;
            unsafe { buf.set_len(amt) };
            Ok(buf)
        });
        let data = match data {
            Ok(a) => a,
            Err(err) => {
                tracing::trace!("fs::read data err=EIO");
                reply.error(libc::EIO);
                return;
            }
        };

        // Return the data
        reply.data(&data);
    }

    fn write(
        &mut self,
        _req: &Request,
        _ino: u64,
        fh: u64,
        offset: i64,
        data: &[u8],
        _flags: u32,
        reply: ReplyWrite,
    ) {
        let fh = fh as u32;

        {
            // Check that the file handle exists
            let mut state = self.state.inner.lock().unwrap();
            if !state.lookup.contains_key(&fh) {
                tracing::trace!("fs::write err=ENOENT");
                reply.error(libc::ENOENT);
                return;
            }
        }

        // Write the entry to the log file
        let fd = fh as u32;
        let entry = JournalEntry::FileDescriptorWriteV1 {
            fd,
            offset: offset as u64,
            data: data.into(),
            is_64bit: false,
        };

        let res = match self.journal.write(entry) {
            Ok(res) => res,
            Err(err) => {
                tracing::trace!("fs::write err=EIO - {err}");
                reply.error(libc::EIO);
                return;
            }
        };

        // We load the record from the journal and use this to write to the memory file system
        // because the memory file system has an optimization where it will automatically offload
        // the data to the mmap of the journal rather than store it in memory. In effect it offloads
        // to the disk
        {
            let mut state = self.state.inner.lock().unwrap();
            let handle = state.handle.clone();
            if let Some(file) = state.lookup.get_mut(&fd) {
                let res: Result<_, io::Error> = handle.block_on(async {
                    let mut file = file.lock().await;
                    file.seek(io::SeekFrom::Start(offset as u64)).await;

                    // Unsafe!!! This assumes the structure does not change
                    // where the first bytes in the entry are an aligned
                    // array that corresponds to the data itself
                    let size = data.len() as u64;
                    let mut mmap_offset = res.record_start;
                    let align = mmap_offset % 16;
                    if align != 0 {
                        mmap_offset += 16 - align;
                    }

                    // Add the entry
                    if file.write_from_mmap(mmap_offset, size).is_err() {
                        // We fall back on just writing the data normally
                        file.seek(io::SeekFrom::Start(offset as u64)).await;
                        file.write_all(&data).await?;
                    }
                    Ok(())
                });
                if let Err(err) = res {
                    tracing::trace!("fs::write err=EIO");
                    reply.error(libc::EIO);
                    return;
                }
            } else {
                tracing::trace!("fs::write err=EIO");
                reply.error(libc::EIO);
                return;
            }
        }

        reply.written(data.len() as u32);
    }

    fn readdir(
        &mut self,
        _req: &Request,
        ino: u64,
        _fh: u64,
        offset: i64,
        mut reply: ReplyDirectory,
    ) {
        // Get the path from the ino otherwise it is not a known
        // path (this means the other methods have to be hit first)
        let path = match self.reverse_ino(ino) {
            Ok(a) => a,
            Err(err) => {
                tracing::trace!("fs::readir reverse_ino({ino}) err={}", err);
                reply.error(err);
                return;
            }
        };

        let mut state = self.state.inner.lock().unwrap();
        let read_dir = state.mem_fs.read_dir(&Path::new(path.as_ref()));
        let read_dir = match read_dir {
            Ok(a) => a,
            Err(FsError::EntryNotFound) => {
                tracing::trace!("fs::readir read_dir({}) err=ENOENT", path);
                return;
            }
            Err(err) => {
                tracing::trace!("fs::readir read_dir({}) err={}", path, err);
                reply.error(libc::EIO);
                return;
            }
        };

        for (i, entry) in read_dir.into_iter().enumerate().skip(offset as usize) {
            let entry = match entry {
                Ok(a) => a,
                Err(err) => {
                    tracing::trace!("fs::readir direntry(index={i}) err={}", err);
                    reply.error(libc::EIO);
                    return;
                }
            };
            let path = entry.path.to_string_lossy();
            let name = match entry.path.file_name() {
                Some(n) => n,
                None => {
                    tracing::trace!("fs::readir file_name err=EIO");
                    reply.error(libc::EIO);
                    return;
                }
            };

            // The ino is just the hash of the name
            let mut hasher = std::collections::hash_map::DefaultHasher::new();
            path.hash(&mut hasher);
            let ino = hasher.finish();
            state
                .inos
                .entry(ino)
                .or_insert_with(|| path.into_owned().into());

            // Compute the directory kind
            let kind = match entry.file_type() {
                Ok(ft) => file_type_to_kind(ft),
                _ => fuser::FileType::RegularFile,
            };

            // i + 1 means the index of the next entry
            reply.add(ino, (i + 1) as i64, kind, name);
        }
        reply.ok();
    }

    fn mkdir(&mut self, _req: &Request, parent: u64, name: &OsStr, _mode: u32, reply: ReplyEntry) {
        let path = match self.compute_path(parent, name) {
            Ok(a) => a,
            Err(err) => {
                tracing::trace!("fs::mkdir compute_path err={err}");
                return reply.error(err);
            }
        };

        let entry = JournalEntry::CreateDirectoryV1 {
            fd: VIRTUAL_ROOT_FD,
            path: path.clone(),
        };
        self.state.write(entry.clone());
        self.journal.write(entry);

        match self.attr(path) {
            Ok(meta) => {
                tracing::trace!("fs::mkdir ok");
                reply.entry(&time01::Timespec::new(1, 0), &meta, 0)
            }
            Err(err) => {
                tracing::trace!("fs::mkdir attr err={err}");
                reply.error(err)
            }
        }
    }

    fn rmdir(&mut self, _req: &Request, parent: u64, name: &OsStr, reply: ReplyEmpty) {
        let path = match self.compute_path(parent, name) {
            Ok(a) => a,
            Err(err) => {
                tracing::trace!("fs::rmdir err={err}");
                return reply.error(err);
            }
        };

        let entry = JournalEntry::RemoveDirectoryV1 {
            fd: VIRTUAL_ROOT_FD,
            path: path.clone(),
        };
        self.state.write(entry.clone());
        self.journal.write(entry);
        tracing::trace!("fs::rmdir ok");
        reply.ok();
    }

    fn unlink(&mut self, _req: &Request, parent: u64, name: &OsStr, reply: ReplyEmpty) {
        let path = match self.compute_path(parent, name) {
            Ok(a) => a,
            Err(err) => {
                tracing::trace!("fs::unlink err={err}");
                return reply.error(err);
            }
        };

        let entry = JournalEntry::UnlinkFileV1 {
            fd: VIRTUAL_ROOT_FD,
            path: path.clone(),
        };
        self.state.write(entry.clone());
        self.journal.write(entry);
        tracing::trace!("fs::unlink ok");
        reply.ok();
    }

    fn forget(&mut self, _req: &Request, _ino: u64, _nlookup: u64) {
        tracing::trace!("fs::forget ok");
    }

    fn readlink(&mut self, _req: &Request, _ino: u64, reply: ReplyData) {
        tracing::trace!("fs::readlink err=ENOSYS");
        reply.error(libc::ENOSYS);
    }

    fn mknod(
        &mut self,
        _req: &Request,
        _parent: u64,
        _name: &OsStr,
        _mode: u32,
        _rdev: u32,
        reply: ReplyEntry,
    ) {
        tracing::trace!("fs::mknod err=ENOSYS");
        reply.error(libc::ENOSYS);
    }

    fn symlink(
        &mut self,
        _req: &Request,
        _parent: u64,
        _name: &OsStr,
        _link: &Path,
        reply: ReplyEntry,
    ) {
        tracing::trace!("fs::symlink err=ENOSYS");
        reply.error(libc::ENOSYS);
    }

    fn rename(
        &mut self,
        _req: &Request,
        _parent: u64,
        _name: &OsStr,
        _newparent: u64,
        _newname: &OsStr,
        reply: ReplyEmpty,
    ) {
        tracing::trace!("fs::rename err=ENOSYS");
        reply.error(libc::ENOSYS);
    }

    fn link(
        &mut self,
        _req: &Request,
        _ino: u64,
        _newparent: u64,
        _newname: &OsStr,
        reply: ReplyEntry,
    ) {
        tracing::trace!("fs::link err=ENOSYS");
        reply.error(libc::ENOSYS);
    }

    fn fsync(&mut self, _req: &Request, _ino: u64, _fh: u64, _datasync: bool, reply: ReplyEmpty) {
        tracing::trace!("fs::fsync err=ENOSYS");
        reply.error(libc::ENOSYS);
    }

    fn opendir(&mut self, _req: &Request, _ino: u64, _flags: u32, reply: ReplyOpen) {
        tracing::trace!("fs::opendir opened");
        reply.opened(0, 0);
    }

    fn releasedir(&mut self, _req: &Request, _ino: u64, _fh: u64, _flags: u32, reply: ReplyEmpty) {
        tracing::trace!("fs::releasedir ok");
        reply.ok();
    }

    fn fsyncdir(
        &mut self,
        _req: &Request,
        _ino: u64,
        _fh: u64,
        _datasync: bool,
        reply: ReplyEmpty,
    ) {
        tracing::trace!("fs::fsyncdir err=ENOSYS");
        reply.error(libc::ENOSYS);
    }

    fn statfs(&mut self, _req: &Request, _ino: u64, reply: ReplyStatfs) {
        tracing::trace!("fs::statfs ok");
        reply.statfs(0, 0, 0, 0, 0, 512, 255, 0);
    }

    fn listxattr(&mut self, _req: &Request, _ino: u64, _size: u32, reply: ReplyXattr) {
        tracing::trace!("fs::listxattr err=ENOSYS");
        reply.error(libc::ENOSYS);
    }

    fn removexattr(&mut self, _req: &Request, _ino: u64, _name: &OsStr, reply: ReplyEmpty) {
        tracing::trace!("fs::removexattr err=ENOSYS");
        reply.error(libc::ENOSYS);
    }

    fn access(&mut self, _req: &Request, _ino: u64, _mask: u32, reply: ReplyEmpty) {
        tracing::trace!("fs::access err=ENOSYS");
        reply.error(libc::ENOSYS);
    }

    fn getlk(
        &mut self,
        _req: &Request,
        _ino: u64,
        _fh: u64,
        _lock_owner: u64,
        _start: u64,
        _end: u64,
        _typ: u32,
        _pid: u32,
        reply: ReplyLock,
    ) {
        tracing::trace!("fs::getlk err=ENOSYS");
        reply.error(libc::ENOSYS);
    }

    fn setlk(
        &mut self,
        _req: &Request,
        _ino: u64,
        _fh: u64,
        _lock_owner: u64,
        _start: u64,
        _end: u64,
        _typ: u32,
        _pid: u32,
        _sleep: bool,
        reply: ReplyEmpty,
    ) {
        tracing::trace!("fs::setlk err=ENOSYS");
        reply.error(libc::ENOSYS);
    }

    fn bmap(&mut self, _req: &Request, _ino: u64, _blocksize: u32, _idx: u64, reply: ReplyBmap) {
        tracing::trace!("fs::bmp err=ENOSYS");
        reply.error(libc::ENOSYS);
    }

    #[cfg(target_os = "macos")]
    fn setvolname(&mut self, _req: &Request, _name: &OsStr, reply: ReplyEmpty) {
        tracing::trace!("fs::setvolname err=ENOSYS");
        reply.error(libc::ENOSYS);
    }

    #[cfg(target_os = "macos")]
    fn exchange(
        &mut self,
        _req: &Request,
        _parent: u64,
        _name: &OsStr,
        _newparent: u64,
        _newname: &OsStr,
        _options: u64,
        reply: ReplyEmpty,
    ) {
        tracing::trace!("fs::exchange err=ENOSYS");
        reply.error(libc::ENOSYS);
    }

    #[cfg(target_os = "macos")]
    fn getxtimes(&mut self, _req: &Request, _ino: u64, reply: ReplyXTimes) {
        tracing::trace!("fs::getxtimes err=ENOSYS");
        reply.error(libc::ENOSYS);
    }
}

fn file_type_to_kind(ft: virtual_fs::FileType) -> fuser::FileType {
    if ft.dir {
        fuser::FileType::Directory
    } else if ft.symlink {
        fuser::FileType::Symlink
    } else if ft.block_device {
        fuser::FileType::BlockDevice
    } else if ft.char_device {
        fuser::FileType::CharDevice
    } else if ft.socket {
        fuser::FileType::Socket
    } else {
        fuser::FileType::RegularFile
    }
}