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
628
629
630
//! `serve --events-socket`: one datagram on a local Unix socket when a task reaches its handler and
//! one when its reply is ready, for a collector beside the worker that shows each as it happens.
//!
//! The collector owns the socket: it binds it and reads. The worker only sends, from an unbound,
//! non-blocking socket, and drops a datagram nobody can take at once.

use std::fmt;
use std::io;
use std::os::unix::net::{SocketAddr, UnixDatagram};
use std::path::{Path, PathBuf};
use std::sync::{Mutex, MutexGuard, PoisonError};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

use legit_streams::Task;

/// The version of the datagram, its `"v"`: `1`.
pub const SOCKET_FORMAT: u32 = 1;

/// The most bytes a datagram takes: 200. The longest possible one, every number at its largest,
/// is 159.
pub const MAX_DATAGRAM_BYTES: usize = 200;

/// A task's `kind` when it asks for neither an image nor a text to be hashed: a distance task, or a
/// task whose payload couldn't be told.
pub const KIND_OTHER: u8 = 0;

/// A task's `kind` when it asks for an image to be hashed, by `image_data` or by `image_url`.
pub const KIND_IMAGE: u8 = 1;

/// A task's `kind` when it asks for a text to be hashed, by `text_data`.
pub const KIND_TEXT: u8 = 2;

/// One event as its datagram gives it: numbers only, and nothing that could name the task.
///
/// [`socket_datagram`] writes it. `ok` and `us` are written for a finish only.
///
/// ```
/// use legit_hasher::serve::{KIND_IMAGE, SocketEvent, socket_datagram};
///
/// let mut event = SocketEvent::default();
/// event.started_at = 1_796_250_904;
/// event.seq = 48_260;
/// event.finish = true;
/// event.at_us = 1_796_251_199_350_441;
/// event.slot = 17;
/// event.kind = KIND_IMAGE;
/// event.ok = true;
/// event.us = 229_104;
/// assert_eq!(
///     socket_datagram(&event),
///     r#"{"v":1,"w":1796250904,"seq":48260,"e":1,"t":1796251199350441,"lane":0,"slot":17,"kind":1,"ok":1,"us":229104}"#
/// );
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub struct SocketEvent {
    /// `w`: when the worker started, in Unix seconds, as the stats and events files give it.
    pub started_at: u64,
    /// `seq`: 1 for the process's first event, one more for each after it, sent or not.
    pub seq: u64,
    /// `e`: `false` (0) for a start, `true` (1) for a finish.
    pub finish: bool,
    /// `t`: when it happened, in Unix microseconds.
    pub at_us: u64,
    /// `lane`: `false` (0) for the bulk lane, `true` (1) for the fast lane.
    pub fast: bool,
    /// `slot`: the task's slot on its lane, the same in its start and its finish.
    pub slot: u32,
    /// `kind`: [`KIND_IMAGE`], [`KIND_TEXT`] or [`KIND_OTHER`].
    pub kind: u8,
    /// `ok`, on a finish: `true` (1) when answered without a failure, `false` (0) when it failed.
    pub ok: bool,
    /// `us`, on a finish: the microseconds the worker spent on the task.
    pub us: u64,
}

/// The datagram of `event`: one JSON object, UTF-8, without a newline, of at most
/// [`MAX_DATAGRAM_BYTES`]. Its keys are `v`, `w`, `seq`, `e`, `t`, `lane`, `slot` and `kind`, then
/// `ok` and `us` on a finish, each a whole number, and there is no other.
#[must_use]
pub fn socket_datagram(event: &SocketEvent) -> String {
    let mut text = String::with_capacity(MAX_DATAGRAM_BYTES);
    // Numbers only, into a string, so writing can't fail...
    let _ = write_datagram(event, &mut text);
    text
}

