legit-hasher 0.1.6

Every legit-hashes definition, images and text, for callers in any language: a command-line runner over JSON lines with resumable batches, and with the `serve` feature a worker that takes hashing tasks from Redis Streams
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
//! `serve --events-file`: the tasks a worker answered in the last interval, four numbers each, as
//! one JSON document a collector beside it reads, replaced whole at every interval.

use std::io;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, PoisonError};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

use serde::Serialize;

use super::StatsState;
use super::stats::{beside, replace};

/// The version of the events document: `1`. A change that isn't only a new field raises it.
pub const EVENTS_FORMAT: u32 = 1;

/// How often `serve --events-file` writes by default: every second.
pub const DEFAULT_EVENTS_INTERVAL: Duration = Duration::from_secs(1);

/// The shortest interval `--events-interval` takes: 0.2 s.
pub const MIN_EVENTS_INTERVAL: Duration = Duration::from_millis(200);

/// The longest interval `--events-interval` takes: 60 s.
pub const MAX_EVENTS_INTERVAL: Duration = Duration::from_secs(60);

/// How many answered tasks an interval keeps by default, `--events-max`; the ones past it are
/// counted in `dropped`.
pub const DEFAULT_EVENTS_MAX: usize = 10_000;

/// The most answered tasks an interval may keep, the largest `--events-max`: 100,000, which is
/// 3.2 MB of buffers.
pub const MAX_EVENTS_MAX: usize = 100_000;

/// The bit of [`Record::took`] that marks a task of the fast lane.
const FAST: u64 = 1 << 63;
/// The bit of [`Record::took`] that marks a failed task.
const FAILED: u64 = 1 << 62;
/// The bits of [`Record::took`] that hold the microseconds: about 146,000 years.
const MICROS: u64 = FAILED - 1;

/// One answered task as the buffer holds it: 16 bytes, and nothing that could name the task.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Record {
    /// When it was answered, in microseconds since the server started, by the monotonic clock.
    at_us: u64,
    /// How long the worker spent on it, in microseconds, with its lane and outcome in the two top
    /// bits.
    took: u64,
}

const _: () = assert!(size_of::<Record>() <= 16);

impl Record {
    fn new(at: Duration, took: Duration, fast: bool, failed: bool) -> Self {
        let micros = |duration: Duration| u64::try_from(duration.as_micros()).unwrap_or(u64::MAX);
        let mut packed = micros(took).min(MICROS);
        if fast {
            packed |= FAST;
        }
        if failed {
            packed |= FAILED;
        }
        Self {
            at_us: micros(at),
            took: packed,
        }
    }

    /// The record as the document gives it: its offset after `from_us`, in milliseconds and at most
    /// `length_ms`, its lane, its outcome and its time.
    fn row(self, from_us: u64, length_ms: u64) -> [u64; 4] {
        [
            (self.at_us.saturating_sub(from_us) / 1_000).min(length_ms),
            u64::from(self.took & FAST != 0),
            u64::from(self.took & FAILED == 0),
            self.took & MICROS,
        ]
    }
}

/// What the task path adds to and the writer takes, under one lock.
#[derive(Debug)]
struct Pending {
    /// The tasks answered since the writer last took them, allocated to `max` once.
    records: Vec<Record>,
    /// The tasks answered since then that found `records` full.
    dropped: u64,
}

/// The bounded buffer the handlers record answered tasks in.
///
/// A [`Mutex`] rather than a lock-free queue: the critical section is a length check and a push
/// into room allocated at the start, or one addition when it's full, so the lock is held for a few
/// instructions; the writer holds it once an interval, only to swap the vector for an empty one
/// of the same capacity. The standard library has no bounded lock-free queue, and none is worth a
/// dependency for a lock that's free nearly every time it's taken.
#[derive(Debug)]
pub(crate) struct Buffer {
    /// When the server started: the origin of [`Record::at_us`].
    origin: Instant,
    max: usize,
    pending: Mutex<Pending>,
}

impl Buffer {
    pub(crate) fn new(origin: Instant, max: usize) -> Self {
        Self {
            origin,
            max,
            pending: Mutex::new(Pending {
                records: Vec::with_capacity(max),
                dropped: 0,
            }),
        }
    }

