zoter 0.2.0

Restart systemd services without dropping their clients
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
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
use std::{
    cell::RefCell,
    iter,
    os::fd::{AsFd, OwnedFd},
};

use rustix::{
    io::{read, write},
    process::{Resource, getrlimit, setrlimit},
};

use super::*;
use crate::{
    test_utils::{in_own_process, pipe, read_byte},
    testing::{self, Manager},
};

/// What one instance hands over, the next takes over, through the store: the state, and the items
/// in order, with their ids, records and file descriptors, more than a datagram of a queue takes,
/// one of an open file description that another one has, and none, included. What the store held
/// of it is removed from it, and the sockets of socket activation are left to the service.
#[test]
fn round_trip() {
    let mut manager = Manager::new().unwrap();
    manager.add_socket("test.socket", pipe().1);
    let (read_a, write_a) = pipe();
    let (read_b, write_b) = pipe();
    let many: Vec<_> = iter::repeat_with(|| pipe().1).take(MAX_FDS + 10).collect();
    let bytes = b"bytes only".to_vec();
    let many = Item::new(b"many", many);
    let twice = vec![write_a.try_clone().unwrap(), write_a.try_clone().unwrap()];
    let twice = Item::new(b"", twice);
    let items: [(u64, &dyn Save); 4] = [(1, &bytes), (2, &write_a), (3, &many), (u64::MAX, &twice)];
    let state = Item::new(b"state", vec![write_b]);
    let stored = store(&manager).hand_over(state, items).unwrap();
    assert_eq!(stored.items(), 4);
    assert_eq!(stored.fds(), 1 + 1 + MAX_FDS + 10 + 2);
    assert_eq!(manager.stored_names(), ["test/state", "test/fds"]);

    let mut passed = manager.passed().unwrap();
    let mut second = store(&manager);
    let mut restored = second.take_over(&mut passed).unwrap().unwrap();
    manager.barrier(WAIT).unwrap();
    assert_eq!(manager.take_removed(), ["test/fds", "test/state"]);
    let names: Vec<_> = passed.iter().map(|(name, _)| name).collect();
    assert_eq!(names, ["test.socket"]);

    assert_eq!(restored.state(), b"state");
    let [fd] = <[OwnedFd; 1]>::try_from(restored.take_state_fds()).unwrap();
    write(&fd, b"b").unwrap();
    assert_eq!(read_byte(&read_b), b'b');
    assert!(restored.take_state_fds().is_empty());
    let mut items = restored.take_items();
    let item = items.next().unwrap();
    assert_eq!(item.id, 1);
    assert_eq!(item.restore::<Vec<u8>>().unwrap(), b"bytes only");
    let item = items.next().unwrap();
    assert_eq!(item.id, 2);
    let fd = item.restore::<OwnedFd>().unwrap();
    write(&fd, b"a").unwrap();
    assert_eq!(read_byte(&read_a), b'a');
    let item = items.next().unwrap();
    assert_eq!(
        (item.id, item.record, item.fds.len()),
        (3, &b"many"[..], MAX_FDS + 10)
    );
    let item = items.next().unwrap();
    assert_eq!(item.id, u64::MAX);
    // Each of the two goes as it is, rather than once, as the store would keep it.
    assert_eq!(item.fds.len(), 2);
    for fd in &item.fds {
        write(fd, b"t").unwrap();
        assert_eq!(read_byte(&read_a), b't');
    }
    assert!(items.next().is_none());
    drop(items);
    assert_eq!(restored.take_items().count(), 0);
}

/// Nothing was handed over without the memfd of the hand-over, whatever else there is, and the
/// queue sockets that came without it close.
#[test]
fn nothing_to_take_over() {
    let mut manager = Manager::new().unwrap();
    manager.add_socket("test.socket", pipe().1);
    let mut passed = manager.passed().unwrap();
    assert!(store(&manager).take_over(&mut passed).unwrap().is_none());
    assert_eq!(passed.len(), 1);

    let queue = Queue::new().unwrap().into_socket();
    manager.replace_store(vec![("test/fds".to_owned(), queue)]);
    let mut passed = manager.passed().unwrap();
    let mut store = store(&manager);
    assert!(store.take_over(&mut passed).unwrap().is_none());
    manager.barrier(WAIT).unwrap();
    assert_eq!(manager.take_removed(), ["test/fds"]);
    assert_eq!(passed.len(), 1);
}

