pointblitz-io 0.3.0

PLY stream parser and GPU-ready chunk format for PointBlitz
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
//! Replay-server client: SSE events and chunk deliveries over plain HTTP/1.1 (std only). Shared by
//! the native viewer and the video server (P3.2); not built for wasm (the browser uses fetch).
//!
//! Two threads, so a delivery in progress never delays the timestamp of the next event:
//! - the event thread reads `/events` and stamps each snapshot the moment its line arrives;
//! - the fetch thread takes snapshots in order and streams `/chunks/<seq>`, forwarding every chunk
//!   as soon as its bytes are complete (decision 0026) — or, with a local data directory (decision
//!   0050), reads the snapshot's PLY there and converts it in this process, without HTTP.
//!
//! A replay server of a slot diff stream (decision 0052) announces `slots` events instead; follow it
//! with [`spawn_slots`] / [`spawn_slots_cold`], which hand over each event's message whole.

use crate::chunk::{FLAG_LAST_IN_GENERATION, HEADER_LEN, MAGIC, decode_header};
use std::io::{BufRead, BufReader, Read, Write};
use std::net::TcpStream;
use std::path::PathBuf;
use std::sync::mpsc;
use std::time::Instant;

#[derive(Debug, Clone)]
pub struct Snapshot {
    pub seq: u32,
    pub kind: String,
    pub points: usize,
}

/// Messages to the window thread.
#[derive(Debug)]
pub enum Msg {
    Received {
        snap: Snapshot,
        at: Instant,
    },
    Chunk {
        seq: u32,
        bytes: Vec<u8>,
        last: bool,
        /// When the chunk's last byte arrived.
        at: Instant,
    },
    Delivered {
        seq: u32,
        delivery: String,
        generation: u32,
        bytes: u64,
        fetch_start: Instant,
        /// Response headers received: the server has read the snapshot and starts converting.
        headers_at: Instant,
    },
    End,
    Error(String),
}

/// `http://127.0.0.1:8700` → `127.0.0.1:8700`.
pub fn host_port(url: &str) -> Result<String, String> {
    let rest = url
        .strip_prefix("http://")
        .ok_or("server URL must start with http://")?;
    Ok(rest.trim_end_matches('/').to_string())
}

type Headers = Vec<(String, String)>;

/// Sends a GET and returns the response headers (lower-case names) and the body reader.
pub fn get(host: &str, path: &str) -> std::io::Result<(Headers, BufReader<TcpStream>)> {
    let mut stream = TcpStream::connect(host)?;
    stream.set_nodelay(true)?;
    write!(
        stream,
        "GET {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n\r\n"
    )?;
    stream.flush()?;
    let mut r = BufReader::with_capacity(1 << 20, stream);
    let mut line = String::new();
    r.read_line(&mut line)?;
    if line.split_whitespace().nth(1) != Some("200") {
        return Err(std::io::Error::other(format!(
            "GET {path}: {}",
            line.trim_end()
        )));
    }
    let mut headers = Vec::new();
    loop {
        line.clear();
        if r.read_line(&mut line)? <= 2 {
            break;
        }
        if let Some((k, v)) = line.split_once(':') {
            headers.push((k.trim().to_ascii_lowercase(), v.trim().to_string()));
        }
    }
    Ok((headers, r))
}

fn header<'a>(h: &'a [(String, String)], name: &str) -> Option<&'a str> {
    h.iter().find(|(k, _)| k == name).map(|(_, v)| v.as_str())
}

pub fn parse_snapshot(json: &str) -> Option<Snapshot> {
    let v: serde_json::Value = serde_json::from_str(json).ok()?;
    Some(Snapshot {
        seq: u32::try_from(v["seq"].as_u64()?).ok()?,
        kind: v["kind"].as_str()?.to_string(),
        points: usize::try_from(v["points"].as_u64()?).ok()?,
    })
}

