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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
//! `legit-hasher serve`: the command-line front of [`legit_hasher::serve`].

use std::path::{Path, PathBuf};
use std::process::ExitCode;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{self, RecvTimeoutError};
use std::thread::JoinHandle;
use std::time::{Duration, Instant};

use legit_hasher::Settings;
use legit_hasher::serve::{
    self, BACKLOG_TIMEOUT, DEFAULT_EVENTS_INTERVAL, DEFAULT_EVENTS_MAX, DEFAULT_HEARTBEAT, Events, EventsFile,
    FetchPolicy, MAX_EVENTS_INTERVAL, MAX_EVENTS_MAX, MIN_EVENTS_INTERVAL, ServeConfig, Server, StatsFile, StatsState,
};
use legit_streams::{RedisStreams, Streams};

use crate::{HELP_ASKED, Usage, number};

/// The environment variable `--redis` defaults to, so a password needn't be on the command line.
const REDIS_URL_VARIABLE: &str = "LEGIT_HASHER_REDIS_URL";

/// How often the main loop looks for a signal or a stopped worker.
const POLL: Duration = Duration::from_millis(100);

/// The settings `serve` takes from its command line.
#[derive(Debug)]
struct Arguments {
    redis: Option<String>,
    key_prefix: String,
    kind: String,
    consumer: Option<String>,
    jobs: Option<usize>,
    fast_jobs: usize,
    no_fast: bool,
    fetch: FetchPolicy,
    hosts_files: Vec<PathBuf>,
    shutdown_grace: Duration,
    heartbeat: Duration,
    stats_file: Option<PathBuf>,
    events_file: Option<PathBuf>,
    events_interval: Option<Duration>,
    events_max: Option<usize>,
    #[cfg(unix)]
    events_socket: Option<PathBuf>,
    settings: Settings,
}