/// A memfd that isn't a hand-over fails the take-over, after all of what was stored under the key
/// was removed from the store, names that zoter doesn't know included, while what was stored under
/// other keys stays.
#[test]
fn no_take_over_of_garbage() {
    let manager = Manager::new().unwrap();
    let garbage = memfd::sealed("test", b"not a hand-over").unwrap();
    manager.replace_store(vec![
        ("test/state".to_owned(), garbage),
        ("test/other".to_owned(), pipe().1),
        ("other/state".to_owned(), pipe().1),
    ]);

    let mut passed = manager.passed().unwrap();
    let mut store = store(&manager);
    let error = store.take_over(&mut passed).unwrap_err();
    assert!(matches!(error, Error::InvalidHandover(_)), "{error:?}");
    manager.barrier(WAIT).unwrap();
    assert_eq!(manager.take_removed(), ["test/other", "test/state"]);
    let names: Vec<_> = passed.iter().map(|(name, _)| name).collect();
    assert_eq!(names, ["other/state"]);
}

/// Taking over tells the manager that the service has started, after it removed what it took
/// from the store: with a hand-over, with none, and with one that it fails to take over.
#[test]
fn taking_over_tells_that_the_service_started() {
    let manager = Manager::new().unwrap();
    let mut passed = manager.passed().unwrap();
    let mut first = store(&manager);
    assert!(first.take_over(&mut passed).unwrap().is_none());
    manager.barrier(WAIT).unwrap();
    assert_eq!(manager.take_notifications(), ["READY=1", "BARRIER=1"]);

    first.hand_over(b"state".to_vec(), NO_ITEMS).unwrap();
    manager.take_notifications();
    let garbage = memfd::sealed("test", b"not a hand-over").unwrap();
    for taken_over in [true, false] {
        if !taken_over {
            manager.replace_store(vec![(
                "test/state".to_owned(),
                garbage.try_clone().unwrap(),
            )]);
        }
        let mut passed = manager.passed().unwrap();
        let mut next = store(&manager);
        assert_eq!(next.take_over(&mut passed).is_ok(), taken_over);
        manager.barrier(WAIT).unwrap();
        assert_eq!(
            manager.take_notifications(),
            ["FDSTOREREMOVE=1\nFDNAME=test/state", "READY=1", "BARRIER=1"],
            "taken over: {taken_over}"
        );
    }
}

/// An item that can't be saved, as one whose record fails to be saved, fails the hand-over, naming
/// the item, and nothing is stored.
#[test]
fn unsaved_items_fail_the_hand_over() {
    for (unsaved, failed) in [
        (Box::new(Unsaved) as Box<dyn Save>, false),
        (Box::new(Failing(pipe().1)), true),
    ] {
        let manager = Manager::new().unwrap();
        let items: [(u64, Box<dyn Save>); 3] = [
            (1, Box::new(Item::new(b"one", vec![pipe().1]))),
            (2, unsaved),
            (3, Box::new(Item::new(b"three", vec![pipe().1]))),
        ];
        let error = store(&manager).hand_over(&[][..], items).unwrap_err();
        let Error::Unsaved {
            item: Some(2),
            source,
        } = &error
        else {
            panic!("{error:?}");
        };
        assert_eq!(source.is_some(), failed, "{error:?}");
        assert!(error.to_string().contains("item 2 "), "{error}");

        let mut passed = manager.passed().unwrap();
        assert!(store(&manager).take_over(&mut passed).unwrap().is_none());
    }
}

/// A take-over fails if file descriptors of an item aren't all there, and what was stored is
/// removed from the store all the same.
#[test]
fn missing_fds_fail_the_take_over() {
    let manager = Manager::new().unwrap();
    let items = [
        (1, Item::new(b"one", vec![pipe().1])),
        (2, Item::new(b"two", vec![pipe().1, pipe().1])),
        (3, Item::new(b"three", vec![pipe().1])),
    ];
    store(&manager).hand_over(&[][..], items).unwrap();

    // The second file descriptor, the first of the second item, goes missing.
    let mut stored = manager.stored().unwrap();
    let queue = Queue::new().unwrap();
    queue::take(stored[1].1.as_fd(), |index, fds, _| {
        for (index, fd) in (index..).zip(fds) {
            if index != 1 {
                assert!(queue.push(index, &[fd.as_fd()]).unwrap());
            }
        }
    })
    .unwrap();
    stored[1].1 = queue.into_socket();
    manager.replace_store(stored);

    let mut passed = manager.passed().unwrap();
    let mut store = store(&manager);
    let error = store.take_over(&mut passed).unwrap_err();
    assert!(matches!(error, Error::InvalidHandover(_)), "{error:?}");
    assert!(error.to_string().contains("item 2 "), "{error}");
    manager.barrier(WAIT).unwrap();
    assert_eq!(manager.take_removed(), ["test/fds", "test/state"]);
}

