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
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
//! `legit-hasher serve`: the runner as a worker on the Redis Streams work contract of
//! [`legit_streams`], so it can run on another machine than the application that wants hashes.
//!
//! A task of the kind `hash` carries one source (`text_data`, `image_data` or `image_url`) and an
//! `options` field holding the same JSON object a batch request's `options` holds; its result's
//! `result` field holds the same JSON object `legit-hasher run` writes for that request, without
//! `line`. A task may instead carry a pair of stored hashes, `a` and `b`, and get what
//! `legit-hasher distance` writes. The crate's README states every field.
//!
//! [`Server`] runs a bulk [`Worker`] on `hash_tasks` and, unless it's
//! turned off, a [`FastWorker`] on `hash_tasks:fast` for text and
//! distances a caller waits for, both on one [`Streams`] connection.
//!
//! ```
//! use std::sync::Arc;
//! use std::time::Duration;
//! use legit_hasher::serve::{ServeConfig, Server};
//! use legit_streams::{MemoryStreams, Producer, ResultReader, Streams, Task};
//!
//! // The in-memory double here; `RedisStreams::open(url)` on a server...
//! let streams: Arc<dyn Streams> = Arc::new(MemoryStreams::new());
//! let mut config = ServeConfig::new("hasher-1", 7);
//! config.worker.read_block = Duration::from_millis(100);
//! let server = Server::start(config, Arc::clone(&streams), None)?;
//!
//! let task = Task::builder("app", "post", "42")
//!     .reply_to(legit_streams::reply_to("app", "hash"))
//!     .field("text_data", "The quick brown fox")
//!     .field("options", r#"{"format": 1, "definitions": [{"id": "simhash-v1", "tokens": "words"}]}"#)
//!     .build()?;
//! Producer::new(Arc::clone(&streams), "hash_tasks").send(&task)?;
//!
//! let reader = ResultReader::new(Arc::clone(&streams), "results:app:hash", "app", "app-1");
//! let received = loop {
//!     let received = reader.read(10, Some(Duration::from_millis(100)))?;
//!     if !received.is_empty() {
//!         break received;
//!     }
//! };
//! let result = received[0].result.as_ref().expect("a result");
//! assert!(result.is_success());
//! let object: serde_json::Value = serde_json::from_str(result.get("result").expect("`result`"))?;
//! assert_eq!(object["id"], task.task_id());
//! assert!(object["hashes"][0]["value"].as_str().expect("a value").starts_with("simhash-v1:"));
//!
//! server.stop();
//! server.join()?;
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```

mod connect;
mod events;
mod fetch;
#[cfg(unix)]
mod socket;
mod stats;
mod task;

use std::sync::atomic::AtomicU64;
use std::sync::mpsc::{self, RecvTimeoutError};
use std::sync::{Arc, Mutex, PoisonError};
use std::thread::JoinHandle;
use std::time::{Duration, Instant, SystemTime};

use legit_streams::{
    Clock, FastWorker, FastWorkerConfig, Report, Running, Streams, Worker, WorkerConfig, fast_consumer_name,
};
use serde::Serialize;

use crate::Settings;

pub use events::{
    DEFAULT_EVENTS_INTERVAL, DEFAULT_EVENTS_MAX, EVENTS_FORMAT, Events, EventsDocument, EventsFile,
    MAX_EVENTS_INTERVAL, MAX_EVENTS_MAX, MIN_EVENTS_INTERVAL, events_document,
};
pub(crate) use fetch::url_host;
pub use fetch::{
    DEFAULT_CONNECT_RETRIES, DEFAULT_CONNECT_TIMEOUT, DEFAULT_FETCH_TIMEOUT, DEFAULT_IDLE_CONNECTIONS,
    DEFAULT_IDLE_TIMEOUT, DEFAULT_MAX_REDIRECTS, DEFAULT_USER_AGENT, FetchError, FetchPolicy, Fetched, Fetcher, redact,
};
#[cfg(unix)]
pub use socket::{
    EventsSocket, KIND_IMAGE, KIND_OTHER, KIND_TEXT, MAX_DATAGRAM_BYTES, SOCKET_FORMAT, SocketEvent, SocketTask,
    socket_datagram,
};
pub use stats::{BACKLOG_TIMEOUT, Meter, STATS_FORMAT, Sample, StatsFile, StatsState, Times, stats_document};

/// The kind of task served, `hash`, which names the streams, the group and the fast lane's reply
/// keys, as the contract names them after a kind.
pub const KIND: &str = "hash";

/// The payload fields a hashing task may carry: one source of `text_data`, `image_data` and
/// `image_url`, with `options`, and an optional `id`.
pub const TASK_FIELDS: [&str; 5] = ["id", "text_data", "image_data", "image_url", "options"];

/// The payload fields a distance task carries: `a` and `b`, each a stored hash or signature, and
/// an optional `id`.
pub const DISTANCE_FIELDS: [&str; 3] = ["id", "a", "b"];

/// The fields a result adds to the contract's own: `result`, the runner's result object as JSON.
pub const RESULT_FIELDS: [&str; 1] = ["result"];

/// The sources the fast lane takes: text only. Images, inline or by URL, go to the bulk lane.
pub const FAST_SOURCES: [&str; 1] = ["text_data"];

/// The `model_name` a task may give, besides none: this program's name. Any other is
/// `unsupported_model`.
pub const MODEL_NAME: &str = "legit-hasher";

/// The most pixels an image may have on `serve` by default, 50 million: about 700 MB of working
/// memory for one task at [`PEAK_BYTES_PER_PIXEL`](crate::PEAK_BYTES_PER_PIXEL).
pub const DEFAULT_MAX_PIXELS: u64 = 50_000_000;

/// The longest `text_data` `serve` hashes by default, 1 MiB; a longer one is `too_large`.
pub const DEFAULT_MAX_TEXT_BYTES: u64 = 1 << 20;

/// The bulk task stream of a kind: `{kind}_tasks`.
#[must_use]
pub fn task_stream(kind: &str) -> String {
    format!("{kind}_tasks")
}

/// The consumer group of a kind: `{kind}_workers`, which reads both lanes.
#[must_use]
pub fn group(kind: &str) -> String {
    format!("{kind}_workers")
}

/// The default result stream of a kind: `{kind}_results`.
#[must_use]
pub fn result_stream(kind: &str) -> String {
    format!("{kind}_results")
}

/// The fast task stream of a kind: `{kind}_tasks:fast`.
#[must_use]
pub fn fast_stream(kind: &str) -> String {
    format!("{kind}_tasks:fast")
}

/// How a [`Server`] runs: its two workers' settings, the runner's settings, and where URLs may be
/// fetched from.
#[derive(Debug, Clone)]
pub struct ServeConfig {
    /// The bulk worker on `{kind}_tasks`.
    pub worker: WorkerConfig,
    /// The fast worker on `{kind}_tasks:fast`, or `None` to serve the bulk lane only.
    pub fast: Option<FastWorkerConfig>,
    /// The runner's settings for every task: timings, `max_pixels` ([`DEFAULT_MAX_PIXELS`] by
    /// default) and `max_text_bytes` ([`DEFAULT_MAX_TEXT_BYTES`] by default).
    pub settings: Settings,
    /// Where `image_url` sources may be fetched from. With no allowed host, every URL task is
    /// refused with `host_not_allowed`. Unless it says otherwise, its pool keeps as many idle
    /// connections as the bulk worker runs tasks at once.
    pub fetch: FetchPolicy,
}

impl ServeConfig {
    /// The contract's defaults for the kind `hash`, with consumer names made from `prefix` and
    /// the process id: `{prefix}_{pid}` on the bulk lane, `{prefix}-fast_{pid}` on the fast lane.
    /// The bulk lane runs one task per available core and the fast lane one; no URL is fetched;
    /// an image may have at most [`DEFAULT_MAX_PIXELS`] and a text at most
    /// [`DEFAULT_MAX_TEXT_BYTES`].
    ///
    /// ```
    /// let config = legit_hasher::serve::ServeConfig::new("hasher-host1", 4242);
    /// assert_eq!(config.worker.stream, "hash_tasks");
    /// assert_eq!(config.worker.consumer, "hasher-host1_4242");
    /// assert_eq!(config.fast.as_ref().map(|fast| fast.consumer.as_str()), Some("hasher-host1-fast_4242"));
    /// ```
    #[must_use]
    pub fn new(prefix: &str, pid: u32) -> Self {
        Self::for_kind(KIND, prefix, pid)
    }

    /// The same, for another kind's names, such as a second deployment kept apart from the first.
    #[must_use]
    pub fn for_kind(kind: &str, prefix: &str, pid: u32) -> Self {
        let worker = WorkerConfig {
            concurrency: std::thread::available_parallelism().map_or(1, usize::from),
            ..WorkerConfig::new(
                task_stream(kind),
                group(kind),
                format!("{prefix}_{pid}"),
                result_stream(kind),
            )
        };
        let fast = FastWorkerConfig::new(fast_stream(kind), group(kind), fast_consumer_name(prefix, pid), kind);
        Self {
            worker,
            fast: Some(fast),
            settings: Settings {
                max_pixels: Some(DEFAULT_MAX_PIXELS),
                max_text_bytes: Some(DEFAULT_MAX_TEXT_BYTES),
                ..Settings::default()
            },
            fetch: FetchPolicy::new(),
        }
    }
}