/// Reads one chunk (header, then body) from a delivery stream; None at a clean end of stream.
pub fn read_chunk(r: &mut impl Read) -> std::io::Result<Option<Vec<u8>>> {
    let mut buf = vec![0u8; HEADER_LEN];
    let mut got = 0;
    while got < HEADER_LEN {
        match r.read(&mut buf[got..])? {
            0 if got == 0 => return Ok(None),
            0 => return Err(std::io::ErrorKind::UnexpectedEof.into()),
            n => got += n,
        }
    }
    // point_count sits at bytes 16..20 and the point stride at 72..74 (decisions 0022, 0051); the
    // whole chunk is validated once read.
    if buf[..4] != MAGIC {
        return Err(std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            "not a chunk",
        ));
    }
    let n = u32::from_le_bytes([buf[16], buf[17], buf[18], buf[19]]) as usize;
    let stride = usize::from(u16::from_le_bytes([buf[72], buf[73]]));
    if !crate::chunk::STRIDES.contains(&stride) {
        return Err(std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            format!("point stride {stride}"),
        ));
    }
    buf.resize(HEADER_LEN + n * stride, 0);
    r.read_exact(&mut buf[HEADER_LEN..])?;
    decode_header(&buf).map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
    Ok(Some(buf))
}

/// Streams one snapshot's chunks to `send`. Returns (delivery kind, generation, bytes, when the
/// response headers arrived).
fn fetch(
    host: &str,
    seq: u32,
    have: Option<(u32, usize)>,
    send: &impl Fn(Msg),
) -> std::io::Result<(String, u32, u64, Instant)> {
    let path = match have {
        Some((g, n)) => format!("/chunks/{seq}?have={g}.{n}"),
        None => format!("/chunks/{seq}"),
    };
    let (headers, mut r) = get(host, &path)?;
    let headers_at = Instant::now();
    let delivery = header(&headers, "x-pb-delivery").unwrap_or("?").to_string();
    let generation = header(&headers, "x-pb-generation")
        .and_then(|g| g.parse().ok())
        .unwrap_or(0);
    let mut bytes = 0u64;
    while let Some(c) = read_chunk(&mut r)? {
        bytes += c.len() as u64;
        let last = decode_header(&c).map(|h| h.flags & FLAG_LAST_IN_GENERATION != 0) == Ok(true);
        send(Msg::Chunk {
            seq,
            bytes: c,
            last,
            at: Instant::now(),
        });
        if last {
            break;
        }
    }
    Ok((delivery, generation, bytes, headers_at))
}

/// Takes snapshots in arrival order and fetches each one; `have` tracks what the client holds.
/// Where the fetch thread gets a snapshot's chunks from.
enum Source {
    /// `/chunks/<seq>` of the replay server.
    Http,
    /// The PLY in a local directory, converted here (decision 0050).
    Local(Local),
}

/// What converting locally needs from the replay server's manifest.
struct Local {
    dir: PathBuf,
    steps: Vec<crate::convert::Step>,
    files: Vec<String>,
    appends: Vec<bool>,
}

impl Local {
    fn load(host: &str, dir: PathBuf) -> std::io::Result<Self> {
        let (_, mut r) = get(host, "/manifest.json")?;
        let mut text = String::new();
        r.read_to_string(&mut text)?;
        let bad =
            |what: &str| std::io::Error::new(std::io::ErrorKind::InvalidData, what.to_string());
        let v: serde_json::Value = serde_json::from_str(&text)
            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
        let events = v["events"]
            .as_array()
            .ok_or_else(|| bad("manifest without events"))?;
        let mut local = Self {
            dir,
            steps: Vec::new(),
            files: Vec::new(),
            appends: Vec::new(),
        };
        for e in events {
            let snap = parse_snapshot(&e.to_string()).ok_or_else(|| bad("bad manifest event"))?;
            local.steps.push(crate::convert::Step {
                seq: snap.seq,
                preview: snap.kind == "preview",
                points: snap.points,
            });
            local.files.push(
                e["file"]
                    .as_str()
                    .ok_or_else(|| bad("event without file"))?
                    .to_string(),
            );
            // Older replay servers do not say; then every preview is delivered whole.
            local.appends.push(e["appends"].as_bool().unwrap_or(false));
        }
        Ok(local)
    }

