tickflare 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.
Files changed (58) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/README.md +3 -2
  3. package/dist/client/buffered.d.ts +25 -5
  4. package/dist/client/buffered.js +30 -7
  5. package/dist/client/buffered.js.map +1 -1
  6. package/dist/client/index.d.ts +62 -5
  7. package/dist/client/index.js +193 -14
  8. package/dist/client/index.js.map +1 -1
  9. package/dist/client/interpolate.d.ts +6 -5
  10. package/dist/client/interpolate.js +6 -5
  11. package/dist/client/interpolate.js.map +1 -1
  12. package/dist/client/lockstep.d.ts +23 -4
  13. package/dist/client/lockstep.js +47 -4
  14. package/dist/client/lockstep.js.map +1 -1
  15. package/dist/client/predict.js +16 -3
  16. package/dist/client/predict.js.map +1 -1
  17. package/dist/lockstep.d.ts +43 -4
  18. package/dist/lockstep.js +33 -0
  19. package/dist/lockstep.js.map +1 -1
  20. package/dist/protocol.d.ts +93 -5
  21. package/dist/protocol.js +12 -3
  22. package/dist/protocol.js.map +1 -1
  23. package/dist/server/gateway.d.ts +5 -0
  24. package/dist/server/gateway.js +14 -0
  25. package/dist/server/gateway.js.map +1 -1
  26. package/dist/server/index.d.ts +4 -3
  27. package/dist/server/index.js +3 -2
  28. package/dist/server/index.js.map +1 -1
  29. package/dist/server/lockstep.d.ts +29 -4
  30. package/dist/server/lockstep.js +72 -5
  31. package/dist/server/lockstep.js.map +1 -1
  32. package/dist/server/room.d.ts +118 -1
  33. package/dist/server/room.js +557 -30
  34. package/dist/server/room.js.map +1 -1
  35. package/dist/server/schema.d.ts +67 -0
  36. package/dist/server/schema.js +44 -0
  37. package/dist/server/schema.js.map +1 -0
  38. package/dist/server/spectators.d.ts +74 -0
  39. package/dist/server/spectators.js +190 -0
  40. package/dist/server/spectators.js.map +1 -0
  41. package/dist/server/storage.d.ts +13 -1
  42. package/dist/server/storage.js +23 -5
  43. package/dist/server/storage.js.map +1 -1
  44. package/package.json +1 -1
  45. package/src/client/buffered.ts +43 -13
  46. package/src/client/index.ts +237 -14
  47. package/src/client/interpolate.ts +6 -5
  48. package/src/client/lockstep.ts +68 -7
  49. package/src/client/predict.ts +16 -3
  50. package/src/lockstep.ts +67 -4
  51. package/src/protocol.ts +94 -4
  52. package/src/server/gateway.ts +14 -0
  53. package/src/server/index.ts +6 -0
  54. package/src/server/lockstep.ts +70 -6
  55. package/src/server/room.ts +589 -31
  56. package/src/server/schema.ts +101 -0
  57. package/src/server/spectators.ts +221 -0
  58. package/src/server/storage.ts +33 -6
