engawa-chat 0.1.2

A peer-to-peer chat lobby for editors and browsers
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
use std::collections::BTreeMap;
use std::path::Path;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use anyhow::{Context, Result, bail, ensure};
use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey};
use rusqlite::{Connection, OptionalExtension, params};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};

use crate::network::{Cmd, Event};

const WEEK: i64 = 7 * 24 * 60 * 60 * 1000;
const SKEW: i64 = 60_000;
const PRESENCE: i64 = 90_000;
const POSTS: usize = 200;
const ROOMS: usize = 512;
const FRAME: usize = 3600;
const PAGE: usize = 20;
const DEFAULTS: [(&str, &str, bool); 3] = [
    ("雑談", "lounge", true),
    ("もくもく", "focus", false),
    ("質問", "questions", true),
];

fn now() -> i64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_millis() as i64
}

fn digest(domain: &'static str, fields: &[&[u8]]) -> blake3::Hash {
    let mut h = blake3::Hasher::new_derive_key(domain);
    for field in fields {
        h.update(&(field.len() as u64).to_be_bytes());
        h.update(field);
    }
    h.finalize()
}

fn is_hex(s: &str, len: usize) -> bool {
    s.len() == len
        && s.bytes()
            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
}

#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
struct Room {
    id: String,
    name: String,
    history: bool,
}

impl Room {
    fn new(name: &str, history: bool) -> Result<Self> {
        ensure!(
            !name.is_empty()
                && name.len() <= 96
                && name.trim() == name
                && !name.starts_with('#')
                && !name.chars().any(char::is_control),
            "部屋名は空白だけにせず、96バイト以内で入力してください"
        );
        let builtin = DEFAULTS
            .iter()
            .find(|(n, _, h)| *n == name && *h == history);
        let (kind, key) = builtin.map_or(("custom", name), |(_, slug, _)| ("builtin", *slug));
        let id = digest(
            "engawa/v1/room",
            &[kind.as_bytes(), key.as_bytes(), &[u8::from(history)]],
        );
        Ok(Self {
            id: id.to_hex().to_string(),
            name: name.into(),
            history,
        })
    }

    fn consistent(&self) -> bool {
        Self::new(&self.name, self.history).is_ok_and(|r| r.id == self.id)
    }
}

struct Listing {
    room: Room,
    pinned: bool,
    seen: Option<i64>,
}

#[derive(Deserialize, Serialize)]
#[serde(rename_all = "snake_case", deny_unknown_fields)]
enum Body {
    Message { nonce: String, text: String },
    Withdrawal { signature: String },
}

#[derive(Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
struct Record {
    author: String,
    stamp: i64,
    // The original post signature identifies it even when its nonce and text are erased.
    reference: String,
    body: Body,
}

fn valid_text(text: &str) -> bool {
    !text.trim().is_empty()
        && text.len() <= 1024
        && !text
            .chars()
            .any(|c| c.is_control() && c != '\n' && c != '\t')
}

impl Record {
    fn post_digest(room: &str, stamp: i64, nonce: &str, text: &str) -> blake3::Hash {
        digest(
            "engawa/v1/post",
            &[
                room.as_bytes(),
                &stamp.to_be_bytes(),
                nonce.as_bytes(),
                text.as_bytes(),
            ],
        )
    }

    fn new(key: &SigningKey, room: &str, stamp: i64, text: &str) -> Result<Self> {
        ensure!(
            valid_text(text),
            "本文は空白だけにせず、1024バイト以内で入力してください"
        );
        let mut nonce = [0u8; 16];
        getrandom::fill(&mut nonce)?;
        let nonce = hex::encode(nonce);
        let message = Self::post_digest(room, stamp, &nonce, text);
        Ok(Self {
            author: hex::encode(key.verifying_key().to_bytes()),
            stamp,
            reference: hex::encode(key.sign(message.as_bytes()).to_bytes()),
            body: Body::Message {
                nonce,
                text: text.into(),
            },
        })
    }

    fn id(&self, room: &str) -> String {
        digest(
            "engawa/v1/post-id",
            &[
                room.as_bytes(),
                self.author.as_bytes(),
                &self.stamp.to_be_bytes(),
                self.reference.as_bytes(),
            ],
        )
        .to_hex()
        .to_string()
    }

