fauna-api 1.0.856

The Fauna SDK for Rust: accounts, Drive, groups, calendar, chats, payments, Parrot and live rooms.
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
//! Termite's machines, timed the way people using them see it: boots, QEMU's memory, input
//! reaching a watching seat, an animated X11 app over a slow link, and a stop and resume.

use std::collections::HashMap;
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::task::{Context as TaskContext, Poll, ready};
use std::time::{Duration, Instant};

use futures_util::StreamExt;
use futures_util::future::BoxFuture;
use serde_json::json;
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
use tokio_tungstenite::tungstenite::Message;

use super::seat::{
    self, APP_GATE, Booted, DOM_GATE, Gate, Probe, Spread, app_latency, drag_latency, exec, find,
    focus_latency, join, read, round_trip, secs, side_by_side, start_x11_app, terminal_latency,
    web_latency,
};
use super::{
    Benchmark, Phases, Run, Work, ensure, fail, gated, lock, mib, number, since, stopped, tenths,
};
use crate::authentification::CredentialsOrApiKey;
use crate::error::{Error, Result};
use crate::private::benchmarks::BenchmarkGroup;
use crate::termite::os::{AppFrame, MachineRoom};
use crate::termite::spec::{STANDARD_SPEC, Spec};

/// New repositories whose first starts are timed, for their median.
const NEW_REPOSITORIES: usize = 3;
/// The smallest machine people ask for, whose idle memory sets how many fit on a host.
const SMALL: Spec = Spec {
    vcpus: 1,
    memory_bytes: 2 << 30,
    ..STANDARD_SPEC
};
/// How long the desktop sits before its memory is read, at the stop.
const IDLE: Duration = Duration::from_secs(10);
const MARKER: &str = "/tmp/bench-marker";
/// The slow viewer's link: 20 Mbit a second, in bytes.
const SLOW_LINK_BYTES: f64 = 20_000_000.0 / 8.0;
const SLOW_LINK_MBIT: f64 = 20.0;
/// The slow viewer's receive buffer, small so the kernel doesn't stand in for the link.
const SLOW_RECEIVE_BUFFER: u32 = 64 * 1024;
/// How long the animated app streams before and while the slow viewer counts its frames.
const STREAM_WARMUP: Duration = Duration::from_secs(3);
const STREAM_FOR: Duration = Duration::from_secs(15);
/// Frames still arriving this long after the app was killed were queued on the way.
const DRAIN_LIMIT_MS: f64 = 500.0;
const STEADY_FPS: f64 = 28.5;
/// How long the slow viewer listens for frames once the app was killed.
const DRAIN_WAIT: Duration = Duration::from_secs(5);

fn machine_hours(hours: f64) -> Work {
    Work {
        machine_hours: hours,
        ..Work::default()
    }
}

/// A start's phases as measurements, `prefix` before each step's name.
fn phases(run: &Run, prefix: &str, phases: &Phases) {
    for (step, ms) in &phases.ms {
        run.measure(number(&format!("{prefix} {step}"), *ms, "ms"));
    }
}

fn booted(run: &Run, what: &str, booted: &Booted) {
    run.measure(number(&format!("{what} to running"), booted.running, "ms"));
    run.measure(number(
        &format!("{what} to the desktop"),
        booted.desktop,
        "ms",
    ));
}

// ─── Boots ───────────────────────────────────────────────────────────────────

pub(super) struct Boots;

