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
use std::{
    collections::HashSet,
    sync::{Arc, Mutex},
};

use super::*;

/// Journal which leave itself in a consistent state once it commits
/// by closing all the file descriptors that were opened while
/// it was recording writes.
#[derive(Debug)]
pub struct AutoConsistentJournal<W: WritableJournal, R: ReadableJournal> {
    tx: AutoConsistentJournalTx<W>,
    rx: AutoConsistentJournalRx<R>,
}

#[derive(Debug, Default, Clone)]
struct State {
    open_files: HashSet<u32>,
    open_sockets: HashSet<u32>,
}

#[derive(Debug)]
pub struct AutoConsistentJournalTx<W: WritableJournal> {
    state: Arc<Mutex<State>>,
    inner: W,
}

#[derive(Debug)]
pub struct AutoConsistentJournalRx<R: ReadableJournal> {
    inner: R,
}

impl AutoConsistentJournal<Box<DynWritableJournal>, Box<DynReadableJournal>> {
    /// Creates a journal which will automatically correct inconsistencies when
    /// it commits. E.g. it will close any open file descriptors that were left
    /// open as it was processing events.
    pub fn new<J>(inner: J) -> Self
    where
        J: Journal,
    {
        let state = Arc::new(Mutex::new(State::default()));
        let (tx, rx) = inner.split();
        Self {
            tx: AutoConsistentJournalTx {
                inner: tx,
                state: state.clone(),
            },
            rx: AutoConsistentJournalRx { inner: rx },
        }
    }
}

impl<W: WritableJournal, R: ReadableJournal> AutoConsistentJournal<W, R> {
    pub fn into_inner(self) -> RecombinedJournal<W, R> {
        RecombinedJournal::new(self.tx.inner, self.rx.inner)
    }
}

impl<W: WritableJournal> WritableJournal for AutoConsistentJournalTx<W> {
    fn write<'a>(&'a self, entry: JournalEntry<'a>) -> anyhow::Result<LogWriteResult> {
        match &entry {
            JournalEntry::OpenFileDescriptorV1 { fd, .. }
            | JournalEntry::CreateEventV1 { fd, .. } => {
                let mut state = self.state.lock().unwrap();
                state.open_files.insert(*fd);
            }
            JournalEntry::SocketAcceptedV1 { fd, .. } => {
                let mut state = self.state.lock().unwrap();
                state.open_sockets.insert(*fd);
            }
            JournalEntry::CreatePipeV1 { fd1, fd2 } => {
                let mut state = self.state.lock().unwrap();
                state.open_files.insert(*fd1);
                state.open_files.insert(*fd2);
            }
            JournalEntry::RenumberFileDescriptorV1 { old_fd, new_fd } => {
                let mut state = self.state.lock().unwrap();
                if state.open_files.remove(old_fd) {
                    state.open_files.insert(*new_fd);
                }
                if state.open_sockets.remove(old_fd) {
                    state.open_sockets.insert(*new_fd);
                }
            }
            JournalEntry::DuplicateFileDescriptorV1 {
                original_fd,
                copied_fd,
            } => {
                let mut state = self.state.lock().unwrap();
                if state.open_files.contains(original_fd) {
                    state.open_files.insert(*copied_fd);
                }
                if state.open_sockets.contains(original_fd) {
                    state.open_sockets.insert(*copied_fd);
                }
            }
            JournalEntry::CloseFileDescriptorV1 { fd } => {
                let mut state = self.state.lock().unwrap();
                state.open_files.remove(fd);
                state.open_sockets.remove(fd);
            }
            JournalEntry::InitModuleV1 { .. }
            | JournalEntry::ClearEtherealV1 { .. }
            | JournalEntry::ProcessExitV1 { .. } => {
                let mut state = self.state.lock().unwrap();
                state.open_files.clear();
                state.open_sockets.clear();
            }
            _ => {}
        }
        self.inner.write(entry)
    }

    fn flush(&self) -> anyhow::Result<()> {
        self.inner.flush()
    }

    /// Commits the transaction
    fn commit(&self) -> anyhow::Result<usize> {
        let open_files = {
            let mut state = self.state.lock().unwrap();
            let mut open_files = Default::default();
            std::mem::swap(&mut open_files, &mut state.open_files);
            state.open_sockets.clear();
            open_files
        };
        for fd in open_files {
            let entry = JournalEntry::CloseFileDescriptorV1 { fd };
            self.inner.write(entry)?;
        }
        self.inner.commit()
    }

    /// Rolls back the transaction and aborts its changes
    fn rollback(&self) -> anyhow::Result<usize> {
        {
            let mut state = self.state.lock().unwrap();
            state.open_files.clear();
            state.open_sockets.clear();
        }
        self.inner.rollback()
    }
}

impl<R: ReadableJournal> ReadableJournal for AutoConsistentJournalRx<R> {
    fn read(&self) -> anyhow::Result<Option<LogReadResult<'_>>> {
        self.inner.read()
    }

    fn as_restarted(&self) -> anyhow::Result<Box<DynReadableJournal>> {
        Ok(Box::new(AutoConsistentJournalRx {
            inner: self.inner.as_restarted()?,
        }))
    }
}

impl<W: WritableJournal, R: ReadableJournal> WritableJournal for AutoConsistentJournal<W, R> {
    fn write<'a>(&'a self, entry: JournalEntry<'a>) -> anyhow::Result<LogWriteResult> {
        self.tx.write(entry)
    }

    fn flush(&self) -> anyhow::Result<()> {
        self.tx.flush()
    }

    fn commit(&self) -> anyhow::Result<usize> {
        self.tx.commit()
    }

    fn rollback(&self) -> anyhow::Result<usize> {
        self.tx.rollback()
    }
}

impl<W: WritableJournal, R: ReadableJournal> ReadableJournal for AutoConsistentJournal<W, R> {
    fn read(&self) -> anyhow::Result<Option<LogReadResult<'_>>> {
        self.rx.read()
    }

    fn as_restarted(&self) -> anyhow::Result<Box<DynReadableJournal>> {
        self.rx.as_restarted()
    }
}

impl Journal for AutoConsistentJournal<Box<DynWritableJournal>, Box<DynReadableJournal>> {
    fn split(self) -> (Box<DynWritableJournal>, Box<DynReadableJournal>) {
        (Box::new(self.tx), Box::new(self.rx))
    }
}