@@ -0,0 +1,101 @@
1
+ import { reject } from "./room.js";
2
+
3
+ /**
4
+ * A schema from any library that implements Standard Schema
5
+ * (https://standardschema.dev): Zod, Valibot, ArkType and others. This is
6
+ * the part of that specification Tickflare reads, written out here so that
7
+ * it depends on none of them.
8
+ */
9
+ export interface StandardSchemaV1<Input = unknown, Output = Input> {
10
+ /** What the specification asks a schema to carry. */
11
+ readonly "~standard": {
12
+ /** The version of the specification the schema implements. */
13
+ readonly version: 1;
14
+ /** The library the schema comes from, such as `zod`. */
15
+ readonly vendor: string;
16
+ /** Checks a value. A schema with asynchronous checks returns a promise, which `parseWith` does not take. */
17
+ readonly validate: (value: unknown) => StandardSchemaResult<Output> | Promise<StandardSchemaResult<Output>>;
18
+ /** Never there at run time: it carries the types a schema takes and gives, for TypeScript to infer from. */
19
+ readonly types?:
20
+ | {
21
+ /** What the schema takes. */
22
+ readonly input: Input;
23
+ /** What it gives back. */
24
+ readonly output: Output;
25
+ }
26
+ | undefined;
27
+ };
28
+ }
29
+
30
+ /** What a Standard Schema makes of a value: the value as it should be, or what is wrong with it. */
31
+ export type StandardSchemaResult<Output> =
32
+ | {
33
+ /** The value as the schema gives it back: checked, and changed where the schema changes things. */
34
+ readonly value: Output;
35
+ /** Absent when the value fits. */
36
+ readonly issues?: undefined;
37
+ }
38
+ | {
39
+ /** What is wrong with the value, the first thing first. */
40
+ readonly issues: ReadonlyArray<StandardSchemaIssue>;
41
+ };
42
+
43
+ /** One thing a Standard Schema found wrong, and where. */
44
+ export interface StandardSchemaIssue {
45
+ /** What is wrong, in the library's words. */
46
+ readonly message: string;
47
+ /** Where in the value: the keys that lead there, each as it is or as `{ key }`. */
48
+ readonly path?:
49
+ | ReadonlyArray<
50
+ | PropertyKey
51
+ | {
52
+ /** One key on the way. */
53
+ readonly key: PropertyKey;
54
+ }
55
+ >
56
+ | undefined;
57
+ }
58
+
59
+ /** As much of a reason as the room remembers for a client that comes back: see `WelcomeFrame.refused`. */
60
+ const REASON_LENGTH = 120;
61
+
62
+ /**
63
+ * Checks what a client sent against a schema, and gives back what the
64
+ * schema makes of it. For `parseCommand`, and for `parseInput` in a
65
+ * lockstep room, with a schema from any library that implements Standard
66
+ * Schema:
67
+ *
68
+ * const Command = z.discriminatedUnion("type", [
69
+ * z.object({ type: z.literal("move"), x: z.number(), y: z.number() }),
70
+ * z.object({ type: z.literal("say"), text: z.string().max(200) }),
71
+ * ]);
72
+ *
73
+ * export class Game extends Room<State, z.infer<typeof Command>> {
74
+ * protected parseCommand(raw: unknown) {
75
+ * return parseWith(Command, raw);
76
+ * }
77
+ * }
78
+ *
79
+ * What does not fit is refused, as by `reject()`, with the first thing the
80
+ * schema found wrong: `invalid_command: Expected number (at x)`, cut to 120
81
+ * characters. A schema whose checks are asynchronous cannot be used: a hook
82
+ * cannot wait.
83
+ */
84
+ export function parseWith<Output>(schema: StandardSchemaV1<unknown, Output>, raw: unknown): Output {
85
+ const result = schema["~standard"].validate(raw);
86
+ if (typeof (result as PromiseLike<unknown>).then === "function") {
87
+ // Whatever it comes to, nobody is waiting for it.
88
+ (result as Promise<unknown>).then(undefined, () => {});
89
+ const problem = "parseWith: this schema validates asynchronously, and a hook cannot wait for it. Use one without asynchronous checks.";
90
+ // Thrown from `parseCommand` it reaches the client as `invalid_command`, which says nothing of this.
91
+ console.error(`[tickflare] ${problem}`);
92
+ throw new TypeError(problem);
93
+ }
94
+ const { issues } = result as StandardSchemaResult<Output>;
95
+ if (issues) {
96
+ const first = issues[0];
97
+ const path = (first?.path ?? []).map((part) => String(typeof part === "object" ? part.key : part)).join(".");
98
+ reject(`invalid_command: ${first?.message ?? "does not fit the schema"}${path ? ` (at ${path})` : ""}`.slice(0, REASON_LENGTH));
99
+ }
100
+ return (result as { value: Output }).value;
101
+ }
@@ -0,0 +1,221 @@
1
+ import { applyPatch, type Patch } from "../patch.js";
2
+ import type { Player } from "../protocol.js";
3
+ import { DeltaSender } from "./delta.js";
4
+
5
+ /** Marks the socket of a spectator. With no tag that is a player's id, the room takes it for nobody's. */
6
+ export const SPECTATOR_TAG = "\u0001spectator";
7
+ /** Starts the tag that says who a spectator is. */
8
+ export const SPECTATOR_ID_TAG = "\u0001s=";
9
+
10
+ /** A view the spectators have been sent, and what it is of. */
11
+ export interface Shown {
12
+ seq: number;
13
+ tick: number;
14
+ /** A copy nothing else changes. */
15
+ view: unknown;
16
+ }
17
+
18
+ /** A frame on its way to the spectators. */
19
+ interface Queued {
20
+ /** When it is let out, in epoch milliseconds. */
21
+ at: number;
22
+ frame: string;
23
+ /** It brings a view, whole or as a patch: what the spectators hold changes with it. */
24
+ view?: true;
25
+ /** For a frame that says who is here: who that is. */
26
+ players?: Player[];
27
+ }
28
+
29
+ /**
30
+ * How long the line goes on with nobody watching. A spectator whose
31
+ * connection dropped and who is back within this finds the line where it
32
+ * was, and misses only what was let out while they were away.
33
+ */
34
+ export const LINGER_MS = 20_000;
35
+
36
+ /**
37
+ * The most that may be waiting to be let out, in characters of frames. A
38
+ * line that holds more than this has a delay too long for how fast its room
39
+ * changes: it starts over, so that the room does not run out of memory.
40
+ */
41
+ const MAX_QUEUED_CHARS = 16_000_000;
42
+
43
+ /**
44
+ * What a room's spectators are sent, and when: everything, the same for all
45
+ * of them, and `delayMs` after the players were sent it.
46
+ *
47
+ * Each time the room sends its players something, the line takes the
48
+ * spectators' view of that moment, works out the patch from the view it took
49
+ * before, and queues the frame. A timer lets the frames out in order when
50
+ * their time has come, to every spectator connected then. Who is here and
51
+ * what the room broadcasts go through the same queue, so that nothing
52
+ * reaches a spectator sooner than the view it belongs with.
53
+ *
54
+ * Since all spectators are sent the same frames, the line also knows what
55
+ * every one of them holds: the latest view it let out, which is what one who
56
+ * connects is welcomed with. When the line starts there is no such view yet.
57
+ * Its first frame is a whole view, and a spectator welcomed before that has
58
+ * come due is told to wait for it.
59
+ *
60
+ * What waits is kept as the text that will be sent, and nothing else: with a
61
+ * long delay there is a lot of it. The view the spectators hold is worked
62
+ * out from the frames as they are let out.
63
+ *
64
+ * The line runs while someone watches and for `LINGER_MS` after. All of it
65
+ * is in memory: a room that restarts starts the line again, with a whole
66
+ * view for whoever is still connected.
67
+ */
68
+ export class SpectatorLine {
69
+ readonly #watching: () => WebSocket[];
70
+ #sender = new DeltaSender();
71
+ /** What `#sender` last sent. It sends to `#tape`, which keeps the frame instead. */
72
+ #caught: string | undefined;
73
+ readonly #tape = {
74
+ send: (frame: string) => {
75
+ this.#caught = frame;
76
+ },
77
+ } as unknown as WebSocket;
78
+ #queue: Queued[] = [];
79
+ #queuedChars = 0;
80
+ #shown: Shown | undefined;
81
+ #players: Player[] | undefined;
82
+ #running = false;
83
+ #idleSince: number | undefined;
84
+ #timer: ReturnType<typeof setTimeout> | undefined;
85
+
86
+ /** @param watching the open sockets of the spectators, asked for whenever something is let out */
87
+ constructor(watching: () => WebSocket[]) {
88
+ this.#watching = watching;
89
+ }
90
+
91
+ /** Whether views are being taken. */
92
+ get running(): boolean {
93
+ return this.#running;
94
+ }
95
+
96
+ /** The latest view let out, which is what every spectator holds. Undefined until the first has been. */
97
+ get shown(): Shown | undefined {
98
+ return this.#shown;
99
+ }
100
+
101
+ /** Who the spectators have been told is here. Undefined until they have been. */
102
+ get players(): Player[] | undefined {
103
+ return this.#players;
104
+ }
105
+
106
+ /**
107
+ * Whether the line goes on, now that someone is watching or nobody is: it
108
+ * stops once nobody has for `LINGER_MS`.
109
+ */
110
+ keep(watched: boolean, now = Date.now()): boolean {
111
+ if (watched) {
112
+ this.#idleSince = undefined;
113
+ return true;
114
+ }
115
+ this.#idleSince ??= now;
116
+ if (now - this.#idleSince < LINGER_MS) return true;
117
+ this.stop();
118
+ return false;
119
+ }
120
+
121
+ /**
122
+ * Takes the spectators' view as it is now, to be let out in `delayMs`.
123
+ * The first one taken starts the line and goes out whole, the others as
124
+ * what changed. `view` may be the room's own objects: what is kept is a
125
+ * copy.
126
+ */
127
+ take(view: unknown, seq: number, tick: number, delayMs: number, now = Date.now()): void {
128
+ this.#running = true;
129
+ this.#caught = undefined;
130
+ this.#sender.send([{ ws: this.#tape, id: "spectators", arrays: true }], seq, tick, undefined, () => view);
131
+ const frame = this.#caught as string | undefined;
132
+ this.#caught = undefined;
133
+ // Nothing a spectator sees has changed.
134
+ if (frame === undefined) return;
135
+ this.#push({ at: now + delayMs, frame, view: true }, now);
136
+ }
137
+
138
+ /** Queues who is here, as the whole list. */
139
+ tell(players: Player[], delayMs: number, now = Date.now()): void {
140
+ this.#push({ at: now + delayMs, frame: JSON.stringify({ t: "presence", players }), players }, now);
141
+ }
142
+
143
+ /** Queues a frame as it is: a message the room broadcast. */
144
+ say(frame: string, delayMs: number, now = Date.now()): void {
145
+ this.#push({ at: now + delayMs, frame }, now);
146
+ }
147
+
148
+ /** Forgets everything. The next view taken starts a new line. */
149
+ stop(): void {
150
+ if (this.#timer !== undefined) clearTimeout(this.#timer);
151
+ this.#timer = undefined;
152
+ this.#queue = [];
153
+ this.#queuedChars = 0;
154
+ this.#shown = undefined;
155
+ this.#players = undefined;
156
+ this.#running = false;
157
+ this.#idleSince = undefined;
158
+ this.#sender.reset();
159
+ }
160
+
161
+ #push(entry: Queued, now: number): void {
162
+ const last = this.#queue[this.#queue.length - 1];
163
+ // In the order they were queued in, whatever the delay has been changed to since.
164
+ if (last && entry.at < last.at) entry.at = last.at;
165
+ this.#queue.push(entry);
166
+ this.#queuedChars += entry.frame.length;
167
+ if (this.#queuedChars > MAX_QUEUED_CHARS) {
168
+ console.error(
169
+ `[tickflare] more than ${MAX_QUEUED_CHARS} characters are waiting to be sent to spectators; their view starts over. The delay is too long for how fast this room's state changes.`,
170
+ );
171
+ this.stop();
172
+ return;
173
+ }
174
+ this.release(now);
175
+ }
176
+
177
+ /** A frame that brings a view is let out: the spectators hold what it leaves them with. */
178
+ #hold(frame: string): void {
179
+ const sent = JSON.parse(frame) as
180
+ | { t: "state"; seq: number; tick: number; state: unknown }
181
+ | { t: "patch"; seq: number; tick: number; p: Patch };
182
+ if (sent.t === "state") {
183
+ this.#shown = { seq: sent.seq, tick: sent.tick, view: sent.state };
184
+ } else if (this.#shown) {
185
+ this.#shown = { seq: sent.seq, tick: sent.tick, view: applyPatch(this.#shown.view, sent.p) };
186
+ }
187
+ }
188
+
189
+ /** Lets out what has come due by `now`, and sets the timer for what has not. */
190
+ release(now = Date.now()): void {
191
+ if (this.#timer !== undefined) clearTimeout(this.#timer);
192
+ this.#timer = undefined;
193
+ let sockets: WebSocket[] | undefined;
194
+ while (this.#queue.length > 0 && this.#queue[0]!.at <= now) {
195
+ const entry = this.#queue.shift()!;
196
+ this.#queuedChars -= entry.frame.length;
197
+ if (entry.view) this.#hold(entry.frame);
198
+ if (entry.players) this.#players = entry.players;
199
+ for (const ws of (sockets ??= this.#watching())) {
200
+ try {
201
+ ws.send(entry.frame);
202
+ } catch {
203
+ // Socket is closing.
204
+ }
205
+ }
206
+ }
207
+ const next = this.#queue[0];
208
+ if (!next) return;
209
+ this.#timer = setTimeout(
210
+ () => {
211
+ this.#timer = undefined;
212
+ try {
213
+ this.release();
214
+ } catch (err) {
215
+ console.error("[tickflare] could not send to the spectators:", err);
216
+ }
217
+ },
218
+ Math.max(0, next.at - Date.now()),
219
+ );
220
+ }
221
+ }
@@ -7,6 +7,13 @@ export interface StoredRoom {
7
7
  roster: string;
8
8
  /** How many times the simulation has ticked. 0 in a room that does not tick. */
9
9
  tick: number;
10
+ /**
11
+ * Which commands of each client the room had handled when this state was
12
+ * saved, as JSON, or "" for none: what keeps a command that is sent again
13
+ * after a lost connection from being applied twice. In the same row as
14
+ * the state, so that the two are never of different moments.
15
+ */
16
+ handled: string;
10
17
  }