/// A take-over fails with the system's error of too many open files if the file descriptors of the
/// hand-over don't fit under the soft limit of open files of the process.
#[test]
fn take_over_over_the_fd_limit() {
    let test = "store::tests::take_over_over_the_fd_limit";
    if !in_own_process(test, "ZOTER_TEST_LOW_NOFILE=1") {
        return;
    }

    let manager = Manager::new().unwrap();
    let (_read, write) = pipe();
    let fds = iter::repeat_with(|| write.try_clone().unwrap())
        .take(32)
        .collect();
    let items = [(1, Item::new(b"many", fds))];
    store(&manager).hand_over(&[][..], items).unwrap();
    let mut passed = manager.passed().unwrap();
    let mut store = store(&manager);
    // Room for a few file descriptors more than are open, which the manager adds to as it closes
    // what it removes from its store, and far fewer than the hand-over has.
    let open = std::fs::read_dir("/proc/self/fd").unwrap().count() as u64;
    let mut limit = getrlimit(Resource::Nofile);
    limit.current = Some(open + 2);
    setrlimit(Resource::Nofile, limit).unwrap();

    let error = store.take_over(&mut passed).unwrap_err();
    assert!(
        matches!(&error, Error::Io(e) if e.raw_os_error() == Some(Errno::MFILE.raw_os_error())),
        "{error:?}"
    );
}

/// A state that can't be saved fails the hand-over, as one that fails to be saved does.
#[test]
fn unsaved_state() {
    for (state, failed) in [
        (Box::new(Unsaved) as Box<dyn Save>, false),
        (Box::new(Failing(pipe().1)), true),
    ] {
        let manager = Manager::new().unwrap();
        let error = store(&manager).hand_over(state, NO_ITEMS).unwrap_err();
        let Error::Unsaved { item: None, source } = &error else {
            panic!("{error:?}");
        };
        assert_eq!(source.is_some(), failed, "{error:?}");
    }
}

/// A store that takes fewer than 2 file descriptors can't hold a hand-over, so creating it fails.
/// The error names the unit setting to raise.
#[test]
fn no_store_without_room() {
    let manager = Manager::new().unwrap();
    for max in [0, 1] {
        let error = testing::store(manager.notify_socket(), KEY, max).unwrap_err();
        assert!(
            matches!(error, Error::StoreTooSmall { max: too_few } if too_few == max),
            "{max}: {error:?}"
        );
        assert!(
            error.to_string().contains("`FileDescriptorStoreMax=`"),
            "{error}"
        );
    }
    testing::store(manager.notify_socket(), KEY, MIN_STORE).unwrap();
}

/// A service hands over what it borrows: its state, and its items out of an iterator over what it
/// holds, as an async service has them once it stopped taking requests.
#[test]
fn borrowed_state_and_items() {
    let manager = Manager::new().unwrap();
    let store = store(&manager);
    let clients = [(4, pipe().1), (2, pipe().1)];
    let state = b"state".to_vec();
    let items = clients.iter().map(|(id, client)| (*id, client));
    let stored = store.hand_over(&state, items).unwrap();
    assert_eq!((stored.items(), stored.fds()), (2, 2));

    assert_eq!(ids(take_over(&manager)), [4, 2]);
}

/// A store is `Send`, so that an async service can hold it across the awaits of serving and of
/// stopping, on a runtime of several threads.
#[test]
fn store_is_send() {
    fn send<T: Send>() {}

    send::<Store>();
}

#[test]
fn keys() {
    let manager = Manager::new().unwrap();
    let longest = "a".repeat(MAX_KEY_LEN);
    for key in ["busd", "with spaces", "a.b-c_d", &longest] {
        testing::store(manager.notify_socket(), key, 2).unwrap();
    }
    let too_long = "a".repeat(MAX_KEY_LEN + 1);
    for key in ["", "a/b", "a:b", "a\nb", "é", &too_long] {
        let error = testing::store(manager.notify_socket(), key, 2).unwrap_err();
        assert!(matches!(error, Error::InvalidName(_)), "{key:?}: {error:?}");
    }
}

