ostrya-server 0.8.0

HTTP server of ostrya: the archive view of a repository for pull, and the receive endpoint of push
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
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
//! The sessions of the receive endpoint.
//!
//! The table holds one entry for each open session. An entry holds:
//!
//! - the [`ReceiveService`] of the session
//! - the owner key of the session
//! - the time of the last activity
//! - the count of the requests in progress
//! - each request body in flight, with the time it started to wait for the
//!   client
//! - a cancel signal that ends the requests of the session in flight
//!
//! One sweep task applies the idle timeout to every entry. No code holds the
//! lock of the table while it aborts or drops a service.

use std::collections::HashMap;
use std::fmt;
use std::sync::{Arc, Mutex, MutexGuard, OnceLock};
use std::time::{Duration, Instant};

use ostrya::{Checksum, ReceiveService};
use ostrya_rt as rt;

use crate::shutdown::{Shutdown, Wait};

/// The cause of a session with no request in progress for the idle timeout.
const IDLE: &str = "the session was idle for the idle timeout";

/// The cause of a session with a request body that delivered no byte for the
/// idle timeout.
const SILENT: &str = "a request body of the session delivered no byte for the idle timeout";

/// The cause of a session whose request failed.
const FAILED: &str = "a request of the session failed";

/// The cause of a session whose request ended before its response, for
/// example when the client closed the connection.
const CUT: &str = "a request of the session ended before its response";

/// The cause of a session that a `DELETE` ended.
const DELETED: &str = "the client deleted the session";

/// The cause of the end of a session after its commit.
const COMMITTED: &str = "the session committed";

/// The cause of the sessions that the stop of the server ended.
const STOPPED: &str = "the server stopped";

/// The id of a session: 32 random bytes, shown as 64 lowercase hex digits.
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) struct SessionId {
    inner: [u8; 32],
}

impl SessionId {
    /// Creates a new id from the random source of the operating system.
    pub(crate) fn new() -> Result<SessionId, getrandom::Error> {
        let mut inner = [0u8; 32];
        getrandom::fill(&mut inner)?;
        Ok(SessionId { inner })
    }

    /// Returns the id that `text` shows. The text must be exactly 64
    /// lowercase hex digits. Any other text gives `None`.
    pub(crate) fn parse(text: &str) -> Option<SessionId> {
        let checksum = Checksum::from_hex_lower(text).ok()?;
        Some(SessionId {
            inner: *checksum.as_bytes(),
        })
    }
}

impl fmt::Display for SessionId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&Checksum::from_bytes(self.inner).to_hex())
    }
}

/// The signal that ends the requests of one session in flight, and the
/// cause that the requests report.
pub(crate) struct Cancel {
    signal: Arc<Shutdown>,
    cause: OnceLock<&'static str>,
}

impl Cancel {
    fn new() -> Arc<Cancel> {
        Arc::new(Cancel {
            signal: Arc::new(Shutdown::default()),
            cause: OnceLock::new(),
        })
    }

    /// Records `cause`, unless a cause is already recorded, and wakes each
    /// waiter.
    fn fire(&self, cause: &'static str) {
        let _ = self.cause.set(cause);
        self.signal.fire();
    }

    /// Returns a future that completes when the session ends.
    pub(crate) fn wait(&self) -> Wait {
        self.signal.wait()
    }

    /// Returns the cause of the end of the session. If no cause is
    /// recorded, it returns the cause of the stop of the server.
    pub(crate) fn cause(&self) -> &'static str {
        self.cause.get().copied().unwrap_or(STOPPED)
    }
}

/// One open session.
struct Entry {
    service: Arc<ReceiveService>,
    /// The owner key of the session.
    owner: String,
    /// The time of the last activity.
    last: Instant,
    /// The requests of the session in progress.
    active: usize,
    /// Each request body in flight, by its id, with the time it started to
    /// wait for the client, or `None` while it does not wait.
    bodies: HashMap<u64, Option<Instant>>,
    cancel: Arc<Cancel>,
    /// `true` while the commit of the session runs. The sweep and a
    /// `DELETE` do not end the session then.
    committing: bool,
    /// `true` if a request body of the session failed, for example when the
    /// client closed the connection. A failed request then ends the session
    /// with the cause of a request that ended before its response.
    cut: bool,
}