11
18
 
12
19
  /** Something a committed hook promised to deliver: a finished match, or a player handed to another room. */
@@ -34,7 +41,7 @@ export interface Forward {
34
41
  * nothing behind.
35
42
  *
36
43
  * Tables:
37
- * tickflare_room one row: seq, state, seats, tick counter
44
+ * tickflare_room one row: seq, state, seats, tick counter, commands handled
38
45
  * tickflare_parts the rest of a state or a delivery too long for one row
39
46
  * tickflare_timers named timers and when they fire
40
47
  * tickflare_meta small values by key (room id, invited players)
@@ -103,6 +110,13 @@ export class RoomStorage {
103
110
  } catch {
104
111
  sql.exec("ALTER TABLE tickflare_room ADD COLUMN tick INTEGER NOT NULL DEFAULT 0");
105
112
  }
113
+ // Which commands were handled came with protocol version 5. It is a column of the room's row
114
+ // for the same reason: one row a save.
115
+ try {
116
+ sql.exec("SELECT handled FROM tickflare_room LIMIT 0");
117
+ } catch {
118
+ sql.exec("ALTER TABLE tickflare_room ADD COLUMN handled TEXT NOT NULL DEFAULT ''");
119
+ }
106
120
  }
107
121
 
108
122
  /** Creates the tables, before the first thing is written. */