impl Benchmark for Boots {
    fn id(&self) -> &'static str {
        "boots"
    }
    fn name(&self) -> &'static str {
        "Boots"
    }
    fn group(&self) -> BenchmarkGroup {
        BenchmarkGroup::Machines
    }
    fn about(&self) -> &'static str {
        "New repositories' first starts, to the machine running and to its desktop, and what each phase of the start took."
    }
    fn work(&self) -> Work {
        machine_hours(0.3)
    }
    fn timeout(&self) -> Duration {
        Duration::from_secs(20 * 60)
    }
    fn run<'a>(&'a self, run: &'a Run) -> BoxFuture<'a, Result<String>> {
        Box::pin(async move {
            let mut timed = Vec::with_capacity(NEW_REPOSITORIES);
            let mut last = None;
            for n in 1..=NEW_REPOSITORIES {
                run.progress(
                    (n - 1) as f64 / NEW_REPOSITORIES as f64,
                    &format!("Starting new repository {n} of {NEW_REPOSITORIES}"),
                );
                let repository = run.repository(&format!("boot {n}")).await?;
                let (room, timing) = seat::boot(&run.key, repository.id, STANDARD_SPEC).await?;
                timed.push(timing);
                let machine = room.machine();
                let _ = room.stop().await;
                last = Some(machine);
            }
            let median =
                |mark: fn(&Booted) -> f64| Spread::of(timed.iter().map(mark).collect()).p50;
            let medians = Booted {
                running: median(|timing| timing.running),
                desktop: median(|timing| timing.desktop),
            };
            booted(run, "A new repository", &medians);
            let mut how = String::from("an unknown way");
            if let Some(machine) = last {
                let start = run.phases(machine, "start").await?;
                phases(run, "Start phase", &start);
                how = start.how.unwrap_or(how);
            }
            Ok(format!(
                "New repositories ran in {:.1} s and showed their desktop in {:.1} s at the median, the last from {how}.",
                medians.running / 1000.0,
                medians.desktop / 1000.0
            ))
        })
    }
}

// ─── Memory ──────────────────────────────────────────────────────────────────

pub(super) struct Memory;

/// Boots `repository` at `spec`, lets the desktop idle and stops it: QEMU's resident memory as
/// the stop began, and the stop's phases.
async fn idle_memory(run: &Run, repository: u64, spec: Spec) -> Result<Phases> {
    let (room, _) = seat::boot(&run.key, repository, spec).await?;
    let machine = room.machine();
    tokio::time::sleep(IDLE).await;
    room.stop().await?;
    let stop = run.phases(machine, "stop").await?;
    ensure(stop.rss_bytes > 0, || {
        "Termite couldn't read the machine's memory.".into()
    })?;
    Ok(stop)
}

impl Benchmark for Memory {
    fn id(&self) -> &'static str {
        "memory"
    }
    fn name(&self) -> &'static str {
        "Memory"
    }
    fn group(&self) -> BenchmarkGroup {
        BenchmarkGroup::Machines
    }
    fn about(&self) -> &'static str {
        "QEMU's resident memory once the desktop has idled: a standard machine, the same machine resumed from its memory, and the smallest machine people ask for."
    }
    fn work(&self) -> Work {
        machine_hours(0.3)
    }
    fn timeout(&self) -> Duration {
        Duration::from_secs(20 * 60)
    }
    fn run<'a>(&'a self, run: &'a Run) -> BoxFuture<'a, Result<String>> {
        Box::pin(async move {
            run.progress(0.0, "A standard machine idling");
            let standard = run.repository("memory").await?;
            let idle = idle_memory(run, standard.id, STANDARD_SPEC).await?;
            run.measure(number("Idle", mib(idle.rss_bytes), "MiB"));
            run.measure(number("Memory snapshot", mib(idle.memory_bytes), "MiB"));
            run.progress(0.35, "The same machine resumed");
            let resumed = idle_memory(run, standard.id, STANDARD_SPEC).await?;
            run.measure(number("After a resume", mib(resumed.rss_bytes), "MiB"));
            run.progress(0.7, "The smallest machine idling");
            let small = run.repository("memory small").await?;
            let smallest = idle_memory(run, small.id, SMALL).await?;
            run.measure(number(
                "Smallest machine idle",
                mib(smallest.rss_bytes),
                "MiB",
            ));
            Ok(format!(
                "A standard machine held {} MiB idle and {} MiB after a resume; the smallest held {} MiB.",
                mib(idle.rss_bytes),
                mib(resumed.rss_bytes),
                mib(smallest.rss_bytes)
            ))
        })
    }
}

// ─── Input latency ───────────────────────────────────────────────────────────

pub(super) struct InputLatency;

