tickflare 0.0.0-stage → 0.1.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 (117) hide show
  1. package/CHANGELOG.md +233 -0
  2. package/LICENSE +21 -0
  3. package/README.md +110 -2
  4. package/dist/binary.d.ts +91 -0
  5. package/dist/binary.js +466 -0
  6. package/dist/binary.js.map +1 -0
  7. package/dist/client/accounts.d.ts +193 -0
  8. package/dist/client/accounts.js +306 -0
  9. package/dist/client/accounts.js.map +1 -0
  10. package/dist/client/draft.d.ts +17 -0
  11. package/dist/client/draft.js +133 -0
  12. package/dist/client/draft.js.map +1 -0
  13. package/dist/client/index.d.ts +161 -0
  14. package/dist/client/index.js +436 -0
  15. package/dist/client/index.js.map +1 -0
  16. package/dist/client/interpolate.d.ts +31 -0
  17. package/dist/client/interpolate.js +59 -0
  18. package/dist/client/interpolate.js.map +1 -0
  19. package/dist/client/lockstep.d.ts +86 -0
  20. package/dist/client/lockstep.js +339 -0
  21. package/dist/client/lockstep.js.map +1 -0
  22. package/dist/client/matchmaking.d.ts +21 -0
  23. package/dist/client/matchmaking.js +55 -0
  24. package/dist/client/matchmaking.js.map +1 -0
  25. package/dist/client/pacer.d.ts +22 -0
  26. package/dist/client/pacer.js +65 -0
  27. package/dist/client/pacer.js.map +1 -0
  28. package/dist/client/predict.d.ts +75 -0
  29. package/dist/client/predict.js +203 -0
  30. package/dist/client/predict.js.map +1 -0
  31. package/dist/client/token.d.ts +10 -0
  32. package/dist/client/token.js +15 -0
  33. package/dist/client/token.js.map +1 -0
  34. package/dist/lockstep.d.ts +154 -0
  35. package/dist/lockstep.js +140 -0
  36. package/dist/lockstep.js.map +1 -0
  37. package/dist/patch.d.ts +54 -0
  38. package/dist/patch.js +186 -0
  39. package/dist/patch.js.map +1 -0
  40. package/dist/protocol.d.ts +230 -0
  41. package/dist/protocol.js +50 -0
  42. package/dist/protocol.js.map +1 -0
  43. package/dist/server/accounts.d.ts +320 -0
  44. package/dist/server/accounts.js +1223 -0
  45. package/dist/server/accounts.js.map +1 -0
  46. package/dist/server/delta.d.ts +50 -0
  47. package/dist/server/delta.js +426 -0
  48. package/dist/server/delta.js.map +1 -0
  49. package/dist/server/frames.d.ts +15 -0
  50. package/dist/server/frames.js +23 -0
  51. package/dist/server/frames.js.map +1 -0
  52. package/dist/server/gateway.d.ts +80 -0
  53. package/dist/server/gateway.js +144 -0
  54. package/dist/server/gateway.js.map +1 -0
  55. package/dist/server/index.d.ts +21 -0
  56. package/dist/server/index.js +22 -0
  57. package/dist/server/index.js.map +1 -0
  58. package/dist/server/limiter.d.ts +12 -0
  59. package/dist/server/limiter.js +43 -0
  60. package/dist/server/limiter.js.map +1 -0
  61. package/dist/server/lockstep.d.ts +126 -0
  62. package/dist/server/lockstep.js +544 -0
  63. package/dist/server/lockstep.js.map +1 -0
  64. package/dist/server/matches.d.ts +31 -0
  65. package/dist/server/matches.js +69 -0
  66. package/dist/server/matches.js.map +1 -0
  67. package/dist/server/matchmaker.d.ts +121 -0
  68. package/dist/server/matchmaker.js +479 -0
  69. package/dist/server/matchmaker.js.map +1 -0
  70. package/dist/server/room.d.ts +383 -0
  71. package/dist/server/room.js +1766 -0
  72. package/dist/server/room.js.map +1 -0
  73. package/dist/server/signals.d.ts +18 -0
  74. package/dist/server/signals.js +37 -0
  75. package/dist/server/signals.js.map +1 -0
  76. package/dist/server/storage.d.ts +117 -0
  77. package/dist/server/storage.js +330 -0
  78. package/dist/server/storage.js.map +1 -0
  79. package/dist/server/tokens.d.ts +74 -0
  80. package/dist/server/tokens.js +117 -0
  81. package/dist/server/tokens.js.map +1 -0
  82. package/dist/server/tracked.d.ts +47 -0
  83. package/dist/server/tracked.js +270 -0
  84. package/dist/server/tracked.js.map +1 -0
  85. package/dist/world.d.ts +20 -0
  86. package/dist/world.js +21 -0
  87. package/dist/world.js.map +1 -0
  88. package/package.json +74 -4
  89. package/src/binary.ts +496 -0
  90. package/src/client/accounts.ts +423 -0
  91. package/src/client/draft.ts +138 -0
  92. package/src/client/index.ts +573 -0
  93. package/src/client/interpolate.ts +60 -0
  94. package/src/client/lockstep.ts +398 -0
  95. package/src/client/matchmaking.ts +61 -0
  96. package/src/client/pacer.ts +67 -0
  97. package/src/client/predict.ts +239 -0
  98. package/src/client/token.ts +22 -0
  99. package/src/lockstep.ts +285 -0
  100. package/src/patch.ts +188 -0
  101. package/src/protocol.ts +260 -0
  102. package/src/server/accounts.ts +1474 -0
  103. package/src/server/delta.ts +467 -0
  104. package/src/server/frames.ts +23 -0
  105. package/src/server/gateway.ts +213 -0
  106. package/src/server/index.ts +85 -0
  107. package/src/server/limiter.ts +41 -0
  108. package/src/server/lockstep.ts +611 -0
  109. package/src/server/matches.ts +99 -0
  110. package/src/server/matchmaker.ts +537 -0
  111. package/src/server/room.ts +1867 -0
  112. package/src/server/signals.ts +46 -0
  113. package/src/server/storage.ts +392 -0
  114. package/src/server/tokens.ts +184 -0
  115. package/src/server/tracked.ts +260 -0
  116. package/src/world.ts +29 -0
  117. package/tools/rooms-report.mjs +168 -0