impl Entry {
    /// Ends the session with `cause`. It wakes the requests of the session
    /// in flight and aborts the service. The caller must hold no lock of the
    /// table.
    fn close(self, cause: &'static str) {
        self.cancel.fire(cause);
        self.service.abort();
    }
}

struct State {
    entries: HashMap<SessionId, Entry>,
    /// The count of the slots reserved for sessions that open now.
    pending: usize,
    next_body: u64,
    /// `true` after the server stopped. The table then takes no session.
    closed: bool,
}

/// The open sessions of a server.
pub(crate) struct SessionTable {
    max: usize,
    idle: Duration,
    state: Mutex<State>,
}

/// The answer of [`SessionTable::delete`].
pub(crate) enum Deleted {
    /// The session ended.
    Done,
    /// The session commits, and the commit goes on.
    Committing,
    /// No session of the owner has the id.
    NotFound,
}

impl SessionTable {
    /// Creates a table of at most `max` sessions. The sweep aborts a session
    /// after `idle` with no request in progress.
    pub(crate) fn new(max: usize, idle: Duration) -> Arc<SessionTable> {
        Arc::new(SessionTable {
            max,
            idle,
            state: Mutex::new(State {
                entries: HashMap::new(),
                pending: 0,
                next_body: 0,
                closed: false,
            }),
        })
    }

    /// Returns the idle timeout.
    pub(crate) fn idle(&self) -> Duration {
        self.idle
    }

    /// Returns the maximum count of sessions open at the same time.
    pub(crate) fn max(&self) -> usize {
        self.max
    }

    fn lock(&self) -> MutexGuard<'_, State> {
        self.state.lock().expect("session table mutex")
    }

    /// Reserves the slot of a session that opens now. If the open sessions
    /// and the reserved slots are at the limit, or if the server stopped, it
    /// returns `None`.
    pub(crate) fn reserve(self: &Arc<SessionTable>) -> Option<Reservation> {
        let mut state = self.lock();
        if state.closed || state.entries.len() + state.pending >= self.max {
            return None;
        }
        state.pending += 1;
        Some(Reservation {
            table: self.clone(),
            used: false,
        })
    }

    /// Returns the session `id` of the owner key `owner`. The session counts
    /// as active until the returned value drops. An unknown id and a session
    /// of another owner both give `None`.
    pub(crate) fn lookup(self: &Arc<SessionTable>, id: &SessionId, owner: &str) -> Option<Active> {
        let mut state = self.lock();
        let entry = state.entries.get_mut(id).filter(|e| e.owner == owner)?;
        entry.active += 1;
        Some(Active {
            table: self.clone(),
            id: *id,
            service: entry.service.clone(),
            cancel: entry.cancel.clone(),
            complete: false,
        })
    }

    /// Ends the session `id` of the owner key `owner` for a `DELETE`. A
    /// session that commits stays as it is.
    pub(crate) fn delete(&self, id: &SessionId, owner: &str) -> Deleted {
        let entry = {
            let mut state = self.lock();
            match state.entries.get(id) {
                Some(entry) if entry.owner == owner => {
                    if entry.committing {
                        return Deleted::Committing;
                    }
                }
                _ => return Deleted::NotFound,
            }
            state.entries.remove(id)
        };
        if let Some(entry) = entry {
            entry.close(DELETED);
        }
        Deleted::Done
    }

    /// Removes the session `id` and ends it with `cause`. If the id is not
    /// in the table, the call does nothing.
    pub(crate) fn end(&self, id: &SessionId, cause: &'static str) {
        let entry = self.lock().entries.remove(id);
        if let Some(entry) = entry {
            entry.close(cause);
        }
    }

    /// Removes the session `id` and ends it after a failed request. A
    /// session that commits stays, because its commit goes on and removes it
    /// at the end. If a request body of the session failed, the session ends
    /// with the cause of a request that ended before its response.
    pub(crate) fn fail(&self, id: &SessionId) {
        let entry = {
            let mut state = self.lock();
            match state.entries.get(id) {
                Some(entry) if !entry.committing => state.entries.remove(id),
                _ => None,
            }
        };
        if let Some(entry) = entry {
            let cause = if entry.cut { CUT } else { FAILED };
            entry.close(cause);
        }
    }

    /// Ends every session that does not commit, when the server stops. A
    /// session that commits stays, because its commit goes on and removes it
    /// at the end. The table takes no session after this call.
    pub(crate) fn close_all(&self) {
        let entries: Vec<Entry> = {
            let mut state = self.lock();
            state.closed = true;
            state
                .entries
                .extract_if(|_, e| !e.committing)
                .map(|(_, e)| e)
                .collect()
        };
        for entry in entries {
            entry.close(STOPPED);
        }
    }

    /// Aborts each session past its idle timeout, and each session with a
    /// request body that waited for the idle timeout. The loop runs until
    /// the future drops. The sweep never aborts a session that commits.
    ///
    /// The task sleeps until the earliest deadline, for at most one idle
    /// timeout. A deadline that arises during the sleep is one idle timeout
    /// or more after its start, so it never comes before the sleep ends.
    pub(crate) async fn sweep(&self) {
        loop {
            let (expired, wait) = self.expire(Instant::now());
            for (entry, cause) in expired {
                entry.close(cause);
            }
            rt::Timer::after(wait).await;
        }
    }

    /// Removes each session past a deadline at `now` and returns it with its
    /// cause. It also returns the time from `now` to the next deadline, at
    /// most one idle timeout.
    fn expire(&self, now: Instant) -> (Vec<(Entry, &'static str)>, Duration) {
        let mut state = self.lock();
        let mut next = self.idle;
        let mut due = Vec::new();
        for (id, entry) in &state.entries {
            if entry.committing {
                continue;
            }
            let silent = entry
                .bodies
                .values()
                .flatten()
                .map(|since| (*since, SILENT));
            let idle = (entry.active == 0).then_some((entry.last, IDLE));
            let Some((since, cause)) = silent.chain(idle).min_by_key(|(since, _)| *since) else {
                continue;
            };
            match (since + self.idle).checked_duration_since(now) {
                Some(left) if !left.is_zero() => next = next.min(left),
                _ => due.push((*id, cause)),
            }
        }
        let expired = due
            .into_iter()
            .filter_map(|(id, cause)| state.entries.remove(&id).map(|entry| (entry, cause)))
            .collect();
        (expired, next)
    }
}

