fauna-api 1.0.859

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
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
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
//! What a seat sees of a machine, timed as its room hooks see it: the machine booting, and
//! input from the controlling seat reaching a second seat that watches. Each timing starts just
//! before the call that causes it and ends at an `Instant` taken in the room hook that saw the
//! result.

use std::collections::HashMap;
use std::future::Future;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use tokio::sync::{oneshot, watch};

use super::{fail, lock, since, tenths};
use crate::authentification::CredentialsOrApiKey;
use crate::error::{Error, Result};
use crate::marmot::web::{BootstrapMeta, WebMutation, WebNode, WebRoom, WebRoomHooks};
use crate::termite::os::{
    AppFrame, ExecOptions, ExecResult, KeyStroke, MachineOptions, MachineRoom, MachineRoomHooks,
    MachineStatus, MachineTool, StartOptions, Window, WindowApp, WindowKind,
};
use crate::termite::spec::Spec;

/// Samples in each input latency case.
const SAMPLES: usize = 20;
/// How far each move of a drag takes the window, in desktop pixels.
const DRAG_STEP: f64 = 8.0;
/// Between samples, so what one input changed is drawn before the next.
const GAP: Duration = Duration::from_millis(300);
/// How long the viewer may take to see one input's change.
const SAMPLE_WAIT: Duration = Duration::from_secs(10);
const BOOT_WAIT: Duration = Duration::from_secs(600);
/// For what opening or focusing a window draws to pass before samples start.
const SETTLE: Duration = Duration::from_secs(1);
const KEYS_PORT: u16 = 8124;
/// The X11 app's window, 480 by 360.
const APP_SIZE: (u32, u32) = (480, 360);
/// The dock in a copy of the desktop page, there once the desktop has drawn.
const DOCK: &str = r#"class="dock""#;
/// The heights of a window's title bar and a Web window's address bar, in the guest's
/// `desktop/theme.json`.
const TITLE_BAR: f64 = 34.0;
const WEB_BAR: f64 = 39.0;

/// Every key writes how many keys the page has had, and the key, into the page.
const KEYS_PAGE: &str = r#"<!doctype html><title>Keys</title><p id="out">keys ready</p><script>
let n = 0
addEventListener('keydown', (e) => { n += 1; document.getElementById('out').textContent = `key ${n} ${e.key} seen` })
</script>"#;

/// An X11 app on the guest's python3-xlib: a 480 by 360 window of colored stripes, its class
/// `x11app`. With `keys` it repaints whole in the next colors on each key press; with `spin`
/// its stripes move 60 times a second until it's killed.
const X11_APP: &str = r#"import sys, time
from Xlib import X, display

mode = sys.argv[1]
d = display.Display()
s = d.screen()
w = s.root.create_window(0, 0, 480, 360, 0, s.root_depth, X.InputOutput, X.CopyFromParent,
                         background_pixel=s.white_pixel, event_mask=X.ExposureMask | X.KeyPressMask)
w.set_wm_name("x11 app " + mode)
w.set_wm_class("x11app", "X11App")
w.map()
cmap = s.default_colormap
gcs = [w.create_gc(foreground=cmap.alloc_color(*rgb).pixel)
       for rgb in ((65535, 0, 0), (0, 40000, 0), (0, 0, 65535), (65535, 50000, 0))]
n = 0


def paint(shift):
    for band in range(-1, 9):
        w.fill_rectangle(gcs[(band + n) % 4], band * 60 + shift % 60, 0, 60, 360)
    d.flush()


paint(0)
shift = 0
while True:
    if mode == "spin":
        while d.pending_events():
            d.next_event()
        shift += 4
        paint(shift)
        time.sleep(1 / 60)
        continue
    e = d.next_event()
    if e.type == X.KeyPress:
        n += 1
    paint(shift)
"#;

/// The most input may take to show at the viewer, beyond any network round trip.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(super) struct Gate {
    pub(super) p50: f64,
    pub(super) p95: f64,
}

/// A change to the desktop's page: a window, a Web window's page, a terminal's row.
pub(super) const DOM_GATE: Gate = Gate {
    p50: 50.0,
    p95: 100.0,
};
/// An X11 app's frame.
pub(super) const APP_GATE: Gate = Gate {
    p50: 80.0,
    p95: 150.0,
};