/// `spread` past the round trip, held to `gate` when it has one.
fn felt(run: &Run, what: &str, spread: &Spread, rtt: f64, gate: Option<Gate>) -> Option<String> {
    let beyond = spread.beyond(rtt);
    let at = |p: &str| format!("{what} at {p}");
    match gate {
        Some(gate) => {
            let held = gate.holds(&beyond);
            run.measure(gated(
                &at("the median"),
                beyond.p50,
                "ms",
                gate.words(),
                held,
            ));
            run.measure(gated(&at("p95"), beyond.p95, "ms", gate.words(), held));
            (!held).then(|| {
                format!(
                    "{what} took {} ms at the median and {} ms at p95, past {} and {}",
                    beyond.p50, beyond.p95, gate.p50, gate.p95
                )
            })
        }
        None => {
            run.measure(number(&at("the median"), beyond.p50, "ms"));
            run.measure(number(&at("p95"), beyond.p95, "ms"));
            None
        }
    }
}

impl Benchmark for InputLatency {
    fn id(&self) -> &'static str {
        "input-latency"
    }
    fn name(&self) -> &'static str {
        "Input latency"
    }
    fn group(&self) -> BenchmarkGroup {
        BenchmarkGroup::Machines
    }
    fn about(&self) -> &'static str {
        "Input from the controlling seat reaching a second seat that watches, past the network round trip: a window taking focus, a drag, a Web tab, the terminal and an X11 app."
    }
    fn work(&self) -> Work {
        machine_hours(0.5)
    }
    fn timeout(&self) -> Duration {
        Duration::from_secs(20 * 60)
    }
    fn run<'a>(&'a self, run: &'a Run) -> BoxFuture<'a, Result<String>> {
        Box::pin(async move {
            run.progress(0.0, "Starting the machine");
            let repository = run.repository("latency").await?;
            let (room, _) = seat::boot(&run.key, repository.id, STANDARD_SPEC).await?;
            let measured = measure_latency(run, &room).await;
            let _ = room.stop().await;
            let (rtt, missed) = measured?;
            ensure(missed.is_empty(), || missed.join("; "))?;
            Ok(format!(
                "Every kind of window held its gate past a {} ms round trip.",
                rtt.p50
            ))
        })
    }
}

async fn measure_latency(run: &Run, room: &MachineRoom) -> Result<(Spread, Vec<String>)> {
    let viewer = Arc::new(Probe::new());
    let watcher = join(&run.key, room, &viewer).await?;
    let measured = async {
        run.progress(0.1, "The room's round trip");
        let rtt = round_trip(room).await?;
        run.measure(number("Round trip at the median", rtt.p50, "ms"));
        run.measure(number("Round trip at p95", rtt.p95, "ms"));
        let mut missed = Vec::new();
        run.progress(0.25, "A window taking focus");
        let [terminal, files] = side_by_side(room, &viewer).await?;
        let desktop = focus_latency(room, &viewer, [&terminal, &files]).await?;
        missed.extend(felt(run, "The desktop", &desktop, rtt.p50, Some(DOM_GATE)));
        run.progress(0.4, "A dragged window");
        let dragged = drag_latency(room, &viewer, &terminal).await?;
        felt(run, "A drag", &dragged, rtt.p50, None);
        run.progress(0.55, "Typing in the terminal");
        let typed = terminal_latency(room, &viewer, &terminal).await?;
        missed.extend(felt(run, "The terminal", &typed, rtt.p50, Some(DOM_GATE)));
        run.progress(0.7, "Typing in a Web tab");
        let web = web_latency(room, &viewer).await?;
        missed.extend(felt(run, "A Web tab", &web, rtt.p50, Some(DOM_GATE)));
        run.progress(0.85, "Typing in an X11 app");
        let app = app_latency(room, &viewer).await?;
        missed.extend(felt(run, "An X11 app", &app, rtt.p50, Some(APP_GATE)));
        Ok((rtt, missed))
    }
    .await;
    watcher.disconnect();
    measured
}

// ─── An X11 app over a slow link ─────────────────────────────────────────────

pub(super) struct AppStream;