/// Run `legit-hasher serve` with the arguments after the command.
pub(crate) fn serve(rest: &[String]) -> Result<ExitCode, Usage> {
    let mut arguments = parse(rest)?;
    for path in &arguments.hosts_files {
        let text = std::fs::read_to_string(path)
            .map_err(|error| Usage(format!("couldn't read `{}`: {error}", path.display())))?;
        arguments.fetch = arguments
            .fetch
            .clone()
            .allow_hosts_from(&text)
            .map_err(|message| Usage(format!("`{}`, {message}", path.display())))?;
    }
    let stats_file = arguments
        .stats_file
        .as_ref()
        .map(|path| StatsFile::new(path).map_err(|error| Usage(format!("`--stats-file {}`: {error}", path.display()))))
        .transpose()?;
    let events_file = events_file(&arguments, stats_file.as_ref())?;
    #[cfg(unix)]
    let events_socket = events_socket(&arguments)?;
    let url = arguments
        .redis
        .clone()
        .or_else(|| std::env::var(REDIS_URL_VARIABLE).ok())
        .ok_or_else(|| Usage(format!("`serve` needs `--redis URL`, or `{REDIS_URL_VARIABLE}` set")))?;
    if !legit_streams::is_valid_kind(&arguments.kind) {
        return Err(Usage(format!(
            "`--kind` is 1 to 16 of `a-z`, `0-9`, `_` and `-`, not `{}`",
            arguments.kind
        )));
    }
    let prefix = arguments
        .consumer
        .clone()
        .unwrap_or_else(|| format!("legit-hasher-{}", host_name()));
    let mut config = ServeConfig::for_kind(&arguments.kind, &prefix, std::process::id());
    config.worker.concurrency = arguments.jobs.unwrap_or(config.worker.concurrency);
    config.worker.shutdown_grace = arguments.shutdown_grace;
    config.fast = match (arguments.no_fast, config.fast) {
        (false, Some(mut fast)) => {
            fast.concurrency = arguments.fast_jobs;
            Some(fast)
        }
        _ => None,
    };
    config.settings = arguments.settings;
    config.fetch = arguments.fetch;

    // Set directly, never with `try_init`, which would also send the HTTP client's `log` records,
    // whole URLs included, to the log...
    let _ = tracing::subscriber::set_global_default(serve::subscriber(tracing::Level::INFO, std::io::stderr));

    let stop = Arc::new(AtomicBool::new(false));
    for signal in [signal_hook::consts::SIGTERM, signal_hook::consts::SIGINT] {
        // A second signal while stopping ends the process at once...
        signal_hook::flag::register_conditional_shutdown(signal, 1, Arc::clone(&stop))
            .and_then(|_| signal_hook::flag::register(signal, Arc::clone(&stop)))
            .map_err(|error| Usage(format!("couldn't handle signals: {error}")))?;
    }

    let streams = RedisStreams::open(&url)
        .map(|streams| streams.with_key_prefix(arguments.key_prefix.clone()))
        .map_err(|error| Usage(format!("couldn't open `--redis`: {error}")))?;
    // The stats file reads the backlog on a connection of its own, never one of the workers'...
    let mut stats_file = stats_file.map(|file| {
        let backlog: Arc<dyn Streams> = Arc::new(streams.clone().timeout(BACKLOG_TIMEOUT));
        file.with_backlog(backlog, config.worker.stream.clone(), config.worker.group.clone())
    });
    let streams: Arc<dyn Streams> = Arc::new(streams);
    let consumer = config.worker.consumer.clone();
    let events_max = events_file
        .as_ref()
        .map(|_| arguments.events_max.unwrap_or(DEFAULT_EVENTS_MAX));
    #[cfg(unix)]
    let started = match events_socket {
        Some(socket) => Server::start_with_events_socket(config, streams, None, events_max, socket),
        None => start(config, streams, events_max),
    };
    #[cfg(not(unix))]
    let started = start(config, streams, events_max);
    let server = match started {
        Ok(server) => server,
        Err(error) => {
            tracing::error!(error = %error, "The hashing worker couldn't start");
            return Ok(ExitCode::from(2));
        }
    };
    let events_writer = match (events_file, server.events()) {
        (Some(file), Some(events)) => {
            match EventsWriter::spawn(
                file,
                events,
                arguments.events_interval.unwrap_or(DEFAULT_EVENTS_INTERVAL),
            ) {
                Ok(writer) => Some(writer),
                Err(error) => {
                    tracing::error!(error = %error, "The events file's writer couldn't start");
                    server.stop();
                    let _ = server.join();
                    return Ok(ExitCode::from(2));
                }
            }
        }
        _ => None,
    };
    let meter = server.meter();
    // A failed write is logged by the file itself, and never stops the worker...
    let mut write_stats = |state| {
        if let Some(file) = stats_file.as_mut() {
            let _ = file.write(meter.sample(), state);
        }
    };
    write_stats(StatsState::Running);
    let mut last = Instant::now();
    while !stop.load(Ordering::SeqCst) && !server.is_finished() {
        if last.elapsed() >= arguments.heartbeat {
            last = Instant::now();
            heartbeat(&server, &consumer, "running");
            write_stats(StatsState::Running);
        }
        std::thread::sleep(POLL);
    }
    let asked = stop.load(Ordering::SeqCst);
    if asked {
        tracing::info!("Stopping on a signal; running tasks have the shutdown grace to finish");
    }
    server.stop();
    heartbeat(&server, &consumer, "stopping");
    let joined = server.join();
    write_stats(StatsState::Stopped);
    if let Some(writer) = events_writer {
        writer.finish();
    }
    match joined {
        Ok(_) if asked => Ok(ExitCode::SUCCESS),
        Ok(_) => Ok(ExitCode::from(2)),
        Err(error) => {
            tracing::error!(error = %error, "The hashing worker stopped with an error");
            Ok(ExitCode::from(2))
        }
    }
}

/// Start the workers, recording for the events file when it's given.
fn start(config: ServeConfig, streams: Arc<dyn Streams>, events_max: Option<usize>) -> legit_streams::Result<Server> {
    match events_max {
        Some(max) => Server::start_with_events(config, streams, None, max),
        None => Server::start(config, streams, None),
    }
}