impl Gate {
    pub(super) fn holds(&self, spread: &Spread) -> bool {
        spread.p50 <= self.p50 && spread.p95 <= self.p95
    }

    /// The gate in words.
    pub(super) fn words(&self) -> String {
        format!(
            "{} ms at the median and {} ms at p95, past the round trip",
            self.p50, self.p95
        )
    }
}

/// From just before the start call, to the machine running and to the first copy of its
/// desktop with the dock.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(super) struct Booted {
    pub(super) running: f64,
    pub(super) desktop: f64,
}

/// Nearest rank percentiles of `n` samples.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(super) struct Spread {
    pub(super) p50: f64,
    pub(super) p95: f64,
    pub(super) n: usize,
}

impl Spread {
    pub(super) fn of(mut samples: Vec<f64>) -> Spread {
        samples.sort_by(f64::total_cmp);
        let n = samples.len();
        let rank = |p: f64| samples[((p * n as f64).ceil() as usize).clamp(1, n) - 1];
        Spread {
            p50: rank(0.5),
            p95: rank(0.95),
            n,
        }
    }

    /// What's left past a network round trip of `rtt` ms, which each sample carries: the input
    /// travels up from the controlling seat and its change down to the watching one.
    pub(super) fn beyond(&self, rtt: f64) -> Spread {
        Spread {
            p50: tenths((self.p50 - rtt).max(0.0)),
            p95: tenths((self.p95 - rtt).max(0.0)),
            n: self.n,
        }
    }
}

// ─── Machine helpers ─────────────────────────────────────────────────────────

pub(super) fn secs(n: u64) -> Duration {
    Duration::from_secs(n)
}

pub(super) async fn tool(room: &MachineRoom, tool: MachineTool) -> Result<String> {
    room.invoke_tool(&tool).await
}

pub(super) async fn exec(room: &MachineRoom, command: &str) -> Result<ExecResult> {
    room.exec(command, ExecOptions::default()).await
}

/// What a command printed, trimmed.
pub(super) async fn read(room: &MachineRoom, command: &str) -> Result<String> {
    Ok(exec(room, command).await?.stdout.trim().to_string())
}

/// Polls `probe` every half second until it finds something, or fails once `timeout` passes.
pub(super) async fn find<T, F, Fut>(mut probe: F, timeout: Duration, label: &str) -> Result<T>
where
    F: FnMut() -> Fut,
    Fut: Future<Output = Result<Option<T>>>,
{
    let deadline = Instant::now() + timeout;
    loop {
        if let Some(found) = probe().await? {
            return Ok(found);
        }
        if Instant::now() > deadline {
            return fail(format!("Timed out waiting for {label}."));
        }
        tokio::time::sleep(Duration::from_millis(500)).await;
    }
}

pub(super) fn press((x, y): (f64, f64)) -> MachineTool {
    MachineTool::Press { x, y, button: None }
}

pub(super) fn release((x, y): (f64, f64)) -> MachineTool {
    MachineTool::Release { x, y, button: None }
}

/// A key going down and up, as a person types it.
pub(super) fn keyed(key: &str) -> MachineTool {
    let stroke = |down| KeyStroke {
        key: key.to_string(),
        down,
    };
    MachineTool::Keys {
        strokes: vec![stroke(true), stroke(false)],
    }
}

/// The X11 app in `mode` (`keys` or `spin`), running as the agent on the desktop.
pub(super) async fn start_x11_app(room: &MachineRoom, mode: &str) -> Result<()> {
    let started = exec(
        room,
        &format!(
            "echo {} | base64 -d > /tmp/x11app.py && (DISPLAY=:0 nohup python3 /tmp/x11app.py {mode} >/dev/null 2>&1 &)",
            STANDARD.encode(X11_APP)
        ),
    )
    .await?;
    if started.code != 0 {
        return fail(format!("The X11 app didn't start: {}", started.stderr));
    }
    Ok(())
}