impl Benchmark for AppStream {
    fn id(&self) -> &'static str {
        "app-stream"
    }
    fn name(&self) -> &'static str {
        "App stream"
    }
    fn group(&self) -> BenchmarkGroup {
        BenchmarkGroup::Machines
    }
    fn about(&self) -> &'static str {
        "An X11 app animating at 60 frames a second, watched over a 20 Mbit link: the frames a second it gets, how long frames keep coming once the app ends, and termited's share of a CPU."
    }
    fn work(&self) -> Work {
        machine_hours(0.3)
    }
    fn timeout(&self) -> Duration {
        Duration::from_secs(15 * 60)
    }
    fn run<'a>(&'a self, run: &'a Run) -> BoxFuture<'a, Result<String>> {
        Box::pin(async move {
            run.progress(0.0, "Starting the machine");
            let repository = run.repository("app stream").await?;
            let (room, _) = seat::boot(&run.key, repository.id, STANDARD_SPEC).await?;
            run.progress(0.3, "Streaming the animated app over a slow link");
            let streamed = app_stream(&run.key, &room).await;
            let _ = room.stop().await;
            let stream = streamed?;
            let steady = stream.fps >= STEADY_FPS;
            let drained = stream.drain_ms <= DRAIN_LIMIT_MS;
            run.measure(gated(
                "Frames a second",
                stream.fps,
                "fps",
                format!("{STEADY_FPS} or more over {SLOW_LINK_MBIT} Mbit"),
                steady,
            ));
            run.measure(gated(
                "Frames after the app ended",
                stream.drain_ms,
                "ms",
                format!("{DRAIN_LIMIT_MS} ms at most, so no queue grows"),
                drained,
            ));
            run.measure(number("Frames", stream.frames as f64, "frames"));
            run.measure(number(
                "termited's CPU",
                stream.termited_cpu_percent,
                "% of a CPU",
            ));
            ensure(steady && drained, || {
                format!(
                    "The slow viewer got {} frames a second and frames kept arriving {} ms after the app ended",
                    stream.fps, stream.drain_ms
                )
            })?;
            Ok(format!(
                "{} frames a second over {SLOW_LINK_MBIT} Mbit, the last {} ms after the app ended, with termited at {}% of a CPU.",
                stream.fps, stream.drain_ms, stream.termited_cpu_percent
            ))
        })
    }
}

struct Streamed {
    fps: f64,
    frames: usize,
    drain_ms: f64,
    termited_cpu_percent: f64,
}

/// Starts the X11 app that animates on its own, watched by a viewer reading its socket through a
/// 20 Mbit token bucket, and measures what it gets; then kills the app and times the last of
/// its frames reaching that viewer.
async fn app_stream(key: &CredentialsOrApiKey, room: &MachineRoom) -> Result<Streamed> {
    seat::find(
        || async {
            Ok(room
                .controller()
                .filter(|controller| !controller.is_empty())
                .map(|_| ()))
        },
        secs(30),
        "the owner's seat to take control",
    )
    .await?;
    let code = room.generate_access_code().await?;
    let slow = SlowViewer::join(key, &code).await?;
    start_x11_app(room, "spin").await?;
    let spin = find(
        || async { Ok(slow.windows().into_iter().next()) },
        secs(30),
        "the slow viewer to get the animated app's frames",
    )
    .await?;
    tokio::time::sleep(STREAM_WARMUP).await;
    let ticks = || {
        read(
            room,
            "cat /proc/$(pgrep -o -f termited.py)/stat | awk '{print $14 + $15}'",
        )
    };
    let parsed = |text: String| {
        text.parse::<f64>()
            .map_err(|_| Error::Message(format!("Not a number: {text}")))
    };
    let cpu_from = parsed(ticks().await?)?;
    let counted = slow.count(spin);
    let from = Instant::now();
    tokio::time::sleep(STREAM_FOR).await;
    let frames = slow.count(spin) - counted;
    let seconds = from.elapsed().as_secs_f64();
    let cpu_to = parsed(ticks().await?)?;
    let per_second = parsed(read(room, "getconf CLK_TCK").await?)?;
    exec(room, "pkill -f 'x11app.py spin'").await?;
    let killed = Instant::now();
    tokio::time::sleep(DRAIN_WAIT).await;
    let drain_ms = slow.last(spin).map_or(0.0, |at| since(killed, at));
    slow.close();
    Ok(Streamed {
        fps: tenths(frames as f64 / seconds),
        frames,
        drain_ms,
        termited_cpu_percent: tenths((cpu_to - cpu_from) / per_second / seconds * 100.0),
    })
}

/// A stream read through a token bucket, like a slow link: at most `rate` bytes a second, and a
/// tenth of a second's worth at once.
struct Throttled<S> {
    inner: S,
    rate: f64,
    tokens: f64,
    at: Instant,
    wait: Option<Pin<Box<tokio::time::Sleep>>>,
}