    /// Converts the delivery for `seq` (same plan as the replay server) and forwards its chunks as
    /// each is encoded. Returns (delivery, generation, bytes, conversion started).
    fn fetch(
        &self,
        seq: u32,
        have: Option<(u32, usize)>,
        send: &impl Fn(Msg),
    ) -> std::io::Result<(String, u32, u64, Instant)> {
        use crate::convert::{Conversion, Plan, plan};
        let idx = self
            .steps
            .iter()
            .position(|s| s.seq == seq)
            .ok_or_else(|| std::io::Error::other(format!("snapshot {seq} not in the manifest")))?;
        let (generation, skip, delivery) = match plan(&self.steps, idx, have, |k| self.appends[k]) {
            Plan::Full { generation } => (generation, 0, "full"),
            Plan::Delta { generation, skip } => (generation, skip, "delta"),
        };
        let started = Instant::now();
        let c = Conversion::start(self.dir.join(&self.files[idx]), skip, generation);
        let n = c.len().map_err(std::io::Error::other)?;
        let mut bytes = 0u64;
        for i in 0..n {
            let chunk = c.take(i).map_err(std::io::Error::other)?;
            bytes += chunk.len() as u64;
            send(Msg::Chunk {
                seq,
                bytes: chunk,
                last: i + 1 == n,
                at: Instant::now(),
            });
        }
        Ok((delivery.to_string(), generation, bytes, started))
    }
}

fn fetch_loop(host: &str, source: &Source, rx: mpsc::Receiver<Snapshot>, send: &impl Fn(Msg)) {
    let mut have: Option<(u32, usize)> = None;
    for snap in rx {
        let fetch_start = Instant::now();
        let got = match source {
            Source::Http => fetch(host, snap.seq, have, send),
            Source::Local(local) => local.fetch(snap.seq, have, send),
        };
        match got {
            Ok((delivery, generation, bytes, headers_at)) => {
                have = Some((generation, snap.points));
                send(Msg::Delivered {
                    seq: snap.seq,
                    delivery,
                    generation,
                    bytes,
                    fetch_start,
                    headers_at,
                });
            }
            Err(e) => {
                send(Msg::Error(format!("snapshot {}: {e}", snap.seq)));
                have = None; // next delivery is full
            }
        }
    }
    send(Msg::End);
}

/// Replay: follows `/events?speed=…`.
pub fn spawn_replay(host: String, speed: f64, send: impl Fn(Msg) + Send + Sync + 'static) {
    follow(host, None, speed, send);
}

/// Like [`spawn_replay`], but snapshots are read from `dir` (the replay server's data directory on
/// this machine) and converted in this process instead of fetched over HTTP (decision 0050).
pub fn spawn_replay_local(
    host: String,
    dir: PathBuf,
    speed: f64,
    send: impl Fn(Msg) + Send + Sync + 'static,
) {
    follow(host, Some(dir), speed, send);
}

fn source(host: &str, dir: Option<PathBuf>) -> std::io::Result<Source> {
    Ok(match dir {
        Some(dir) => Source::Local(Local::load(host, dir)?),
        None => Source::Http,
    })
}