/// Where an app window's X window starts on the desktop: inside the window's 1 pixel border,
/// below its title bar.
fn app_origin(window: &Window) -> (f64, f64) {
    (window.x + 1.0, window.y + 1.0 + TITLE_BAR)
}

/// Where a Web window's page starts on the desktop: inside the window's 1 pixel border, below
/// its title bar and address bar.
fn page_origin(window: &Window) -> (f64, f64) {
    (window.x + 1.0, window.y + 1.0 + TITLE_BAR + WEB_BAR)
}

// ─── Boots and seats ─────────────────────────────────────────────────────────

/// Starts `repository`'s machine at `spec` and times its boot. Stops it again when it doesn't
/// get there.
pub(super) async fn boot(
    authorization: &CredentialsOrApiKey,
    repository: u64,
    spec: Spec,
) -> Result<(MachineRoom, Booted)> {
    let probe = Arc::new(Probe::new());
    let options = StartOptions {
        spec,
        group: None,
        hooks: Some(Arc::new(Seat(probe.clone()))),
        private: None,
    };
    let from = Instant::now();
    let (room, _) = MachineRoom::start(authorization, repository, options).await?;
    // A room that connects to a machine already running hears no change of status.
    if room.status() == MachineStatus::Running {
        probe
            .marks
            .send_if_modified(|marks| first(&mut marks.running, Instant::now()));
    }
    match probe.booted(&room, from).await {
        Ok(timed) => Ok((room, timed)),
        Err(err) => {
            // A machine that ended has closed its room, so a stop would only wait out its timeout.
            if !matches!(
                room.status(),
                MachineStatus::Stopped | MachineStatus::Failed
            ) {
                let _ = room.stop().await;
            }
            Err(err)
        }
    }
}

/// A second seat for `authorization`, which joined with an access code the owner minted, so it
/// only watches.
pub(super) async fn join(
    authorization: &CredentialsOrApiKey,
    room: &MachineRoom,
    viewer: &Arc<Probe>,
) -> Result<MachineRoom> {
    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 options = MachineOptions {
        hooks: Some(Arc::new(Seat(viewer.clone()))),
        ..MachineOptions::default()
    };
    Ok(MachineRoom::join(authorization, &code, options).await?.0)
}

/// The room socket's round trip: the windows tool, which Termite answers from what it holds
/// without asking the guest.
pub(super) async fn round_trip(room: &MachineRoom) -> Result<Spread> {
    sampled(move |_| async move {
        let sent = Instant::now();
        tool(room, MachineTool::Windows).await?;
        Ok(since(sent, Instant::now()))
    })
    .await
}

/// A terminal and a files window side by side, so neither covers the other's title bar, once
/// the viewer has seen both open.
pub(super) async fn side_by_side(room: &MachineRoom, viewer: &Probe) -> Result<[Window; 2]> {
    let terminal = Window::from_json(&serde_json::from_str(
        &tool(room, open(WindowApp::Terminal, None)).await?,
    )?);
    tool(room, open(WindowApp::Files, Some("/"))).await?;
    let files = find(
        || async {
            Ok(room
                .windows()
                .into_values()
                .find(|w| w.kind == WindowKind::Files))
        },
        secs(30),
        "a files window",
    )
    .await?;
    let windows = [
        arrange(room, terminal.id, 32.0).await?,
        arrange(room, files.id, 704.0).await?,
    ];
    for window in &windows {
        find(
            || async { Ok(viewer.section(window.id)) },
            secs(30),
            "the viewer to see the window open",
        )
        .await?;
    }
    Ok(windows)
}

fn open(app: WindowApp, path: Option<&str>) -> MachineTool {
    MachineTool::Open {
        app,
        url: None,
        path: path.map(str::to_string),
        command: None,
    }
}

/// Sizes a window to 640 by 400 and puts it at (`x`, 48), and returns it as it ended up.
async fn arrange(room: &MachineRoom, id: u64, x: f64) -> Result<Window> {
    let window = id as f64;
    let resize = MachineTool::Resize {
        window,
        width: 640.0,
        height: 400.0,
    };
    tool(room, resize).await?;
    let place = MachineTool::Place { window, x, y: 48.0 };
    tool(room, place).await?;
    room.windows()
        .remove(&id)
        .ok_or_else(|| Error::Message(format!("Window {id} closed.")))
}

