Skip to content
Source
Sign inSign up
samwillis/neonbricks
Open History to see the last commit

test-presence.ts

166 lines4.6 KB

1import assert from "node:assert/strict";
2import "./node-websocket";
3import { createRealtimeClient } from "@neon/realtime/client";
4import { pool } from "../src/server/db";
5import type { Viewer } from "../src/shared/types";
6​
7const base = (process.env.TEST_API_URL || process.env.VITE_API_URL!).replace(
8 /\/$/,
9 "",
10);
11async function request(
12 token: string,
13 path: string,
14 body?: unknown,
15 method?: string,
16) {
17 const response = await fetch(`${base}/api${path}`, {
18 method: method || (body === undefined ? "GET" : "POST"),
19 headers: {
20 "Content-Type": "application/json",
21 ...(token ? { Authorization: `Bearer ${token}` } : {}),
22 },
23 ...(body === undefined ? {} : { body: JSON.stringify(body) }),
24 });
25 return { status: response.status, data: await response.json() };
27async function ok(token: string, path: string, body?: unknown) {
28 const result = await request(token, path, body);
29 assert.ok(result.status < 300, `${result.status}: ${result.data.error}`);
30 return result.data;
32const client = createRealtimeClient({
33 url: process.env.VITE_NEON_REALTIME_URL!,
34});
35try {
36 const [a, b] = await Promise.all(
37 ["Pointer A", "Pointer B"].map(
38 async (name) =>
39 (await ok("", "/session", { name, color: "#289b74" })).token,
40 ),
41 );
42 const world = await ok(a, "/worlds", {
43 title: "Cursor qualification — disposable",
44 starter: "empty",
45 });
46 const [ja, jb] = await Promise.all(
47 [a, b].map((token) => ok(token, `/worlds/${world.slug}/join`, {})),
48 );
49 const sub = client.subscribe<Viewer>(
50 await ok(a, `/worlds/${world.id}/live/presence`),
51 );
52 sub.onChange((snapshot) => {
53 if (snapshot.error)
54 console.error(
55 "Presence subscription:",
56 snapshot.status,
57 snapshot.error.message,
58 );
59 });
60 await sub.awaitRows(
61 (rows) => rows.some((row) => row.id === jb.viewer),
62 10000,
63 );
64 console.log("Presence query admitted.");
65 const presence = (
66 sequence: number,
67 cursor: Viewer["cursor"],
68 sample = true,
69 token = b,
70 ) =>
71 request(token, `/worlds/${world.id}/presence`, {
72 viewer: jb.viewer,
73 sequence,
74 generation: 1,
75 selection: [],
76 preview: null,
77 cursor,
78 sample,
79 });
80 const first = { x: 1.25, y: 6.2, z: -3.5 };
81 assert.equal((await presence(1, first)).status, 200);
82 assert.deepEqual(
83 (
84 await pool.query("SELECT cursor FROM viewer_sessions WHERE id=$1", [
85 jb.viewer,
86 ])
87 ).rows[0].cursor,
88 first,
89 );
90 await sub.awaitRows(
91 (rows) =>
92 rows.some((row) => row.id === jb.viewer && row.cursor?.x === first.x),
93 10000,
94 );
95 const latest = { x: 12.75, y: 8, z: -9 };
96 await presence(3, latest);
97 await presence(2, null);
98 await sub.awaitRows(
99 (rows) =>
100 rows.some((row) => row.id === jb.viewer && row.cursor?.x === latest.x),
101 10000,
102 );
103 const read = async () =>
104 (
105 await pool.query(
106 "SELECT sequence,cursor,cursor_at FROM viewer_sessions WHERE id=$1",
107 [jb.viewer],
108 )
109 ).rows[0];
110 const before = await read();
111 assert.equal(before.sequence, 3);
112 assert.deepEqual(before.cursor, latest);
113 await presence(4, null, false);
114 const after = await read();
115 assert.deepEqual(after.cursor, latest);
116 assert.equal(after.cursor_at.valueOf(), before.cursor_at.valueOf());
117 assert.equal((await presence(5, { x: 1000, y: 0, z: 0 })).status, 400);
118 assert.equal((await presence(6, null, true, a)).status, 410);
119 assert.deepEqual((await read()).cursor, latest);
120 // A pre-feature client must not overwrite a cursor with an absent field.
121 await ok(b, `/worlds/${world.id}/presence`, {
122 viewer: jb.viewer,
123 sequence: 7,
124 generation: 1,
125 selection: [],
126 preview: null,
127 sample: true,
128 });
129 assert.deepEqual((await read()).cursor, latest);
130 await presence(8, null);
131 await sub.awaitRows(
132 (rows) => rows.some((row) => row.id === jb.viewer && row.cursor === null),
133 10000,
134 );
135 await request(
136 b,
137 `/worlds/${world.id}/viewers/${jb.viewer}`,
138 undefined,
139 "DELETE",
140 );
141 await sub.awaitRows(
142 (rows) => !rows.some((row) => row.id === jb.viewer),
143 10000,
144 );
145 assert.equal((await presence(9, first)).status, 410);
146 assert.equal(
147 (
148 await pool.query("SELECT id FROM viewer_sessions WHERE id=$1", [
149 jb.viewer,
150 ])
151 ).rowCount,
152 0,
153 );
154 await request(
155 a,
156 `/worlds/${world.id}/viewers/${ja.viewer}`,
157 undefined,
158 "DELETE",
159 );
160 console.log(
161 "PASS cursor delivery over Realtime, ordering, heartbeat timestamp, bounds, viewer ownership, older clients, clear, leave and delayed packets",
162 );
163} finally {
164 client.close();
165 await pool.end();