    /// Remember a task answered now, on the fast lane or the bulk one, that failed or not, and on
    /// which the worker spent `took`. It never allocates: past `max` the task is only counted.
    pub(crate) fn record(&self, fast: bool, failed: bool, took: Duration) {
        let record = Record::new(
            Instant::now().saturating_duration_since(self.origin),
            took,
            fast,
            failed,
        );
        let mut pending = self.pending.lock().unwrap_or_else(PoisonError::into_inner);
        if pending.records.len() < self.max {
            pending.records.push(record);
        } else {
            pending.dropped += 1;
        }
    }

    /// Swap the records for `spare`, which must be empty, and give the count of those dropped.
    fn take(&self, spare: &mut Vec<Record>) -> u64 {
        let mut pending = self.pending.lock().unwrap_or_else(PoisonError::into_inner);
        std::mem::swap(&mut pending.records, spare);
        std::mem::take(&mut pending.dropped)
    }
}

/// A handle on a [`Server`](super::Server)'s answered tasks, for the events file: see
/// [`Server::events`](super::Server::events). It outlives the server, so the last document can be
/// written after the workers have stopped.
#[derive(Debug, Clone)]
pub struct Events {
    pub(crate) buffer: Arc<Buffer>,
    /// When the server started, in Unix seconds, as the stats file gives it.
    pub(crate) started_at: u64,
    /// The same, in Unix milliseconds.
    pub(crate) started_ms: u64,
}

impl Events {
    /// How many answered tasks an interval keeps.
    #[must_use]
    pub fn max(&self) -> usize {
        self.buffer.max
    }

    /// When the server started, in Unix seconds.
    #[must_use]
    pub const fn started_at(&self) -> u64 {
        self.started_at
    }
}

/// The events document, format 1: what [`events_document`] writes. Every field is a number but
/// `state`, and each record is four.
///
/// ```
/// use legit_hasher::serve::{EventsDocument, events_document};
///
/// let mut document = EventsDocument::default();
/// document.seq = 1;
/// document.records = vec![[3, 0, 1, 229_104], [11, 1, 0, 412]];
/// let text = events_document(&document);
/// assert!(text.starts_with(r#"{"format":1,"program":"legit-hasher","#));
/// assert!(text.ends_with(r#""count":2,"dropped":0,"records":[[3,0,1,229104],[11,1,0,412]]}"#));
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct EventsDocument {
    /// `running`, or `stopped` in the last document.
    pub state: StatsState,
    /// When the worker started, in Unix seconds.
    pub started_at: u64,
    /// 1 for the first document the process writes, one more for each written after it.
    pub seq: u64,
    /// The start of the interval, in Unix milliseconds: the previous document's `at_ms`, or when
    /// the worker started.
    pub from_ms: u64,
    /// The end of the interval, in Unix milliseconds, never before `from_ms`.
    pub at_ms: u64,
    /// The tasks answered in the interval, or in an earlier one whose write failed, that aren't in
    /// `records`.
    pub dropped: u64,
    /// The tasks answered in the interval, in the order they were answered: milliseconds after
    /// `from_ms`, the lane (0 bulk, 1 fast), the outcome (1 answered without a failure, 0
    /// failed) and the microseconds the worker spent on the task.
    pub records: Vec<[u64; 4]>,
}

impl Default for EventsDocument {
    /// A running document with no record, numbered 0, of an interval of no length at the epoch.
    fn default() -> Self {
        Self {
            state: StatsState::Running,
            started_at: 0,
            seq: 0,
            from_ms: 0,
            at_ms: 0,
            dropped: 0,
            records: Vec::new(),
        }
    }
}

/// The events document as one line of JSON without the newline: what `serve --events-file` writes.
/// `count` is the number of records.
///
/// It holds numbers, the program's name and version and `state`, and nothing else: no id, name,
/// URL, address, error, definition, size or hash of any task, by construction, as the buffer the
/// records come from holds four numbers a task.
#[must_use]
pub fn events_document(document: &EventsDocument) -> String {
    #[derive(Serialize)]
    struct Line<'a> {
        format: u32,
        program: &'static str,
        version: &'static str,
        state: StatsState,
        started_at: u64,
        seq: u64,
        from_ms: u64,
        at_ms: u64,
        count: usize,
        dropped: u64,
        records: &'a [[u64; 4]],
    }
    let line = Line {
        format: EVENTS_FORMAT,
        program: crate::RUNNER.name,
        version: env!("CARGO_PKG_VERSION"),
        state: document.state,
        started_at: document.started_at,
        seq: document.seq,
        from_ms: document.from_ms,
        at_ms: document.at_ms,
        count: document.records.len(),
        dropped: document.dropped,
        records: &document.records,
    };
    // Numbers and fixed names only, so serializing can't fail...
    serde_json::to_string(&line).unwrap_or_default()
}