/// A slot of the table for a session that opens now. If the value drops
/// unused, the slot becomes free.
pub(crate) struct Reservation {
    table: Arc<SessionTable>,
    used: bool,
}

impl Reservation {
    /// Puts the session `id` of the owner key `owner` into the slot. If the
    /// server stopped after the reservation, it returns `false`. The call
    /// then aborts and drops the service, and the table holds no entry for
    /// it.
    pub(crate) fn insert(mut self, id: SessionId, service: ReceiveService, owner: String) -> bool {
        let mut state = self.table.lock();
        state.pending -= 1;
        self.used = true;
        if state.closed {
            drop(state);
            service.abort();
            drop(service);
            return false;
        }
        state.entries.insert(
            id,
            Entry {
                service: Arc::new(service),
                owner,
                last: Instant::now(),
                active: 0,
                bodies: HashMap::new(),
                cancel: Cancel::new(),
                committing: false,
                cut: false,
            },
        );
        true
    }
}

impl Drop for Reservation {
    fn drop(&mut self) {
        if !self.used {
            self.table.lock().pending -= 1;
        }
    }
}

/// A request of a session in progress. The drop of the value removes the
/// request from the count of requests in progress, and the idle time of the
/// session starts again. If the request drops before its response, for
/// example when the client closes the connection, the session ends. A
/// session that commits does not end this way.
pub(crate) struct Active {
    table: Arc<SessionTable>,
    id: SessionId,
    service: Arc<ReceiveService>,
    cancel: Arc<Cancel>,
    /// `true` after the request has its response.
    complete: bool,
}

impl Active {
    /// Records that the request has its response.
    pub(crate) fn complete(&mut self) {
        self.complete = true;
    }

    pub(crate) fn id(&self) -> SessionId {
        self.id
    }

    pub(crate) fn service(&self) -> &Arc<ReceiveService> {
        &self.service
    }

    pub(crate) fn cancel(&self) -> &Arc<Cancel> {
        &self.cancel
    }

    pub(crate) fn table(&self) -> &Arc<SessionTable> {
        &self.table
    }