fn follow(
    host: String,
    dir: Option<PathBuf>,
    speed: f64,
    send: impl Fn(Msg) + Send + Sync + 'static,
) {
    let send = std::sync::Arc::new(send);
    let src = match source(&host, dir) {
        Ok(src) => src,
        Err(e) => {
            send(Msg::Error(format!("manifest: {e}")));
            send(Msg::End);
            return;
        }
    };
    let (tx, rx) = mpsc::channel::<Snapshot>();
    let (h2, s2) = (host.clone(), send.clone());
    std::thread::spawn(move || fetch_loop(&h2, &src, rx, &|m| s2(m)));
    std::thread::spawn(move || {
        let run = || -> std::io::Result<()> {
            let (_, r) = get(&host, &format!("/events?speed={speed}"))?;
            let mut event = String::new();
            for line in r.lines() {
                let line = line?;
                let at = Instant::now();
                if let Some(e) = line.strip_prefix("event: ") {
                    event = e.to_string();
                } else if let Some(data) = line.strip_prefix("data: ") {
                    match event.as_str() {
                        "snapshot" => {
                            if let Some(snap) = parse_snapshot(data) {
                                send(Msg::Received {
                                    snap: snap.clone(),
                                    at,
                                });
                                let _ = tx.send(snap);
                            }
                        }
                        "end" => return Ok(()),
                        _ => {}
                    }
                }
            }
            Ok(())
        };
        if let Err(e) = run() {
            send(Msg::Error(format!("events: {e}")));
        }
        // Dropping tx ends the fetch loop, which sends End after the last delivery.
    });
}

/// Cold start: only the last snapshot of the manifest, as one full delivery.
pub fn spawn_cold(host: String, send: impl Fn(Msg) + Send + Sync + 'static) {
    cold(host, None, send);
}

/// Like [`spawn_cold`], reading the snapshot from `dir` (decision 0050).
pub fn spawn_cold_local(host: String, dir: PathBuf, send: impl Fn(Msg) + Send + Sync + 'static) {
    cold(host, Some(dir), send);
}

fn cold(host: String, dir: Option<PathBuf>, send: impl Fn(Msg) + Send + Sync + 'static) {
    std::thread::spawn(move || {
        let run = || -> std::io::Result<()> {
            let src = source(&host, dir.clone())?;
            let (_, mut r) = get(&host, "/manifest.json")?;
            let mut text = String::new();
            r.read_to_string(&mut text)?;
            let v: serde_json::Value = serde_json::from_str(&text)
                .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
            let last = v["events"]
                .as_array()
                .and_then(|a| a.last())
                .and_then(|e| parse_snapshot(&e.to_string()))
                .ok_or_else(|| std::io::Error::other("empty manifest"))?;
            send(Msg::Received {
                snap: last.clone(),
                at: Instant::now(),
            });
            let (tx, rx) = mpsc::channel();
            tx.send(last).ok();
            drop(tx);
            fetch_loop(&host, &src, rx, &send);
            Ok(())
        };
        if let Err(e) = run() {
            send(Msg::Error(format!("cold: {e}")));
            send(Msg::End);
        }
    });
}

// ---- Slot diff streams (decision 0052) --------------------------------------------------------

/// One event of a slot stream, as announced (`event: slots` on `/events`).
#[derive(Debug, Clone)]
pub struct SlotEvent {
    pub seq: u32,
    pub kind: String,
    /// Points shown after the event.
    pub points: u64,
    /// Pack bytes (the message is 32 B more).
    pub bytes: u64,
}

/// Messages of a slot stream follower to the window thread.
#[derive(Debug)]
pub enum SlotMsg {
    Received {
        event: SlotEvent,
        at: Instant,
    },
    /// An event's message is complete.
    Message {
        seq: u32,
        bytes: Vec<u8>,
        /// A folded state through `seq` (cold start, or the fallback after an event could not be
        /// fetched): clear the scene and apply it (`SlotScene::apply_state`).
        state: bool,
        fetch_start: Instant,
        /// When its last byte arrived (or it was read from the local directory).
        at: Instant,
    },
    End,
    Error(String),
}

pub fn parse_slot_event(json: &str) -> Option<SlotEvent> {
    let v: serde_json::Value = serde_json::from_str(json).ok()?;
    Some(SlotEvent {
        seq: u32::try_from(v["seq"].as_u64()?).ok()?,
        kind: v["kind"].as_str()?.to_string(),
        points: v["points"].as_u64()?,
        bytes: v["bytes"].as_u64()?,
    })
}