    fn erase(&mut self, key: &SigningKey, room: &str) -> Result<()> {
        ensure!(
            self.author == hex::encode(key.verifying_key().to_bytes()) && !self.dead(),
            "このセッションの発言だけ取り消せます"
        );
        let proof = digest("engawa/v1/withdraw", &[self.id(room).as_bytes()]);
        self.body = Body::Withdrawal {
            signature: hex::encode(key.sign(proof.as_bytes()).to_bytes()),
        };
        Ok(())
    }

    fn dead(&self) -> bool {
        matches!(self.body, Body::Withdrawal { .. })
    }

    fn verified(&self, room: &str, oldest: i64, time: i64) -> bool {
        if self.stamp <= oldest
            || self.stamp > time + SKEW
            || !is_hex(&self.author, 64)
            || !is_hex(&self.reference, 128)
        {
            return false;
        }
        let mut author = [0; 32];
        if hex::decode_to_slice(&self.author, &mut author).is_err() {
            return false;
        }
        let Ok(key) = VerifyingKey::from_bytes(&author) else {
            return false;
        };
        let (sig, data) = match &self.body {
            Body::Message { nonce, text } if valid_text(text) && is_hex(nonce, 32) => (
                &self.reference,
                Self::post_digest(room, self.stamp, nonce, text),
            ),
            Body::Withdrawal { signature } if is_hex(signature, 128) => (
                signature,
                digest("engawa/v1/withdraw", &[self.id(room).as_bytes()]),
            ),
            _ => return false,
        };
        let mut signature = [0; 64];
        hex::decode_to_slice(sig, &mut signature).is_ok()
            && key
                .verify_strict(data.as_bytes(), &Signature::from_bytes(&signature))
                .is_ok()
    }
}

#[derive(Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
enum Packet {
    Item(Record),
    Hello,
    Offer(Vec<(String, bool)>),
    Need(Vec<(String, bool)>),
}

impl Packet {
    fn encode(&self) -> Result<Vec<u8>> {
        let bytes = serde_json::to_vec(self)?;
        ensure!(bytes.len() <= FRAME, "パケットが大きすぎます");
        Ok(bytes)
    }
}

fn field<'a>(data: &'a Value, key: &str) -> Result<&'a str> {
    data[key].as_str().context("入力が不正です")
}

fn setup(db: &Connection) -> Result<()> {
    db.busy_timeout(Duration::from_secs(3))?;
    db.execute_batch(
        "PRAGMA secure_delete=ON; PRAGMA temp_store=MEMORY;
        CREATE TABLE IF NOT EXISTS records(
            room TEXT NOT NULL, id TEXT NOT NULL, stamp INTEGER NOT NULL, dead INTEGER NOT NULL,
            packet BLOB NOT NULL, local_withdrawal TEXT, PRIMARY KEY(room,id)) WITHOUT ROWID;
        CREATE INDEX IF NOT EXISTS recent ON records(room,dead,stamp,id);
        CREATE INDEX IF NOT EXISTS expiry ON records(stamp);",
    )?;
    Ok(())
}

struct View {
    id: String,
    stamp: i64,
    text: String,
    author: String,
    mine: bool,
}

impl View {
    fn from_record(id: String, room: &str, mine: &str, record: Record) -> Option<Self> {
        let Body::Message { text, .. } = record.body else {
            return None;
        };
        let label = digest(
            "engawa/v1/author",
            &[room.as_bytes(), record.author.as_bytes()],
        )
        .to_hex();
        Some(Self {
            id,
            stamp: record.stamp,
            text,
            author: label[..8].into(),
            mine: mine == record.author,
        })
    }
}

struct Joined {
    room: Room,
    key: SigningKey,
    author: String,
    since: i64,
    visible: Vec<View>,
    // More than a window of ephemeral withdrawals advances a local replay cutoff.
    ephemeral_floor: Option<(i64, String)>,
    offer_after: Option<String>,
    last_offer: Option<i64>,
}

pub struct Model {
    durable: Connection,
    // A separate memory-only database never opens the profile file, journal or temporary files.
    volatile: Connection,
    session: [u8; 32],
    listings: BTreeMap<String, Listing>,
    joined: Option<Joined>,
    status: String,
    version: i64,
}