fn write_datagram(event: &SocketEvent, out: &mut impl fmt::Write) -> fmt::Result {
    write!(
        out,
        r#"{{"v":{SOCKET_FORMAT},"w":{},"seq":{},"e":{},"t":{},"lane":{},"slot":{},"kind":{}"#,
        event.started_at,
        event.seq,
        u8::from(event.finish),
        event.at_us,
        u8::from(event.fast),
        event.slot,
        event.kind,
    )?;
    if event.finish {
        write!(out, r#","ok":{},"us":{}"#, u8::from(event.ok), event.us)?;
    }
    out.write_char('}')
}

/// A datagram written on the stack, so a send allocates nothing.
struct Datagram {
    bytes: [u8; MAX_DATAGRAM_BYTES],
    len: usize,
}

impl fmt::Write for Datagram {
    fn write_str(&mut self, text: &str) -> fmt::Result {
        let end = self.len + text.len();
        let room = self.bytes.get_mut(self.len..end).ok_or(fmt::Error)?;
        room.copy_from_slice(text.as_bytes());
        self.len = end;
        Ok(())
    }
}

/// The `kind` of a task, from its payload fields alone: [`KIND_TEXT`] for `text_data`,
/// [`KIND_IMAGE`] for `image_data` or `image_url`, and [`KIND_OTHER`] for a pair `a` and `b` or a
/// payload that can't be told, such as one with no source or with a text and an image.
pub(crate) fn task_kind(task: &Task) -> u8 {
    let present = |name: &str| task.get(name).is_some_and(|value| !value.is_empty());
    // `text_data` is a source even when empty, as the handler reads it...
    let text = task.get("text_data").is_some();
    let image = present("image_data") || present("image_url");
    if present("a") || present("b") {
        return KIND_OTHER;
    }
    match (text, image) {
        (true, false) => KIND_TEXT,
        (false, true) => KIND_IMAGE,
        _ => KIND_OTHER,
    }
}

/// The slots of one lane's running tasks, a bit each: a task takes the lowest free one.
#[derive(Debug, Default)]
struct Slots {
    held: Vec<u64>,
}

impl Slots {
    fn with_room(slots: usize) -> Self {
        Self {
            held: Vec::with_capacity(slots.div_ceil(64)),
        }
    }

    /// Take the lowest slot not held, and hold it.
    fn take(&mut self) -> u32 {
        let word = match self.held.iter().position(|word| *word != u64::MAX) {
            Some(word) => word,
            None => {
                self.held.push(0);
                self.held.len() - 1
            }
        };
        let bit = self.held[word].trailing_ones();
        self.held[word] |= 1 << bit;
        u32::try_from(word * 64).map_or(u32::MAX, |base| base.saturating_add(bit))
    }

    /// Free a slot [`Slots::take`] gave.
    fn free(&mut self, slot: u32) {
        let (word, bit) = (slot / 64, slot % 64);
        if let Some(word) = usize::try_from(word).ok().and_then(|word| self.held.get_mut(word)) {
            *word &= !(1 << bit);
        }
    }
}

/// What the senders change, under one lock.
#[derive(Debug)]
struct State {
    /// The last event's number, 0 before the first.
    seq: u64,
    /// The bulk lane's slots, then the fast lane's.
    slots: [Slots; 2],
    sent: u64,
    dropped: u64,
    /// The kind of the last failure logged, until a send succeeds.
    failure: Option<io::ErrorKind>,
}

/// The clock events are timed on: the monotonic clock from when the worker started, added to the
/// wall clock read once then.
#[derive(Debug, Clone, Copy)]
struct Clock {
    origin: Instant,
    origin_us: u64,
    started_at: u64,
}

impl Clock {
    fn new(origin: Instant, wall: SystemTime) -> Self {
        let origin_us = wall
            .duration_since(UNIX_EPOCH)
            .map_or(0, |since| u64::try_from(since.as_micros()).unwrap_or(u64::MAX));
        Self {
            origin,
            origin_us,
            started_at: origin_us / 1_000_000,
        }
    }
}

fn micros(duration: Duration) -> u64 {
    u64::try_from(duration.as_micros()).unwrap_or(u64::MAX)
}

/// The sender of `serve --events-socket`: a datagram to a Unix socket a collector has bound at a
/// path, for each task that reaches its handler and each whose reply is ready.
///
/// It never creates, binds, changes or removes anything at the path: it sends from an unbound,
/// non-blocking socket of its own, opened by [`EventsSocket::new`]. A datagram that can't be sent
/// at once, because nothing is bound at the path, its reader went away or its queue is full, is
/// dropped and counted in [`EventsSocket::dropped`]; a send never blocks and is never tried again.
/// A reader that binds the path again receives the events after it. Any other failure, such as a
/// permission refused, drops the datagram too, and is logged at warning level the first time and
/// again only when its kind changes, until a send succeeds.
///
/// Every event takes the next number, `seq`, whether or not it is sent, so a reader sees a dropped
/// event as a gap. The number, the time, the slot and the send are taken under one short lock, so
/// datagrams leave in the order of their numbers and their times. A [`Server`](super::Server)
/// started with [`Server::start_with_events_socket`](super::Server::start_with_events_socket) sends
/// on each task's own thread.
///
/// ```
/// use std::os::unix::net::UnixDatagram;
/// use std::time::Duration;
/// use legit_hasher::serve::{EventsSocket, KIND_TEXT};
///
/// let directory = std::env::temp_dir().join(format!("legit-hasher-socket-doc-{}", std::process::id()));
/// std::fs::create_dir_all(&directory)?;
/// let path = directory.join("events.sock");
/// # let _ = std::fs::remove_file(&path);
/// // The collector binds the socket; the worker only sends to it...
/// let reader = UnixDatagram::bind(&path)?;
/// let socket = EventsSocket::new(&path)?;
/// let task = socket.begin(false, KIND_TEXT);
/// assert_eq!(task.slot(), 0);
/// task.finish(true, Duration::from_micros(412));
///
/// let mut buffer = [0; 256];
/// let mut read = || -> std::io::Result<serde_json::Value> {
///     let length = reader.recv(&mut buffer)?;
///     Ok(serde_json::from_slice(&buffer[..length])?)
/// };
/// let (start, finish) = (read()?, read()?);
/// assert_eq!((&start["seq"], &start["e"], &start["slot"], &start["kind"]), (&1.into(), &0.into(), &0.into(), &2.into()));
/// assert_eq!((&finish["seq"], &finish["e"], &finish["ok"], &finish["us"]), (&2.into(), &1.into(), &1.into(), &412.into()));
///
/// // Nobody reads any more: the next event is dropped, and counted.
/// drop(reader);
/// socket.begin(true, KIND_TEXT).finish(true, Duration::ZERO);
/// assert_eq!((socket.sent(), socket.dropped()), (2, 2));
/// # std::fs::remove_dir_all(&directory)?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug)]
pub struct EventsSocket {
    path: PathBuf,
    address: SocketAddr,
    socket: UnixDatagram,
    clock: Clock,
    state: Mutex<State>,
}

impl EventsSocket {
    /// A sender to the socket a collector binds at `path`, timed from now until a server it's given
    /// to starts. Nothing at `path` is touched, and nothing needs to be there yet.
    ///
    /// # Errors
    ///
    /// [`io::ErrorKind::InvalidInput`] when `path` is empty or too long for a socket address (the
    /// platform's `sun_path`, 107 bytes on Linux), and the error of opening the sending socket.
    ///
    /// ```
    /// use legit_hasher::serve::EventsSocket;
    ///
    /// assert!(EventsSocket::new(std::env::temp_dir().join("events.sock")).is_ok());
    /// assert!(EventsSocket::new(format!("/run/{}/events.sock", "x".repeat(200))).is_err());
    /// ```
    pub fn new(path: impl AsRef<Path>) -> io::Result<Self> {
        let path = path.as_ref();
        if path.as_os_str().is_empty() {
            return Err(io::Error::new(io::ErrorKind::InvalidInput, "the path names no socket"));
        }
        let address = SocketAddr::from_pathname(path).map_err(|_| {
            io::Error::new(
                io::ErrorKind::InvalidInput,
                format!(
                    "the path is {} bytes, more than a Unix socket address holds",
                    path.as_os_str().len()
                ),
            )
        })?;
        let socket = UnixDatagram::unbound()?;
        socket.set_nonblocking(true)?;
        Ok(Self {
            path: path.to_path_buf(),
            address,
            socket,
            clock: Clock::new(Instant::now(), SystemTime::now()),
            state: Mutex::new(State {
                seq: 0,
                slots: [Slots::default(), Slots::default()],
                sent: 0,
                dropped: 0,
                failure: None,
            }),
        })
    }

    /// The same sender timed from a server's start, with room for each lane's slots.
    pub(crate) fn for_server(mut self, origin: Instant, wall: SystemTime, jobs: usize, fast_jobs: usize) -> Self {
        self.clock = Clock::new(origin, wall);
        let state = self.state.get_mut().unwrap_or_else(PoisonError::into_inner);
        state.slots = [Slots::with_room(jobs), Slots::with_room(fast_jobs)];
        self
    }

    /// The path datagrams are sent to.
    #[must_use]
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// When the worker started, in Unix seconds: every datagram's `w`.
    #[must_use]
    pub const fn started_at(&self) -> u64 {
        self.clock.started_at
    }

    /// The datagrams sent so far.
    #[must_use]
    pub fn sent(&self) -> u64 {
        self.lock().sent
    }

    /// The events dropped so far: each a datagram that couldn't be sent at once.
    #[must_use]
    pub fn dropped(&self) -> u64 {
        self.lock().dropped
    }

    fn lock(&self) -> MutexGuard<'_, State> {
        self.state.lock().unwrap_or_else(PoisonError::into_inner)
    }

    /// Send the start of a task of the fast lane or the bulk one, and of `kind`, taking the lowest
    /// slot of its lane no running task holds. The task holds it until its finish is sent, by
    /// [`SocketTask::finish`] or, failed, when the [`SocketTask`] is dropped without it, as in a
    /// handler that panics.
    pub fn begin(&self, fast: bool, kind: u8) -> SocketTask<'_> {
        let mut state = self.lock();
        let at = self.clock.origin.elapsed();
        let slot = state.slots[usize::from(fast)].take();
        state.seq += 1;
        let event = SocketEvent {
            started_at: self.clock.started_at,
            seq: state.seq,
            finish: false,
            at_us: self.clock.origin_us.saturating_add(micros(at)),
            fast,
            slot,
            kind,
            ok: false,
            us: 0,
        };
        self.send(&mut state, &event);
        SocketTask {
            socket: self,
            fast,
            slot,
            kind,
            began: at,
            finished: false,
        }
    }

    /// Send a task's finish and free its slot.
    fn end(&self, task: &SocketTask<'_>, ok: bool, took: Option<Duration>) {
        let mut state = self.lock();
        let at = self.clock.origin.elapsed();
        state.slots[usize::from(task.fast)].free(task.slot);
        state.seq += 1;
        let event = SocketEvent {
            started_at: self.clock.started_at,
            seq: state.seq,
            finish: true,
            at_us: self.clock.origin_us.saturating_add(micros(at)),
            fast: task.fast,
            slot: task.slot,
            kind: task.kind,
            ok,
            us: micros(took.unwrap_or_else(|| at.saturating_sub(task.began))),
        };
        self.send(&mut state, &event);
    }

    /// Send one datagram, once, without blocking, and count it sent or dropped.
    fn send(&self, state: &mut State, event: &SocketEvent) {
        let mut datagram = Datagram {
            bytes: [0; MAX_DATAGRAM_BYTES],
            len: 0,
        };
        // The longest datagram is 159 bytes, so the buffer can't run out...
        let _ = write_datagram(event, &mut datagram);
        match self.socket.send_to_addr(&datagram.bytes[..datagram.len], &self.address) {
            Ok(_) => {
                state.sent += 1;
                state.failure = None;
            }
            Err(error) => {
                state.dropped += 1;
                let kind = error.kind();
                // Nobody bound, a reader gone, or a full queue: dropped without a word...
                let quiet = matches!(
                    kind,
                    io::ErrorKind::WouldBlock | io::ErrorKind::NotFound | io::ErrorKind::ConnectionRefused
                );
                if !quiet {
                    if state.failure != Some(kind) {
                        tracing::warn!(
                            path = %self.path.display(),
                            error = %error,
                            "Couldn't send to the events socket; the worker carries on"
                        );
                    }
                    state.failure = Some(kind);
                }
            }
        }
    }
}