/// The file descriptors go on in the next queue socket once one is full, and come back by the
/// index that each was queued as, whatever the order of the queue sockets, each as it went, one of
/// the same open file description as another one included.
#[test]
fn queued_fds_come_back_by_their_index() {
    let pipes: Vec<_> = (0..3).map(|_| pipe()).collect();
    // The last is of the same open file description as the first, which the store would keep
    // once.
    let mut fds: Vec<_> = pipes.iter().map(|(_, write)| write.as_fd()).collect();
    fds.push(fds[0]);
    let stored = RefCell::new(Vec::new());

    // Datagrams without file descriptors fill the first queue socket, between two that have some.
    let (first, last) = fds.split_at(2);
    let (mut first, mut last) = (Some(first), Some(last));
    let chunks = iter::from_fn(|| match stored.borrow().is_empty() {
        true => Some(first.take().unwrap_or_default()),
        false => last.take(),
    });
    queue_fds(chunks, 3, |socket| {
        stored.borrow_mut().push(socket);

        Ok(())
    })
    .unwrap();
    let mut stored = stored.into_inner();
    assert_eq!(
        stored.len(),
        2,
        "the file descriptors went in other than two sockets"
    );

    stored.reverse();
    let mut taken = take_queued(stored).unwrap();
    // What goes into each file descriptor comes out of the pipe that it was queued of.
    for (index, pipe) in [(0, 0), (1, 1), (2, 2), (3, 0)] {
        let fd = taken.remove(&index).unwrap();
        let byte = [index as u8];
        assert_eq!(write(&fd, &byte).unwrap(), 1);
        let mut read_byte = [0];
        assert_eq!(read(&pipes[pipe].0, &mut read_byte).unwrap(), 1);
        assert_eq!(read_byte, byte);
    }
    assert!(taken.is_empty(), "{taken:?}");
}

/// The file descriptors go in no more queue sockets than the store has room for, and queueing
/// fails, naming the setting of the unit to raise, if they don't fit in them.
#[test]
fn queued_fds_that_overflow_the_store() {
    let fd = pipe().1;
    let fds = [fd.as_fd()];
    let mut stored = Vec::new();

    // One datagram with a file descriptor, then ones without, more than any queue socket takes.
    let chunks = iter::once(&fds[..]).chain(iter::repeat(&fds[..0]));
    let error = queue_fds(chunks, 1, |socket| {
        stored.push(socket);

        Ok(())
    })
    .unwrap_err();
    assert!(matches!(error, Error::StoreFull), "{error:?}");
    assert!(
        error.to_string().contains("`FileDescriptorStoreMax=`"),
        "{error}"
    );
    // The queue socket that the store had room for was stored all the same.
    assert_eq!(stored.len(), 1);
    let taken = take_queued(stored).unwrap();
    assert_eq!(taken.into_keys().collect::<Vec<_>>(), [0]);

    // A store without room takes none, but for none at all.
    let error = queue_fds([&fds[..]], 0, |_| unreachable!()).unwrap_err();
    assert!(matches!(error, Error::StoreFull), "{error:?}");
    queue_fds([], 0, |_| unreachable!()).unwrap();
}

/// An item gets the file descriptors at its place, if they are all there, and none otherwise,
/// while those that are there go all the same.
#[test]
fn items_take_their_fds() {
    let mut fds: HashMap<u64, OwnedFd> = [0, 1, 2, 4].map(|index| (index, pipe().1)).into();

    assert_eq!(take_fds(&mut fds, 0..2).unwrap().len(), 2);
    assert!(take_fds(&mut fds, 2..4).is_none(), "{fds:?}");
    assert!(!fds.contains_key(&2), "{fds:?}");
    assert!(take_fds(&mut fds, 4..u64::MAX).is_none());
    assert!(fds.is_empty(), "{fds:?}");
    assert_eq!(take_fds(&mut fds, 5..5).unwrap().len(), 0);
}