/// Where `serve --events-file` writes, and what it remembers between writes: the number and the
/// end of the last document written, the tasks dropped since, and the last failure it logged.
///
/// [`EventsFile::write`] takes the tasks answered since the previous call and, when there is at
/// least one, replaces the file with a document of exactly those. Each write is whole, as the
/// stats file's: the document goes to the file's name plus `.tmp` in the same directory, with mode
/// 0644, and is then renamed over the file. A write that fails removes the temporary file, is
/// logged at warning level when it's the first failure since a success or its error's kind differs
/// from the last one's, and drops its records: the next document counts them in `dropped`, so the
/// file never carries a backlog.
///
/// ```
/// use std::sync::Arc;
/// use legit_hasher::serve::{EventsFile, ServeConfig, Server, StatsState};
/// use legit_streams::{MemoryStreams, Streams};
///
/// let streams: Arc<dyn Streams> = Arc::new(MemoryStreams::new());
/// let server = Server::start_with_events(ServeConfig::new("hasher-1", 7), streams, None, 1_000)?;
/// let events = server.events().expect("recording");
/// let path = std::env::temp_dir().join(format!("legit-hasher-events-doc-{}.json", std::process::id()));
/// let mut file = EventsFile::new(&path)?;
/// // The first document is written, with no record: tasks answered before it go in the next...
/// let first = file.write(&events, StatsState::Running)?.expect("a first document");
/// assert_eq!((first.seq, first.records.len()), (1, 0));
/// // ...an interval with no answered task writes nothing...
/// assert_eq!(file.write(&events, StatsState::Running)?, None);
/// server.stop();
/// server.join()?;
/// // ...and the last is written whatever was answered.
/// file.write(&events, StatsState::Stopped)?;
/// let document: serde_json::Value = serde_json::from_slice(&std::fs::read(&path)?)?;
/// assert_eq!((&document["seq"], &document["state"]), (&2.into(), &"stopped".into()));
/// # std::fs::remove_file(&path)?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug)]
pub struct EventsFile {
    path: PathBuf,
    temporary: PathBuf,
    /// The number of the last document written, 0 before the first.
    seq: u64,
    /// The end of the last document written, in Unix milliseconds and in microseconds since the
    /// server started by the monotonic clock.
    from: Option<(u64, u64)>,
    /// The tasks dropped since the last document written: the buffer's, and a failed write's.
    dropped: u64,
    /// The records taken from the buffer, and the room it's given back in exchange.
    spare: Vec<Record>,
    /// The kind of the last failed write, until a write succeeds.
    failure: Option<io::ErrorKind>,
}

impl EventsFile {
    /// An events file at `path`. Nothing is written until [`EventsFile::write`].
    ///
    /// # Errors
    ///
    /// As [`StatsFile::new`](super::StatsFile::new): [`io::ErrorKind::NotFound`] when the
    /// directory `path` would be in doesn't exist, and [`io::ErrorKind::InvalidInput`] when `path`
    /// names no file or names a directory.
    ///
    /// ```
    /// use legit_hasher::serve::EventsFile;
    ///
    /// assert!(EventsFile::new(std::env::temp_dir().join("events.json")).is_ok());
    /// assert!(EventsFile::new("/no/such/directory/events.json").is_err());
    /// ```
    pub fn new(path: impl AsRef<Path>) -> io::Result<Self> {
        let (path, temporary) = beside(path.as_ref())?;
        Ok(Self {
            path,
            temporary,
            seq: 0,
            from: None,
            dropped: 0,
            spare: Vec::new(),
            failure: None,
        })
    }