/// Counts of what a [`Server`] has done, for its heartbeat.
#[derive(Debug, Default)]
pub(crate) struct Counters {
    in_flight: AtomicU64,
    done: AtomicU64,
    failed: AtomicU64,
    fast_done: AtomicU64,
    fast_failed: AtomicU64,
    fetched: AtomicU64,
    fetched_bytes: AtomicU64,
    /// How long each answered task took, per lane, since the stats file's last write.
    bulk_times: stats::Histogram,
    fast_times: stats::Histogram,
    /// What each definition has computed, both lanes together.
    definitions: stats::DefinitionCounts,
    /// Each answered task, both lanes, when the server records them for the events file.
    events: Option<Arc<events::Buffer>>,
    /// The sender of a datagram when each task starts and finishes, when the server has one.
    #[cfg(unix)]
    socket: Option<Arc<socket::EventsSocket>>,
}

/// A snapshot of a [`Server`]'s counts, as its heartbeat line reports them.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize)]
#[non_exhaustive]
pub struct Stats {
    /// Bulk tasks being handled now.
    pub in_flight: u64,
    /// Bulk tasks answered, errors included.
    pub done: u64,
    /// Of those, the ones answered with an error, or with an error on any definition.
    pub failed: u64,
    /// Fast tasks answered, errors included.
    pub fast_done: u64,
    /// Of those, the failures.
    pub fast_failed: u64,
    /// URLs fetched.
    pub fetched: u64,
    /// Bytes fetched from URLs.
    pub fetched_bytes: u64,
    /// Connections opened to fetch URLs, TLS included for `https`.
    pub connections_opened: u64,
    /// Requests written to a connection an earlier fetch had opened.
    pub connections_reused: u64,
    /// Requests tried again after a failure at the connect level.
    pub connect_retries: u64,
    /// Seconds since the server started.
    pub uptime_s: u64,
}