    /// Records a request body of the session. The new body does not wait
    /// for the client yet.
    pub(crate) fn track(&self) -> BodyTrack {
        let mut state = self.table.lock();
        let body = state.next_body;
        state.next_body += 1;
        if let Some(entry) = state.entries.get_mut(&self.id) {
            entry.bodies.insert(body, None);
        }
        BodyTrack {
            table: self.table.clone(),
            id: self.id,
            body,
        }
    }

    /// Marks the session as committing, unless it commits already or it
    /// ended.
    pub(crate) fn begin_commit(&self) -> Begin {
        let mut state = self.table.lock();
        let Some(entry) = state.entries.get_mut(&self.id) else {
            return Begin::Ended;
        };
        if entry.committing {
            return Begin::Committing;
        }
        entry.committing = true;
        Begin::Started(CommitEnd {
            table: self.table.clone(),
            id: self.id,
            cause: FAILED,
        })
    }
}

/// The answer of [`Active::begin_commit`].
pub(crate) enum Begin {
    /// The session commits from now on. The guard ends the session when it
    /// drops.
    Started(CommitEnd),
    /// The session commits already, and its commit goes on.
    Committing,
    /// The session ended.
    Ended,
}

/// The guard of a session that commits. When the guard drops, it removes the
/// session and ends it. If [`committed`](Self::committed) ran, the cause is
/// that of a commit. If not, the cause is that of a failed request. A commit
/// that panics or drops also frees its slot, because the guard drops with it.
pub(crate) struct CommitEnd {
    table: Arc<SessionTable>,
    id: SessionId,
    cause: &'static str,
}

impl CommitEnd {
    /// Records that the commit succeeded.
    pub(crate) fn committed(&mut self) {
        self.cause = COMMITTED;
    }
}

impl Drop for CommitEnd {
    fn drop(&mut self) {
        self.table.end(&self.id, self.cause);
    }
}

impl Drop for Active {
    fn drop(&mut self) {
        let cut = {
            let mut state = self.table.lock();
            let Some(entry) = state.entries.get_mut(&self.id) else {
                return;
            };
            entry.active -= 1;
            entry.last = Instant::now();
            if self.complete || entry.committing {
                return;
            }
            state.entries.remove(&self.id)
        };
        if let Some(entry) = cut {
            entry.close(CUT);
        }
    }
}

/// The record of one request body in its session. It drops with the body.
pub(crate) struct BodyTrack {
    table: Arc<SessionTable>,
    id: SessionId,
    body: u64,
}

impl BodyTrack {
    /// Records that the body waits for the client from now on.
    pub(crate) fn waiting(&self) {
        self.set(Some(Instant::now()));
    }

    /// Records that the body delivered bytes now. This also sets the time of
    /// the last activity of the session.
    pub(crate) fn progress(&self) {
        self.set(None);
    }

    /// Records that the body failed, for example when the client closed the
    /// connection.
    pub(crate) fn cut(&self) {
        if let Some(entry) = self.table.lock().entries.get_mut(&self.id) {
            entry.cut = true;
        }
    }

    fn set(&self, since: Option<Instant>) {
        let mut state = self.table.lock();
        if let Some(entry) = state.entries.get_mut(&self.id) {
            if since.is_none() {
                entry.last = Instant::now();
            }
            if let Some(slot) = entry.bodies.get_mut(&self.body) {
                *slot = since;
            }
        }
    }
}

impl Drop for BodyTrack {
    fn drop(&mut self) {
        let mut state = self.table.lock();
        if let Some(entry) = state.entries.get_mut(&self.id) {
            entry.bodies.remove(&self.body);
        }
    }
}

#[cfg(test)]
pub(crate) mod tests {
    use std::path::PathBuf;

    use ostrya::remote::proto::{CommitRequest, Hello};
    use ostrya::remote::{Expected, RefUpdate};
    use ostrya::{CreateOptions, ReceivePolicies, ReceivePolicy, Repo, RepoMode};
    use ostrya_rt::block_on;

    use super::*;

    /// A client group that lets each request with no credential write a
    /// commit to each ref as a fast-forward.
    pub(crate) const ANONYMOUS_PUSH: &str =
        "[ex-ostrya client \"push\"]\nauth=anonymous\nallow=w:**\n";

