@foony/chat 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/messages.ts CHANGED
@@ -10,24 +10,136 @@
10
10
  import type { Channel, MessageFrame, UnsubscribeFn } from '@foony/realtime';
11
11
  import { MESSAGE_EVENT, PAYLOAD_VERSION, type MessagePayload } from './protocol.js';
12
12
  import { MessageReconciler } from './reconciler.js';
13
+ import type { ChatStorage } from './storage.js';
13
14
  import type { ChatMessageEvent, Message, MessagePage, SendMessageParams, UpdateMessageParams } from './types.js';
14
15
  import { newMessageId } from './util.js';
15
16
 
16
17
  /** Listener invoked for every materialized message change on the room. */
17
18
  export type MessageListener = (event: ChatMessageEvent) => void;
18
19
 
20
+ /**
21
+ * How many stored frames a room keeps. Matches a deep scrollback page: anything older is
22
+ * re-fetchable through `history()` and not worth the disk.
23
+ */
24
+ const PERSIST_MAX_FRAMES = 300;
25
+
26
+ /** Delay between an applied frame and the storage write, so bursts save once. */
27
+ const PERSIST_DEBOUNCE_MS = 300;
28
+
29
+ /** Page size fetched when a stored resume cursor has aged out of retention. */
30
+ const RECOVER_PAGE_LIMIT = 100;
31
+
32
+ /** Default history page size, matching the server's default. */
33
+ const DEFAULT_HISTORY_LIMIT = 100;
34
+
19
35
  /** The message feature of a {@link Room}. */