/// True when the replay server at `host` serves a slot stream (`"stream":"slots"` in its manifest)
/// rather than snapshots.
pub fn is_slot_stream(host: &str) -> std::io::Result<bool> {
    let (_, mut r) = get(host, "/manifest.json")?;
    let mut text = String::new();
    r.read_to_string(&mut text)?;
    let v: serde_json::Value = serde_json::from_str(&text)
        .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
    Ok(v["stream"].as_str() == Some("slots"))
}

/// Where a slot follower gets messages from: `/slots/…` of the replay server, or the stream
/// directory on this machine (decision 0050).
enum SlotSource {
    Http,
    Local(crate::slots::dir::StreamDir),
}

impl SlotSource {
    fn new(dir: Option<PathBuf>) -> std::io::Result<Self> {
        Ok(match dir {
            Some(d) => Self::Local(crate::slots::dir::StreamDir::open(d)?),
            None => Self::Http,
        })
    }

    /// The message of event `seq`, or with `state` everything through it folded.
    fn fetch(&mut self, host: &str, seq: u32, state: bool) -> std::io::Result<Vec<u8>> {
        match self {
            Self::Http => {
                let path = if state {
                    format!("/slots/state?seq={seq}")
                } else {
                    format!("/slots/{seq}")
                };
                let (headers, mut r) = get(host, &path)?;
                let len = header(&headers, "content-length").and_then(|v| v.parse().ok());
                let mut bytes = Vec::with_capacity(len.unwrap_or(0));
                r.read_to_end(&mut bytes)?;
                crate::slots::validate(&bytes)
                    .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
                Ok(bytes)
            }
            Self::Local(dir) => {
                if dir.events().iter().all(|e| e.seq != seq) {
                    dir.refresh()?;
                }
                if !state {
                    return dir.message(seq);
                }
                let mut fold = crate::slots::Fold::new();
                let seqs: Vec<u32> = dir
                    .events()
                    .iter()
                    .map(|e| e.seq)
                    .filter(|s| *s <= seq)
                    .collect();
                for s in seqs {
                    fold.apply(&dir.message(s)?)
                        .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
                }
                Ok(fold.message())
            }
        }
    }
}

/// Fetches announced events strictly in order (a client applies them in `seq` order anyway).
fn slot_fetch_loop(
    host: &str,
    mut source: SlotSource,
    rx: mpsc::Receiver<SlotEvent>,
    send: &impl Fn(SlotMsg),
) {
    for event in rx {
        let fetch_start = Instant::now();
        match fetch_or_state(host, &mut source, event.seq) {
            Ok((bytes, state)) => send(SlotMsg::Message {
                seq: event.seq,
                bytes,
                state,
                fetch_start,
                at: Instant::now(),
            }),
            Err(e) => send(SlotMsg::Error(format!("event {}: {e}", event.seq))),
        }
    }
    send(SlotMsg::End);
}

/// Attempts at an event's message before falling back to the folded state.
const SLOT_ATTEMPTS: u32 = 3;
/// Wait between attempts.
const SLOT_RETRY: std::time::Duration = std::time::Duration::from_millis(100);

/// Event `seq`'s message, retried; if it still cannot be had, the folded state through `seq` (true):
/// a client holding later events would otherwise wait for this one forever, and a client without
/// event 1 must not start from event 2.
fn fetch_or_state(
    host: &str,
    source: &mut SlotSource,
    seq: u32,
) -> std::io::Result<(Vec<u8>, bool)> {
    let mut last = None;
    for k in 0..SLOT_ATTEMPTS {
        if k > 0 {
            std::thread::sleep(SLOT_RETRY);
        }
        match source.fetch(host, seq, false) {
            Ok(bytes) => return Ok((bytes, false)),
            Err(e) => last = Some(e),
        }
    }
    let e = last.expect("at least one attempt");
    source
        .fetch(host, seq, true)
        .map(|b| (b, true))
        .map_err(|s| std::io::Error::other(format!("{e}; folded state through {seq}: {s}")))
}