/// A point on a window's title bar, clear of its icon and buttons.
fn title_bar(window: &Window) -> (f64, f64) {
    (window.x + window.width / 2.0, window.y + 12.0)
}

fn unseen(window: &Window) -> Error {
    Error::Message(format!("The viewer never saw window {} open.", window.id))
}

/// Presses on the title bar of whichever of the two windows isn't focused, until the viewer
/// sees that window's element take the `focused` class, then lets go.
pub(super) async fn focus_latency(
    room: &MachineRoom,
    viewer: &Probe,
    pair: [&Window; 2],
) -> Result<Spread> {
    let section = |window: &Window| viewer.section(window.id).ok_or_else(|| unseen(window));
    let sections = [section(pair[0])?, section(pair[1])?];
    let start = usize::from(room.windows().get(&pair[0].id).is_some_and(|w| w.focused));
    sampled(move |i| {
        let next = (start + i) % 2;
        let node = sections[next];
        let bar = title_bar(pair[next]);
        async move {
            let pressed = latency(room, viewer, press(bar), move |m| focuses(m, node)).await;
            tool(room, release(bar)).await?;
            pressed
        }
    })
    .await
}

/// Holds a window's title bar and moves the pointer right `DRAG_STEP` at a time, each move
/// timed until the viewer's copy of the window sits where it put it, then lets go.
pub(super) async fn drag_latency(
    room: &MachineRoom,
    viewer: &Probe,
    window: &Window,
) -> Result<Spread> {
    let node = viewer.section(window.id).ok_or_else(|| unseen(window))?;
    let left = room.windows().get(&window.id).map_or(window.x, |w| w.x);
    let (x, y) = title_bar(window);
    tool(room, press((x, y))).await?;
    let dragged = sampled(move |i| {
        let step = DRAG_STEP * (i + 1) as f64;
        let moved = MachineTool::Pointer { x: x + step, y };
        latency(room, viewer, moved, move |m| placed(m, node, left + step))
    })
    .await;
    tool(room, release((x + DRAG_STEP * SAMPLES as f64, y))).await?;
    dragged
}

/// Types into the focused terminal at its prompt, after a `#`, until the viewer's copy of the
/// prompt's row holds the key as text: `#q`, then `#qq`, and so on.
pub(super) async fn terminal_latency(
    room: &MachineRoom,
    viewer: &Probe,
    terminal: &Window,
) -> Result<Spread> {
    let focus = MachineTool::Focus {
        window: terminal.id as f64,
    };
    tool(room, focus).await?;
    tool(room, keyed("#")).await?;
    tokio::time::sleep(SETTLE).await;
    sampled(move |i| {
        let seen = format!("#{}", "q".repeat(i + 1));
        latency(room, viewer, keyed("q"), move |m| shows(m, &seen))
    })
    .await
}

/// Types into a page the guest serves in a Web window, until the page's change reaches the
/// viewer's copy of it: the key goes straight to the window's tab, and the tab's own DOM is
/// stitched into the desktop's stream.
pub(super) async fn web_latency(room: &MachineRoom, viewer: &Probe) -> Result<Spread> {
    let served = exec(
        room,
        &format!(
            "mkdir -p /tmp/keys && echo {} | base64 -d > /tmp/keys/index.html && (cd /tmp/keys && nohup python3 -m http.server {KEYS_PORT} >/dev/null 2>&1 &) && curl -s -o /dev/null --retry 20 --retry-connrefused --retry-delay 1 http://127.0.0.1:{KEYS_PORT}/",
            STANDARD.encode(KEYS_PAGE)
        ),
    )
    .await?;
    if served.code != 0 {
        return fail(format!("The page's server didn't start: {}", served.stderr));
    }
    let open = MachineTool::Open {
        app: WindowApp::Web,
        url: Some(format!("http://localhost:{KEYS_PORT}/")),
        path: None,
        command: None,
    };
    let window = Window::from_json(&serde_json::from_str(&tool(room, open).await?)?);
    if window.title != "Keys" {
        return fail(format!(
            "The page didn't load: its window says {}.",
            window.title
        ));
    }
    tokio::time::sleep(SETTLE).await;
    let (left, top) = page_origin(&window);
    let page = (left + window.width / 2.0, top + window.height / 2.0);
    tool(room, press(page)).await?;
    tool(room, release(page)).await?;
    tokio::time::sleep(GAP).await;
    sampled(move |i| {
        let seen = format!("key {} k seen", i + 1);
        latency(room, viewer, keyed("k"), move |m| shows(m, &seen))
    })
    .await
}