/// A running task's hold on its slot, from [`EventsSocket::begin`]. Give its finish with
/// [`SocketTask::finish`]; dropped without one, it sends the finish as a failure, so every start
/// has exactly one finish.
#[derive(Debug)]
#[must_use = "dropping it at once sends the task's finish as a failure"]
pub struct SocketTask<'socket> {
    socket: &'socket EventsSocket,
    fast: bool,
    slot: u32,
    kind: u8,
    /// When the start was taken, on the socket's monotonic clock.
    began: Duration,
    finished: bool,
}

impl SocketTask<'_> {
    /// The slot the task holds on its lane.
    #[must_use]
    pub const fn slot(&self) -> u32 {
        self.slot
    }

    /// Send the finish: `ok` when the task was answered without a failure, and `took`, the time the
    /// worker spent on it.
    pub fn finish(mut self, ok: bool, took: Duration) {
        self.socket.end(&self, ok, Some(took));
        self.finished = true;
    }
}

impl Drop for SocketTask<'_> {
    fn drop(&mut self) {
        if !self.finished {
            self.socket.end(self, false, None);
        }
    }
}

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

    use legit_streams::Task;

    use super::{
        EventsSocket, KIND_IMAGE, KIND_OTHER, KIND_TEXT, MAX_DATAGRAM_BYTES, Slots, SocketEvent, socket_datagram,
        task_kind,
    };

    #[test]
    fn the_longest_datagram_fits() {
        let event = SocketEvent {
            started_at: u64::MAX,
            seq: u64::MAX,
            finish: true,
            at_us: u64::MAX,
            fast: true,
            slot: u32::MAX,
            kind: u8::MAX,
            ok: true,
            us: u64::MAX,
        };
        let text = socket_datagram(&event);
        assert_eq!(text.len(), 161, "{text}");
        assert!(text.len() <= MAX_DATAGRAM_BYTES);
        // With the kinds there are, a datagram is two bytes shorter: the 159 the docs give.
        let event = SocketEvent {
            kind: KIND_TEXT,
            ..event
        };
        assert_eq!(socket_datagram(&event).len(), 159);
    }

    #[test]
    fn a_slot_is_the_lowest_free_and_freed_ones_are_taken_again() {
        let mut slots = Slots::with_room(4);
        let taken: Vec<u32> = (0..130).map(|_| slots.take()).collect();
        assert_eq!(taken, (0..130).collect::<Vec<_>>());
        slots.free(70);
        slots.free(3);
        assert_eq!((slots.take(), slots.take(), slots.take()), (3, 70, 130));
        slots.free(1_000);
    }

    #[test]
    fn a_kind_comes_from_the_payload_field() {
        let task = |fields: &[(&str, &str)]| {
            let mut builder = Task::builder("app", "post", "1");
            for (name, value) in fields {
                builder = builder.field(*name, *value);
            }
            builder.build().expect("a valid task")
        };
        assert_eq!(task_kind(&task(&[("text_data", "")])), KIND_TEXT);
        assert_eq!(task_kind(&task(&[("image_data", "AAAA")])), KIND_IMAGE);
        assert_eq!(
            task_kind(&task(&[("image_url", "https://example.com/a.png")])),
            KIND_IMAGE
        );
        assert_eq!(task_kind(&task(&[("a", "x"), ("b", "y")])), KIND_OTHER);
        assert_eq!(
            task_kind(&task(&[("text_data", "t"), ("image_data", "AAAA")])),
            KIND_OTHER
        );
        assert_eq!(task_kind(&task(&[("text_data", "t"), ("a", "x")])), KIND_OTHER);
        assert_eq!(task_kind(&task(&[("options", "{}")])), KIND_OTHER);
    }

    #[test]
    fn a_task_dropped_without_its_finish_sends_it_failed_and_frees_its_slot() {
        let socket = EventsSocket::new("/nonexistent-legit-hasher/events.sock").expect("a short path");
        let first = socket.begin(false, KIND_TEXT);
        let second = socket.begin(false, KIND_TEXT);
        assert_eq!((first.slot(), second.slot()), (0, 1));
        drop(first);
        assert_eq!(socket.begin(false, KIND_TEXT).slot(), 0);
        second.finish(true, Duration::ZERO);
        // Nothing is bound, so every event was dropped, and none logged...
        assert_eq!((socket.sent(), socket.dropped()), (0, 6));
    }

    #[test]
    fn a_handler_that_panics_still_sends_its_finish_failed_and_frees_its_slot() {
        use std::os::unix::net::UnixDatagram;
        use std::sync::Arc;

        use legit_streams::{MemoryStreams, Producer, ResultReader, Streams};

        use crate::serve::{ServeConfig, Server};

        let directory = std::env::temp_dir().join(format!("legit-hasher-socket-panic-{}", std::process::id()));
        std::fs::create_dir_all(&directory).expect("a directory");
        let path = directory.join("events.sock");
        let _ = std::fs::remove_file(&path);
        let reader = UnixDatagram::bind(&path).expect("bound");
        reader
            .set_read_timeout(Some(Duration::from_secs(30)))
            .expect("a timeout");
        let mut config = ServeConfig::new("socket-panic", 1);
        config.worker.concurrency = 1;
        config.worker.read_block = Duration::from_millis(50);
        config.fast = None;
        let streams: Arc<dyn Streams> = Arc::new(MemoryStreams::new());
        let socket = EventsSocket::new(&path).expect("a short path");
        let server = Server::start_with_events_socket(config, Arc::clone(&streams), None, None, socket)
            .expect("the server starts");
        let producer = Producer::new(Arc::clone(&streams), "hash_tasks");
        let results = ResultReader::new(Arc::clone(&streams), "hash_results", "readers", "reader");
        let task = |panics: bool| {
            let builder = Task::builder("app", "post", "1").field("text_data", "a text").field(
                "options",
                r#"{"format":1,"definitions":[{"id":"simhash-v1","tokens":"words"}]}"#,
            );
            let builder = if panics {
                builder.field("panic_in_test", "1")
            } else {
                builder
            };
            builder.build().expect("a valid task")
        };
        let mut answered = Vec::new();
        for panics in [true, false] {
            producer.send(&task(panics)).expect("sent");
            loop {
                let read = results.read(10, Some(Duration::from_millis(50))).expect("read");
                if let Some(entry) = read.into_iter().next() {
                    answered.push(entry.result.expect("a result").is_success());
                    break;
                }
            }
        }
        server.stop();
        server.join().expect("the server stops");
        assert_eq!(answered, [false, true], "the panic is answered as an error");
        let mut buffer = [0u8; 256];
        let events: Vec<serde_json::Value> = (0..4)
            .map(|_| {
                let length = reader.recv(&mut buffer).expect("a datagram");
                serde_json::from_slice(&buffer[..length]).expect("JSON")
            })
            .collect();
        let numbers = |key: &str| events.iter().map(|event| event[key].as_u64()).collect::<Vec<_>>();
        assert_eq!(numbers("seq"), [Some(1), Some(2), Some(3), Some(4)]);
        assert_eq!(numbers("e"), [Some(0), Some(1), Some(0), Some(1)]);
        assert_eq!(numbers("slot"), [Some(0); 4], "the slot was freed and taken again");
        assert_eq!(numbers("ok"), [None, Some(0), None, Some(1)]);
        let _ = std::fs::remove_dir_all(&directory);
    }
}