/// A worker for the hashing task kind: a bulk [`Worker`] and, when
/// configured, a [`FastWorker`], each on threads of its own.
#[derive(Debug)]
pub struct Server {
    bulk: Running,
    fast: Option<Running>,
    meter: Meter,
    /// Closes the fetcher's idle connections once the idle timeout passes with no fetch.
    sweeper: Sweeper,
    events: Option<Events>,
    #[cfg(unix)]
    socket: Option<Arc<socket::EventsSocket>>,
}

/// The thread that closes idle connections, and the way to stop it: dropping the sender.
#[derive(Debug)]
struct Sweeper {
    stop: Mutex<Option<mpsc::Sender<()>>>,
    thread: Option<JoinHandle<()>>,
}

impl Sweeper {
    /// How often the sweeper looks, at most: the idle timeout, if it's shorter.
    const EVERY: Duration = Duration::from_secs(1);

    fn start(shared: &Arc<task::Shared>) -> legit_streams::Result<Self> {
        let (stop, stopped) = mpsc::channel::<()>();
        let shared = Arc::clone(shared);
        let every = shared
            .fetcher
            .policy()
            .idle_timeout
            .clamp(Duration::from_millis(10), Self::EVERY);
        let thread = std::thread::Builder::new()
            .name("legit-hasher-idle".to_owned())
            .spawn(move || {
                while let Err(RecvTimeoutError::Timeout) = stopped.recv_timeout(every) {
                    shared.fetcher.close_idle();
                }
            })
            .map_err(|error| legit_streams::Error::Thread(error.to_string()))?;
        Ok(Self {
            stop: Mutex::new(Some(stop)),
            thread: Some(thread),
        })
    }