@@ -114,7 +128,8 @@ export class RoomStorage {
114
128
  seq INTEGER NOT NULL,
115
129
  state TEXT NOT NULL,
116
130
  players TEXT NOT NULL,
117
- tick INTEGER NOT NULL DEFAULT 0
131
+ tick INTEGER NOT NULL DEFAULT 0,
132
+ handled TEXT NOT NULL DEFAULT ''
118
133
  )`,
119
134
  );
120
135
  this.#tables();
@@ -195,11 +210,13 @@ export class RoomStorage {
195
210
  room(): StoredRoom | undefined {
196
211
  if (!this.#made) return undefined;
197
212
  const row = this.#sql
198
- .exec<{ seq: number; state: string; players: string; tick: number }>(
199
- "SELECT seq, state, players, tick FROM tickflare_room WHERE id = 1",
213
+ .exec<{ seq: number; state: string; players: string; tick: number; handled: string }>(
214
+ "SELECT seq, state, players, tick, handled FROM tickflare_room WHERE id = 1",
200
215
  )
201
216
  .toArray()[0];
202
- return row && { seq: row.seq, state: row.state + this.#rest("state"), roster: row.players, tick: row.tick };
217
+ return (
218
+ row && { seq: row.seq, state: row.state + this.#rest("state"), roster: row.players, tick: row.tick, handled: row.handled }
219
+ );
203
220
  }
204
221
 
205
222
  /**
@@ -211,15 +228,25 @@ export class RoomStorage {
211
228
  this.#make();
212
229
  const [first, ...rest] = pieces(room.state);
213
230
  this.#sql.exec(
214
- "INSERT OR REPLACE INTO tickflare_room (id, seq, state, players, tick) VALUES (1, ?, ?, ?, ?)",
231
+ "INSERT OR REPLACE INTO tickflare_room (id, seq, state, players, tick, handled) VALUES (1, ?, ?, ?, ?, ?)",
215
232
  room.seq,
216
233
  first,
217
234
  room.roster,
218
235
  room.tick,
236
+ room.handled,
219
237
  );
220
238
  this.#putRest("state", rest);
221
239
  }
222
240
 
241
+ /**
242
+ * Writes which commands were handled, and nothing else of the room: one
243
+ * row, however long the state is. False if the room has no row yet.
244
+ */
245
+ writeHandled(handled: string): boolean {
246
+ if (!this.#made) return false;
247
+ return this.#sql.exec("UPDATE tickflare_room SET handled = ? WHERE id = 1", handled).rowsWritten > 0;
248
+ }
249
+
223
250
  /** What follows the first piece of a text that was split, or "" for one that was not. */
224
251
  #rest(owner: string): string {
225
252
  if (!this.#split.has(owner)) return "";