#[test]
fn from_the_environment() {
    let exports = "NOTIFY_SOCKET=/run/systemd/notify FDSTORE=16";
    if !in_own_process("store::tests::from_the_environment", exports) {
        return;
    }

    let passed = passed(&["web"]);
    let store = Store::from_env(KEY, &passed).unwrap();
    assert_eq!(store.max, 16);
    // A number that `$FDSTORE` tells is judged as one that `testing::store` is given: a
    // hand-over doesn't fit in a store that takes fewer than 2 file descriptors.
    for max in [0, 1] {
        // SAFETY: The test runs in a process of its own, which has no other thread that reads or
        // writes the environment. So do the ones below.
        unsafe { env::set_var("FDSTORE", max.to_string()) };
        let error = Store::from_env(KEY, &passed).unwrap_err();
        assert!(
            matches!(error, Error::StoreTooSmall { max: too_few } if too_few == max),
            "{max}: {error:?}"
        );
    }
    // Without a number in `$FDSTORE`, systemd keeps no store for the service that it takes
    // notifications from, and the error names the unit setting that has it keep one.
    for value in ["", "-1", "x", "1.5", " 1", "99999999999999999999"] {
        // SAFETY: As above.
        unsafe { env::set_var("FDSTORE", value) };
        let error = Store::from_env(KEY, &passed).unwrap_err();
        assert!(
            matches!(error, Error::NoStore),
            "$FDSTORE={value:?}: {error:?}"
        );
    }
    // SAFETY: As above.
    unsafe { env::remove_var("FDSTORE") };
    let error = Store::from_env(KEY, &passed).unwrap_err();
    assert!(matches!(error, Error::NoStore), "{error:?}");
    assert!(
        error.to_string().contains("`FileDescriptorStoreMax=`"),
        "{error}"
    );
    // Without a notification socket, systemd takes no notifications from the process, as when it
    // doesn't run it at all, which is an error of its own, whatever `$FDSTORE` tells.
    for fd_store in [None, Some("16")] {
        for socket in [Some(""), None] {
            // SAFETY: As above.
            unsafe {
                match fd_store {
                    Some(fd_store) => env::set_var("FDSTORE", fd_store),
                    None => env::remove_var("FDSTORE"),
                }
                match socket {
                    Some(socket) => env::set_var("NOTIFY_SOCKET", socket),
                    None => env::remove_var("NOTIFY_SOCKET"),
                }
            }
            let error = Store::from_env(KEY, &passed).unwrap_err();
            assert!(
                matches!(error, Error::NoManager),
                "$NOTIFY_SOCKET={socket:?} $FDSTORE={fd_store:?}: {error:?}"
            );
        }
    }
}

/// A store needs a socket of socket activation: something systemd passed other than what is stored
/// under its key.
#[test]
fn no_store_without_a_socket() {
    let exports = "NOTIFY_SOCKET=/run/systemd/notify FDSTORE=16";
    if !in_own_process("store::tests::no_store_without_a_socket", exports) {
        return;
    }

    let state = format!("{KEY}/state");
    let fds = format!("{KEY}/fds");
    let no_socket = |names: &[&str]| {
        let error = Store::from_env(KEY, &passed(names)).unwrap_err();
        assert!(matches!(error, Error::NoSocket), "{names:?}: {error:?}");
        assert!(error.to_string().contains("`Requires=`"), "{error}");
        assert_eq!(io::Error::from(error).kind(), io::ErrorKind::Unsupported);
    };
    // Nothing is passed, or only what is stored under the key.
    no_socket(&[]);
    no_socket(&[&state, &fds]);
    no_socket(&[&fds, &fds, &state]);

    assert_eq!(Store::from_env(KEY, &passed(&["web"])).unwrap().max, 16);
    assert!(Store::from_env(KEY, &passed(&["web", &state, &fds])).is_ok());
    assert!(Store::from_env(KEY, &passed(&[&state, "web"])).is_ok());
    // A name that only starts as the key does is another key's, which counts as a socket.
    assert!(Store::from_env(KEY, &passed(&["test"])).is_ok());
    assert!(Store::from_env(KEY, &passed(&[&format!("{KEY}x/state")])).is_ok());
}

/// A store is made whether or not the socket was taken out of `passed` before, as a service takes
/// its socket as it likes, before or after it makes the store.
#[test]
fn store_with_the_socket_taken_before() {
    let exports = "NOTIFY_SOCKET=/run/systemd/notify FDSTORE=16";
    if !in_own_process("store::tests::store_with_the_socket_taken_before", exports) {
        return;
    }

    let mut passed = passed(&["web", &format!("{KEY}/state")]);
    assert!(passed.take("web").is_some());
    assert!(passed.take_prefixed(&format!("{KEY}/")).len() == 1);
    assert!(passed.is_empty());
    assert!(Store::from_env(KEY, &passed).is_ok());
}