impl Model {
    pub fn open(dir: &Path) -> Result<Self> {
        std::fs::create_dir_all(dir)?;
        let db = Connection::open(dir.join("history.sqlite3"))?;
        setup(&db)?;
        // Keep a flood of valid seven-day withdrawal receipts from filling the user's disk.
        db.execute_batch("PRAGMA max_page_count=65536;
            CREATE TABLE IF NOT EXISTS rooms(id TEXT PRIMARY KEY, name TEXT NOT NULL, touched INTEGER NOT NULL);")?;
        let time = now();
        db.execute("DELETE FROM records WHERE stamp<=?1", [time - WEEK])?;
        db.execute("DELETE FROM rooms WHERE touched<=?1 AND NOT EXISTS (SELECT 1 FROM records WHERE records.room=rooms.id)", [time - WEEK])?;
        let volatile = Connection::open_in_memory()?;
        setup(&volatile)?;
        volatile.execute_batch(
            "CREATE TABLE floors(room TEXT PRIMARY KEY, stamp INTEGER NOT NULL, id TEXT NOT NULL)",
        )?;
        let mut session = [0; 32];
        getrandom::fill(&mut session)?;
        let mut listings = BTreeMap::new();
        for (name, _, history) in DEFAULTS {
            let room = Room::new(name, history)?;
            listings.insert(
                room.id.clone(),
                Listing {
                    room,
                    pinned: true,
                    seen: None,
                },
            );
        }
        {
            let mut rows =
                db.prepare("SELECT id,name FROM rooms ORDER BY touched DESC LIMIT ?1")?;
            for row in rows.query_map([ROOMS as i64], |r| {
                Ok(Room {
                    id: r.get(0)?,
                    name: r.get(1)?,
                    history: true,
                })
            })? {
                let room = row?;
                if room.consistent() {
                    listings.insert(
                        room.id.clone(),
                        Listing {
                            room,
                            pinned: true,
                            seen: None,
                        },
                    );
                }
            }
        }
        let version = db.query_row("PRAGMA data_version", [], |r| r.get(0))?;
        Ok(Self {
            durable: db,
            volatile,
            session,
            listings,
            joined: None,
            status: "ロビーで参加者を探しています".into(),
            version,
        })
    }

    pub fn state(&self) -> Value {
        let time = now();
        let current = self.joined.as_ref().map(|j| &j.room.id);
        let rooms: Vec<_> = self.listings.values().map(|r| json!({
            "id": r.room.id, "name": r.room.name, "history": r.room.history,
            "active": Some(&r.room.id) == current || r.seen.is_some_and(|s| s > time - PRESENCE)
        })).collect();
        let messages: Vec<_> = self
            .joined
            .iter()
            .flat_map(|j| &j.visible)
            .filter(|m| m.stamp > time - WEEK)
            .map(|m| json!({"id": m.id, "text": m.text, "mine": m.mine, "author": m.author}))
            .collect();
        json!({"rooms": rooms, "room": current, "messages": messages, "status": self.status})
    }

    fn db(&self, history: bool) -> &Connection {
        if history {
            &self.durable
        } else {
            &self.volatile
        }
    }

    fn refresh(db: &Connection, joined: &mut Joined, time: i64) -> Result<()> {
        let mut stmt = db.prepare_cached("SELECT id,packet,local_withdrawal IS NOT NULL FROM records WHERE room=?1 AND dead=0 AND stamp>?2 ORDER BY stamp,id")?;
        let mut rows = stmt.query(params![joined.room.id, time - WEEK])?;
        let mut visible = Vec::new();
        while let Some(r) = rows.next()? {
            let data = r.get_ref(1)?.as_blob()?;
            if let Packet::Item(record) = serde_json::from_slice(data)?
                && let Some(mut view) =
                    View::from_record(r.get(0)?, &joined.room.id, &joined.author, record)
            {
                view.mine |= r.get::<_, bool>(2)?;
                visible.push(view);
            }
        }
        joined.visible = visible;
        Ok(())
    }

    fn leave_buffer(&self, time: i64) -> Result<()> {
        // Erase bodies immediately. Keep only receipts still replayable on a quick rejoin.
        self.volatile.execute(
            "DELETE FROM records WHERE dead=0 OR stamp<=?1",
            [time - SKEW],
        )?;
        self.volatile
            .execute("DELETE FROM floors WHERE stamp<=?1", [time - SKEW])?;
        Ok(())
    }

    fn join(&mut self, room: Room, time: i64) -> Result<Vec<Cmd>> {
        if self.joined.as_ref().is_some_and(|j| j.room.id == room.id) {
            return Ok(vec![]);
        }
        if !self.listings.contains_key(&room.id) && self.listings.len() >= ROOMS {
            let evict = self
                .listings
                .iter()
                .filter(|(_, l)| !l.pinned)
                .min_by_key(|(_, l)| l.seen)
                .map(|(id, _)| id.clone());
            if let Some(id) = evict {
                self.listings.remove(&id);
            } else {
                bail!("部屋の登録上限に達しました");
            }
        }
        let key = SigningKey::from_bytes(
            blake3::keyed_hash(&self.session, room.id.as_bytes()).as_bytes(),
        );
        let author = hex::encode(key.verifying_key().to_bytes());
        let mut joined = Joined {
            key,
            author,
            room,
            since: time,
            visible: vec![],
            ephemeral_floor: None,
            offer_after: None,
            last_offer: None,
        };
        let room = &joined.room;
        if room.history {
            self.durable.execute("INSERT INTO rooms(id,name,touched) VALUES(?1,?2,?3) ON CONFLICT(id) DO UPDATE SET touched=excluded.touched", params![room.id, room.name, time])?;
            Self::refresh(&self.durable, &mut joined, time)?;
        } else {
            joined.ephemeral_floor = self
                .volatile
                .query_row(
                    "SELECT stamp,id FROM floors WHERE room=?1 AND stamp>?2",
                    params![room.id, time - SKEW],
                    |r| Ok((r.get(0)?, r.get(1)?)),
                )
                .optional()?;
        }
        self.leave_buffer(time)?;
        let room = &joined.room;
        let cmds = vec![
            Cmd::Join(room.id.clone()),
            Cmd::Announce(serde_json::to_vec(room)?),
        ];
        let listing = self
            .listings
            .entry(room.id.clone())
            .or_insert_with(|| Listing {
                room: room.clone(),
                pinned: false,
                seen: None,
            });
        listing.pinned |= room.history;
        listing.seen = Some(time);
        self.joined = Some(joined);
        Ok(cmds)
    }

    pub fn action(&mut self, op: &str, data: Value) -> Result<Vec<Cmd>> {
        let time = now();
        match op {
            "rooms" => self.join(
                Room::new(
                    field(&data, "name")?.trim().trim_start_matches('#').trim(),
                    data["history"]
                        .as_bool()
                        .context("履歴設定を選んでください")?,
                )?,
                time,
            ),
            "join" => self.join(
                self.listings
                    .get(field(&data, "id")?)
                    .context("部屋が見つかりません")?
                    .room
                    .clone(),
                time,
            ),
            "leave" => {
                self.leave_buffer(time)?;
                self.joined = None;
                Ok(vec![Cmd::Leave])
            }
            "send" | "retract" => {
                let j = self.joined.as_ref().context("部屋に入ってください")?;
                let record = if op == "send" {
                    Record::new(&j.key, &j.room.id, time, field(&data, "text")?)?
                } else {
                    let id = field(&data, "id")?;
                    ensure!(is_hex(id, 64), "不正な発言IDです");
                    let (bytes, receipt): (Vec<u8>, Option<String>) = self.db(j.room.history).query_row(
                        "SELECT packet,local_withdrawal FROM records WHERE room=?1 AND id=?2 AND dead=0 AND stamp>?3",
                        params![j.room.id,id,time-WEEK], |r| Ok((r.get(0)?, r.get(1)?)))
                        .optional()?.context("発言が見つかりません")?;
                    let Packet::Item(mut item) = serde_json::from_slice(&bytes)? else {
                        bail!("履歴形式が不正です");
                    };
                    if let Some(signature) = receipt {
                        item.body = Body::Withdrawal { signature };
                    } else {
                        item.erase(&j.key, &j.room.id)?;
                    }
                    item
                };
                let packet = Packet::Item(record);
                let bytes = packet.encode()?;
                let Packet::Item(record) = packet else {
                    unreachable!()
                };
                self.apply(record, &bytes)?;
                Ok(vec![Cmd::Send(bytes)])
            }
            _ => bail!("不明な操作です"),
        }
    }

    fn apply(&mut self, rec: Record, bytes: &[u8]) -> Result<()> {
        let Some(j) = self.joined.as_mut() else {
            return Ok(());
        };
        let room = &j.room.id;
        let id = rec.id(room);
        if j.ephemeral_floor
            .as_ref()
            .is_some_and(|(s, i)| (rec.stamp, &id) <= (*s, i))
        {
            return Ok(());
        }
        let db = if j.room.history {
            &mut self.durable
        } else {
            &mut self.volatile
        };
        let tx = db.transaction()?;
        // Save only the per-post authorization locally, never a long-lived signing key.
        let receipt = (j.room.history && !rec.dead() && rec.author == j.author).then(|| {
            let proof = digest("engawa/v1/withdraw", &[id.as_bytes()]);
            hex::encode(j.key.sign(proof.as_bytes()).to_bytes())
        });
        let changed = tx.execute("INSERT INTO records(room,id,stamp,dead,packet,local_withdrawal) VALUES(?1,?2,?3,?4,?5,?6)
            ON CONFLICT(room,id) DO UPDATE SET dead=1,packet=excluded.packet,local_withdrawal=NULL WHERE excluded.dead=1 AND records.dead=0",
            params![room, id, rec.stamp, rec.dead(), bytes, receipt])?;
        if changed == 0 {
            return Ok(());
        }
        let mut floor: Option<(i64, String)> = None;
        if !rec.dead() {
            tx.execute("DELETE FROM records WHERE room=?1 AND id IN
                (SELECT id FROM records WHERE room=?1 AND dead=0 ORDER BY stamp DESC,id DESC LIMIT -1 OFFSET ?2)", params![room, POSTS as i64])?;
        } else if !j.room.history {
            floor = tx.query_row("SELECT stamp,id FROM records WHERE room=?1 AND dead=1 ORDER BY stamp DESC,id DESC LIMIT 1 OFFSET ?2", params![room, POSTS as i64], |r| Ok((r.get(0)?, r.get(1)?))).optional()?;
            if let Some((stamp, ref id)) = floor {
                tx.execute(
                    "DELETE FROM records WHERE room=?1 AND (stamp,id)<=(?2,?3)",
                    params![room, stamp, id],
                )?;
                tx.execute(
                    "INSERT OR REPLACE INTO floors(room,stamp,id) VALUES(?1,?2,?3)",
                    params![room, stamp, id],
                )?;
            }
        }
        tx.commit()?;
        if let Some((stamp, id)) = floor {
            j.visible.retain(|v| (v.stamp, &v.id) > (stamp, &id));
            j.ephemeral_floor = Some((stamp, id));
        }
        if rec.dead() {
            j.visible.retain(|v| v.id != id);
        } else if let Some(v) = View::from_record(id, room, &j.author, rec) {
            match j
                .visible
                .binary_search_by(|o| (o.stamp, &o.id).cmp(&(v.stamp, &v.id)))
            {
                Ok(_) => {}
                Err(at) => j.visible.insert(at, v),
            }
            if j.visible.len() > POSTS {
                j.visible.remove(0);
            }
        }
        Ok(())
    }

    // Keyset paging bounds both the gossip fanout and memory, even with many unexpired withdrawals.
    fn offers(&mut self, time: i64, first: bool) -> Result<Vec<Cmd>> {
        let Some(j) = self.joined.as_mut().filter(|j| j.room.history) else {
            return Ok(vec![]);
        };
        if first {
            if j.last_offer.is_some_and(|last| last > time - 2000) {
                return Ok(vec![]);
            }
            j.offer_after.get_or_insert_with(String::new);
            j.last_offer = Some(time);
        }
        let Some(after) = j.offer_after.as_ref() else {
            return Ok(vec![]);
        };
        const CHUNK: usize = PAGE * 10;
        let mut stmt = self.durable.prepare_cached(
            "SELECT id,dead FROM records WHERE room=?1 AND id>?2 AND stamp>?3 ORDER BY id LIMIT ?4",
        )?;
        let mut batch = Vec::with_capacity(PAGE);
        let mut cmds = Vec::new();
        let mut rows = stmt.query(params![j.room.id, after, time - WEEK, CHUNK as i64])?;
        let mut next = None;
        let mut n = 0;
        while let Some(r) = rows.next()? {
            let id: String = r.get(0)?;
            n += 1;
            if n == CHUNK {
                next = Some(id.clone());
            }
            batch.push((id, r.get(1)?));
            if batch.len() == PAGE {
                cmds.push(Cmd::Send(
                    Packet::Offer(std::mem::take(&mut batch)).encode()?,
                ));
            }
        }
        if !batch.is_empty() {
            cmds.push(Cmd::Send(Packet::Offer(batch).encode()?));
        }
        j.offer_after = next;
        Ok(cmds)
    }

    pub fn event(&mut self, event: Event) -> Result<Vec<Cmd>> {
        let time = now();
        match event {
            Event::Status(s) => self.status = s,
            Event::Lobby(bytes) => {
                if bytes.len() <= 512
                    && let Ok(room) = serde_json::from_slice::<Room>(&bytes)
                    && room.consistent()
                {
                    if let Some(l) = self.listings.get_mut(&room.id) {
                        l.seen = Some(time);
                    } else if self.listings.len() < ROOMS {
                        self.listings.insert(
                            room.id.clone(),
                            Listing {
                                room,
                                pinned: false,
                                seen: Some(time),
                            },
                        );
                    }
                }
            }
            Event::Ready(id) => {
                if self
                    .joined
                    .as_ref()
                    .is_some_and(|j| j.room.id == id && j.room.history)
                {
                    let mut cmds = self.offers(time, true)?;
                    cmds.push(Cmd::Send(Packet::Hello.encode()?));
                    return Ok(cmds);
                }
            }
            Event::Room(id, bytes) => {
                let Some(j) = self.joined.as_ref().filter(|j| j.room.id == id) else {
                    return Ok(vec![]);
                };
                if bytes.len() > FRAME {
                    return Ok(vec![]);
                }
                let Ok(packet) = serde_json::from_slice::<Packet>(&bytes) else {
                    return Ok(vec![]);
                };
                match packet {
                    Packet::Item(r) => {
                        let oldest = if j.room.history {
                            time - WEEK
                        } else {
                            (j.since - SKEW).max(time - WEEK)
                        };
                        if r.verified(&id, oldest, time) {
                            self.apply(r, &bytes)?;
                        }
                    }
                    Packet::Hello if j.room.history => return self.offers(time, true),
                    Packet::Offer(items) if j.room.history && items.len() <= PAGE => {
                        let mut stmt = self
                            .durable
                            .prepare_cached("SELECT dead FROM records WHERE room=?1 AND id=?2")?;
                        let mut need = Vec::new();
                        for (key, dead) in items {
                            if !is_hex(&key, 64) {
                                return Ok(vec![]);
                            }
                            let local: Option<bool> =
                                stmt.query_row(params![id, key], |r| r.get(0)).optional()?;
                            if local.is_none() || (local == Some(false) && dead) {
                                need.push((key, dead));
                            }
                        }
                        if !need.is_empty() {
                            return Ok(vec![Cmd::Send(Packet::Need(need).encode()?)]);
                        }
                    }
                    Packet::Need(mut keys) if j.room.history && keys.len() <= PAGE => {
                        let mut stmt = self.durable.prepare_cached("SELECT packet FROM records WHERE room=?1 AND id=?2 AND stamp>?3 AND dead>=?4")?;
                        keys.sort_unstable();
                        keys.dedup();
                        let mut cmds = Vec::new();
                        for (key, dead) in keys {
                            if !is_hex(&key, 64) {
                                return Ok(vec![]);
                            }
                            if let Some(bytes) = stmt
                                .query_row(params![id, key, time - WEEK, dead], |r| r.get(0))
                                .optional()?
                            {
                                cmds.push(Cmd::Send(bytes));
                            }
                        }
                        return Ok(cmds);
                    }
                    _ => {}
                }
            }
        }
        Ok(vec![])
    }

    pub fn tick(&mut self) -> Result<Vec<Cmd>> {
        let time = now();
        self.durable
            .execute("DELETE FROM records WHERE stamp<=?1", [time - WEEK])?;
        let current = self.joined.as_ref().map(|j| &j.room.id);
        self.volatile.execute(
            "DELETE FROM records WHERE stamp<=?1 OR (room IS NOT ?2 AND stamp<=?3)",
            params![time - WEEK, current, time - SKEW],
        )?;
        self.volatile.execute(
            "DELETE FROM floors WHERE room IS NOT ?1 AND stamp<=?2",
            params![current, time - SKEW],
        )?;
        self.listings.retain(|id, l| {
            l.pinned || current == Some(id) || l.seen.is_some_and(|s| s > time - PRESENCE)
        });
        let Some(j) = self.joined.as_mut() else {
            return Ok(vec![]);
        };
        let mut cmds = vec![Cmd::Announce(serde_json::to_vec(&j.room)?)];
        let version = self
            .durable
            .query_row("PRAGMA data_version", [], |r| r.get(0))?;
        if j.room.history && self.version != version {
            Self::refresh(&self.durable, j, time)?;
        }
        self.version = version;
        j.visible.retain(|v| v.stamp > time - WEEK);
        // Reconcile again after dropped packets without continuously replaying chat bodies.
        let restart = j.last_offer.is_some_and(|s| s <= time - 60_000) && j.offer_after.is_none();
        cmds.extend(self.offers(time, restart)?);
        Ok(cmds)
    }
}

#[cfg(test)]
mod tests;