/// The sender `--events-socket` names, or `None` without it. The path may not be either file nor
/// either's temporary file, and must fit a socket address.
#[cfg(unix)]
fn events_socket(arguments: &Arguments) -> Result<Option<serve::EventsSocket>, Usage> {
    let Some(path) = &arguments.events_socket else {
        return Ok(None);
    };
    let files = [
        (&arguments.stats_file, "--stats-file"),
        (&arguments.events_file, "--events-file"),
    ];
    for (file, flag) in files {
        let Some(file) = file else { continue };
        if same_file(path, file) {
            return Err(Usage(format!(
                "`--events-socket` and `{flag}` name the same path; give each its own"
            )));
        }
        if same_file(path, &temporary(file)) {
            return Err(Usage(format!(
                "`--events-socket` names the temporary file `{flag}` is written through; give it another name"
            )));
        }
    }
    serve::EventsSocket::new(path)
        .map(Some)
        .map_err(|error| Usage(format!("`--events-socket {}`: {error}", path.display())))
}

/// The events file `--events-file` names, checked as the stats file is, or `None` without it, when
/// `--events-interval` and `--events-max` are refused.
fn events_file(arguments: &Arguments, stats_file: Option<&StatsFile>) -> Result<Option<EventsFile>, Usage> {
    let Some(path) = &arguments.events_file else {
        return match (arguments.events_interval, arguments.events_max) {
            (None, None) => Ok(None),
            (Some(_), _) => Err(Usage("`--events-interval` goes with `--events-file`".to_owned())),
            (None, Some(_)) => Err(Usage("`--events-max` goes with `--events-file`".to_owned())),
        };
    };
    let file = EventsFile::new(path).map_err(|error| Usage(format!("`--events-file {}`: {error}", path.display())))?;
    if let Some(stats_file) = stats_file {
        let (stats, events) = (stats_file.path(), file.path());
        if same_file(stats, events) {
            return Err(Usage(
                "`--events-file` and `--stats-file` name the same file; give each its own".to_owned(),
            ));
        }
        // Each file is written beside itself, to its name plus `.tmp`, then renamed over it...
        for (path, other, flag) in [(events, stats, "--stats-file"), (stats, events, "--events-file")] {
            if same_file(path, &temporary(other)) {
                return Err(Usage(format!(
                    "`{}` is the temporary file `{flag}` is written through; give it another name",
                    path.display()
                )));
            }
        }
    }
    Ok(Some(file))
}

/// The temporary file a stats or events file at `path` is written to before it's renamed over it:
/// its name plus `.tmp`, in the same directory.
fn temporary(path: &Path) -> PathBuf {
    let mut name = path.as_os_str().to_os_string();
    name.push(".tmp");
    PathBuf::from(name)
}

/// Whether two paths, whose directories exist, name the same file: the same name in the same
/// directory once links are followed, or two names of one file that exists.
fn same_file(a: &Path, b: &Path) -> bool {
    let resolve = |path: &Path| {
        std::fs::canonicalize(path).ok().or_else(|| {
            let directory = path.parent().filter(|parent| !parent.as_os_str().is_empty());
            let directory = std::fs::canonicalize(directory.unwrap_or(Path::new("."))).ok()?;
            Some(directory.join(path.file_name()?))
        })
    };
    a == b || resolve(a).is_some_and(|a| resolve(b).is_some_and(|b| a == b))
}

/// The thread that writes the events file every interval, never one a task runs on.
struct EventsWriter {
    stop: mpsc::Sender<()>,
    thread: JoinHandle<EventsFile>,
    events: Events,
}