impl<S> Throttled<S> {
    fn new(inner: S, rate: f64) -> Throttled<S> {
        Throttled {
            inner,
            rate,
            tokens: 0.0,
            at: Instant::now(),
            wait: None,
        }
    }
}

impl<S: AsyncRead + Unpin> AsyncRead for Throttled<S> {
    fn poll_read(
        self: Pin<&mut Self>,
        cx: &mut TaskContext<'_>,
        buf: &mut ReadBuf<'_>,
    ) -> Poll<std::io::Result<()>> {
        let me = self.get_mut();
        loop {
            if let Some(wait) = me.wait.as_mut() {
                ready!(wait.as_mut().poll(cx));
                me.wait = None;
            }
            let now = Instant::now();
            me.tokens =
                (me.tokens + now.duration_since(me.at).as_secs_f64() * me.rate).min(me.rate / 10.0);
            me.at = now;
            if me.tokens >= 1.0 {
                break;
            }
            let short = Duration::from_secs_f64((1.0 - me.tokens) / me.rate);
            me.wait = Some(Box::pin(tokio::time::sleep(
                short.max(Duration::from_millis(1)),
            )));
        }
        let allowed = (me.tokens as usize).min(buf.remaining());
        let mut limited = buf.take(allowed);
        ready!(Pin::new(&mut me.inner).poll_read(cx, &mut limited))?;
        let n = limited.filled().len();
        // SAFETY: the inner stream filled these `n` bytes of `buf`'s unfilled part.
        unsafe { buf.assume_init(n) };
        buf.advance(n);
        me.tokens -= n as f64;
        Poll::Ready(Ok(()))
    }
}

impl<S: AsyncWrite + Unpin> AsyncWrite for Throttled<S> {
    fn poll_write(
        self: Pin<&mut Self>,
        cx: &mut TaskContext<'_>,
        data: &[u8],
    ) -> Poll<std::io::Result<usize>> {
        Pin::new(&mut self.get_mut().inner).poll_write(cx, data)
    }

