-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.ts
394 lines (362 loc) · 10.2 KB
/
test.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
import * as fjp from "fast-json-patch";
import { diff } from "./src/crdt/text.ts";
import type { VolumeListResponse } from "./src/realtime.ts";
import type {
FileSystemNode,
ServerEvent,
VolumePatchRequest,
VolumePatchResponse,
} from "./src/realtime.types.ts";
const jp = fjp.default;
const useProd = false;
const prod = "https://durable-realtime-fs.deco-cx.workers.dev/";
const localhost = "http://0.0.0.0:8002";
const base = useProd ? prod : localhost;
const volume = crypto.randomUUID();
const client = () => {
const ctrl = new AbortController();
const socket = new WebSocket(
new URL(`/volumes/${volume}/files`, base.replace("http", "ws")).href,
);
const socketReady = new Promise<unknown>((resolve, reject) => {
socket.addEventListener("open", resolve);
socket.addEventListener("error", reject);
});
return {
create: async (node: FileSystemNode): Promise<void> => {
await fetch(new URL(`/volumes/${volume}/files`), {
method: "PUT",
body: JSON.stringify(node),
headers: { "Content-Type": "application/json" },
});
},
patch: (vpr: VolumePatchRequest): Promise<VolumePatchResponse> =>
fetch(new URL(`/volumes/${volume}/files`, base), {
method: "PATCH",
body: JSON.stringify(vpr),
headers: { "Content-Type": "application/json" },
})
.then((res) => res.json()),
list: (
{ path, content }: { path: string; content?: boolean },
): Promise<VolumeListResponse> =>
fetch(new URL(`/volumes/${volume}/files${path}?content=${content}`, base))
.then((res) => res.json()),
watch: async function* watch() {
// Wait for the WebSocket connection to open
await socketReady;
// Infinite loop to keep listening for incoming messages
while (!ctrl.signal.aborted) {
try {
// Wait for the next message
const event = await new Promise<ServerEvent>((resolve, reject) => {
ctrl.signal.addEventListener("abort", reject);
socket.addEventListener(
"message",
(e: MessageEvent) =>
resolve(JSON.parse(e.data as string) as ServerEvent),
{ once: true },
);
});
// Yield the received message
yield event;
} catch {
/** */
}
}
},
[Symbol.dispose]: () => {
socket.close();
ctrl.abort();
},
};
};
using realtime = client();
const assertEquals = (e1: unknown, e2: unknown) => {
if (e1 !== e2) {
throw new Error(`Expected ${e1} to match ${e2}`);
}
};
const assertAll = (...elems: unknown[]) => {
if (!elems.every((e) => e)) {
throw new Error("Expected all elements to be true");
}
};
const tests = {
"diff should calculate text diff": async () => {
const from = "BC";
const to = "ABC";
assertEquals(
JSON.stringify(diff(from, to)),
JSON.stringify([{ at: 0, text: "A" }]),
);
},
"diff should calculate text diff with deletions": async () => {
const from = "BC";
const to = "AB";
assertEquals(
JSON.stringify(diff(from, to)),
JSON.stringify([{ at: 0, text: "A" }, { at: 1, length: 1 }]),
);
},
"diff should calculate text longer texts": async () => {
const from = "Lorem ipsum abcd !";
const to = "Lom ips!!!um abcd";
assertEquals(
JSON.stringify(diff(from, to)),
JSON.stringify([{ at: 2, length: 2 }, { at: 9, text: "!!!" }, {
at: 16,
length: 2,
}]),
);
},
"Should be accepted": async () => {
const { results } = await realtime.patch({
patches: [
{
path: "/home.json",
patches: jp.compare({}, { "title": "home" }),
},
{
path: "/pdp.json",
patches: jp.compare({}, { "title": "pdp" }),
},
{
path: "/sections/ProductShelf.tsx",
content: `BC`,
},
],
});
assertAll(...results.map((r) => r.accepted));
},
"Should return updated value": async () => {
const vlr = await realtime.list({ path: "/", content: true });
assertEquals(
vlr.fs["/home.json"]?.content,
JSON.stringify({ "title": "home" }),
);
assertEquals(
vlr.fs["/pdp.json"]?.content,
JSON.stringify({ "title": "pdp" }),
);
assertEquals(
vlr.fs["/sections/ProductShelf.tsx"]?.content,
"BC",
);
},
"Should not return value": async () => {
const vlr = await realtime.list({ path: "/" });
assertEquals(
vlr.fs["/home.json"]?.content,
null,
);
assertEquals(
vlr.fs["/pdp.json"]?.content,
null,
);
assertEquals(
vlr.fs["/sections/ProductShelf.tsx"]?.content,
null,
);
},
"should return specific listing value": async () => {
const vlr = await realtime.list({ path: "/home.json" });
assertAll(vlr.fs["/home.json"]);
assertEquals(vlr.fs["/pdp.json"], undefined);
},
"should accept text patch": async () => {
const shelf = "/sections/ProductShelf.tsx";
const vlr = await realtime.list({ path: shelf, content: true });
assertEquals(vlr.fs[shelf]?.content, "BC");
const { results } = await realtime.patch({
patches: [
{
path: shelf,
operations: [{
text: "A",
at: 0,
}],
timestamp: vlr.timestamp,
},
],
});
const snapshot = JSON.stringify([{
accepted: true,
path: shelf,
content: "ABC",
}]);
assertEquals(JSON.stringify(results), snapshot);
const vlrUpdated = await realtime.list({ path: shelf, content: true });
assertEquals(vlrUpdated.fs[shelf]?.content, "ABC");
},
"should accept multiple text patch": async () => {
const shelf = "/sections/ProductShelf.tsx";
const vlr = await realtime.list({ path: shelf, content: true });
assertEquals(vlr.fs[shelf]?.content, "ABC");
const { results } = await realtime.patch({
patches: [
{
path: shelf,
operations: [{
text: "!",
at: 0,
}, {
text: "Z",
at: 0,
}],
timestamp: vlr.timestamp,
},
],
});
const snapshot = JSON.stringify([{
accepted: true,
path: shelf,
content: "!ZABC"
}]);
assertEquals(JSON.stringify(results), snapshot);
const vlrUpdated = await realtime.list({ path: shelf, content: true });
assertEquals(vlrUpdated.fs[shelf]?.content, "!ZABC");
const { results: resultsWithOldTimestamp } = await realtime.patch({
patches: [
{
path: shelf,
operations: [{ // ABC!
text: "!",
at: 3,
}, { // AB!
length: 1,
at: 2,
}],
timestamp: vlr.timestamp, // from an old timestamp insert ! at the end, AB! as result
},
],
});
const snapShotWithOldTimestamp = JSON.stringify([{
accepted: true,
path: shelf,
content: "!ZAB!"
}]);
assertEquals(
JSON.stringify(resultsWithOldTimestamp),
snapShotWithOldTimestamp,
);
const vlrWithOldTimestamp = await realtime.list({
path: shelf,
content: true,
});
assertEquals(vlrWithOldTimestamp.fs[shelf]?.content, "!ZAB!");
},
"should not accept patch because of conflicts": async () => {
const { results } = await realtime.patch({
patches: [
{
path: "/home.json",
patches: jp.compare(
{ "title": "not home" },
{ "title": "home" },
true,
),
},
],
});
const snapshot = JSON.stringify([{
accepted: false,
path: "/home.json",
content: '{"title":"home"}',
}]);
assertEquals(JSON.stringify(results), snapshot);
},
"should accept nested patches": async () => {
const { results } = await realtime.patch({
patches: [
{
path: "/home/home.json",
patches: jp.compare({}, { "title": "home" }, true),
},
],
});
assertAll(...results.map((r) => r.accepted));
},
"should delete files": async () => {
const { results } = await realtime.patch({
patches: [
{
path: "/home/home.json",
patches: [{ op: "remove", path: "" }],
},
],
});
const vlr = await realtime.list({ path: "/home/home.json" });
assertAll(...results.map((r) => r.deleted));
assertEquals(Object.keys(vlr.fs).length, 0);
},
"should respect timestamps": async () => {
const { timestamp } = await realtime.patch({
patches: [
{
path: "/home/home.json",
patches: [{ op: "add", path: "/hello", value: "world" }],
},
],
});
const vlr = await realtime.list({ path: "/home/home.json" });
assertEquals(timestamp, vlr.timestamp);
},
"should watch file changes": async () => {
setTimeout(() =>
realtime.patch({
patches: [
{
path: "/home/home.json",
patches: [{ op: "replace", path: "/hello", value: "deco" }],
},
],
}), 500);
for await (const event of realtime.watch()) {
assertEquals(event.path, "/home/home.json");
break;
}
},
"should watch timestamp file changes": async () => {
let p: Promise<VolumePatchResponse>;
setTimeout(() => {
p = realtime.patch({
patches: [
{
path: "/home/home.json",
patches: [{ op: "replace", path: "/hello", value: "deco" }],
},
],
});
}, 500);
for await (const event of realtime.watch()) {
// @ts-expect-error I know better
assertEquals((await p).timestamp, event.timestamp);
break;
}
},
"should watch deleted files": async () => {
setTimeout(() =>
realtime.patch({
patches: [
{
path: "/home/home.json",
patches: [{ op: "remove", path: "" }],
},
],
}), 500);
for await (const event of realtime.watch()) {
assertEquals(event.deleted, true);
break;
}
},
};
for (const test of Object.entries(tests)) {
try {
await test[1]();
} catch (error) {
console.error(test[0], "\n", error);
}
}
// @ts-expect-error deno types are not available
Deno.exit(0);