    /// The file's path.
    #[must_use]
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// Take the tasks `events` has recorded since the last call and, when at least one was
    /// answered or when `state` is [`StatsState::Stopped`], write the document of the interval since
    /// the last document written. Until a first document is written, a running write writes one
    /// with no record and takes none: the tasks answered before it go in the next.
    ///
    /// # Errors
    ///
    /// The error of creating, writing or renaming the temporary file, which is removed. The
    /// interval's records are dropped and counted in the next document's `dropped`; the failure is
    /// logged as [`EventsFile`] says.
    pub fn write(&mut self, events: &Events, state: StatsState) -> io::Result<Option<EventsDocument>> {
        let buffer = &events.buffer;
        // The wall clock once, and the monotonic clock the offsets are measured on...
        let at_ms = unix_ms(SystemTime::now());
        let at_us = u64::try_from(buffer.origin.elapsed().as_micros()).unwrap_or(u64::MAX);
        if self.spare.capacity() < buffer.max {
            self.spare.reserve_exact(buffer.max);
        }
        let first = self.seq == 0 && state == StatsState::Running;
        // The first document is empty: what was answered before it stays for the next...
        let full = if first { 0 } else { buffer.take(&mut self.spare) };
        let answered = !self.spare.is_empty() || full > 0;
        if !answered && !first && state == StatsState::Running {
            return Ok(None);
        }
        let (from_ms, from_us) = self.from.unwrap_or((events.started_ms, 0));
        let at_ms = at_ms.max(from_ms);
        let length_ms = at_ms - from_ms;
        // Two handlers may push in the other order than they read the clock...
        self.spare.sort_by_key(|record| record.at_us);
        let records: Vec<[u64; 4]> = self.spare.iter().map(|record| record.row(from_us, length_ms)).collect();
        self.spare.clear();
        let dropped = self.dropped + full;
        let document = EventsDocument {
            state,
            started_at: events.started_at,
            seq: self.seq + 1,
            from_ms,
            at_ms,
            dropped,
            records,
        };
        let mut text = events_document(&document);
        text.push('\n');
        match replace(&self.temporary, &self.path, text.as_bytes()) {
            Ok(()) => {
                self.seq = document.seq;
                self.from = Some((at_ms, at_us));
                self.dropped = 0;
                self.failure = None;
                Ok(Some(document))
            }
            Err(error) => {
                self.dropped = dropped + document.records.len() as u64;
                if self.failure != Some(error.kind()) {
                    tracing::warn!(path = %self.path.display(), error = %error, "Couldn't write the events file; the worker carries on");
                }
                self.failure = Some(error.kind());
                Err(error)
            }
        }
    }
}

fn unix_ms(time: SystemTime) -> u64 {
    time.duration_since(UNIX_EPOCH)
        .map_or(0, |since| u64::try_from(since.as_millis()).unwrap_or(u64::MAX))
}

/// When `time` was, in Unix milliseconds and seconds.
pub(crate) fn unix_ms_and_seconds(time: SystemTime) -> (u64, u64) {
    let ms = unix_ms(time);
    (ms, ms / 1_000)
}

#[cfg(test)]
mod tests {
    use std::time::{Duration, Instant};

    use super::{Buffer, MICROS, Record};

    #[test]
    fn a_record_keeps_its_lane_outcome_and_time_apart() {
        for (fast, failed) in [(false, false), (false, true), (true, false), (true, true)] {
            let record = Record::new(
                Duration::from_millis(1_500),
                Duration::from_micros(229_104),
                fast,
                failed,
            );
            assert_eq!(
                record.row(1_000_000, 1_000),
                [500, u64::from(fast), u64::from(!failed), 229_104]
            );
        }
        let longest = Record::new(Duration::ZERO, Duration::MAX, true, false);
        assert_eq!(longest.row(0, 0), [0, 1, 1, MICROS]);
    }

    #[test]
    fn an_offset_is_clamped_to_the_interval() {
        let record = Record::new(Duration::from_millis(10), Duration::ZERO, false, false);
        assert_eq!(record.row(20_000, 100)[0], 0, "answered before the interval");
        assert_eq!(record.row(0, 5)[0], 5, "past its end");
    }

    #[test]
    fn a_full_buffer_counts_what_it_drops_and_a_take_empties_it() {
        let buffer = Buffer::new(Instant::now(), 3);
        for _ in 0..5 {
            buffer.record(false, false, Duration::from_millis(1));
        }
        let mut spare = Vec::with_capacity(3);
        assert_eq!(buffer.take(&mut spare), 2);
        assert_eq!(spare.len(), 3);
        spare.clear();
        assert_eq!(buffer.take(&mut spare), 0);
        assert!(spare.is_empty());
        // The room handed back is the room taken: nothing is allocated on the task path...
        assert!(buffer.pending.lock().expect("unpoisoned").records.capacity() >= 3);
    }
}