    fn poll_flush(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<std::io::Result<()>> {
        Pin::new(&mut self.get_mut().inner).poll_flush(cx)
    }

    fn poll_shutdown(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<std::io::Result<()>> {
        Pin::new(&mut self.get_mut().inner).poll_shutdown(cx)
    }
}

/// A viewer that joined with an access code on a socket of its own, read through the slow link:
/// each X window's frames it got, and when the last came.
struct SlowViewer {
    seen: Arc<Mutex<HashMap<u32, (usize, Instant)>>>,
    reading: tokio::task::JoinHandle<()>,
}

impl SlowViewer {
    async fn join(authorization: &CredentialsOrApiKey, code: &str) -> Result<SlowViewer> {
        let base = reqwest::Url::parse(&crate::termite::get_url())
            .map_err(|err| Error::Message(err.to_string()))?;
        let host = base
            .host_str()
            .ok_or_else(|| Error::Message(format!("No host in {base}")))?
            .to_string();
        let port = base
            .port_or_known_default()
            .ok_or_else(|| Error::Message(format!("No port in {base}")))?;
        let header = match authorization {
            CredentialsOrApiKey::Credentials(credentials) => format!("Token {}", credentials.token),
            CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
        };
        let packed = json!({ "Authorization": header, "AccessCode": code }).to_string();
        let scheme = if base.scheme() == "https" {
            "wss"
        } else {
            "ws"
        };
        let url = format!(
            "{scheme}://{host}:{port}/termite/machine/live?authorization={}",
            crate::http::encode(&packed)
        );
        let address = tokio::net::lookup_host((host.as_str(), port))
            .await
            .map_err(|err| Error::Message(err.to_string()))?
            .next()
            .ok_or_else(|| Error::Message(format!("{host} has no address")))?;
        let socket = if address.is_ipv4() {
            tokio::net::TcpSocket::new_v4()
        } else {
            tokio::net::TcpSocket::new_v6()
        }
        .map_err(|err| Error::Message(err.to_string()))?;
        socket
            .set_recv_buffer_size(SLOW_RECEIVE_BUFFER)
            .map_err(|err| Error::Message(err.to_string()))?;
        let stream = socket
            .connect(address)
            .await
            .map_err(|err| Error::Message(err.to_string()))?;
        let (mut ws, _) =
            tokio_tungstenite::client_async_tls(url, Throttled::new(stream, SLOW_LINK_BYTES))
                .await?;
        let seen: Arc<Mutex<HashMap<u32, (usize, Instant)>>> = Arc::default();
        let into = seen.clone();
        let reading = tokio::spawn(async move {
            while let Some(Ok(message)) = ws.next().await {
                let Message::Binary(data) = message else {
                    continue;
                };
                if let Some(frame) = AppFrame::from_bytes(&data) {
                    let at = Instant::now();
                    let mut seen = lock(&into);
                    let entry = seen.entry(frame.window).or_insert((0, at));
                    *entry = (entry.0 + 1, at);
                }
            }
        });
        Ok(SlowViewer { seen, reading })
    }

    fn windows(&self) -> Vec<u32> {
        lock(&self.seen).keys().copied().collect()
    }

    fn count(&self, window: u32) -> usize {
        lock(&self.seen).get(&window).map_or(0, |(n, _)| *n)
    }

    fn last(&self, window: u32) -> Option<Instant> {
        lock(&self.seen).get(&window).map(|(_, at)| *at)
    }

    fn close(self) {
        self.reading.abort();
    }
}

// ─── Saving ──────────────────────────────────────────────────────────────────

pub(super) struct Saving;

impl Benchmark for Saving {
    fn id(&self) -> &'static str {
        "saving"
    }
    fn name(&self) -> &'static str {
        "Saving"
    }
    fn group(&self) -> BenchmarkGroup {
        BenchmarkGroup::Machines
    }
    fn about(&self) -> &'static str {
        "A stop that saves a revision with the machine's memory, then a resume from it: how long each took, the snapshot's size, and whether a file in memory lived through it."
    }
    fn work(&self) -> Work {
        machine_hours(0.2)
    }
    fn timeout(&self) -> Duration {
        Duration::from_secs(15 * 60)
    }
    fn run<'a>(&'a self, run: &'a Run) -> BoxFuture<'a, Result<String>> {
        Box::pin(async move {
            run.progress(0.0, "Starting the machine");
            let repository = run.repository("saving").await?;
            let (room, _) = seat::boot(&run.key, repository.id, STANDARD_SPEC).await?;
            let marker = uuid::Uuid::new_v4().simple().to_string();
            let wrote = exec(&room, &format!("echo {marker} > {MARKER}")).await?;
            if wrote.code != 0 {
                let _ = room.stop().await;
                return fail(format!("Writing the marker failed: {}", wrote.stderr));
            }
            run.progress(0.3, "Stopping, which saves the machine's memory");
            let machine = room.machine();
            let from = Instant::now();
            room.stop().await?;
            let stop_ms = since(from, Instant::now());
            run.measure(number("Stop and save", stop_ms, "ms"));
            let stop = run.phases(machine, "stop").await?;
            run.measure(number("Memory snapshot", mib(stop.memory_bytes), "MiB"));
            phases(run, "Stop phase", &stop);
            stopped(&run.key, repository.id).await?;
            run.progress(0.6, "Resuming from the snapshot");
            let (room, resume) = seat::boot(&run.key, repository.id, STANDARD_SPEC).await?;
            booted(run, "The resume", &resume);
            let start = run.phases(room.machine(), "start").await?;
            phases(run, "Resume phase", &start);
            let read = exec(&room, &format!("cat {MARKER}")).await;
            let _ = room.stop().await;
            let lived = read?.stdout.trim() == marker;
            run.measure(gated(
                "A file in /tmp lived",
                if lived { 1.0 } else { 0.0 },
                "",
                "The resume keeps what memory held".into(),
                lived,
            ));
            ensure(lived, || {
                "The file written to /tmp before the stop was gone after the resume.".into()
            })?;
            Ok(format!(
                "Saved in {:.1} s with a {} MiB memory snapshot, and resumed to the desktop in {:.1} s {}.",
                stop_ms / 1000.0,
                mib(stop.memory_bytes),
                resume.desktop / 1000.0,
                start
                    .how
                    .map_or(String::new(), |how| format!("from a {how}"))
            ))
        })
    }
}