impl EventsWriter {
    /// Write the first document, then one every `interval` that answered a task.
    fn spawn(mut file: EventsFile, events: Events, interval: Duration) -> std::io::Result<Self> {
        let (stop, stopped) = mpsc::channel::<()>();
        let handle = events.clone();
        let thread = std::thread::Builder::new()
            .name("legit-hasher-events".to_owned())
            .spawn(move || {
                // A failed write is logged by the file itself, and never stops the worker...
                let _ = file.write(&handle, StatsState::Running);
                let mut next = Instant::now() + interval;
                while let Err(RecvTimeoutError::Timeout) =
                    stopped.recv_timeout(next.saturating_duration_since(Instant::now()))
                {
                    let _ = file.write(&handle, StatsState::Running);
                    // Each interval starts where the last ended, unless a write outlasted it...
                    next += interval;
                    let now = Instant::now();
                    if next < now {
                        next = now + interval;
                    }
                }
                file
            })?;
        Ok(Self { stop, thread, events })
    }

    /// Stop the thread and write the last document, with whatever is buffered.
    fn finish(self) {
        drop(self.stop);
        if let Ok(mut file) = self.thread.join() {
            let _ = file.write(&self.events, StatsState::Stopped);
        }
    }
}

/// `--events-interval`: seconds, a decimal from 0.2 to 60.
fn interval(flag: &str, text: &str) -> Result<Duration, Usage> {
    text.parse::<f64>()
        .ok()
        .filter(|seconds| seconds.is_finite())
        .and_then(|seconds| Duration::try_from_secs_f64(seconds).ok())
        .filter(|interval| (MIN_EVENTS_INTERVAL..=MAX_EVENTS_INTERVAL).contains(interval))
        .ok_or_else(|| {
            Usage(format!(
                "`{flag}` takes seconds from {} to {}, such as 0.5, not `{text}`",
                MIN_EVENTS_INTERVAL.as_secs_f64(),
                MAX_EVENTS_INTERVAL.as_secs_f64()
            ))
        })
}

/// One heartbeat line on standard error.
fn heartbeat(server: &Server, consumer: &str, state: &str) {
    let stats = server.stats();
    // Two counts more with `--events-socket`, and none without it...
    #[cfg(unix)]
    let socket = server.events_socket();
    #[cfg(unix)]
    let (events_sent, events_dropped) = (
        socket.as_ref().map(|socket| socket.sent()),
        socket.as_ref().map(|socket| socket.dropped()),
    );
    #[cfg(not(unix))]
    let (events_sent, events_dropped): (Option<u64>, Option<u64>) = (None, None);
    tracing::info!(
        state,
        consumer,
        uptime_s = stats.uptime_s,
        in_flight = stats.in_flight,
        done = stats.done,
        failed = stats.failed,
        fast_done = stats.fast_done,
        fast_failed = stats.fast_failed,
        fetched = stats.fetched,
        fetched_bytes = stats.fetched_bytes,
        connections_opened = stats.connections_opened,
        connections_reused = stats.connections_reused,
        connect_retries = stats.connect_retries,
        events_sent,
        events_dropped,
        "Heartbeat"
    );
}

/// The machine's name for the default consumer name, keeping only the characters a consumer name
/// takes without quoting.
fn host_name() -> String {
    let name = std::fs::read_to_string("/proc/sys/kernel/hostname")
        .ok()
        .or_else(|| std::env::var("HOSTNAME").ok())
        .or_else(|| std::env::var("COMPUTERNAME").ok())
        .unwrap_or_default();
    let name: String = name
        .trim()
        .chars()
        .filter(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))
        .take(64)
        .collect();
    if name.is_empty() { "host".to_owned() } else { name }
}