/// Replay of a slot stream: follows `/events?speed=…` and fetches each event's message as it is
/// announced; with `dir`, the messages are read from the stream directory on this machine instead
/// of fetched (decision 0050).
pub fn spawn_slots(
    host: String,
    dir: Option<PathBuf>,
    speed: f64,
    send: impl Fn(SlotMsg) + Send + Sync + 'static,
) {
    let send = std::sync::Arc::new(send);
    let source = match SlotSource::new(dir) {
        Ok(s) => s,
        Err(e) => {
            send(SlotMsg::Error(format!("stream directory: {e}")));
            send(SlotMsg::End);
            return;
        }
    };
    let (tx, rx) = mpsc::channel::<SlotEvent>();
    let (h2, s2) = (host.clone(), send.clone());
    std::thread::spawn(move || slot_fetch_loop(&h2, source, rx, &|m| s2(m)));
    std::thread::spawn(move || {
        let run = || -> std::io::Result<()> {
            let (_, r) = get(&host, &format!("/events?speed={speed}"))?;
            let mut event = String::new();
            for line in r.lines() {
                let line = line?;
                let at = Instant::now();
                if let Some(e) = line.strip_prefix("event: ") {
                    event = e.to_string();
                } else if let Some(data) = line.strip_prefix("data: ") {
                    match event.as_str() {
                        "slots" => {
                            if let Some(ev) = parse_slot_event(data) {
                                send(SlotMsg::Received {
                                    event: ev.clone(),
                                    at,
                                });
                                let _ = tx.send(ev);
                            }
                        }
                        "end" => return Ok(()),
                        _ => {}
                    }
                }
            }
            Ok(())
        };
        if let Err(e) = run() {
            send(SlotMsg::Error(format!("events: {e}")));
        }
    });
}