    fn stop(&self) {
        drop(self.stop.lock().unwrap_or_else(PoisonError::into_inner).take());
    }

    fn join(mut self) {
        self.stop();
        if let Some(thread) = self.thread.take() {
            let _ = thread.join();
        }
    }
}

/// What each worker of a [`Server`] did before it stopped.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Reports {
    /// The bulk worker's report.
    pub bulk: Report,
    /// The fast worker's report, when it ran.
    pub fast: Option<Report>,
}

impl Server {
    /// Start the workers on `streams`, on `clock` when given (a manual clock in tests) or the
    /// system clock.
    ///
    /// # Errors
    ///
    /// [`legit_streams::Error::InvalidConfig`] for settings either worker refuses, and
    /// [`legit_streams::Error::Thread`] when a worker's thread can't be started. A server that
    /// can't reach Redis starts, and its workers stop with the error: see [`Server::join`].
    pub fn start(config: ServeConfig, streams: Arc<dyn Streams>, clock: Option<Clock>) -> legit_streams::Result<Self> {
        Self::start_inner(
            config,
            streams,
            clock,
            None,
            #[cfg(unix)]
            None,
        )
    }

    /// Start the workers as [`Server::start`] does, and remember each task they answer, on both
    /// lanes, for the events file: at most `events_max` an interval, the rest only counted. See
    /// [`Server::events`] and [`EventsFile`].
    ///
    /// # Errors
    ///
    /// Those of [`Server::start`], and [`legit_streams::Error::InvalidConfig`] when `events_max`
    /// isn't from 1 to [`MAX_EVENTS_MAX`].
    pub fn start_with_events(
        config: ServeConfig,
        streams: Arc<dyn Streams>,
        clock: Option<Clock>,
        events_max: usize,
    ) -> legit_streams::Result<Self> {
        if !(1..=MAX_EVENTS_MAX).contains(&events_max) {
            return Err(legit_streams::Error::InvalidConfig(format!(
                "the events kept an interval are 1 to {MAX_EVENTS_MAX}, not {events_max}"
            )));
        }
        Self::start_inner(
            config,
            streams,
            clock,
            Some(events_max),
            #[cfg(unix)]
            None,
        )
    }

    /// Start the workers as [`Server::start`] does, or as [`Server::start_with_events`] does when
    /// `events_max` is given, and send a datagram through `socket` when each task, on either lane,
    /// reaches its handler and when its reply is ready: see [`EventsSocket`]. The socket is timed
    /// from the server's start. See [`Server::events_socket`].
    ///
    /// ```
    /// use std::sync::Arc;
    /// use legit_hasher::serve::{EventsSocket, ServeConfig, Server};
    /// use legit_streams::{MemoryStreams, Streams};
    ///
    /// let streams: Arc<dyn Streams> = Arc::new(MemoryStreams::new());
    /// let socket = EventsSocket::new(std::env::temp_dir().join("no-reader-here.sock"))?;
    /// let server = Server::start_with_events_socket(ServeConfig::new("hasher-1", 7), streams, None, None, socket)?;
    /// let socket = server.events_socket().expect("sending");
    /// assert_eq!((socket.sent(), socket.dropped()), (0, 0));
    /// assert_eq!(socket.started_at(), server.meter().sample().started_at);
    /// server.stop();
    /// server.join()?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Those of [`Server::start_with_events`] when `events_max` is given, else those of
    /// [`Server::start`].
    #[cfg(unix)]
    pub fn start_with_events_socket(
        config: ServeConfig,
        streams: Arc<dyn Streams>,
        clock: Option<Clock>,
        events_max: Option<usize>,
        socket: EventsSocket,
    ) -> legit_streams::Result<Self> {
        if let Some(events_max) = events_max
            && !(1..=MAX_EVENTS_MAX).contains(&events_max)
        {
            return Err(legit_streams::Error::InvalidConfig(format!(
                "the events kept an interval are 1 to {MAX_EVENTS_MAX}, not {events_max}"
            )));
        }
        Self::start_inner(config, streams, clock, events_max, Some(socket))
    }