fn parse(rest: &[String]) -> Result<Arguments, Usage> {
    let mut arguments = Arguments {
        redis: None,
        key_prefix: String::new(),
        kind: serve::KIND.to_owned(),
        consumer: None,
        jobs: None,
        fast_jobs: 2,
        no_fast: false,
        fetch: FetchPolicy::new(),
        hosts_files: Vec::new(),
        shutdown_grace: Duration::from_secs(30),
        heartbeat: DEFAULT_HEARTBEAT,
        stats_file: None,
        events_file: None,
        events_interval: None,
        events_max: None,
        #[cfg(unix)]
        events_socket: None,
        settings: ServeConfig::new("", 0).settings,
    };
    let mut iter = rest.iter();
    while let Some(flag) = iter.next() {
        let (flag, inline) = match flag.split_once('=') {
            Some((flag, value)) if flag.starts_with("--") => (flag, Some(value.to_owned())),
            _ => (flag.as_str(), None),
        };
        let mut value = || {
            inline
                .clone()
                .or_else(|| iter.next().cloned())
                .ok_or_else(|| Usage(format!("`{flag}` needs a value")))
        };
        let seconds = |text: String| number::<u64>(flag, &text, 1).map(Duration::from_secs);
        match flag {
            "--redis" => arguments.redis = Some(value()?),
            "--key-prefix" => arguments.key_prefix = value()?,
            "--kind" => arguments.kind = value()?,
            "--consumer" => arguments.consumer = Some(value()?),
            "--jobs" => arguments.jobs = Some(number(flag, &value()?, 1)?),
            "--fast-jobs" => arguments.fast_jobs = number(flag, &value()?, 1)?,
            "--no-fast" => arguments.no_fast = true,
            "--allow-host" => {
                arguments.fetch = arguments.fetch.allow_host(&value()?).map_err(Usage)?;
            }
            "--allow-hosts-file" => arguments.hosts_files.push(PathBuf::from(value()?)),
            "--allow-range" => {
                arguments.fetch = arguments.fetch.allow_range(&value()?).map_err(Usage)?;
            }
            "--allow-http" => arguments.fetch.allow_http = true,
            "--max-fetch-bytes" => arguments.fetch.max_bytes = number(flag, &value()?, 1)?,
            "--connect-timeout" => arguments.fetch.connect_timeout = seconds(value()?)?,
            "--fetch-timeout" => arguments.fetch.timeout = seconds(value()?)?,
            "--max-redirects" => arguments.fetch.max_redirects = number(flag, &value()?, 0)?,
            "--connect-retries" => arguments.fetch.connect_retries = number(flag, &value()?, 0)?,
            "--idle-timeout" => arguments.fetch.idle_timeout = seconds(value()?)?,
            "--user-agent" => {
                arguments.fetch = arguments
                    .fetch
                    .with_user_agent(&value()?)
                    .map_err(|message| Usage(format!("`--user-agent`: {message}")))?;
            }
            "--shutdown-grace" => arguments.shutdown_grace = seconds(value()?)?,
            "--heartbeat" => arguments.heartbeat = seconds(value()?)?,
            "--stats-file" => arguments.stats_file = Some(PathBuf::from(value()?)),
            "--events-file" => arguments.events_file = Some(PathBuf::from(value()?)),
            "--events-interval" => arguments.events_interval = Some(interval(flag, &value()?)?),
            #[cfg(unix)]
            "--events-socket" => arguments.events_socket = Some(PathBuf::from(value()?)),
            #[cfg(not(unix))]
            "--events-socket" => {
                return Err(Usage(
                    "`--events-socket` sends to a Unix domain socket, which this platform doesn't have".to_owned(),
                ));
            }
            "--events-max" => {
                let text = value()?;
                let max: usize = number(flag, &text, 1)?;
                if max > MAX_EVENTS_MAX {
                    return Err(Usage(format!(
                        "`{flag}` takes a whole number from 1 to {MAX_EVENTS_MAX}, not `{text}`"
                    )));
                }
                arguments.events_max = Some(max);
            }
            "--timings" => arguments.settings.timings = true,
            "--max-pixels" => arguments.settings.max_pixels = Some(number(flag, &value()?, 1)?),
            "--max-text-bytes" => arguments.settings.max_text_bytes = Some(number(flag, &value()?, 0)?),
            "--help" | "-h" => return Err(Usage(HELP_ASKED.to_owned())),
            _ => return Err(Usage(format!("`{flag}` isn't an option here"))),
        }
    }
    Ok(arguments)
}