@graffiti-garden/implementation-decentralized 0.1.2 → 0.1.4
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.
- package/dist/1-services/4-inboxes/cache.d.ts +34 -0
- package/dist/1-services/4-inboxes/cache.d.ts.map +1 -0
- package/dist/1-services/4-inboxes/messages.d.ts +70 -0
- package/dist/1-services/4-inboxes/messages.d.ts.map +1 -0
- package/dist/1-services/4-inboxes.d.ts +28 -67
- package/dist/1-services/4-inboxes.d.ts.map +1 -1
- package/dist/3-protocol/2-handles.d.ts.map +1 -1
- package/dist/3-protocol/4-graffiti.d.ts +2 -2
- package/dist/3-protocol/4-graffiti.d.ts.map +1 -1
- package/dist/3-protocol/login-dialog.html.d.ts +1 -1
- package/dist/3-protocol/login-dialog.html.d.ts.map +1 -1
- package/dist/browser/index.js +7 -7
- package/dist/browser/index.js.map +4 -4
- package/dist/browser/{login-dialog.html-E6VRKMXH.js → login-dialog.html-WIDO3XZF.js} +18 -4
- package/dist/browser/{login-dialog.html-E6VRKMXH.js.map → login-dialog.html-WIDO3XZF.js.map} +2 -2
- package/dist/cjs/1-services/4-inboxes/cache.js +186 -0
- package/dist/cjs/1-services/4-inboxes/cache.js.map +7 -0
- package/dist/cjs/1-services/4-inboxes/messages.js +69 -0
- package/dist/cjs/1-services/4-inboxes/messages.js.map +7 -0
- package/dist/cjs/1-services/4-inboxes-tests.js +339 -9
- package/dist/cjs/1-services/4-inboxes-tests.js.map +3 -3
- package/dist/cjs/1-services/4-inboxes.js +210 -399
- package/dist/cjs/1-services/4-inboxes.js.map +3 -3
- package/dist/cjs/3-protocol/2-handles-tests.js +8 -0
- package/dist/cjs/3-protocol/2-handles-tests.js.map +2 -2
- package/dist/cjs/3-protocol/2-handles.js +3 -4
- package/dist/cjs/3-protocol/2-handles.js.map +2 -2
- package/dist/cjs/3-protocol/4-graffiti.js +49 -53
- package/dist/cjs/3-protocol/4-graffiti.js.map +2 -2
- package/dist/cjs/3-protocol/login-dialog.html.js +17 -3
- package/dist/cjs/3-protocol/login-dialog.html.js.map +2 -2
- package/dist/cjs/index.spec.js +90 -0
- package/dist/cjs/index.spec.js.map +3 -3
- package/dist/esm/1-services/4-inboxes/cache.js +156 -0
- package/dist/esm/1-services/4-inboxes/cache.js.map +7 -0
- package/dist/esm/1-services/4-inboxes/messages.js +60 -0
- package/dist/esm/1-services/4-inboxes/messages.js.map +7 -0
- package/dist/esm/1-services/4-inboxes-tests.js +340 -10
- package/dist/esm/1-services/4-inboxes-tests.js.map +3 -3
- package/dist/esm/1-services/4-inboxes.js +222 -383
- package/dist/esm/1-services/4-inboxes.js.map +3 -3
- package/dist/esm/3-protocol/2-handles-tests.js +8 -0
- package/dist/esm/3-protocol/2-handles-tests.js.map +2 -2
- package/dist/esm/3-protocol/2-handles.js +3 -4
- package/dist/esm/3-protocol/2-handles.js.map +2 -2
- package/dist/esm/3-protocol/4-graffiti.js +49 -53
- package/dist/esm/3-protocol/4-graffiti.js.map +2 -2
- package/dist/esm/3-protocol/login-dialog.html.js +17 -3
- package/dist/esm/3-protocol/login-dialog.html.js.map +2 -2
- package/dist/esm/index.spec.js +92 -2
- package/dist/esm/index.spec.js.map +2 -2
- package/package.json +1 -1
- package/src/1-services/4-inboxes/cache.ts +227 -0
- package/src/1-services/4-inboxes/messages.ts +63 -0
- package/src/1-services/4-inboxes-tests.ts +387 -2
- package/src/1-services/4-inboxes.ts +297 -512
- package/src/3-protocol/2-handles-tests.ts +12 -0
- package/src/3-protocol/2-handles.ts +3 -5
- package/src/3-protocol/4-graffiti.ts +69 -83
- package/src/3-protocol/login-dialog.html.ts +17 -3
- package/src/index.spec.ts +106 -2
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
import { encode as dagCborEncode } from "@ipld/dag-cbor";
|
|
2
|
+
import { LABELED_MESSAGE_ID_KEY, type LabeledMessageBase } from "./messages";
|
|
3
|
+
|
|
4
|
+
// One record per inbox query. Messages live in the separate message cache;
|
|
5
|
+
// this record tracks their IDs and where to continue fetching from the server.
|
|
6
|
+
export type CacheQueryValue = {
|
|
7
|
+
// Server continuation state for the next page.
|
|
8
|
+
cursor: string;
|
|
9
|
+
// Identifies this local query history, not a server version. It stays the
|
|
10
|
+
// same as pages arrive; a reset creates a new one so old caller cursors expire.
|
|
11
|
+
version: string;
|
|
12
|
+
// All message IDs fetched for this query so far, in order. A caller's
|
|
13
|
+
// numSeen cursor indexes into this list to replay only unseen messages.
|
|
14
|
+
messageIds: string[];
|
|
15
|
+
waitTil?: number;
|
|
16
|
+
// Changes on every cached page write, even if the page is empty and neither
|
|
17
|
+
// messageIds nor cursor changes. A tab waiting on the query lock can use this
|
|
18
|
+
// to detect and reuse a page fetched by another tab. Older entries lack it.
|
|
19
|
+
generation?: string;
|
|
20
|
+
// Whether the server has another page; needed when reusing another tab's
|
|
21
|
+
// cached page. Older cache entries lack this and are refreshed on next query.
|
|
22
|
+
hasMore?: boolean;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
export async function canUseIDB(): Promise<boolean> {
|
|
26
|
+
try {
|
|
27
|
+
if (!globalThis.indexedDB) return false;
|
|
28
|
+
|
|
29
|
+
// Small probe database
|
|
30
|
+
await new Promise<void>((resolve, reject) => {
|
|
31
|
+
const req = indexedDB.open("__idb_probe__", 1);
|
|
32
|
+
req.onupgradeneeded = () => req.result.createObjectStore("k");
|
|
33
|
+
req.onsuccess = () => {
|
|
34
|
+
req.result.close();
|
|
35
|
+
resolve();
|
|
36
|
+
};
|
|
37
|
+
req.onerror = () => reject(req.error);
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
return true;
|
|
41
|
+
} catch {
|
|
42
|
+
return false;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export type Cache = {
|
|
47
|
+
messages: {
|
|
48
|
+
get(k: string): Promise<LabeledMessageBase | null | undefined>;
|
|
49
|
+
set(k: string, value: LabeledMessageBase | null): Promise<void>;
|
|
50
|
+
setMany(entries: [string, LabeledMessageBase][]): Promise<void>;
|
|
51
|
+
del(k: string): Promise<void>;
|
|
52
|
+
};
|
|
53
|
+
messageIds: {
|
|
54
|
+
get(k: string): Promise<CacheQueryValue | undefined>;
|
|
55
|
+
set(k: string, value: CacheQueryValue): Promise<void>;
|
|
56
|
+
del(k: string): Promise<void>;
|
|
57
|
+
};
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
export function getMessageCacheKey(inboxUrl: string, messageId: string) {
|
|
61
|
+
return `${encodeURIComponent(inboxUrl)}:${encodeURIComponent(messageId)}`;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export async function replayQuery(
|
|
65
|
+
cache: Cache,
|
|
66
|
+
inboxUrl: string,
|
|
67
|
+
messageIdsCacheKey: string,
|
|
68
|
+
query: CacheQueryValue,
|
|
69
|
+
numSeen = 0,
|
|
70
|
+
): Promise<LabeledMessageBase[]> {
|
|
71
|
+
// Filter out all messageIds before
|
|
72
|
+
// the number already seen
|
|
73
|
+
const messageIds = query.messageIds.slice(numSeen);
|
|
74
|
+
|
|
75
|
+
// Get all the messages pointed to in the cache
|
|
76
|
+
return Promise.all(
|
|
77
|
+
messageIds.map(async (id) => {
|
|
78
|
+
const message = await cache.messages.get(getMessageCacheKey(inboxUrl, id));
|
|
79
|
+
if (!message) {
|
|
80
|
+
// Something is very wrong with the cache,
|
|
81
|
+
// it refers to message IDs that are not cached
|
|
82
|
+
try {
|
|
83
|
+
await cache.messageIds.del(messageIdsCacheKey);
|
|
84
|
+
} catch {}
|
|
85
|
+
throw new Error("Cache out of sync - perhaps clear browser storage");
|
|
86
|
+
}
|
|
87
|
+
return message;
|
|
88
|
+
}),
|
|
89
|
+
);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export async function storeQueryPage(
|
|
93
|
+
cache: Cache,
|
|
94
|
+
inboxUrl: string,
|
|
95
|
+
messageIdsCacheKey: string,
|
|
96
|
+
previous: CacheQueryValue | undefined,
|
|
97
|
+
page: {
|
|
98
|
+
messages: LabeledMessageBase[];
|
|
99
|
+
cursor: string;
|
|
100
|
+
hasMore: boolean;
|
|
101
|
+
waitTil?: number;
|
|
102
|
+
},
|
|
103
|
+
): Promise<CacheQueryValue> {
|
|
104
|
+
// First cache the messages with their labels
|
|
105
|
+
await cache.messages.setMany(
|
|
106
|
+
page.messages.map((message) => [
|
|
107
|
+
getMessageCacheKey(inboxUrl, message[LABELED_MESSAGE_ID_KEY]),
|
|
108
|
+
message,
|
|
109
|
+
]),
|
|
110
|
+
);
|
|
111
|
+
// Then store all the messageids
|
|
112
|
+
const query = {
|
|
113
|
+
cursor: page.cursor,
|
|
114
|
+
version: previous?.version ?? crypto.randomUUID(),
|
|
115
|
+
messageIds: [
|
|
116
|
+
...(previous?.messageIds ?? []),
|
|
117
|
+
...page.messages.map((message) => message[LABELED_MESSAGE_ID_KEY]),
|
|
118
|
+
],
|
|
119
|
+
generation: crypto.randomUUID(),
|
|
120
|
+
hasMore: page.hasMore,
|
|
121
|
+
waitTil: page.waitTil,
|
|
122
|
+
};
|
|
123
|
+
await cache.messageIds.set(messageIdsCacheKey, query);
|
|
124
|
+
return query;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export async function getMessageIdsCacheKey(
|
|
128
|
+
inboxUrl: string,
|
|
129
|
+
type: "query" | "export",
|
|
130
|
+
body?: Uint8Array,
|
|
131
|
+
): Promise<string> {
|
|
132
|
+
const cacheIdData = dagCborEncode({
|
|
133
|
+
inboxUrl,
|
|
134
|
+
type,
|
|
135
|
+
body: body ?? null,
|
|
136
|
+
});
|
|
137
|
+
return crypto.subtle
|
|
138
|
+
.digest("SHA-256", new Uint8Array(cacheIdData))
|
|
139
|
+
.then((bytes) =>
|
|
140
|
+
Array.from(new Uint8Array(bytes))
|
|
141
|
+
.map((byte) => byte.toString(16).padStart(2, "0"))
|
|
142
|
+
.join(""),
|
|
143
|
+
);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
async function resetCacheDB() {
|
|
147
|
+
await new Promise<void>((resolve) => {
|
|
148
|
+
const req = indexedDB.deleteDatabase("graffiti-inbox-cache");
|
|
149
|
+
req.onsuccess = () => resolve();
|
|
150
|
+
req.onerror = () => resolve(); // best effort
|
|
151
|
+
req.onblocked = () => resolve(); // best effort
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export async function createCache(): Promise<Cache> {
|
|
156
|
+
if (await canUseIDB()) {
|
|
157
|
+
const { openDB } = await import("idb");
|
|
158
|
+
const db = await openDB("graffiti-inbox-cache", 1, {
|
|
159
|
+
upgrade(db) {
|
|
160
|
+
if (!db.objectStoreNames.contains("m")) db.createObjectStore("m");
|
|
161
|
+
if (!db.objectStoreNames.contains("q")) db.createObjectStore("q");
|
|
162
|
+
},
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
return {
|
|
166
|
+
messages: {
|
|
167
|
+
get: async (k) => {
|
|
168
|
+
try {
|
|
169
|
+
return db.get("m", k);
|
|
170
|
+
} catch (error) {
|
|
171
|
+
console.error("Error getting message from cache:", error);
|
|
172
|
+
console.error("resetting cache...");
|
|
173
|
+
await resetCacheDB();
|
|
174
|
+
return undefined;
|
|
175
|
+
}
|
|
176
|
+
},
|
|
177
|
+
set: async (k, v) => {
|
|
178
|
+
await db.put("m", v, k);
|
|
179
|
+
},
|
|
180
|
+
setMany: async (entries) => {
|
|
181
|
+
if (entries.length === 0) return;
|
|
182
|
+
const tx = db.transaction("m", "readwrite");
|
|
183
|
+
await Promise.all([
|
|
184
|
+
...entries.map(([k, v]) => tx.store.put(v, k)),
|
|
185
|
+
tx.done,
|
|
186
|
+
]);
|
|
187
|
+
},
|
|
188
|
+
del: (k) => db.delete("m", k),
|
|
189
|
+
},
|
|
190
|
+
messageIds: {
|
|
191
|
+
get: async (k) => {
|
|
192
|
+
try {
|
|
193
|
+
return await db.get("q", k);
|
|
194
|
+
} catch (error) {
|
|
195
|
+
console.error("Error getting message IDs from cache:", error);
|
|
196
|
+
console.error("resetting cache...");
|
|
197
|
+
await resetCacheDB();
|
|
198
|
+
return undefined;
|
|
199
|
+
}
|
|
200
|
+
},
|
|
201
|
+
set: async (k, v) => {
|
|
202
|
+
await db.put("q", v, k);
|
|
203
|
+
},
|
|
204
|
+
del: (k) => db.delete("q", k),
|
|
205
|
+
},
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
const m = new Map<string, LabeledMessageBase | null>();
|
|
210
|
+
const q = new Map<string, CacheQueryValue>();
|
|
211
|
+
|
|
212
|
+
return {
|
|
213
|
+
messages: {
|
|
214
|
+
get: async (k) => m.get(k),
|
|
215
|
+
set: async (k, v) => void m.set(k, v),
|
|
216
|
+
setMany: async (entries) => {
|
|
217
|
+
for (const [k, v] of entries) m.set(k, v);
|
|
218
|
+
},
|
|
219
|
+
del: async (k) => void m.delete(k),
|
|
220
|
+
},
|
|
221
|
+
messageIds: {
|
|
222
|
+
get: async (k) => q.get(k),
|
|
223
|
+
set: async (k, v) => void q.set(k, v),
|
|
224
|
+
del: async (k) => void q.delete(k),
|
|
225
|
+
},
|
|
226
|
+
};
|
|
227
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import type { JSONSchema, GraffitiObject } from "@graffiti-garden/api";
|
|
2
|
+
import {
|
|
3
|
+
type infer as infer_,
|
|
4
|
+
string,
|
|
5
|
+
url,
|
|
6
|
+
array,
|
|
7
|
+
optional,
|
|
8
|
+
nullable,
|
|
9
|
+
strictObject,
|
|
10
|
+
looseObject,
|
|
11
|
+
custom,
|
|
12
|
+
number,
|
|
13
|
+
boolean,
|
|
14
|
+
} from "zod/mini";
|
|
15
|
+
|
|
16
|
+
const GraffitiObjectSchema = strictObject({
|
|
17
|
+
value: looseObject({}),
|
|
18
|
+
channels: array(string()),
|
|
19
|
+
allowed: optional(nullable(array(url()))),
|
|
20
|
+
url: url(),
|
|
21
|
+
actor: url(),
|
|
22
|
+
});
|
|
23
|
+
export const Uint8ArraySchema = custom<Uint8Array>(
|
|
24
|
+
(v): v is Uint8Array => v instanceof Uint8Array,
|
|
25
|
+
);
|
|
26
|
+
export const TagsSchema = array(Uint8ArraySchema);
|
|
27
|
+
|
|
28
|
+
export const MESSAGE_TAGS_KEY = "t";
|
|
29
|
+
export const MESSAGE_OBJECT_KEY = "o";
|
|
30
|
+
export const MESSAGE_METADATA_KEY = "m";
|
|
31
|
+
export const MessageBaseSchema = strictObject({
|
|
32
|
+
[MESSAGE_TAGS_KEY]: TagsSchema,
|
|
33
|
+
[MESSAGE_OBJECT_KEY]: GraffitiObjectSchema,
|
|
34
|
+
[MESSAGE_METADATA_KEY]: Uint8ArraySchema,
|
|
35
|
+
});
|
|
36
|
+
type MessageBase = infer_<typeof MessageBaseSchema>;
|
|
37
|
+
|
|
38
|
+
export const LABELED_MESSAGE_ID_KEY = "id";
|
|
39
|
+
export const LABELED_MESSAGE_MESSAGE_KEY = "m";
|
|
40
|
+
export const LABELED_MESSAGE_LABEL_KEY = "l";
|
|
41
|
+
export const LabeledMessageBaseSchema = strictObject({
|
|
42
|
+
[LABELED_MESSAGE_ID_KEY]: string(),
|
|
43
|
+
[LABELED_MESSAGE_MESSAGE_KEY]: MessageBaseSchema,
|
|
44
|
+
[LABELED_MESSAGE_LABEL_KEY]: number(),
|
|
45
|
+
});
|
|
46
|
+
export type LabeledMessageBase = infer_<typeof LabeledMessageBaseSchema>;
|
|
47
|
+
|
|
48
|
+
export type Message<Schema extends JSONSchema> = MessageBase & {
|
|
49
|
+
[MESSAGE_OBJECT_KEY]: GraffitiObject<Schema>;
|
|
50
|
+
};
|
|
51
|
+
export type LabeledMessage<Schema extends JSONSchema> = LabeledMessageBase & {
|
|
52
|
+
[LABELED_MESSAGE_MESSAGE_KEY]: {
|
|
53
|
+
[MESSAGE_OBJECT_KEY]: GraffitiObject<Schema>;
|
|
54
|
+
};
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
export const SendResponseSchema = strictObject({ id: string() });
|
|
58
|
+
|
|
59
|
+
export const MessageResultSchema = strictObject({
|
|
60
|
+
results: array(LabeledMessageBaseSchema),
|
|
61
|
+
hasMore: boolean(),
|
|
62
|
+
cursor: string(),
|
|
63
|
+
});
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { assert, describe, expect, test } from "vitest";
|
|
1
|
+
import { afterEach, assert, describe, expect, test, vi } from "vitest";
|
|
2
2
|
import { Inboxes, LABELED_MESSAGE_LABEL_KEY } from "./4-inboxes";
|
|
3
3
|
import { GraffitiErrorUnauthorized } from "./utilities";
|
|
4
4
|
import { randomBytes } from "@noble/hashes/utils.js";
|
|
5
|
-
import type
|
|
5
|
+
import { GraffitiErrorCursorExpired, type GraffitiObjectBase } from "@graffiti-garden/api";
|
|
6
6
|
import { encode as dagCborEncode, decode as dagCborDecode } from "@ipld/dag-cbor";
|
|
7
7
|
|
|
8
8
|
export function inboxTests(inboxEndpoint: string, inboxToken: string) {
|
|
@@ -179,3 +179,388 @@ export function inboxTests(inboxEndpoint: string, inboxToken: string) {
|
|
|
179
179
|
}, 100000);
|
|
180
180
|
});
|
|
181
181
|
}
|
|
182
|
+
|
|
183
|
+
// Focused client behavior tests use mocked network and browser locks.
|
|
184
|
+
const inboxUrl = "https://example.test/inbox";
|
|
185
|
+
const message = {
|
|
186
|
+
id: "message-1",
|
|
187
|
+
m: {
|
|
188
|
+
t: [new Uint8Array([1])],
|
|
189
|
+
o: {
|
|
190
|
+
url: "https://example.test/object",
|
|
191
|
+
actor: "did:example:author",
|
|
192
|
+
channels: ["test"],
|
|
193
|
+
value: {},
|
|
194
|
+
},
|
|
195
|
+
m: new Uint8Array([2]),
|
|
196
|
+
},
|
|
197
|
+
l: 0,
|
|
198
|
+
};
|
|
199
|
+
|
|
200
|
+
function cborResponse(value: unknown) {
|
|
201
|
+
return new Response(new Uint8Array(dagCborEncode(value)).slice(), {
|
|
202
|
+
headers: { "Content-Type": "application/cbor" },
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
function queryPage(results: (typeof message)[], cursor: string, hasMore = false) {
|
|
207
|
+
return cborResponse({ results, hasMore, cursor });
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
class TestInboxes extends Inboxes {
|
|
211
|
+
async prepareCache() {
|
|
212
|
+
await this.cache;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
async deleteCachedQuery(key: string) {
|
|
216
|
+
await (await this.cache).messageIds.del(key);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
async fetchQueryBatch() {
|
|
220
|
+
const batch = await this.fetchMessageBatch(
|
|
221
|
+
"https://example.test/inbox",
|
|
222
|
+
"query",
|
|
223
|
+
undefined,
|
|
224
|
+
);
|
|
225
|
+
await batch.response.arrayBuffer();
|
|
226
|
+
return batch;
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
function enableLockPath(request: unknown) {
|
|
231
|
+
vi.stubGlobal("indexedDB", {
|
|
232
|
+
open: () => {
|
|
233
|
+
const probe: { result?: { close: () => void }; onsuccess?: () => void } = {};
|
|
234
|
+
queueMicrotask(() => {
|
|
235
|
+
probe.result = { close() {} };
|
|
236
|
+
probe.onsuccess?.();
|
|
237
|
+
});
|
|
238
|
+
return probe;
|
|
239
|
+
},
|
|
240
|
+
});
|
|
241
|
+
vi.stubGlobal("window", { navigator: { locks: { request } } });
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
export function inboxUnitTests() {
|
|
245
|
+
describe("Inboxes unit", () => {
|
|
246
|
+
afterEach(() => {
|
|
247
|
+
vi.unstubAllGlobals();
|
|
248
|
+
vi.restoreAllMocks();
|
|
249
|
+
});
|
|
250
|
+
|
|
251
|
+
describe("inbox stream lock and network failures", () => {
|
|
252
|
+
test("backs off for five seconds after an initial request failure", async () => {
|
|
253
|
+
const failure = new Error("offline");
|
|
254
|
+
const fetch = vi.fn(() => Promise.reject(failure));
|
|
255
|
+
vi.stubGlobal("fetch", fetch);
|
|
256
|
+
vi.spyOn(console, "error").mockImplementation(() => {});
|
|
257
|
+
const realSetTimeout = globalThis.setTimeout;
|
|
258
|
+
const timer = vi.spyOn(globalThis, "setTimeout").mockImplementation(
|
|
259
|
+
((handler: TimerHandler, delay?: number, ...args: unknown[]) =>
|
|
260
|
+
realSetTimeout(
|
|
261
|
+
handler,
|
|
262
|
+
delay === 5000 ? 0 : delay,
|
|
263
|
+
...args,
|
|
264
|
+
)) as typeof setTimeout,
|
|
265
|
+
);
|
|
266
|
+
|
|
267
|
+
await expect(new Inboxes().query(inboxUrl, [], {}).next()).rejects.toBe(
|
|
268
|
+
failure,
|
|
269
|
+
);
|
|
270
|
+
expect(fetch).toHaveBeenCalledOnce();
|
|
271
|
+
expect(timer).toHaveBeenCalledWith(expect.any(Function), 5000);
|
|
272
|
+
});
|
|
273
|
+
|
|
274
|
+
test("a rejected lock request rejects the stream", async () => {
|
|
275
|
+
const inboxes = new TestInboxes();
|
|
276
|
+
await inboxes.prepareCache();
|
|
277
|
+
const error = new Error("lock request failed");
|
|
278
|
+
enableLockPath(vi.fn(() => Promise.reject(error)));
|
|
279
|
+
|
|
280
|
+
await expect(
|
|
281
|
+
inboxes.query("https://example.test/inbox", [], {}).next(),
|
|
282
|
+
).rejects.toBe(error);
|
|
283
|
+
});
|
|
284
|
+
|
|
285
|
+
test("waiting for another tab's lock has a deadline", async () => {
|
|
286
|
+
const inboxes = new TestInboxes();
|
|
287
|
+
await inboxes.prepareCache();
|
|
288
|
+
const timeoutError = new DOMException("timed out", "TimeoutError");
|
|
289
|
+
vi.spyOn(AbortSignal, "timeout").mockReturnValue(
|
|
290
|
+
AbortSignal.abort(timeoutError),
|
|
291
|
+
);
|
|
292
|
+
const request = vi.fn(
|
|
293
|
+
(
|
|
294
|
+
_key: string,
|
|
295
|
+
_options: { signal?: AbortSignal },
|
|
296
|
+
) => Promise.reject(timeoutError),
|
|
297
|
+
);
|
|
298
|
+
enableLockPath(request);
|
|
299
|
+
|
|
300
|
+
await expect(
|
|
301
|
+
inboxes.query("https://example.test/inbox", [], {}).next(),
|
|
302
|
+
).rejects.toThrow("Timed out waiting for another tab's inbox query");
|
|
303
|
+
expect(request).toHaveBeenCalledOnce();
|
|
304
|
+
});
|
|
305
|
+
|
|
306
|
+
test("a stalled request is aborted", async () => {
|
|
307
|
+
const realTimeout = AbortSignal.timeout;
|
|
308
|
+
vi.spyOn(AbortSignal, "timeout").mockImplementation(() => realTimeout(5));
|
|
309
|
+
vi.stubGlobal(
|
|
310
|
+
"fetch",
|
|
311
|
+
vi.fn((_url: string, options: RequestInit) =>
|
|
312
|
+
new Promise<Response>((_resolve, reject) => {
|
|
313
|
+
const signal = options.signal as AbortSignal;
|
|
314
|
+
signal.addEventListener("abort", () => reject(signal.reason), {
|
|
315
|
+
once: true,
|
|
316
|
+
});
|
|
317
|
+
}),
|
|
318
|
+
),
|
|
319
|
+
);
|
|
320
|
+
|
|
321
|
+
await expect(new TestInboxes().fetchQueryBatch()).rejects.toMatchObject({
|
|
322
|
+
name: "TimeoutError",
|
|
323
|
+
});
|
|
324
|
+
});
|
|
325
|
+
|
|
326
|
+
test("the deadline remains active while reading a response body", async () => {
|
|
327
|
+
const realTimeout = AbortSignal.timeout;
|
|
328
|
+
vi.spyOn(AbortSignal, "timeout").mockImplementation(() => realTimeout(5));
|
|
329
|
+
vi.stubGlobal(
|
|
330
|
+
"fetch",
|
|
331
|
+
vi.fn((_url: string, options: RequestInit) => {
|
|
332
|
+
const signal = options.signal as AbortSignal;
|
|
333
|
+
const body = new ReadableStream({
|
|
334
|
+
start(controller) {
|
|
335
|
+
signal.addEventListener("abort", () => controller.error(signal.reason), {
|
|
336
|
+
once: true,
|
|
337
|
+
});
|
|
338
|
+
},
|
|
339
|
+
});
|
|
340
|
+
return Promise.resolve(new Response(body));
|
|
341
|
+
}),
|
|
342
|
+
);
|
|
343
|
+
|
|
344
|
+
await expect(new TestInboxes().fetchQueryBatch()).rejects.toMatchObject({
|
|
345
|
+
name: "TimeoutError",
|
|
346
|
+
});
|
|
347
|
+
});
|
|
348
|
+
});
|
|
349
|
+
|
|
350
|
+
describe("inbox query cache", () => {
|
|
351
|
+
test("fetches the next page while the current message is yielded", async () => {
|
|
352
|
+
const inboxes = new TestInboxes();
|
|
353
|
+
await inboxes.prepareCache();
|
|
354
|
+
let held = 0;
|
|
355
|
+
enableLockPath(vi.fn(async (
|
|
356
|
+
key: string,
|
|
357
|
+
_options: { signal?: AbortSignal },
|
|
358
|
+
callback: (lock: Lock) => Promise<unknown>,
|
|
359
|
+
) => {
|
|
360
|
+
held++;
|
|
361
|
+
try {
|
|
362
|
+
return await callback({ name: key, mode: "exclusive" });
|
|
363
|
+
} finally {
|
|
364
|
+
held--;
|
|
365
|
+
}
|
|
366
|
+
}));
|
|
367
|
+
let prefetchAborted = false;
|
|
368
|
+
const fetch = vi.fn((_url: string, options: RequestInit) => {
|
|
369
|
+
if (fetch.mock.calls.length === 1) {
|
|
370
|
+
return Promise.resolve(queryPage([message], "cursor-1", true));
|
|
371
|
+
}
|
|
372
|
+
return new Promise<Response>((_resolve, reject) => {
|
|
373
|
+
const signal = options.signal as AbortSignal;
|
|
374
|
+
signal.addEventListener("abort", () => {
|
|
375
|
+
prefetchAborted = true;
|
|
376
|
+
reject(signal.reason);
|
|
377
|
+
}, { once: true });
|
|
378
|
+
});
|
|
379
|
+
});
|
|
380
|
+
vi.stubGlobal("fetch", fetch);
|
|
381
|
+
|
|
382
|
+
const iterator = inboxes.query(inboxUrl, [new Uint8Array([1])], {});
|
|
383
|
+
expect((await iterator.next()).value).toEqual(message);
|
|
384
|
+
await vi.waitFor(() => expect(fetch).toHaveBeenCalledTimes(2));
|
|
385
|
+
expect(fetch.mock.calls[1][0]).toBe(`${inboxUrl}/query?cursor=cursor-1`);
|
|
386
|
+
await iterator.return("");
|
|
387
|
+
expect(prefetchAborted).toBe(true);
|
|
388
|
+
await vi.waitFor(() => expect(held).toBe(0));
|
|
389
|
+
});
|
|
390
|
+
|
|
391
|
+
test("reports a cursor that expires after the first page", async () => {
|
|
392
|
+
const fetch = vi.fn()
|
|
393
|
+
.mockResolvedValueOnce(queryPage([message], "cursor-1", true))
|
|
394
|
+
.mockResolvedValueOnce(new Response("stale", { status: 410 }));
|
|
395
|
+
vi.stubGlobal("fetch", fetch);
|
|
396
|
+
|
|
397
|
+
const iterator = new Inboxes().query(inboxUrl, [new Uint8Array([1])], {});
|
|
398
|
+
expect((await iterator.next()).value).toEqual(message);
|
|
399
|
+
await expect(iterator.next()).rejects.toBeInstanceOf(
|
|
400
|
+
GraffitiErrorCursorExpired,
|
|
401
|
+
);
|
|
402
|
+
expect(fetch).toHaveBeenCalledTimes(2);
|
|
403
|
+
});
|
|
404
|
+
|
|
405
|
+
test("does not replay messages after another tab resets the cache", async () => {
|
|
406
|
+
const inboxes = new TestInboxes();
|
|
407
|
+
await inboxes.prepareCache();
|
|
408
|
+
let markPrefetchStarted!: () => void;
|
|
409
|
+
const prefetchStarted = new Promise<void>((resolve) => {
|
|
410
|
+
markPrefetchStarted = resolve;
|
|
411
|
+
});
|
|
412
|
+
let releasePrefetch!: () => void;
|
|
413
|
+
const pause = new Promise<void>((resolve) => {
|
|
414
|
+
releasePrefetch = resolve;
|
|
415
|
+
});
|
|
416
|
+
let lockCalls = 0;
|
|
417
|
+
let cacheKey = "";
|
|
418
|
+
enableLockPath(vi.fn(async (
|
|
419
|
+
name: string,
|
|
420
|
+
_options: { signal?: AbortSignal },
|
|
421
|
+
work: (lock: Lock) => Promise<unknown>,
|
|
422
|
+
) => {
|
|
423
|
+
cacheKey = name.slice("graffiti:inbox:".length);
|
|
424
|
+
if (++lockCalls === 2) {
|
|
425
|
+
markPrefetchStarted();
|
|
426
|
+
await pause;
|
|
427
|
+
}
|
|
428
|
+
return work({ name, mode: "exclusive" });
|
|
429
|
+
}));
|
|
430
|
+
vi.stubGlobal("fetch", vi.fn(async () => queryPage([message], "cursor-1", true)));
|
|
431
|
+
|
|
432
|
+
const iterator = inboxes.query(inboxUrl, [new Uint8Array([1])], {});
|
|
433
|
+
expect((await iterator.next()).value).toEqual(message);
|
|
434
|
+
await prefetchStarted;
|
|
435
|
+
await inboxes.deleteCachedQuery(cacheKey);
|
|
436
|
+
releasePrefetch();
|
|
437
|
+
await expect(iterator.next()).rejects.toBeInstanceOf(
|
|
438
|
+
GraffitiErrorCursorExpired,
|
|
439
|
+
);
|
|
440
|
+
});
|
|
441
|
+
|
|
442
|
+
test("a later query reads messages from the cached server cursor", async () => {
|
|
443
|
+
const fetch = vi.fn()
|
|
444
|
+
.mockResolvedValueOnce(queryPage([message], "cursor-1"))
|
|
445
|
+
.mockResolvedValueOnce(queryPage([], "cursor-2"));
|
|
446
|
+
vi.stubGlobal("fetch", fetch);
|
|
447
|
+
const inboxes = new Inboxes();
|
|
448
|
+
const tags = [new Uint8Array([1])];
|
|
449
|
+
|
|
450
|
+
const first = inboxes.query(inboxUrl, tags, {});
|
|
451
|
+
expect((await first.next()).value).toEqual(message);
|
|
452
|
+
expect((await first.next()).done).toBe(true);
|
|
453
|
+
|
|
454
|
+
const second = inboxes.query(inboxUrl, tags, {});
|
|
455
|
+
expect((await second.next()).value).toEqual(message);
|
|
456
|
+
expect((await second.next()).done).toBe(true);
|
|
457
|
+
expect(fetch).toHaveBeenCalledTimes(2);
|
|
458
|
+
expect(fetch.mock.calls[1][0]).toBe(`${inboxUrl}/query?cursor=cursor-1`);
|
|
459
|
+
});
|
|
460
|
+
|
|
461
|
+
test("does not hold the query lock while a message is yielded", async () => {
|
|
462
|
+
const inboxes = new TestInboxes();
|
|
463
|
+
await inboxes.prepareCache();
|
|
464
|
+
let held = false;
|
|
465
|
+
enableLockPath(vi.fn(async (
|
|
466
|
+
key: string,
|
|
467
|
+
_options: { ifAvailable?: boolean },
|
|
468
|
+
callback: (lock: Lock) => Promise<unknown>,
|
|
469
|
+
) => {
|
|
470
|
+
held = true;
|
|
471
|
+
try {
|
|
472
|
+
return await callback({ name: key, mode: "exclusive" });
|
|
473
|
+
} finally {
|
|
474
|
+
held = false;
|
|
475
|
+
}
|
|
476
|
+
}));
|
|
477
|
+
vi.stubGlobal("fetch", vi.fn(async () => queryPage([message], "cursor-1")));
|
|
478
|
+
|
|
479
|
+
const iterator = inboxes.query(inboxUrl, [new Uint8Array([1])], {});
|
|
480
|
+
try {
|
|
481
|
+
expect((await iterator.next()).value).toEqual(message);
|
|
482
|
+
expect(held).toBe(false);
|
|
483
|
+
} finally {
|
|
484
|
+
await iterator.return("");
|
|
485
|
+
}
|
|
486
|
+
});
|
|
487
|
+
|
|
488
|
+
test("closing a yielded query leaves no lock held", async () => {
|
|
489
|
+
const inboxes = new TestInboxes();
|
|
490
|
+
await inboxes.prepareCache();
|
|
491
|
+
let held = false;
|
|
492
|
+
enableLockPath(vi.fn(async (
|
|
493
|
+
key: string,
|
|
494
|
+
_options: { ifAvailable?: boolean },
|
|
495
|
+
callback: (lock: Lock) => Promise<unknown>,
|
|
496
|
+
) => {
|
|
497
|
+
held = true;
|
|
498
|
+
try {
|
|
499
|
+
return await callback({ name: key, mode: "exclusive" });
|
|
500
|
+
} finally {
|
|
501
|
+
held = false;
|
|
502
|
+
}
|
|
503
|
+
}));
|
|
504
|
+
vi.stubGlobal("fetch", vi.fn(async () => queryPage([message], "cursor-1")));
|
|
505
|
+
|
|
506
|
+
const iterator = inboxes.query(inboxUrl, [new Uint8Array([1])], {});
|
|
507
|
+
expect((await iterator.next()).value).toEqual(message);
|
|
508
|
+
expect(held).toBe(false);
|
|
509
|
+
await iterator.return("");
|
|
510
|
+
expect(held).toBe(false);
|
|
511
|
+
});
|
|
512
|
+
|
|
513
|
+
test("concurrent queries reuse a page fetched under the lock", async () => {
|
|
514
|
+
const inboxes = new TestInboxes();
|
|
515
|
+
await inboxes.prepareCache();
|
|
516
|
+
let releasePrevious = Promise.resolve();
|
|
517
|
+
let requests = 0;
|
|
518
|
+
let bothRequested!: () => void;
|
|
519
|
+
const ready = new Promise<void>((resolve) => { bothRequested = resolve; });
|
|
520
|
+
enableLockPath(vi.fn(async (
|
|
521
|
+
key: string,
|
|
522
|
+
_options: { signal?: AbortSignal },
|
|
523
|
+
callback: (lock: Lock) => Promise<unknown>,
|
|
524
|
+
) => {
|
|
525
|
+
requests++;
|
|
526
|
+
if (requests === 2) bothRequested();
|
|
527
|
+
const previous = releasePrevious;
|
|
528
|
+
let release!: () => void;
|
|
529
|
+
releasePrevious = new Promise<void>((resolve) => { release = resolve; });
|
|
530
|
+
await previous;
|
|
531
|
+
try {
|
|
532
|
+
return await callback({ name: key, mode: "exclusive" });
|
|
533
|
+
} finally {
|
|
534
|
+
release();
|
|
535
|
+
}
|
|
536
|
+
}));
|
|
537
|
+
const nextMessage = { ...message, id: "message-2" };
|
|
538
|
+
const fetch = vi.fn(async () => {
|
|
539
|
+
await ready;
|
|
540
|
+
return fetch.mock.calls.length === 1
|
|
541
|
+
? queryPage([message], "cursor-1", true)
|
|
542
|
+
: queryPage([nextMessage], "cursor-2");
|
|
543
|
+
});
|
|
544
|
+
vi.stubGlobal("fetch", fetch);
|
|
545
|
+
|
|
546
|
+
const tags = [new Uint8Array([1])];
|
|
547
|
+
const first = inboxes.query(inboxUrl, tags, {});
|
|
548
|
+
const second = inboxes.query(inboxUrl, tags, {});
|
|
549
|
+
const [firstResult, secondResult] = await Promise.all([
|
|
550
|
+
first.next(), second.next(),
|
|
551
|
+
]);
|
|
552
|
+
expect(firstResult.value).toEqual(message);
|
|
553
|
+
expect(secondResult.value).toEqual(message);
|
|
554
|
+
const [firstNext, secondNext] = await Promise.all([
|
|
555
|
+
first.next(), second.next(),
|
|
556
|
+
]);
|
|
557
|
+
expect(firstNext.value).toEqual(nextMessage);
|
|
558
|
+
expect(secondNext.value).toEqual(nextMessage);
|
|
559
|
+
expect(fetch).toHaveBeenCalledTimes(2);
|
|
560
|
+
expect((await first.next()).done).toBe(true);
|
|
561
|
+
expect((await second.next()).done).toBe(true);
|
|
562
|
+
});
|
|
563
|
+
|
|
564
|
+
});
|
|
565
|
+
});
|
|
566
|
+
}
|