20
36
  export class Messages {
21
37
  private readonly reconciler: MessageReconciler;
22
38
  private readonly listeners = new Set<MessageListener>();
23
39
  private channelUnsubscribe: UnsubscribeFn | null = null;
24
40
 
41
+ /** Resolves once the stored snapshot (if any) has been replayed and the resume cursor seeded. */
42
+ private readonly ready: Promise<void>;
43
+ /** Frames worth persisting (those with a seq), oldest-first after each normalize. */
44
+ private frameLog: MessageFrame[] = [];
45
+ /** True when older messages remain on the server below the stored window. */
46
+ private storedHasMore = false;
47
+ /** The seeded resume serial, until the first attach reports whether it held. */
48
+ private seededSerial = 0;
49
+ private channelStateOff: UnsubscribeFn | null = null;
50
+ private persistTimer: ReturnType<typeof setTimeout> | null = null;
51
+ private pendingSubscribe = false;
52
+
25
53
  constructor(
26
54
  private readonly channel: Channel,
27
55
  private readonly roomName: string,
28
56
  private readonly getClientId: () => string | null,
57
+ private readonly storage: ChatStorage | null = null,
29
58
  ) {
30
59
  this.reconciler = new MessageReconciler(roomName);
60
+ this.ready = this.storage ? this.restore() : Promise.resolve();
61
+ }
62
+
63
+ /**
64
+ * Replay the stored snapshot into the reconciler and seed the channel's resume cursor, so the
65
+ * first attach replays only the gap. Runs before the first channel subscribe (see
66
+ * `ensureChannelSubscription`), because a seed after attach is a no-op.
67
+ */
68
+ private async restore(): Promise<void> {
69
+ let state = null;
70
+ try {
71
+ state = await this.storage!.load(this.roomName);
72
+ } catch {
73
+ return;
74
+ }
75
+ if (!state || state.frames.length === 0) {
76
+ return;
77
+ }
78
+ for (const frame of state.frames) {
79
+ if (frame.name === MESSAGE_EVENT) {
80
+ this.reconciler.apply(frame);
81
+ }
82
+ if (frame.seq !== undefined && frame.seq > 0) {
83
+ this.frameLog.push(frame);
84
+ }
85
+ }
86
+ this.storedHasMore = state.hasMore;
87
+ if (state.serial > 0) {
88
+ this.seededSerial = state.serial;
89
+ this.channel.resumeFrom(state.serial);
90
+ this.channelStateOff = this.channel.on((change) => this.onChannelState(change));
91
+ }
92
+ }
93
+
94
+ /**
95
+ * The seeded cursor is judged by the first attach: `resumed: false` means the serial aged out
96
+ * of retention, so the stored copy may be missing messages and is thrown away.
97
+ */
98
+ private onChannelState(change: { readonly current: string; readonly resumed: boolean }): void {
99
+ if (change.current !== 'attached' || this.seededSerial === 0) {
100
+ return;
101
+ }
102
+ this.seededSerial = 0;
103
+ this.channelStateOff?.();
104
+ this.channelStateOff = null;
105
+ if (!change.resumed) {
106
+ void this.recoverFromLostCursor();
107
+ }
108
+ }
109
+
110
+ /**
111
+ * The stored window could not be stitched to the live stream, so drop it and fetch a fresh
112
+ * page, emitting the result to subscribers like live traffic (their render already happened
113
+ * from the stale copy).
114
+ */
115
+ private async recoverFromLostCursor(): Promise<void> {
116
+ try {
117
+ await this.storage!.remove(this.roomName);
118
+ } catch {
119
+ // Best effort: a failed remove leaves a stale copy that the next failed resume retries.
120
+ }
121
+ this.frameLog = [];
122
+ this.storedHasMore = true;
123
+ try {
124
+ const { messages: frames, more } = await this.channel.history({ limit: RECOVER_PAGE_LIMIT });
125
+ this.storedHasMore = more;
126
+ for (const frame of frames) {
127
+ this.addToFrameLog(frame);
128
+ if (frame.name !== MESSAGE_EVENT) {
129
+ continue;
130
+ }
131
+ const event = this.reconciler.apply(frame);
132
+ if (event === null) {
133
+ continue;
134
+ }
135
+ for (const listener of [...this.listeners]) {
136
+ listener(event);
137
+ }
138
+ }
139
+ this.schedulePersist();
140
+ } catch {
141
+ // The room still works live; the next history() call backfills.
142
+ }
31
143
  }
32
144
 
33
145
  /** Send a new message. Returns the message optimistically; its `id` is stable. */
@@ -98,12 +210,22 @@ export class Messages {
98
210
  * `nextCursor`) to page further back.
99
211
  */
100
212
  async history(params?: { limit?: number; cursor?: number }): Promise<MessagePage> {
213
+ if (this.storage) {
214
+ await this.ready;
215
+ if (params?.cursor === undefined) {
216
+ const stored = this.storedPage(params?.limit ?? DEFAULT_HISTORY_LIMIT);
217
+ if (stored) {
218
+ return stored;
219
+ }
220
+ }
221
+ }
101
222
  const { messages: frames, more } = await this.channel.history({
102
223
  ...(params?.limit === undefined ? {} : { limit: params.limit }),
103
224
  ...(params?.cursor === undefined ? {} : { before: params.cursor }),
104
225
  });
105
226
  const touched: string[] = [];
106
227
  for (const frame of frames) {
228
+ this.addToFrameLog(frame);
107
229
  if (frame.name !== MESSAGE_EVENT) {
108
230
  continue;
109
231
  }
@@ -113,6 +235,7 @@ export class Messages {
113
235
  touched.push(id);
114
236
  }
115
237
  }
238
+ this.schedulePersist();
116
239
  const messages = touched
117
240
  .map((id) => this.reconciler.get(id))
118
241
  .filter((message): message is Message => message !== undefined);
@@ -123,20 +246,113 @@ export class Messages {
123
246
  };
124
247
  }
125
248
 
249
+ /**
250
+ * Build the newest page from the stored window, or null when the window is too small for the
251
+ * request (fewer frames than asked and older messages remain on the server).
252
+ */
253
+ private storedPage(limit: number): MessagePage | null {
254
+ this.normalizeFrameLog();
255
+ if (this.frameLog.length === 0 || (this.frameLog.length < limit && this.storedHasMore)) {
256
+ return null;
257
+ }
258
+ const window = this.frameLog.slice(-limit);
259
+ const touched: string[] = [];
260
+ for (const frame of window) {
261
+ const id = messageIdOf(frame);
262
+ if (id !== null && !touched.includes(id)) {
263
+ touched.push(id);
264
+ }
265
+ }
266
+ const messages = touched
267
+ .map((id) => this.reconciler.get(id))
268
+ .filter((message): message is Message => message !== undefined);
269
+ return {
270
+ messages,
271
+ hasMore: this.storedHasMore || this.frameLog.length > window.length,
272
+ ...(window[0]?.seq === undefined ? {} : { nextCursor: window[0].seq }),
273
+ };
274
+ }
275
+
126
276
  /** Lazily attach the single channel subscription that feeds the reconciler. */
127
277
  private ensureChannelSubscription(): void {
128
- if (this.channelUnsubscribe) {
278
+ if (this.channelUnsubscribe || this.pendingSubscribe) {
129
279
  return;
130
280
  }
131
- this.channelUnsubscribe = this.channel.subscribe(MESSAGE_EVENT, (frame) => {
132
- const event = this.reconciler.apply(frame);
133
- if (event === null) {
281
+ if (!this.storage) {
282
+ this.channelUnsubscribe = this.channel.subscribe(MESSAGE_EVENT, (frame) => this.onLiveFrame(frame));
283
+ return;
284
+ }
285
+ // With storage, the subscribe waits for the restore: the resume seed must be in place
286
+ // before the attach the subscription triggers, or the server backfills nothing.
287
+ this.pendingSubscribe = true;
288
+ void this.ready.then(() => {
289
+ this.pendingSubscribe = false;
290
+ if (this.channelUnsubscribe || this.listeners.size === 0) {
134
291
  return;
135
292
  }
293
+ this.channelUnsubscribe = this.channel.subscribe(MESSAGE_EVENT, (frame) => this.onLiveFrame(frame));
294
+ });
295
+ }
296
+
297
+ /** Apply one live frame, fan it out, and keep the stored window fresh. */
298
+ private onLiveFrame(frame: MessageFrame): void {
299
+ this.addToFrameLog(frame);
300
+ const event = this.reconciler.apply(frame);
301
+ if (event !== null) {
136
302
  for (const listener of [...this.listeners]) {
137
303
  listener(event);
138
304
  }
139
- });
305
+ }
306
+ this.schedulePersist();
307
+ }
308
+
309
+ /** Track a sequenced frame for persistence. No-op without storage. */
310
+ private addToFrameLog(frame: MessageFrame): void {
311
+ if (!this.storage || frame.seq === undefined || frame.seq <= 0) {
312
+ return;
313
+ }
314
+ this.frameLog.push(frame);
315
+ if (this.frameLog.length > PERSIST_MAX_FRAMES * 2) {
316
+ this.normalizeFrameLog();
317
+ }
318
+ }
319
+
320
+ /** Sort, dedupe by seq, and trim the frame log to the newest window. */
321
+ private normalizeFrameLog(): void {
322
+ if (this.frameLog.length === 0) {
323
+ return;
324
+ }
325
+ const bySeq = new Map<number, MessageFrame>();
326
+ for (const frame of this.frameLog) {
327
+ bySeq.set(frame.seq!, frame);
328
+ }
329
+ const sorted = [...bySeq.values()].sort((left, right) => left.seq! - right.seq!);
330
+ if (sorted.length > PERSIST_MAX_FRAMES) {
331
+ this.frameLog = sorted.slice(-PERSIST_MAX_FRAMES);
332
+ this.storedHasMore = true;
333
+ } else {
334
+ this.frameLog = sorted;
335
+ }
336
+ }
337
+
338
+ /** Save the stored window shortly, coalescing bursts into one write. */
339
+ private schedulePersist(): void {
340
+ if (!this.storage || this.persistTimer !== null) {
341
+ return;
342
+ }
343
+ this.persistTimer = setTimeout(() => {
344
+ this.persistTimer = null;
345
+ this.normalizeFrameLog();
346
+ if (this.frameLog.length === 0) {
347
+ return;
348
+ }
349
+ const serial = this.frameLog[this.frameLog.length - 1]!.seq!;
350
+ void this.storage!
351
+ .save(this.roomName, { frames: [...this.frameLog], serial, hasMore: this.storedHasMore })
352
+ .catch(() => {
353
+ // Best effort: a lost save costs the next load a server history fetch, nothing more.
354
+ });
355
+ }, PERSIST_DEBOUNCE_MS);
140
356
  }
141
357
  }
142
358
 
package/src/room.ts CHANGED
@@ -6,6 +6,7 @@
6
6
  */
7
7
 
8
8
  import type { Channel, ChannelStateChange, UnsubscribeFn } from '@foony/realtime';
9
+ import type { ChatStorage } from './storage.js';
9
10
  import { Messages } from './messages.js';
10
11
  import { Occupancy } from './occupancy.js';
11
12
  import { Presence } from './presence.js';
@@ -41,8 +42,9 @@ export class Room {
41
42
  private readonly channel: Channel,
42
43
  getClientId: () => string | null,
43
44
  options?: RoomOptions,
45
+ storage: ChatStorage | null = null,
44
46
  ) {
45
- this.messages = new Messages(channel, name, getClientId);
47
+ this.messages = new Messages(channel, name, getClientId, storage);
46
48
  this.presence = new Presence(channel);
47
49
  this.typing = new Typing(channel, getClientId, options?.typing?.heartbeatThrottleMs);
48
50
  this.reactions = new Reactions(channel, getClientId);
package/src/rooms.ts CHANGED
@@ -7,6 +7,7 @@
7
7
  import type { Realtime } from '@foony/realtime';
8
8
  import { roomChannelName } from './protocol.js';
9
9
  import { Room } from './room.js';
10
+ import type { ChatStorage } from './storage.js';
10
11
  import type { RoomOptions } from './types.js';
11
12
 
12
13
  /** Factory and cache for {@link Room} instances on a {@link ChatClient}. */
@@ -16,6 +17,7 @@ export class Rooms {
16
17
  constructor(
17
18
  private readonly realtime: Realtime,
18
19
  private readonly getClientId: () => string | null,
20
+ private readonly storage: ChatStorage | null = null,
19
21
  ) {}
20
22
 
21
23
  /** Get (or create) the room named `name`. Stable instance per name. */
@@ -23,7 +25,7 @@ export class Rooms {
23
25
  let existing = this.byName.get(name);
24
26
  if (!existing) {
25
27
  const channel = this.realtime.channels.get(roomChannelName(name), options?.cipher ? { cipher: options.cipher } : undefined);
26
- existing = new Room(name, channel, this.getClientId, options);
28
+ existing = new Room(name, channel, this.getClientId, options, this.storage);
27
29
  this.byName.set(name, existing);
28
30
  }
29
31
  return existing;
package/src/storage.ts ADDED
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Optional message persistence. A {@link ChatStorage} keeps a per-room snapshot between page
3
+ * loads, so a returning client renders instantly from its own copy and the server replays only
4
+ * what was missed (via the channel's resume cursor) instead of serving history again.
5
+ */
6
+
7
+ import type { MessageFrame } from '@foony/realtime';
8
+
9
+ /** Snapshot of one room persisted between sessions. */
10
+ export type PersistedRoomState = {
11
+ /** Raw message frames, oldest-first, replayed through the reconciler on load. */
12
+ readonly frames: readonly MessageFrame[];
13
+ /** Newest stored seq, seeded as the resume cursor so the server replays only the gap. */
14
+ readonly serial: number;
15
+ /** True when older messages remained on the server below the stored window when saved. */
16
+ readonly hasMore: boolean;
17
+ };
18
+
19
+ /** Where room snapshots live. Implementations must tolerate concurrent tabs (last write wins). */
20
+ export type ChatStorage = {
21
+ /** The stored snapshot for `room`, or null when none exists. */
22
+ load(room: string): Promise<PersistedRoomState | null>;
23
+ /** Overwrite `room`'s snapshot. */
24
+ save(room: string, state: PersistedRoomState): Promise<void>;
25
+ /** Drop `room`'s snapshot (its resume cursor aged out, or the room was released). */
26
+ remove(room: string): Promise<void>;
27
+ };
28
+
29
+ /** Object store holding one record per room inside the IndexedDB database. */
30
+ const STORE = 'rooms';
31
+
32
+ /**
33
+ * A {@link ChatStorage} backed by IndexedDB, or null where IndexedDB does not exist (Node,
34
+ * some webviews) so callers can pass the result straight to `new ChatClient(...)`.
35
+ *
36
+ * @example
37
+ * const chat = new ChatClient(realtime, { storage: indexedDbChatStorage() ?? undefined });
38
+ */
39
+ export function indexedDbChatStorage(dbName = 'foony-chat'): ChatStorage | null {
40
+ if (typeof indexedDB === 'undefined') {
41
+ return null;
42
+ }
43
+ const database = openDatabase(dbName);
44
+ return {
45
+ async load(room: string): Promise<PersistedRoomState | null> {
46
+ const db = await database;
47
+ return await requestOf<PersistedRoomState | undefined>(
48
+ db.transaction(STORE, 'readonly').objectStore(STORE).get(room),
49
+ ) ?? null;
50
+ },
51
+ async save(room: string, state: PersistedRoomState): Promise<void> {
52
+ const db = await database;
53
+ await requestOf(db.transaction(STORE, 'readwrite').objectStore(STORE).put(state, room));
54
+ },
55
+ async remove(room: string): Promise<void> {
56
+ const db = await database;
57
+ await requestOf(db.transaction(STORE, 'readwrite').objectStore(STORE).delete(room));
58
+ },
59
+ };
60
+ }
61
+
62
+ /** Open (or create) the database with its single room store. */
63
+ function openDatabase(dbName: string): Promise<IDBDatabase> {
64
+ return new Promise((resolve, reject) => {
65
+ const request = indexedDB.open(dbName, 1);
66
+ request.onupgradeneeded = () => {
67
+ request.result.createObjectStore(STORE);
68
+ };
69
+ request.onsuccess = () => resolve(request.result);
70
+ request.onerror = () => reject(request.error ?? new Error('indexedDB open failed'));
71
+ });
72
+ }
73
+
74
+ /** Promisify one IDBRequest. */
75
+ function requestOf<T>(request: IDBRequest<T>): Promise<T> {
76
+ return new Promise((resolve, reject) => {
77
+ request.onsuccess = () => resolve(request.result);
78
+ request.onerror = () => reject(request.error ?? new Error('indexedDB request failed'));
79
+ });
80
+ }