/// Opens the X11 app that repaints on each key, focuses it, and types into it, each key timed
/// until the viewer gets the app frame of its repaint.
pub(super) async fn app_latency(room: &MachineRoom, viewer: &Probe) -> Result<Spread> {
    start_x11_app(room, "keys").await?;
    let window = find(
        || async { Ok(room.windows().into_values().find(|w| w.app == "x11app")) },
        secs(30),
        "the X11 app's window",
    )
    .await?;
    let xid = find(
        || async { Ok(viewer.app_windows().into_iter().next()) },
        secs(30),
        "the viewer to get the X11 app's frames",
    )
    .await?;
    let (left, top) = app_origin(&window);
    let point = (left + 40.0, top + 40.0);
    tool(room, press(point)).await?;
    tool(room, release(point)).await?;
    tokio::time::sleep(SETTLE).await;
    sampled(move |_| async move {
        let key = keyed("k");
        let arrived = viewer.awaits_frame(xid);
        let sent = Instant::now();
        let (done, arrived) = tokio::join!(
            room.invoke_tool(&key),
            tokio::time::timeout(SAMPLE_WAIT, arrived)
        );
        done?;
        let at = arrived
            .map_err(|_| {
                Error::Message(format!(
                    "The viewer got no frame within {} s.",
                    SAMPLE_WAIT.as_secs()
                ))
            })?
            .map_err(|_| Error::Message("The viewer went away.".into()))?;
        Ok(since(sent, at))
    })
    .await
}

/// Whether a change gives node `node` the `focused` class.
fn focuses(mutation: &WebMutation, node: u64) -> bool {
    matches!(
        mutation,
        WebMutation::Attribute { id, name, value: Some(value) }
            if *id == node && name == "class" && value.split_whitespace().any(|class| class == "focused")
    )
}

/// Whether a change puts window element `node` `left` pixels from the desktop's left edge.
fn placed(mutation: &WebMutation, node: u64, left: f64) -> bool {
    let at = format!("left: {left}px;");
    matches!(
        mutation,
        WebMutation::Attribute { id, name, value: Some(value) }
            if *id == node && name == "style" && value.contains(&at)
    )
}

/// Whether a change carries `text`.
fn shows(mutation: &WebMutation, text: &str) -> bool {
    serde_json::to_string(mutation).is_ok_and(|json| json.contains(text))
}

/// `SAMPLES` latencies, `GAP` apart.
async fn sampled<F>(mut sample: impl FnMut(usize) -> F) -> Result<Spread>
where
    F: Future<Output = Result<f64>>,
{
    let mut samples = Vec::with_capacity(SAMPLES);
    for i in 0..SAMPLES {
        samples.push(sample(i).await?);
        tokio::time::sleep(GAP).await;
    }
    Ok(Spread::of(samples))
}

/// How long `input` from the controlling seat takes to reach the viewer as a change `shows`
/// matches.
async fn latency(
    room: &MachineRoom,
    viewer: &Probe,
    input: MachineTool,
    shows: impl Fn(&WebMutation) -> bool + Send + 'static,
) -> Result<f64> {
    let arrived = viewer.awaits(shows);
    let sent = Instant::now();
    let (done, arrived) = tokio::join!(
        room.invoke_tool(&input),
        tokio::time::timeout(SAMPLE_WAIT, arrived)
    );
    done?;
    let at = arrived
        .map_err(|_| {
            Error::Message(format!(
                "The viewer saw nothing within {} s.",
                SAMPLE_WAIT.as_secs()
            ))
        })?
        .map_err(|_| Error::Message("The viewer went away.".into()))?;
    Ok(since(sent, at))
}