/// A file descriptor under the name of another key counts as a socket.
#[test]
fn store_with_a_name_under_another_key() {
    let exports = "NOTIFY_SOCKET=/run/systemd/notify FDSTORE=16";
    if !in_own_process("store::tests::store_with_a_name_under_another_key", exports) {
        return;
    }

    let passed = passed(&["other/state", "other/fds"]);
    assert!(Store::from_env(KEY, &passed).is_ok());
}

/// The error for a missing store comes before that for a missing socket, and that for a missing
/// manager before both.
#[test]
fn the_checks_of_from_env_come_in_order() {
    let exports = "NOTIFY_SOCKET=/run/systemd/notify";
    if !in_own_process(
        "store::tests::the_checks_of_from_env_come_in_order",
        exports,
    ) {
        return;
    }

    let nothing = passed(&[]);
    let error = Store::from_env(KEY, &nothing).unwrap_err();
    assert!(matches!(error, Error::NoStore), "{error:?}");
    // SAFETY: The test runs in a process of its own, which has no other thread that reads or
    // writes the environment.
    unsafe { env::set_var("FDSTORE", "1") };
    let error = Store::from_env(KEY, &nothing).unwrap_err();
    assert!(
        matches!(error, Error::StoreTooSmall { max: 1 }),
        "{error:?}"
    );
    // SAFETY: As above.
    unsafe { env::set_var("FDSTORE", "16") };
    let error = Store::from_env("bad/key", &nothing).unwrap_err();
    assert!(matches!(error, Error::InvalidName(_)), "{error:?}");
    // SAFETY: As above.
    unsafe { env::remove_var("NOTIFY_SOCKET") };
    let error = Store::from_env(KEY, &nothing).unwrap_err();
    assert!(matches!(error, Error::NoManager), "{error:?}");
}

/// What systemd passed, as these names: each is a pipe.
fn passed(names: &[&str]) -> Passed {
    Passed::new(
        names
            .iter()
            .map(|name| (name.to_string(), pipe().1))
            .collect(),
    )
}

/// A store of the manager, under `KEY`, that takes as many file descriptors as the store of the
/// manager does.
fn store(manager: &Manager) -> Store {
    testing::store(manager.notify_socket(), KEY, manager.store_max()).unwrap()
}

/// What the manager passes the next instance, taken over.
fn take_over(manager: &Manager) -> Restored {
    let mut passed = manager.passed().unwrap();

    store(manager).take_over(&mut passed).unwrap().unwrap()
}

/// The ids of the items of `restored`.
fn ids(mut restored: Restored) -> Vec<u64> {
    restored.take_items().map(|item| item.id).collect()
}

/// An item of bytes and file descriptors of the test's choosing.
struct Item {
    bytes: Vec<u8>,
    fds: Vec<OwnedFd>,
}

impl Item {
    fn new(bytes: &[u8], fds: Vec<OwnedFd>) -> Self {
        Self {
            bytes: bytes.to_vec(),
            fds,
        }
    }
}

impl Save for Item {
    fn saved_len(&self) -> Option<usize> {
        Some(self.bytes.len())
    }

    fn save(&self, dest: &mut [u8]) -> Result<()> {
        dest.copy_from_slice(&self.bytes);

        Ok(())
    }

    fn fds(&self) -> Vec<BorrowedFd<'_>> {
        self.fds.iter().map(AsFd::as_fd).collect()
    }
}

/// An item that can't be saved.
struct Unsaved;

impl Save for Unsaved {
    fn saved_len(&self) -> Option<usize> {
        None
    }

    fn save(&self, _dest: &mut [u8]) -> Result<()> {
        unreachable!("an item that can't be saved was saved")
    }

    fn fds(&self) -> Vec<BorrowedFd<'_>> {
        Vec::new()
    }
}

/// An item whose record fails to be saved, after writing some of it.
struct Failing(OwnedFd);

impl Save for Failing {
    fn saved_len(&self) -> Option<usize> {
        Some(8)
    }

    fn save(&self, dest: &mut [u8]) -> Result<()> {
        dest[0] = 1;

        Err(io::Error::other("the record failed").into())
    }

    fn fds(&self) -> Vec<BorrowedFd<'_>> {
        vec![self.0.as_fd()]
    }
}

const KEY: &str = "test";
/// No items, for a hand-over of the state alone.
const NO_ITEMS: [(u64, &[u8]); 0] = [];
const WAIT: Duration = Duration::from_secs(10);