    fn start_inner(
        config: ServeConfig,
        streams: Arc<dyn Streams>,
        clock: Option<Clock>,
        events_max: Option<usize>,
        #[cfg(unix)] socket: Option<EventsSocket>,
    ) -> legit_streams::Result<Self> {
        // The start, on both clocks, before any task can be answered...
        let started = Instant::now();
        let wall = SystemTime::now();
        let (started_ms, started_at) = events::unix_ms_and_seconds(wall);
        let buffer = events_max.map(|max| Arc::new(events::Buffer::new(started, max)));
        #[cfg(unix)]
        let socket = socket.map(|socket| {
            let fast_jobs = config.fast.as_ref().map_or(0, |fast| fast.concurrency);
            Arc::new(socket.for_server(started, wall, config.worker.concurrency, fast_jobs))
        });
        let counters = Arc::new(Counters {
            events: buffer.clone(),
            #[cfg(unix)]
            socket: socket.clone(),
            ..Counters::default()
        });
        let mut fetch = config.fetch;
        // Each bulk job fetching from one host keeps a connection of its own...
        fetch
            .max_idle_connections
            .get_or_insert(config.worker.concurrency.max(1));
        let shared = Arc::new(task::Shared {
            settings: config.settings,
            fetcher: Fetcher::new(fetch),
            counters: Arc::clone(&counters),
        });
        let jobs = config.worker.concurrency as u64;
        let fast = match config.fast {
            Some(fast_config) => {
                let handler = task::Handler::new(Arc::clone(&shared), task::Lane::Fast);
                let mut worker = FastWorker::new(fast_config, Arc::clone(&streams), handler)?;
                if let Some(clock) = &clock {
                    worker = worker.clock(clock.clone());
                }
                Some(worker)
            }
            None => None,
        };
        let mut bulk = Worker::new(
            config.worker,
            streams,
            task::Handler::new(Arc::clone(&shared), task::Lane::Bulk),
        )?;
        if let Some(clock) = clock {
            bulk = bulk.clock(clock);
        }
        let fast = fast.map(FastWorker::spawn).transpose()?;
        let bulk = match bulk.spawn() {
            Ok(bulk) => bulk,
            Err(error) => {
                if let Some(fast) = fast {
                    fast.stop();
                    let _ = fast.join();
                }
                return Err(error);
            }
        };
        let sweeper = match Sweeper::start(&shared) {
            Ok(sweeper) => sweeper,
            Err(error) => {
                bulk.stop();
                let _ = bulk.join();
                if let Some(fast) = fast {
                    fast.stop();
                    let _ = fast.join();
                }
                return Err(error);
            }
        };
        tracing::info!(kind = KIND, fast = fast.is_some(), "Hashing worker started");
        let meter = Meter {
            counters,
            shared,
            started,
            started_at,
            jobs,
            fast: fast.is_some(),
        };
        Ok(Self {
            bulk,
            fast,
            meter,
            sweeper,
            events: buffer.map(|buffer| Events {
                buffer,
                started_at,
                started_ms,
            }),
            #[cfg(unix)]
            socket,
        })
    }

    /// What the server has done so far.
    #[must_use]
    pub fn stats(&self) -> Stats {
        self.meter.stats()
    }