    /// A policy that writes a commit to each ref as a fast-forward.
    pub(crate) fn pushing_policy() -> ReceivePolicy {
        ReceivePolicy {
            rules: ostrya::access::AccessRules {
                allow: vec![ostrya::access::AllowItem::parse("w:**").unwrap()],
                deny: Vec::new(),
            },
            ..ReceivePolicy::default()
        }
    }

    /// A repository in a directory of its own. The drop of the value removes
    /// the directory when no staging directory is left.
    pub(crate) struct TmpRepo {
        path: PathBuf,
        pub(crate) repo: Repo,
    }

    impl TmpRepo {
        pub(crate) fn new(tag: &str) -> TmpRepo {
            let path = std::env::temp_dir().join(format!(
                "ostrya-server-session-{}-{tag}",
                std::process::id()
            ));
            let _ = std::fs::remove_dir_all(&path);
            let repo =
                block_on(Repo::create(&path, CreateOptions::new(RepoMode::Archive))).unwrap();
            TmpRepo { path, repo }
        }

        /// Writes the client groups `groups` at the end of the config of the
        /// repository, and returns their policies. The open repository keeps
        /// the config that it read.
        pub(crate) fn policies(&self, groups: &str) -> Arc<ReceivePolicies> {
            let config = self.path.join("config");
            let mut text = std::fs::read_to_string(&config).unwrap();
            text.push_str(groups);
            std::fs::write(&config, text).unwrap();
            block_on(async {
                let repo = Repo::open(&self.path).await.unwrap();
                Arc::new(ReceivePolicies::from_config(&repo).await.unwrap())
            })
        }

        /// Returns a new open session over the repository.
        fn service(&self) -> ReceiveService {
            let hello = Hello {
                version: 1,
                agent: None,
                refs: vec!["main".into()],
                collection: None,
                one_way: false,
            };
            let policy = Arc::new(pushing_policy());
            block_on(ReceiveService::hello(self.repo.clone(), policy, 1, hello))
                .unwrap()
                .0
        }
    }

    impl Drop for TmpRepo {
        /// The core of an ended session goes on the blocking pool, so the
        /// staging directory can stay for a short time. The drop waits up to
        /// 30 seconds for the `staging-` entries of `tmp` to go, then removes
        /// the repository.
        fn drop(&mut self) {
            let deadline = Instant::now() + Duration::from_secs(30);
            while Instant::now() < deadline {
                let staging = std::fs::read_dir(self.path.join("tmp")).map(|dir| {
                    dir.flatten()
                        .any(|e| e.file_name().to_string_lossy().starts_with("staging-"))
                });
                if !matches!(staging, Ok(true)) {
                    break;
                }
                std::thread::sleep(Duration::from_millis(10));
            }
            let _ = std::fs::remove_dir_all(&self.path);
        }
    }

    /// Returns a table of one session over `repo`, and the id of the session.
    fn one_session(repo: &TmpRepo) -> (Arc<SessionTable>, SessionId) {
        let table = SessionTable::new(1, Duration::from_secs(60));
        let id = SessionId::new().unwrap();
        let slot = table.reserve().unwrap();
        assert!(slot.insert(id, repo.service(), "anonymous".into()));
        (table, id)
    }

