Skip to content
Source
Sign inSign up
samwillis/one-million-boxes
Open History to see the last commit

realtime.spec.ts

196 lines7.8 KB

1import { expect, test } from "@playwright/test"
2import type { WebSocketRoute } from "@playwright/test"
3import { userInfo } from "node:os"
4import pg from "pg"
5import { coordsToEdgeId, getBoxEdges } from "../../shared/edge-math"
6import { TEAMS } from "../../shared/teams"
7import { GameStore } from "../../server/store"
8import { openGame } from "./helpers"
9​
10test("staggered browser reloads recover and report snapshot timings and sizes", async ({
11 browser,
12 baseURL,
13}, testInfo) => {
14 test.setTimeout(60000)
15 const contexts = await Promise.all([
16 browser.newContext({ baseURL }),
17 browser.newContext({ baseURL }),
18 ])
19 try {
20 const pages = await Promise.all(contexts.map((context) => context.newPage()))
21 await Promise.all(pages.map(openGame))
22 const observations = pages.map(() => ({
23 loaded: [] as Array<{
24 receivedMs: number
25 appliedMs: number
26 applyDurationMs: number
27 rows: number
28 packedKB: number
29 protocolRowsKB: number
30 }>,
31 rowBytes: new Map<string, number>(),
32 boardId: "",
33 rejections: [] as string[],
34 }))
35 pages.forEach((page, index) => {
36 const result = observations[index]
37 page.on("console", async (message) => {
38 if (message.text().startsWith("[Board Realtime] Game state loaded"))
39 result.loaded.push(await message.args()[1].jsonValue())
40 })
41 page.on("websocket", (socket) => {
42 socket.on("framereceived", ({ payload }) => {
43 const frame = JSON.parse(payload.toString())
44 if (frame.type === "subscribe_rejected") result.rejections.push(frame.code)
45 if (frame.type === "subscribed" && frame.columns[0]?.name === "tile_id") {
46 result.boardId = frame.live_id
47 result.rowBytes.set(frame.live_id, 0)
48 }
49 if (frame.type === "baseline_sync_batch" && frame.live_id === result.boardId)
50 result.rowBytes.set(
51 frame.live_id,
52 (result.rowBytes.get(frame.live_id) ?? 0) +
53 frame.rows.reduce(
54 (total: number, row: unknown) => total + Buffer.byteLength(JSON.stringify(row)),
55 0,
56 ),
57 )
58 })
59 })
60 })
61 await pages[0].reload()
62 // Join while the other browser is still receiving the large board snapshot.
63 await pages[1].waitForTimeout(400)
64 await pages[1].reload()
65 for (const [index, page] of pages.entries()) {
66 const result = observations[index]
67 await expect.poll(() => result.loaded.length, { timeout: 30000 }).toBeGreaterThan(0)
68 await expect(page.getByTestId("connection-status")).toBeHidden({ timeout: 30000 })
69 const loaded = result.loaded.at(-1)!
70 expect(loaded.rows).toBe(15625)
71 expect(loaded.packedKB).toBe(1125.75)
72 expect(loaded.appliedMs).toBeGreaterThanOrEqual(loaded.receivedMs)
73 expect(loaded.applyDurationMs).toBeGreaterThanOrEqual(0)
74 expect(loaded.protocolRowsKB).toBe(result.rowBytes.get(result.boardId)! / 1000)
75 }
76 await testInfo.attach("reload-diagnostics", {
77 body: JSON.stringify(observations, (_key, value) =>
78 value instanceof Map ? Object.fromEntries(value) : value,
79 ),
80 contentType: "application/json",
81 })
82 } finally {
83 await Promise.all(contexts.map((context) => context.close()))
84 }
85})
86​
87test("two browsers claim boxes, reconnect, reload and observe an atomic game reset", async ({
88 browser,
89 baseURL,
90}) => {
91 test.setTimeout(120000)
92 const firstContext = await browser.newContext({ baseURL }),
93 secondContext = await browser.newContext({ baseURL })
94 const first = await firstContext.newPage(),
95 second = await secondContext.newPage()
96 let disconnectRealtime = false
97 const sockets: WebSocketRoute[] = []
98 await second.routeWebSocket("ws://127.0.0.1:8081", (socket) => {
99 if (disconnectRealtime) {
100 socket.close({ code: 1013, reason: "Test outage" })
101 return
102 }
103 socket.connectToServer()
104 sockets.push(socket)
105 })
106 const errors: string[] = []
107 for (const page of [first, second]) page.on("pageerror", (error) => errors.push(error.message))
108 try {
109 await Promise.all([openGame(first), openGame(second)])
110 const identity = await (await first.request.get("/api/team")).json()
111 const scoreId = `score-${TEAMS[identity.teamId].toLowerCase()}`
112 const shared = coordsToEdgeId(500, 499, false)
113 const edges = [...new Set([...getBoxEdges(499, 499), ...getBoxEdges(500, 499)])].filter(
114 (id) => id !== shared,
115 )
116 for (const edgeId of edges) {
117 const response = await first.request.post("/api/draw", { data: { edgeId } })
118 expect(response.status()).toBe(200)
119 }
120 const canvas = first.getByTestId("game-canvas")
121 const bounds = (await canvas.boundingBox())!
122 const accepted = first.waitForResponse(
123 (response) => response.url().endsWith("/api/draw") && response.request().method() === "POST",
124 )
125 // Move first so React installs the hover target before the click handler runs.
126 await first.mouse.move(bounds.x + bounds.width / 2, bounds.y + bounds.height / 2 - 10)
127 await expect(canvas).toBeVisible()
128 await canvas.click({ position: { x: bounds.width / 2, y: bounds.height / 2 - 10 } })
129 const response = await accepted
130 expect(response.status()).toBe(200)
131 expect(await response.json()).toMatchObject({ ok: true, boxesClaimed: 2, quotaRemaining: 5 })
132 for (const page of [first, second]) {
133 await expect(
134 page.getByTestId(scoreId).filter({ visible: true }).locator(".scoreboard-value"),
135 ).toHaveText(/^2/)
136 await expect(page.getByTestId("connection-status")).toBeHidden()
137 }
138 await first.screenshot({ path: ".local/screenshots/realtime-game.png" })
139​
140 const pixel = () =>
141 second.getByTestId("game-canvas").evaluate((element) => {
142 const canvas = element as HTMLCanvasElement
143 const dpr = devicePixelRatio
144 // Midpoint of the horizontal edge (502,502) at the default 20px cell spacing.
145 return Array.from(
146 canvas
147 .getContext("2d")!
148 .getImageData(
149 Math.floor(canvas.width / 2 + 50 * dpr),
150 Math.floor(canvas.height / 2 + 40 * dpr),
151 1,
152 1,
153 ).data,
154 )
155 })
156 const before = await pixel()
157 disconnectRealtime = true
158 sockets.forEach((socket) => socket.close({ code: 1012, reason: "Test disconnect" }))
159 await expect(second.getByTestId("connection-status")).toContainText("Reconnecting", {
160 timeout: 15000,
161 })
162 const remote = await first.request.post("/api/draw", {
163 data: { edgeId: coordsToEdgeId(502, 502, true) },
164 })
165 expect(remote.status()).toBe(200)
166 disconnectRealtime = false
167 await expect(second.getByTestId("connection-status")).toBeHidden({ timeout: 30000 })
168 await expect.poll(pixel).not.toEqual(before)
169 await second.reload()
170 await expect(second.getByTestId("connection-status")).toBeHidden({ timeout: 30000 })
171 await expect(
172 second.getByTestId(scoreId).filter({ visible: true }).locator(".scoreboard-value"),
173 ).toHaveText(/^2/)
174​
175 // Only this test stack's database is touched; dev data uses a different port.
176 const pool = new pg.Pool({
177 connectionString: `postgresql://${encodeURIComponent(userInfo().username)}@127.0.0.1:55441/postgres`,
178 })
179 try {
180 await new GameStore(pool).reset()
181 } finally {
182 await pool.end()
183 }
184 for (const page of [first, second]) {
185 await expect(
186 page.getByTestId(scoreId).filter({ visible: true }).locator(".scoreboard-value"),
187 ).toHaveText("0", { timeout: 30000 })
188 await expect(page.getByTestId("connection-status")).toBeHidden({ timeout: 30000 })
189 await expect(page.getByTestId("quota-meter-count")).toHaveText("8")
190 }
191 expect(errors).toEqual([])
192 } finally {
193 await firstContext.close()
194 await secondContext.close()
195 }
196})