@@ -0,0 +1,260 @@
1
+
2
+ /**
3
+ * Tracks what a hook writes to the room's state, so that the kernel knows
4
+ * whether anything changed and can put it back, without making a copy of the
5
+ * whole state before every hook.
6
+ *
7
+ * Inside a hook `this.state` is not the state itself but a proxy of it, and
8
+ * so is every object and array reached through it. Reading passes straight
9
+ * through. Writing is noted first: which slot, and what was in it. Undoing
10
+ * a hook is replaying those notes backwards.
11
+ *
12
+ * The state underneath stays made of plain objects only: a proxy that is
13
+ * written into the state is replaced by the object it stands for. So the
14
+ * simulation, the views and the saves, which run outside these hooks, work
15
+ * on plain objects at full speed.
16
+ */
17
+
18
+ /** The object behind each proxy, for every tracker: `plain()` needs no tracker to look it up. */
19
+ const TARGETS = new WeakMap<object, object>();
20
+
21
+ /** One write, as it has to be undone. */
22
+ type Note =
23
+ | { target: Record<PropertyKey, unknown>; key: PropertyKey; had: boolean; value: unknown; length?: number }
24
+ | { target: object; key: PropertyKey; descriptor: PropertyDescriptor | undefined }
25
+ | { undo: () => void };
26
+
27
+ /** An object literal, or anything else with no class of its own: what JSON turns back into an object. */
28
+ function isPlainObject(value: object): boolean {
29
+ const prototype: unknown = Object.getPrototypeOf(value);
30
+ return prototype === Object.prototype || prototype === null;
31
+ }
32
+
33
+ const NOT_JSON = "Room state must be JSON-serializable";
34
+ const OUTSIDE =
35
+ "The room's state was changed outside a hook. Change it in a hook, or from `act()` after an await.";
36
+
37
+ /**
38
+ * The object itself behind something read from `this.state` inside a hook,
39
+ * for the few things a proxy cannot stand in for: `structuredClone`, or
40
+ * comparing with `===` against an object that did not come from the state.
41
+ * Read from it; a change made through it is not tracked, so it is neither
42
+ * sent nor undone with the hook.
43
+ */
44
+ export function plain<T>(value: T): T {
45
+ if (typeof value !== "object" || value === null) return value;
46
+ return (TARGETS.get(value) as T | undefined) ?? value;
47
+ }
48
+
49
+ export class Tracker {
50
+ /** The proxy of each object of the state that has been read through one. */
51
+ #proxies = new WeakMap<object, object>();
52
+ /** What the running hook has written, oldest first. Null while no hook is running. */
53
+ #notes: Note[] | null = null;
54
+ /**
55
+ * The keys of each object the running hook has deleted a key from, as they
56
+ * were before. Putting a deleted key back puts it last, and the order of
57
+ * the keys is part of what the state looks like as JSON.
58
+ */
59
+ #orders = new Map<Record<PropertyKey, unknown>, string[]>();
60
+ #handler: ProxyHandler<Record<PropertyKey, unknown>>;
61
+ /** `includes`, `indexOf` and `lastIndexOf` for proxied arrays: see `#search`. */
62
+ #searches: Record<string, (this: unknown[], ...args: unknown[]) => unknown>;
63
+
64
+ constructor() {
65
+ this.#handler = {
66
+ get: (target, key, receiver) => this.#get(target, key, receiver),
67
+ set: (target, key, value) => this.#set(target, key, value),
68
+ deleteProperty: (target, key) => this.#delete(target, key),
69
+ defineProperty: (target, key, descriptor) => this.#define(target, key, descriptor),
70
+ };
71
+ this.#searches = {
72
+ includes: this.#search("includes"),
73
+ indexOf: this.#search("indexOf"),
74
+ lastIndexOf: this.#search("lastIndexOf"),
75
+ };
76
+ }
77
+
78
+ /** Whether a hook is being tracked. */
79
+ get active(): boolean {
80
+ return this.#notes !== null;
81
+ }
82
+
83
+ /** Whether the hook being tracked has changed anything so far. */
84
+ get changed(): boolean {
85
+ return this.#notes !== null && this.#notes.length > 0;
86
+ }
87
+
88
+ /** Start tracking a hook. */
89
+ begin(): void {
90
+ this.#notes = [];
91
+ }
92
+
93
+ /** The hook is over and its changes stand. */
94
+ end(): void {
95
+ this.#notes = null;
96
+ this.#orders.clear();
97
+ }
98
+
99
+ /** The hook is over and everything it wrote is put back. */
100
+ undo(): void {
101
+ const notes = this.#notes;
102
+ this.#notes = null;
103
+ if (!notes) return;
104
+ for (let i = notes.length - 1; i >= 0; i--) {
105
+ const note = notes[i]!;
106
+ if ("undo" in note) {
107
+ note.undo();
108
+ } else if ("descriptor" in note) {
109
+ if (note.descriptor) Object.defineProperty(note.target, note.key, note.descriptor);
110
+ else delete (note.target as Record<PropertyKey, unknown>)[note.key];
111
+ } else {
112
+ if (note.had) note.target[note.key] = note.value;
113
+ else delete note.target[note.key];
114
+ // Writing past the end of an array made it longer, and deleting does not make it shorter.
115
+ if (note.length !== undefined) (note.target as unknown as unknown[]).length = note.length;
116
+ }
117
+ }
118
+ for (const [target, keys] of this.#orders) {
119
+ // Every key is back, with its value. Taking each out and putting it in again, in the
120
+ // order they were in, leaves them in that order.
121
+ for (const key of keys) {
122
+ // A key the hook added before it first deleted one is in the list, and gone again by now.
123
+ if (!Object.hasOwn(target, key)) continue;
124
+ const value = target[key];
125
+ delete target[key];
126
+ target[key] = value;
127
+ }
128
+ }
129
+ this.#orders.clear();
130
+ }
131
+
132
+ /** Note a change the tracker cannot see by itself, with how to undo it. */
133
+ note(undo: () => void): void {
134
+ if (this.#notes === null) throw new TypeError(OUTSIDE);
135
+ this.#notes.push({ undo });
136
+ }
137
+
138
+ /** What `this.state` gives a hook: the proxy of `value` if it is an object or an array of the state. */
139
+ wrap<T>(value: T): T {
140
+ if (typeof value !== "object" || value === null) return value;
141
+ const known = this.#proxies.get(value);
142
+ if (known) return known as T;
143
+ if (!Array.isArray(value) && !isPlainObject(value)) return value;
144
+ const proxy = new Proxy(value as Record<PropertyKey, unknown>, this.#handler);
145
+ this.#proxies.set(value, proxy);
146
+ TARGETS.set(proxy, value);
147
+ return proxy as T;
148
+ }
149
+
150
+ /**
151
+ * A value on its way into the state, with every proxy in it replaced by the
152
+ * object it stands for. New objects are looked through, and changed in
153
+ * place: they are the state's from here on.
154
+ */
155
+ clean<T>(value: T): T {
156
+ return this.#clean(value, undefined) as T;
157
+ }
158
+
159
+ #clean(value: unknown, above: Set<object> | undefined): unknown {
160
+ if (typeof value === "bigint") throw new TypeError(NOT_JSON);
161
+ if (typeof value !== "object" || value === null) return value;
162
+ const target = TARGETS.get(value);
163
+ if (target) return target;
164
+ // Already part of the state, which holds no proxies; or not something JSON looks into.
165
+ if (this.#proxies.has(value)) return value;
166
+ const list = Array.isArray(value);
167
+ if (!list && !isPlainObject(value)) return value;
168
+ if (above?.has(value)) throw new TypeError(NOT_JSON);
169
+ (above ??= new Set()).add(value);
170
+ const inside = value as Record<PropertyKey, unknown>;
171
+ for (const key of list ? (value as unknown[]).keys() : Object.keys(value)) {
172
+ const item = inside[key];
173
+ if (typeof item === "bigint") throw new TypeError(NOT_JSON);
174
+ if (typeof item !== "object" || item === null) continue;
175
+ const cleaned = this.#clean(item, above);
176
+ if (cleaned !== item) inside[key] = cleaned;
177
+ }
178
+ above.delete(value);
179
+ return value;
180
+ }
181
+
182
+ #get(target: Record<PropertyKey, unknown>, key: PropertyKey, receiver: unknown): unknown {
183
+ const value = Reflect.get(target, key, receiver);
184
+ if (typeof value === "function") {
185
+ return typeof key === "string" && Array.isArray(target) && Object.hasOwn(this.#searches, key)
186
+ ? this.#searches[key]
187
+ : value;
188
+ }
189
+ if (typeof value !== "object" || value === null) return value;
190
+ // A proxy has to hand out a frozen object's own values as they are.
191
+ if (!Object.isExtensible(target)) {
192
+ const own = Reflect.getOwnPropertyDescriptor(target, key);
193
+ if (own && !own.configurable && !own.writable) return value;
194
+ }
195
+ return this.wrap(value);
196
+ }
197
+
198
+ #set(target: Record<PropertyKey, unknown>, key: PropertyKey, incoming: unknown): boolean {
199
+ const notes = this.#notes;
200
+ if (notes === null) throw new TypeError(OUTSIDE);
201
+ const value = this.#clean(incoming, undefined);
202
+ const had = Object.hasOwn(target, key);
203
+ const old = had ? target[key] : undefined;
204
+ if (had && Object.is(old, value)) return true;
205
+
206
+ if (!Array.isArray(target)) {
207
+ if (!Reflect.set(target, key, value)) return false;
208
+ notes.push({ target, key, had, value: old });
209
+ return true;
210
+ }
211
+ const length = target.length;
212
+ // Making an array shorter drops what was past its new end without a word.
213
+ const dropped: Note[] = [];
214
+ if (key === "length" && typeof value === "number" && value < length) {
215
+ for (let i = value; i < length; i++) {
216
+ if (i in target) dropped.push({ target, key: String(i), had: true, value: target[i], length });
217
+ }
218
+ }
219
+ if (!Reflect.set(target, key, value)) return false;
220
+ notes.push(...dropped, { target, key, had, value: old, length });
221
+ return true;
222
+ }
223
+
224
+ #delete(target: Record<PropertyKey, unknown>, key: PropertyKey): boolean {
225
+ const notes = this.#notes;
226
+ if (notes === null) throw new TypeError(OUTSIDE);
227
+ if (!Object.hasOwn(target, key)) return Reflect.deleteProperty(target, key);
228
+ const old = target[key];
229
+ const list = Array.isArray(target);
230
+ if (!list && !this.#orders.has(target)) this.#orders.set(target, Object.keys(target));
231
+ if (!Reflect.deleteProperty(target, key)) return false;
232
+ const note: Note = { target, key, had: true, value: old };
233
+ if (list) note.length = target.length;
234
+ notes.push(note);
235
+ return true;
236
+ }
237
+
238
+ #define(target: Record<PropertyKey, unknown>, key: PropertyKey, descriptor: PropertyDescriptor): boolean {
239
+ const notes = this.#notes;
240
+ if (notes === null) throw new TypeError(OUTSIDE);
241
+ const before = Reflect.getOwnPropertyDescriptor(target, key);
242
+ const cleaned = "value" in descriptor ? { ...descriptor, value: this.#clean(descriptor.value, undefined) } : descriptor;
243
+ if (!Reflect.defineProperty(target, key, cleaned)) return false;
244
+ notes.push({ target, key, descriptor: before });
245
+ return true;
246
+ }
247
+
248
+ /**
249
+ * A new object that a hook has just put in an array is still held by the
250
+ * hook as the object itself, while the array hands out its proxy. So
251
+ * looking for it in the array has to compare the objects underneath.
252
+ */
253
+ #search(name: "includes" | "indexOf" | "lastIndexOf") {
254
+ const method = Array.prototype[name] as (this: unknown[], ...args: unknown[]) => unknown;
255
+ return function (this: unknown[], ...args: unknown[]): unknown {
256
+ if (args.length > 0) args[0] = plain(args[0]);
257
+ return method.apply(plain(this), args);
258
+ };
259
+ }
260
+ }
package/src/world.ts ADDED
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Helpers for worlds that are too big for one room. Cut the world into
3
+ * square cells, give each cell its own room, and hand players from room to
4
+ * room with `movePlayer` as they cross a border.
5
+ */
6
+
7
+ /**
8
+ * The id of the room responsible for a position, for a world cut into square
9
+ * cells `cellSize` units wide. Positions may be negative. The result is a
10
+ * valid room id, e.g. `overworld_3_-2`.
11
+ */
12
+ export function shardFor(x: number, y: number, cellSize: number, world = "world"): string {
13
+ return `${world}_${Math.floor(x / cellSize)}_${Math.floor(y / cellSize)}`;
14
+ }
15
+
16
+ /** A cell of a world cut into squares: its column and row. */
17
+ export interface Cell {
18
+ /** Column: 0 holds x from 0 up to `cellSize`, -1 the column before it. */
19
+ cx: number;
20
+ /** Row: 0 holds y from 0 up to `cellSize`, -1 the row before it. */
21
+ cy: number;
22
+ }
23
+
24
+ /** The cell a shard id stands for, or undefined if it is not one of `world`'s. */
25
+ export function cellOf(shardId: string, world = "world"): Cell | undefined {
26
+ const match = /^(.*)_(-?\d+)_(-?\d+)$/.exec(shardId);
27
+ if (!match || match[1] !== world) return undefined;
28
+ return { cx: Number(match[2]), cy: Number(match[3]) };
29
+ }
@@ -0,0 +1,168 @@
1
+ #!/usr/bin/env node
2
+ // Which rooms Cloudflare billed you for, and for how long, from its analytics.
3
+ //
4
+ // CLOUDFLARE_API_TOKEN=… CLOUDFLARE_ACCOUNT_ID=… node tools/rooms-report.mjs --worker my-game --since 24h
5
+ //
6
+ // The token needs to read account analytics and Workers settings ("Account Analytics: Read" and
7
+ // "Workers Scripts: Read"). It is read from the environment only, never from an argument, so
8
+ // that it does not end up in your shell's history.
9
+ //
10
+ // Options:
11
+ // --worker <name> the Worker whose rooms to report on (its Durable Object namespaces)
12
+ // --namespace <id> a namespace by id instead, for a Worker that is gone; may repeat
13
+ // --since <time> how far back: 30m, 6h, 7d, or a date such as 2026-11-01T00:00:00Z. Default 24h.
14
+ // --top <n> how many rooms to list, the most expensive first. Default 30.
15
+ // --json print JSON instead of a table
16
+ //
17
+ // Analytics lag by some minutes, and are kept for about a month. Once a Worker is deleted, its
18
+ // rooms' analytics can no longer be asked for, even by namespace.
19
+
20
+ const args = process.argv.slice(2);
21
+ const option = (name) => {
22
+ const at = args.indexOf(`--${name}`);
23
+ return at === -1 ? undefined : args[at + 1];
24
+ };
25
+ const all = (name) => args.flatMap((arg, at) => (arg === `--${name}` ? [args[at + 1]] : []));
26
+
27
+ const token = process.env.CLOUDFLARE_API_TOKEN;
28
+ const account = process.env.CLOUDFLARE_ACCOUNT_ID;
29
+ const worker = option("worker");
30
+ const top = Number(option("top") ?? 30);
31
+ const json = args.includes("--json");
32
+ if (!token || !account) fail("Set CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID.");
33
+ if (!worker && all("namespace").length === 0) fail("Say which rooms: --worker <name>, or --namespace <id>.");
34
+
35
+ /** Workers Paid list prices, November 2026, before what the plan includes each month. */
36
+ const PRICE = { perGbSecond: 12.5 / 1e6, perRowWritten: 1 / 1e6, perRequest: 0.15 / 1e6, messagesPerRequest: 20 };
37
+
38
+ function fail(message) {
39
+ console.error(message);
40
+ process.exit(2);
41
+ }
42
+
43
+ function since(text = "24h") {
44
+ const relative = /^(\d+(?:\.\d+)?)(m|h|d)$/.exec(text);
45
+ if (relative) {
46
+ const unit = { m: 60_000, h: 3_600_000, d: 86_400_000 }[relative[2]];
47
+ return new Date(Date.now() - Number(relative[1]) * unit);
48
+ }
49
+ const date = new Date(text);
50
+ if (Number.isNaN(date.getTime())) fail(`--since: not a time: ${text}`);
51
+ return date;
52
+ }
53
+
54
+ async function api(path) {
55
+ const response = await fetch(`https://api.cloudflare.com/client/v4${path}`, { headers: { Authorization: `Bearer ${token}` } });
56
+ const body = await response.json().catch(() => null);
57
+ if (!response.ok || !body?.success) fail(`Cloudflare refused ${path.split("?")[0]} (${response.status}): ${JSON.stringify(body?.errors ?? body).slice(0, 300)}`);
58
+ return body.result;
59
+ }
60
+
61
+ async function graphql(query) {
62
+ const response = await fetch("https://api.cloudflare.com/client/v4/graphql", {
63
+ method: "POST",
64
+ headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
65
+ body: JSON.stringify({ query }),
66
+ });
67
+ const body = await response.json().catch(() => null);
68
+ if (!response.ok || body?.errors?.length) {
69
+ fail(`Cloudflare's analytics refused (${response.status}): ${JSON.stringify(body?.errors ?? body).slice(0, 400)}`);
70
+ }
71
+ return body.data.viewer.accounts[0];
72
+ }
73
+
74
+ /** The Worker's Durable Object namespaces, by id, with their class names. */
75
+ async function namespaces() {
76
+ const known = new Map(all("namespace").map((id) => [id, id]));
77
+ if (!worker) return known;
78
+ for (let page = 1; ; page++) {
79
+ const result = await api(`/accounts/${account}/workers/durable_objects/namespaces?per_page=100&page=${page}`);
80
+ for (const namespace of result) if (namespace.script === worker) known.set(namespace.id, namespace.class);
81
+ if (result.length < 100) break;
82
+ }
83
+ if (known.size === 0) fail(`The Worker ${worker} has no Durable Object namespaces on this account.`);
84
+ return known;
85
+ }
86
+
87
+ const classes = await namespaces();
88
+ const from = since(option("since"));
89
+ const window = `datetime_geq: "${from.toISOString()}", datetime_leq: "${new Date().toISOString()}", namespaceId_in: ${JSON.stringify([...classes.keys()])}`;
90
+
91
+ // Every room, with what it was billed for. `name` is what the room was reached by: its id.
92
+ const data = await graphql(`{ viewer { accounts(filter: { accountTag: "${account}" }) {
93
+ durableObjectsPeriodicGroups(limit: 10000, filter: { ${window} }) {
94
+ dimensions { namespaceId name objectId }
95
+ sum { activeTime duration rowsWritten inboundWebsocketMsgCount }
96
+ max { activeWebsocketConnections }
97
+ }
98
+ } } }`);
99
+
100
+ const rooms = (data.durableObjectsPeriodicGroups ?? []).map(({ dimensions, sum, max }) => ({
101
+ class: classes.get(dimensions.namespaceId) ?? dimensions.namespaceId,
102
+ room: dimensions.name || `(no name) ${dimensions.objectId.slice(0, 12)}`,
103
+ objectId: dimensions.objectId,
104
+ namespaceId: dimensions.namespaceId,
105
+ awakeSeconds: sum.activeTime / 1e6,
106
+ cost: sum.duration * PRICE.perGbSecond + sum.rowsWritten * PRICE.perRowWritten + (sum.inboundWebsocketMsgCount / PRICE.messagesPerRequest) * PRICE.perRequest,
107
+ rowsWritten: sum.rowsWritten,
108
+ mostConnections: max.activeWebsocketConnections,
109
+ }));
110
+ rooms.sort((a, b) => b.cost - a.cost);
111
+
112
+ // For the most expensive, how long they were awake with nobody connected: five-minute spans in
113
+ // which Cloudflare counted time awake and not one connection. A room that plays on alone on
114
+ // purpose shows up here as well as one that should have gone to sleep.
115
+ const listed = rooms.slice(0, top);
116
+ for (const room of listed) {
117
+ const spans = await graphql(`{ viewer { accounts(filter: { accountTag: "${account}" }) {
118
+ durableObjectsPeriodicGroups(limit: 10000, filter: { ${window.replace(/namespaceId_in: [^\]]*\]/, `namespaceId: "${room.namespaceId}"`)}, objectId: "${room.objectId}" }) {
119
+ dimensions { datetimeFiveMinutes }
120
+ sum { activeTime }
121
+ max { activeWebsocketConnections }
122
+ }
123
+ } } }`);
124
+ let alone = 0;
125
+ let longest = 0;
126
+ let run = 0;
127
+ const ordered = (spans.durableObjectsPeriodicGroups ?? []).sort((a, b) =>
128
+ a.dimensions.datetimeFiveMinutes < b.dimensions.datetimeFiveMinutes ? -1 : 1,
129
+ );
130
+ for (const span of ordered) {
131
+ if (span.sum.activeTime > 0 && span.max.activeWebsocketConnections === 0) {
132
+ alone += span.sum.activeTime / 1e6;
133
+ run += span.sum.activeTime / 1e6;
134
+ longest = Math.max(longest, run);
135
+ } else {
136
+ run = 0;
137
+ }
138
+ }
139
+ room.awakeAloneSeconds = alone;
140
+ room.longestAloneSeconds = longest;
141
+ }
142
+
143
+ const total = rooms.reduce((sum, room) => sum + room.cost, 0);
144
+ const awake = rooms.reduce((sum, room) => sum + room.awakeSeconds, 0);
145
+ const flags = (room) =>
146
+ [
147
+ room.longestAloneSeconds >= 600 ? "awake 10+ min with nobody connected" : room.awakeAloneSeconds >= 60 ? "awake with nobody connected" : "",
148
+ room.awakeSeconds >= 3 * 3600 ? "awake 3+ hours" : "",
149
+ ]
150
+ .filter(Boolean)
151
+ .join("; ");
152
+
153
+ if (json) {
154
+ console.log(JSON.stringify({ since: from.toISOString(), rooms: rooms.length, awakeHours: awake / 3600, cost: total, top: listed.map((room) => ({ ...room, flags: flags(room) || undefined })) }, null, 2));
155
+ process.exit(0);
156
+ }
157
+
158
+ const hours = (seconds) => (seconds >= 3600 ? `${(seconds / 3600).toFixed(1)} h` : seconds >= 60 ? `${(seconds / 60).toFixed(1)} min` : `${seconds.toFixed(1)} s`);
159
+ const money = (dollars) => (dollars >= 0.01 ? `$${dollars.toFixed(2)}` : `$${dollars.toFixed(5)}`);
160
+ console.log(`Since ${from.toISOString()}: ${rooms.length} rooms, awake ${hours(awake)} in all, ${money(total)} at list price before what the plan includes.`);
161
+ console.log("");
162
+ const rows = [["Room", "Class", "Awake", "Alone", "Cost", "Most connected", ""]];
163
+ for (const room of listed) {
164
+ rows.push([room.room, room.class, hours(room.awakeSeconds), hours(room.awakeAloneSeconds), money(room.cost), String(room.mostConnections), flags(room)]);
165
+ }
166
+ const widths = rows[0].map((_, column) => Math.max(...rows.map((row) => row[column].length)));
167
+ for (const row of rows) console.log(row.map((cell, column) => cell.padEnd(widths[column])).join(" ").trimEnd());
168
+ if (rooms.length > listed.length) console.log(`\n${rooms.length - listed.length} more rooms, cheaper than these. --top to see more.`);