// ─── What a seat sees ────────────────────────────────────────────────────────

/// One seat's view of the machine, each event timed as its hook sees it: how far the boot got,
/// which element is each window, and the one change a measurement waits for.
pub(super) struct Probe {
    marks: watch::Sender<Marks>,
    /// Each window's `<section>`, by window id.
    sections: Mutex<HashMap<u64, u64>>,
    awaited: Mutex<Option<Awaited>>,
    /// The X windows of the X11 app's size it got app frames of, in the order it first did.
    apps: Mutex<Vec<u32>>,
    /// The next app frame of a window a measurement waits for.
    awaited_frame: Mutex<Option<(u32, oneshot::Sender<Instant>)>>,
}

#[derive(Clone, Copy, Default)]
struct Marks {
    running: Option<Instant>,
    desktop: Option<Instant>,
    /// The machine stopped or failed.
    ended: bool,
}

impl Marks {
    fn done(&self) -> bool {
        self.ended || (self.running.is_some() && self.desktop.is_some())
    }
}

struct Awaited {
    wants: Box<dyn Fn(&WebMutation) -> bool + Send>,
    seen: oneshot::Sender<Instant>,
}

/// Keeps the first time something happened. Whether this was it.
fn first(slot: &mut Option<Instant>, at: Instant) -> bool {
    let first = slot.is_none();
    if first {
        *slot = Some(at);
    }
    first
}

impl Probe {
    pub(super) fn new() -> Probe {
        Probe {
            marks: watch::Sender::new(Marks::default()),
            sections: Mutex::new(HashMap::new()),
            awaited: Mutex::new(None),
            apps: Mutex::default(),
            awaited_frame: Mutex::default(),
        }
    }

    fn app_windows(&self) -> Vec<u32> {
        lock(&self.apps).clone()
    }

    /// When the next app frame of X window `window` arrives, from now on.
    fn awaits_frame(&self, window: u32) -> oneshot::Receiver<Instant> {
        let (seen, arrived) = oneshot::channel();
        *lock(&self.awaited_frame) = Some((window, seen));
        arrived
    }

    fn on_app_frame(&self, frame: &AppFrame) {
        let at = Instant::now();
        if (frame.window_width, frame.window_height) == APP_SIZE {
            let mut apps = lock(&self.apps);
            if !apps.contains(&frame.window) {
                apps.push(frame.window);
            }
        }
        let mut awaited = lock(&self.awaited_frame);
        if awaited
            .as_ref()
            .is_some_and(|(window, _)| *window == frame.window)
            && let Some((_, seen)) = awaited.take()
        {
            let _ = seen.send(at);
        }
    }

    fn section(&self, window: u64) -> Option<u64> {
        lock(&self.sections).get(&window).copied()
    }

    /// When the next change `wants` matches arrives, from now on.
    fn awaits(
        &self,
        wants: impl Fn(&WebMutation) -> bool + Send + 'static,
    ) -> oneshot::Receiver<Instant> {
        let (seen, arrived) = oneshot::channel();
        *lock(&self.awaited) = Some(Awaited {
            wants: Box::new(wants),
            seen,
        });
        arrived
    }

    /// The boot from `from`, once the machine runs and the desktop has drawn.
    async fn booted(&self, room: &MachineRoom, from: Instant) -> Result<Booted> {
        let mut seen = self.marks.subscribe();
        let waited = tokio::time::timeout(BOOT_WAIT, seen.wait_for(Marks::done)).await;
        let marks = *waited
            .map_err(|_| Error::Message("Timed out waiting for the machine to boot.".into()))?
            .map_err(|_| Error::Message("The machine's room went away.".into()))?;
        match (marks.running, marks.desktop) {
            (Some(running), Some(desktop)) if !marks.ended => Ok(Booted {
                running: since(from, running),
                desktop: since(from, desktop),
            }),
            _ => fail(format!(
                "The machine ended while booting ({:?}) {}",
                room.status(),
                room.error()
            )),
        }
    }
}