/// Cold start of a slot stream: the last event of the manifest, as one folded state.
pub fn spawn_slots_cold(
    host: String,
    dir: Option<PathBuf>,
    send: impl Fn(SlotMsg) + Send + Sync + 'static,
) {
    std::thread::spawn(move || {
        let run = || -> std::io::Result<()> {
            let mut source = SlotSource::new(dir)?;
            let (_, mut r) = get(&host, "/manifest.json")?;
            let mut text = String::new();
            r.read_to_string(&mut text)?;
            let v: serde_json::Value = serde_json::from_str(&text)
                .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
            let last = v["events"]
                .as_array()
                .and_then(|a| a.last())
                .and_then(|e| parse_slot_event(&e.to_string()))
                .ok_or_else(|| std::io::Error::other("empty manifest"))?;
            let seq = last.seq;
            send(SlotMsg::Received {
                event: last,
                at: Instant::now(),
            });
            let fetch_start = Instant::now();
            let bytes = source.fetch(&host, seq, true)?;
            send(SlotMsg::Message {
                seq,
                bytes,
                state: true,
                fetch_start,
                at: Instant::now(),
            });
            Ok(())
        };
        if let Err(e) = run() {
            send(SlotMsg::Error(format!("cold: {e}")));
        }
        send(SlotMsg::End);
    });
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Point;
    use crate::chunk::encode;

    /// A replay server where `/slots/1` fails once, `/slots/2` always fails and
    /// `/slots/state?seq=2` works: the follower retries 1, falls back to the state for 2, then 3.
    #[test]
    fn slot_follower_retries_then_falls_back_to_the_folded_state() {
        use crate::slots::{SlotHeader, encode};
        use std::net::TcpListener;
        let m = |seq: u32| {
            let h = SlotHeader {
                seq,
                ..Default::default()
            };
            encode(&h, &[]).unwrap()
        };
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let host = listener.local_addr().unwrap().to_string();
        let served = std::sync::Arc::new(std::sync::Mutex::new(Vec::<String>::new()));
        let log = served.clone();
        std::thread::spawn(move || {
            let mut first_one = true;
            for stream in listener.incoming() {
                let mut stream = stream.unwrap();
                let mut line = String::new();
                let mut r = BufReader::new(&stream);
                r.read_line(&mut line).unwrap();
                // Read the whole request, so closing does not reset the connection.
                let mut h = String::new();
                while r.read_line(&mut h).unwrap() > 2 {
                    h.clear();
                }
                let path = line.split_whitespace().nth(1).unwrap_or("").to_string();
                log.lock().unwrap().push(path.clone());
                let body = match path.as_str() {
                    "/slots/1" if first_one => {
                        first_one = false;
                        None
                    }
                    "/slots/1" => Some(m(1)),
                    "/slots/state?seq=2" => Some(m(2)),
                    "/slots/3" => Some(m(3)),
                    _ => None,
                };
                let head = match &body {
                    Some(b) => format!("HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n", b.len()),
                    None => "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n".into(),
                };
                stream.write_all(head.as_bytes()).unwrap();
                stream.write_all(&body.unwrap_or_default()).unwrap();
            }
        });
        let (tx, rx) = mpsc::channel();
        for seq in 1..=3 {
            tx.send(SlotEvent {
                seq,
                kind: "refined".into(),
                points: 0,
                bytes: 0,
            })
            .unwrap();
        }
        drop(tx);
        let got = std::sync::Mutex::new(Vec::new());
        slot_fetch_loop(&host, SlotSource::Http, rx, &|msg| {
            if let SlotMsg::Message { seq, state, .. } = msg {
                got.lock().unwrap().push((seq, state));
            }
        });
        assert_eq!(
            got.into_inner().unwrap(),
            vec![(1, false), (2, true), (3, false)]
        );
        let served = served.lock().unwrap();
        assert_eq!(served.iter().filter(|p| *p == "/slots/1").count(), 2);
        assert_eq!(
            served.iter().filter(|p| *p == "/slots/2").count(),
            SLOT_ATTEMPTS as usize
        );
    }

    #[test]
    fn parses_slot_events() {
        let e = parse_slot_event(
            r#"{"seq":6,"time_s":195.83,"t":195.83,"kind":"replace","zone":1,"points":1543927,"n_add":386295,"n_move":264502,"n_remove":395137,"bytes":14596488,"capacity":1939064,"url":"/slots/6"}"#,
        )
        .unwrap();
        assert_eq!(
            (e.seq, e.kind.as_str(), e.points, e.bytes),
            (6, "replace", 1_543_927, 14_596_488)
        );
        assert!(parse_slot_event(r#"{"seq":1}"#).is_none());
    }

    #[test]
    fn reads_back_to_back_chunks_until_the_end() {
        let p = |x: f32| Point {
            position: [x, 0.0, 0.0],
            color: [1, 2, 3],
        };
        let a = encode(4, 0, 0, &[p(1.0), p(2.0)]);
        let b = encode(4, 1, FLAG_LAST_IN_GENERATION, &[]);
        let stream: Vec<u8> = [a.clone(), b.clone()].concat();
        let mut r = &stream[..];
        assert_eq!(read_chunk(&mut r).unwrap(), Some(a));
        assert_eq!(read_chunk(&mut r).unwrap(), Some(b));
        assert_eq!(read_chunk(&mut r).unwrap(), None);
        // Cut inside a chunk: an error, not a silent end.
        let mut cut = &stream[..90];
        assert!(read_chunk(&mut cut).is_err());
    }

    #[test]
    fn parses_server_urls_and_snapshots() {
        assert_eq!(
            host_port("http://127.0.0.1:8700/").unwrap(),
            "127.0.0.1:8700"
        );
        assert!(host_port("https://x").is_err());
        let s = parse_snapshot(
            r#"{"seq":3,"time_s":298.9,"kind":"preview","region":1,"file":"f","url":"/data/f","bytes":1,"points":371585}"#,
        )
        .unwrap();
        assert_eq!((s.seq, s.kind.as_str(), s.points), (3, "preview", 371_585));
    }
}