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
use std::{
    borrow::Cow,
    ffi::OsStr,
    fs,
    io::{
        self,
        LineWriter,
        Write,
    },
    path::{
        Path,
        PathBuf,
    },
};

use crate::error::{
    Error,
    Result,
};

/// `LogFileMeta` allows us to keep track of an estimated length for a given
/// file.
#[derive(Clone, Default)]
pub struct LogFileMeta {
    est_len: u64,
}
impl LogFileMeta {
    pub fn from_meta(meta: &fs::Metadata) -> Self {
        Self {
            est_len: meta.len(),
        }
    }

    pub fn try_from_file(file: &fs::File) -> io::Result<Self> {
        Ok(Self::from_meta(&file.metadata()?))
    }

    fn wrote(&mut self, bs_count: usize) {
        self.est_len = self.est_len.saturating_add(bs_count as u64);
    }

    fn len_estimate(&self) -> u64 {
        self.est_len
    }
}

/// A Trigger which specifies when to roll a file.
#[derive(Clone)]
pub enum Trigger {
    Size { limit: u64 },
}
impl Trigger {
    /// Has the trigger been met.
    fn should_roll(&self, meta: &LogFileMeta) -> bool {
        matches!(self, Self::Size{limit} if *limit < meta.len_estimate())
    }
}
/// Ex. If count is `3` and pattern is 'log/foo.{}' we'll have the following
/// layout
/// ```text
/// /log
///   - foo.0 # the latest rolled log file
///   - foo.1
///   - foo.2 # the oldest rolled log file
/// ```
#[derive(Clone)]
pub struct FixedWindow {
    /// invariant last < count
    last:    Option<usize>,
    count:   usize,
    pattern: String,
}
impl FixedWindow {
    const COUNT_BASE: usize = 0;
    pub(crate) const INDEX_TOKEN: &'static str = "{}";

    /// Increment the last rolled file (highest index)
    fn inc_last(&mut self) -> usize {
        match &mut self.last {
            None => {
                self.last.replace(Self::COUNT_BASE);
                Self::COUNT_BASE
            },
            // invariant: current < count
            Some(x) if (x.saturating_add(1)) == self.count => *x,
            Some(x) => {
                *x = x.saturating_add(1);
                *x
            },
        }
    }

    // eas: Idk why im so dumb but this function is _bad_.
    fn roll(&mut self, path: &Path) -> io::Result<()> {
        // if None, we just need to roll to zero, which happens after this block
        'outer: {
            if let Some(mut c) = self.last {
                // holding max rolls, saturation should be fine
                if c.saturating_add(1) == self.count {
                    // if Some(0) and 1 = self.count we skip
                    if c == 0 {
                        break 'outer;
                    }
                    // We skip the last file if we're at the max so it'll get overwritten.
                    c = c.saturating_sub(1);
                }

                while c > 0 && c > Self::COUNT_BASE {
                    Self::pattern_roll(&self.pattern, c, c.saturating_add(1))?;
                    c = c.saturating_sub(1);
                }
                // current == COUNT_BASE
                Self::pattern_roll(&self.pattern, c, c.saturating_add(1))?;
            }
        }
        self.inc_last();

        let new_path = self
            .pattern
            .replace(Self::INDEX_TOKEN, &Self::COUNT_BASE.to_string());

        fs::rename(path, new_path)
    }

    /// Roll from for example `./foo.0` to `./foo.1`
    fn pattern_roll(pattern: &str, from: usize, to: usize) -> io::Result<()> {
        fs::rename(
            pattern.replace(Self::INDEX_TOKEN, &from.to_string()),
            pattern.replace(Self::INDEX_TOKEN, &to.to_string()),
        )
    }
}

/// Roller specifies how to roll a file.
#[derive(Clone)]
pub enum Roller {
    Delete,
    FixedWindow(FixedWindow),
}
impl Roller {
    /// Construct a new fixed window roller.
    pub fn new_fixed(pattern: String, count: usize) -> Self {
        Self::FixedWindow(FixedWindow {
            last: None,
            pattern,
            count,
        })
    }

    /// Perform the roll.
    pub fn roll(
        &mut self,
        path: &Path,
        writer: &mut Option<LineWriter<fs::File>>,
    ) -> io::Result<()> {
        if let Some(w) = writer {
            w.flush()?;
        }
        writer.take();
        match self {
            Self::FixedWindow(x) => {
                x.roll(path)?;
            },
            Self::Delete => fs::remove_file(path)?,
        }
        writer.replace(RollingFile::new_writer(path)?);
        Ok(())
    }
}

/// An appender which writes to a file and manages rolling said file, either to
/// backups or by deletion.
pub struct RollingFile {
    path:    PathBuf,
    /// Writer will always be some except when it is being rolled or if there
    /// was an error initing a new writer after abandonment of the previous.
    writer:  Option<LineWriter<fs::File>>,
    meta:    LogFileMeta,
    trigger: Trigger,
    roller:  Roller,
}
impl RollingFile {
    const DEFAULT_FILE_NAME: &'static str = "log";
    const DEFAULT_ROLL_PATTERN: &'static str = "{filename}.{}";
    const FILE_NAME_TOKEN: &'static str = "{filename}";