    /// A handle on the server's counts for the stats file: [`Meter::sample`] gives what
    /// [`stats_document`] reports, and the handle can still be read after [`Server::join`], for
    /// the last document.
    ///
    /// ```
    /// use std::sync::Arc;
    /// use legit_hasher::serve::{ServeConfig, Server};
    /// use legit_streams::{MemoryStreams, Streams};
    ///
    /// let streams: Arc<dyn Streams> = Arc::new(MemoryStreams::new());
    /// let server = Server::start(ServeConfig::new("hasher-1", 7), streams, None)?;
    /// let meter = server.meter();
    /// server.stop();
    /// server.join()?;
    /// assert_eq!(meter.sample().stats.done, 0);
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    #[must_use]
    pub fn meter(&self) -> Meter {
        self.meter.clone()
    }

    /// A handle on the tasks the server has answered, for [`EventsFile::write`]: `None` unless it
    /// was started with [`Server::start_with_events`], in which case no task is recorded at all.
    /// The handle can still be read after [`Server::join`], for the last document.
    #[must_use]
    pub fn events(&self) -> Option<Events> {
        self.events.clone()
    }

    /// The sender of the events socket, for its counts: `None` unless the server was started with
    /// [`Server::start_with_events_socket`], in which case no socket is opened and nothing is sent.
    #[cfg(unix)]
    #[must_use]
    pub fn events_socket(&self) -> Option<Arc<EventsSocket>> {
        self.socket.clone()
    }

    /// Ask both workers to stop: they take no new task, and the fast worker answers what it has
    /// read. The bulk worker releases to other workers at once a task it hasn't begun to fetch,
    /// lets a task whose fetch has begun, or that has no fetch, finish within its shutdown grace
    /// and answers it, and releases what still runs when the grace ends.
    pub fn stop(&self) {
        self.sweeper.stop();
        self.bulk.stop();
        if let Some(fast) = &self.fast {
            fast.stop();
        }
    }

    /// Whether either worker has stopped: both after [`Server::stop`], or one on its own when it
    /// couldn't start, such as when Redis can't be reached. Stop the server and join it then.
    #[must_use]
    pub fn is_finished(&self) -> bool {
        self.bulk.is_finished() || self.fast.as_ref().is_some_and(Running::is_finished)
    }

    /// Wait for both workers to stop.
    ///
    /// # Errors
    ///
    /// The first error either worker stopped with, such as [`legit_streams::Error::Redis`] when
    /// its group couldn't be created at the start.
    ///
    /// # Panics
    ///
    /// When a worker's thread panicked, with its panic.
    pub fn join(self) -> legit_streams::Result<Reports> {
        let bulk = self.bulk.join();
        let fast = self.fast.map(Running::join).transpose();
        self.sweeper.join();
        let reports = Reports {
            bulk: bulk?,
            fast: fast?,
        };
        tracing::info!(
            results = reports.bulk.results,
            released = reports.bulk.released.len(),
            fast_results = reports.fast.as_ref().map_or(0, |fast| fast.results),
            "Hashing worker stopped"
        );
        Ok(reports)
    }
}

/// The log subscriber `legit-hasher serve` writes with: one JSON object a line, its fields at the
/// top level, at `level` and above, to `writer`. Set it with
/// [`tracing::subscriber::set_global_default`].
///
/// It installs no bridge for the `log` crate's records, whatever features the build unifies, so
/// the HTTP client's own records, which name whole URLs, query strings included, are never
/// written. Don't route `log` records from `ureq` to a logger at `debug` or below in a program of
/// your own.
pub fn subscriber<W>(level: tracing::Level, writer: W) -> impl tracing::Subscriber + Send + Sync + 'static
where
    W: for<'writer> tracing_subscriber::fmt::MakeWriter<'writer> + Send + Sync + 'static,
{
    tracing_subscriber::fmt()
        .json()
        .flatten_event(true)
        .with_current_span(false)
        .with_span_list(false)
        .with_writer(writer)
        .with_max_level(level)
        .finish()
}

/// How long the heartbeat waits between lines by default.
pub const DEFAULT_HEARTBEAT: Duration = Duration::from_secs(30);