impl WebRoomHooks for Probe {
    fn on_bootstrap(&self, _room: &WebRoom, bootstrap: &BootstrapMeta) {
        let at = Instant::now();
        if bootstrap
            .html
            .as_deref()
            .is_some_and(|html| html.contains(DOCK))
        {
            self.marks
                .send_if_modified(|marks| first(&mut marks.desktop, at));
        }
    }

    fn on_mutation(&self, _room: &WebRoom, mutation: &WebMutation) {
        let at = Instant::now();
        if let WebMutation::Insert { node, subtree, .. } = mutation {
            let mut sections = lock(&self.sections);
            for node in std::iter::once(node).chain(subtree) {
                if let WebNode::Element {
                    id,
                    tag,
                    attributes,
                    ..
                } = node
                    && tag.eq_ignore_ascii_case("section")
                    && let Some(window) = attributes.get("data-window").and_then(|w| w.parse().ok())
                {
                    sections.insert(window, *id);
                }
            }
        }
        let mut awaited = lock(&self.awaited);
        if awaited
            .as_ref()
            .is_some_and(|awaited| (awaited.wants)(mutation))
            && let Some(awaited) = awaited.take()
        {
            let _ = awaited.seen.send(at);
        }
    }
}

/// A probe as a seat's room hooks.
pub(super) struct Seat(pub(super) Arc<Probe>);

impl MachineRoomHooks for Seat {
    fn web(&self) -> Option<Arc<dyn WebRoomHooks>> {
        Some(self.0.clone())
    }

    fn on_app_frame(&self, _room: &MachineRoom, frame: &AppFrame) {
        self.0.on_app_frame(frame);
    }

    fn on_status(&self, room: &MachineRoom) {
        let at = Instant::now();
        let marks = &self.0.marks;
        match room.status() {
            MachineStatus::Running => {
                marks.send_if_modified(|marks| first(&mut marks.running, at));
            }
            MachineStatus::Stopped | MachineStatus::Failed => {
                marks.send_if_modified(|marks| !std::mem::replace(&mut marks.ended, true));
            }
            MachineStatus::Booting | MachineStatus::Stopping => {}
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn takes_nearest_rank_percentiles() {
        let samples: Vec<f64> = (1..=20).rev().map(f64::from).collect();
        assert_eq!(
            Spread::of(samples),
            Spread {
                p50: 10.0,
                p95: 19.0,
                n: 20
            }
        );
        assert_eq!(
            Spread::of(vec![7.5]),
            Spread {
                p50: 7.5,
                p95: 7.5,
                n: 1
            }
        );
    }

    #[test]
    fn takes_the_round_trip_off_and_holds_it_to_its_gate() {
        let felt = Spread {
            p50: 92.4,
            p95: 140.0,
            n: 20,
        };
        let beyond = felt.beyond(41.3);
        assert_eq!(
            beyond,
            Spread {
                p50: 51.1,
                p95: 98.7,
                n: 20
            }
        );
        assert_eq!(felt.beyond(200.0).p95, 0.0);
        assert!(!DOM_GATE.holds(&beyond));
        assert!(APP_GATE.holds(&beyond));
        assert!(!APP_GATE.holds(&Spread {
            p50: 40.0,
            p95: 151.0,
            n: 20,
        }));
    }

    #[test]
    fn knows_a_window_taking_focus_a_key_reaching_a_row_and_a_drag_landing() {
        let attribute = |id, name: &str, value: &str| WebMutation::Attribute {
            id,
            name: name.into(),
            value: Some(value.into()),
        };
        assert!(focuses(&attribute(7, "class", "window focused"), 7));
        assert!(!focuses(&attribute(7, "class", "window"), 7));
        assert!(!focuses(&attribute(8, "class", "window focused"), 7));
        let row = WebMutation::Text {
            id: 4,
            text: "agent@machine:/repository$ #qq".into(),
        };
        assert!(shows(&row, "#qq") && !shows(&row, "#qqq") && !focuses(&row, 4));
        let moved = attribute(7, "style", "left: 40px; top: 48px; width: 640px;");
        assert!(placed(&moved, 7, 40.0));
        assert!(!placed(&moved, 7, 4.0));
        assert!(!placed(&moved, 8, 40.0));
    }
}