    /// Create a new `RollingFile`
    ///
    /// `RollingFile` accepts a path that will be the target of logs. Env
    /// variables are expanded with the following syntax:
    /// `$ENV{var_name}`.
    ///
    /// Note: If the variable fails to resolve, `$ENV{var_name}` will NOT
    /// be replaced in the path.
    pub fn new(p: impl AsRef<str>, trigger: Trigger, roller: Roller) -> Result<Self> {
        let path = PathBuf::from(crate::env::expand_env_vars(p.as_ref()).as_ref());
        let (writer, meta) = {
            let writer = Self::new_writer(&path).map_err(|e| Error::CreateFailed {
                path:   path.clone(),
                source: e,
            })?;
            let meta = writer
                .get_ref()
                .metadata()
                .map_err(|e| Error::MetadataFailed {
                    path:   path.clone(),
                    source: e,
                })?;
            (writer, LogFileMeta::from_meta(&meta))
        };

        Ok(Self {
            path,
            writer: Some(writer),
            meta,
            trigger,
            roller,
        })
    }

    /// Verify that the currently open file is still at the original path.
    pub fn correct_path(&mut self) -> io::Result<()> {
        let correct = fs::metadata(&self.path);
        let existing = self.writer.as_ref().map(|w| w.get_ref().metadata());

        if needs_remount(existing, correct) {
            self.remount()?;
        }
        Ok(())
    }

    /// Get the target path as a string.
    pub fn path_str(&self) -> String {
        self.path.to_string_lossy().to_string()
    }

    /// Remount the file at the specified path.
    /// This is useful when the file has been moved since the fd was originally
    /// mounted.
    fn remount(&mut self) -> io::Result<()> {
        self.writer
            .as_mut()
            .map(std::io::Write::flush)
            .transpose()?;
        if let Some(parent) = self.path.parent() {
            fs::create_dir_all(parent)?;
        }

        let p = self.path.clone();
        self.swap_writer(|| Self::new_writer(&p))?;
        self.meta = self
            .writer
            .as_mut()
            .map(|w| LogFileMeta::try_from_file(w.get_ref()))
            .transpose()?
            .unwrap_or_default();

        Ok(())
    }

    /// Takes the `path` of the active log file and makes the roll path pattern
    /// with the specified `pat_opt` or if `None` specified, the default
    /// pattern: "{filename}.{}".
    ///
    /// ```ignore
    /// 
    /// make_qualified_pattern(Path::from("./foo/bar.log"), None); // -> "./foo/bar.log.{}"
    /// make_qualified_pattern(Path::from("./foo/bar.log"), Some("bar_roll.{}")); // -> "./foo/bar_roll.{}"
    /// ```
    pub(crate) fn make_qualified_pattern(path: &Path, pat_opt: Option<&str>) -> String {
        let parent = path.parent().unwrap_or_else(|| Path::new("/"));
        if let Some(pat) = pat_opt {
            parent.join(pat).to_string_lossy().to_string()
        } else {
            let file_name = path.file_name().map_or_else(
                || Cow::Borrowed(Self::DEFAULT_FILE_NAME),
                OsStr::to_string_lossy,
            );

            let file_name_pattern =
                Self::DEFAULT_ROLL_PATTERN.replacen(Self::FILE_NAME_TOKEN, &file_name, 1);

            parent.join(file_name_pattern).to_string_lossy().to_string()
        }
    }

    fn swap_writer(&mut self, f: impl Fn() -> io::Result<LineWriter<fs::File>>) -> io::Result<()> {
        self.writer.take();
        self.writer = Some(f()?);
        Ok(())
    }

    fn new_writer(path: &Path) -> io::Result<LineWriter<fs::File>> {
        let f = fs::File::options().append(true).create(true).open(path)?;

        Ok(LineWriter::new(f))
    }

    fn maybe_roll(&mut self) -> io::Result<()> {
        if self.trigger.should_roll(&self.meta) {
            self.roller.roll(&self.path, &mut self.writer)?;
            self.meta = self
                .writer
                .as_mut()
                .map(|w| LogFileMeta::try_from_file(w.get_ref()))
                .transpose()?
                .unwrap_or_default();
        }
        Ok(())
    }
}

impl io::Write for RollingFile {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        if let Some(w) = &mut self.writer {
            let bs_written = w.write(buf)?;
            self.meta.wrote(bs_written);
            self.maybe_roll()?;
            Ok(bs_written)
        } else {
            Ok(0)
        }
    }

    fn flush(&mut self) -> io::Result<()> {
        self.writer
            .as_mut()
            .map(std::io::Write::flush)
            .transpose()?;
        Ok(())
    }
}
pub(crate) fn needs_remount(
    existing: Option<io::Result<fs::Metadata>>,
    correct: io::Result<fs::Metadata>,
) -> bool {
    match (existing, correct) {
        // existing file get metadata success _or_ not provided while correct file path unsuccessful
        (Some(Ok(_)) | None, Err(_)) => true,
        (Some(Ok(e)), Ok(c)) => needs_remount_inner(&e, &c),
        _ => false,
    }
}

fn needs_remount_inner(existing: &fs::Metadata, correct: &fs::Metadata) -> bool {
    #[cfg(unix)]
    {
        use std::os::unix::fs::MetadataExt;
        existing.dev() != correct.dev() || existing.ino() != correct.ino()
    }
    #[cfg(windows)]
    {
        // we can only really approximate file comparison to identify if the existing
        // file is the one we are writing to
        use std::os::windows::fs::MetadataExt;
        existing.file_size() != correct.file_size()
            || existing.creation_time() != correct.creation_time()
            || existing.last_write_time() != correct.last_write_time()
    }
    #[cfg(not(any(unix, windows)))]
    // unsupported
    {
        false
    }
}