    /// A new id is 64 lowercase hex digits, and the parser takes that form
    /// alone.
    #[test]
    fn a_session_id_is_64_lowercase_hex_digits() {
        let a = SessionId::new().unwrap();
        let b = SessionId::new().unwrap();
        assert!(a != b, "two ids of 32 random bytes differ");
        let text = a.to_string();
        assert_eq!(text.len(), 64);
        assert!(
            text.bytes()
                .all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)),
            "{text}"
        );
        assert!(SessionId::parse(&text) == Some(a));
        let upper = text.to_ascii_uppercase();
        let short = &text[..63];
        let long = format!("{text}0");
        let other = format!("{}g", &text[..63]);
        for bad in [upper.as_str(), short, long.as_str(), other.as_str(), ""] {
            assert!(SessionId::parse(bad).is_none(), "{bad}");
        }
    }

    /// A slot counts against the limit until it is used or dropped.
    #[test]
    fn a_reservation_counts_against_the_limit() {
        let table = SessionTable::new(1, Duration::from_secs(60));
        let slot = table.reserve().unwrap();
        assert!(table.reserve().is_none());
        drop(slot);
        assert!(table.reserve().is_some());
    }

    /// A request that drops before its response ends its session with the
    /// cause of a cut request. The other requests of the session see the
    /// cause. A request with its response does not end the session.
    #[test]
    fn a_request_dropped_before_its_response_ends_the_session() {
        let repo = TmpRepo::new("cut");
        let (table, id) = one_session(&repo);
        let mut done = table.lookup(&id, "anonymous").unwrap();
        done.complete();
        drop(done);
        let other = table.lookup(&id, "anonymous").unwrap();
        let cut = table.lookup(&id, "anonymous").unwrap();
        drop(cut);
        assert!(table.lookup(&id, "anonymous").is_none());
        assert_eq!(other.cancel().cause(), CUT);
        assert!(table.reserve().is_some(), "the slot is free");
    }

    /// A failed request ends its session with the cause of a failed request.
    /// If a body of the session failed, the cause is that of a cut request.
    #[test]
    fn a_failed_request_names_a_cut_body() {
        let repo = TmpRepo::new("fail");
        for (cut, cause) in [(false, FAILED), (true, CUT)] {
            let (table, id) = one_session(&repo);
            let mut active = table.lookup(&id, "anonymous").unwrap();
            let track = active.track();
            if cut {
                track.cut();
            }
            drop(track);
            table.fail(&id);
            assert_eq!(active.cancel().cause(), cause);
            active.complete();
        }
    }

    /// A second commit leaves the session to the first. The end of a commit
    /// frees the slot. If the commit succeeded, the cause is that of a
    /// commit. If the commit failed or never reached its end, as after a
    /// panic, the cause is that of a failed request.
    #[test]
    fn the_end_of_a_commit_frees_its_slot() {
        let repo = TmpRepo::new("commit");
        for (ok, cause) in [(true, COMMITTED), (false, FAILED)] {
            let (table, id) = one_session(&repo);
            let mut active = table.lookup(&id, "anonymous").unwrap();
            let Begin::Started(mut end) = active.begin_commit() else {
                panic!("the first commit starts");
            };
            assert!(matches!(active.begin_commit(), Begin::Committing));
            assert!(matches!(
                table.delete(&id, "anonymous"),
                Deleted::Committing
            ));
            assert!(table.reserve().is_none(), "the commit holds the slot");
            if ok {
                end.committed();
            }
            drop(end);
            assert_eq!(active.cancel().cause(), cause);
            assert!(matches!(active.begin_commit(), Begin::Ended));
            assert!(table.reserve().is_some(), "the slot is free");
            active.complete();
        }
    }

    /// The stop of the server leaves a session that commits: the commit
    /// goes on to its end and then frees the slot. The table takes no
    /// session after the stop.
    #[test]
    fn a_commit_outlives_the_stop_of_the_server() {
        let repo = TmpRepo::new("commit-stop");
        let (table, id) = one_session(&repo);
        let mut active = table.lookup(&id, "anonymous").unwrap();
        let Begin::Started(mut end) = active.begin_commit() else {
            panic!("the commit starts");
        };
        table.close_all();
        assert!(table.reserve().is_none());
        let request = CommitRequest {
            updates: vec![RefUpdate {
                name: "main".into(),
                expected: Expected::Absent,
                new: None,
            }],
            force: false,
            server_commit: None,
        };
        let result = block_on(active.service().commit(request));
        assert!(result.is_ok(), "{:?}", result.err());
        end.committed();
        drop(end);
        assert_eq!(active.cancel().cause(), COMMITTED);
        assert!(table.lookup(&id, "anonymous").is_none());
        assert!(table.lock().entries.is_empty());
        assert!(table.reserve().is_none());
        active.complete();
    }

    /// After the stop of the server, the table reserves no slot, and a slot
    /// reserved before the stop takes no session.
    #[test]
    fn a_stopped_table_takes_no_session() {
        let repo = TmpRepo::new("closed");
        let table = SessionTable::new(2, Duration::from_secs(60));
        let slot = table.reserve().unwrap();
        table.close_all();
        assert!(table.reserve().is_none());
        let id = SessionId::new().unwrap();
        assert!(!slot.insert(id, repo.service(), "anonymous".into()));
        assert!(table.lookup(&id, "anonymous").is_none());
        assert_eq!(table.lock().pending, 0);
    }
}