-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
312 lines (285 loc) · 8.97 KB
/
index.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
import type { ComAtprotoSyncSubscribeRepos } from "@atproto/api";
import { cborToLexRecord, readCar } from "@atproto/repo";
import { Frame } from "@atproto/xrpc-server";
import type { CID } from "multiformats";
import { EventEmitter } from "node:events";
import * as WS from "ws";
/**
* Options for the Firehose class.
*/
export interface FirehoseOptions {
/**
* The cursor to listen from. If not provided, the firehose will start from the latest event.
*/
cursor?: string;
/**
* How frequently to update the stored cursor, in milliseconds.
* @default 5000
*/
setCursorInterval?: number;
}
export class Firehose extends EventEmitter {
/** WebSocket connection to the relay. */
public ws?: WS.WebSocket;
/** The current cursor. */
public cursor = "";
private cursorInterval?: NodeJS.Timeout | undefined;
/**
* Creates a new Firehose instance.
* @param relay The relay to connect to.
* @param options Optional configuration.
*/
constructor(public relay = "wss://bsky.network", private options: FirehoseOptions = {}) {
super();
this.cursor = options.cursor ?? "";
this.options.setCursorInterval ??= 5000;
}
/**
* Opens a WebSocket connection to the relay.
*/
start() {
this.ws = new WS.WebSocket(
`${this.relay}/xrpc/com.atproto.sync.subscribeRepos${this.cursor}`,
);
this.ws.on("open", () => {
this.emit("open");
});
this.ws.on("message", async (data) => {
try {
const message = await this.parseMessage(data);
if ("seq" in message && message.seq && typeof message.seq === "string") {
this.setCursor(message.seq);
}
switch (message.$type) {
case "com.atproto.sync.subscribeRepos#handle":
this.emit("handle", message);
break;
case "com.atproto.sync.subscribeRepos#tombstone":
this.emit("tombstone", message);
break;
case "com.atproto.sync.subscribeRepos#migrate":
this.emit("migrate", message);
break;
case "com.atproto.sync.subscribeRepos#identity":
this.emit("identity", message);
break;
case "com.atproto.sync.subscribeRepos#info":
this.emit("info", message);
break;
case "com.atproto.sync.subscribeRepos#commit":
this.emit("commit", message);
break;
default:
this.emit("unknown", message);
break;
}
} catch (error) {
this.emit("error", { cursor: this.cursor, error });
}
});
this.ws.on("close", () => {
this.emit("close", this.cursor);
});
this.ws.on("error", (error) => {
this.emit("websocketError", { cursor: this.cursor, error });
});
}
/**
* Closes the WebSocket connection.
*/
close() {
this.ws?.close();
}
/** Emitted when the connection is opened. */
override on(event: "open", listener: () => void): this;
/** Emitted when the connection is closed. */
override on(event: "close", listener: (cursor: string) => void): this;
/** Emitted when an error occurs while handling a message. */
override on(
event: "error",
listener: ({ cursor, error }: { cursor: string; error: Error }) => void,
): this;
/** Emitted when an error occurs within the websocket. */
override on(
event: "websocketError",
listener: ({ cursor, error }: { cursor: string; error: unknown }) => void,
): this;
/** Emitted when an unknown message is received. */
override on(event: "unknown", listener: (message: unknown) => void): this;
/**
* Represents an update of an account's handle, or transition to/from invalid state.
* NOTE: Will be deprecated in favor of #identity.
*/
override on(
event: "handle",
listener: (
message: ComAtprotoSyncSubscribeRepos.Handle & {
$type: "com.atproto.sync.subscribeRepos#handle";
},
) => void,
): this;
/**
* Represents an account moving from one PDS instance to another.
* NOTE: not implemented; account migration uses #identity instead
*/
override on(
event: "migrate",
listener: (
message: ComAtprotoSyncSubscribeRepos.Migrate & {
$type: "com.atproto.sync.subscribeRepos#migrate";
},
) => void,
): this;
/**
* Indicates that an account has been deleted.
* NOTE: may be deprecated in favor of #identity or a future #account event
*/
override on(
event: "tombstone",
listener: (
message: ComAtprotoSyncSubscribeRepos.Tombstone & {
$type: "com.atproto.sync.subscribeRepos#tombstone";
},
) => void,
): this;
/**
* Represents a change to an account's identity.
* Could be an updated handle, signing key, or pds hosting endpoint.
*/
override on(
event: "identity",
listener: (
message: ComAtprotoSyncSubscribeRepos.Identity & {
$type: "com.atproto.sync.subscribeRepos#identity";
},
) => void,
): this;
/** Represents a commit to a user's repository. */
override on(event: "commit", listener: (message: ParsedCommit) => void): this;
/** An informational message from the relay. */
override on(
event: "info",
listener: (
message: ComAtprotoSyncSubscribeRepos.Info & {
$type: "com.atproto.sync.subscribeRepos#info";
},
) => void,
): this;
override on(event: string, listener: (...args: any[]) => void): this {
super.on(event, listener);
return this;
}
private async parseMessage(data: WS.RawData) {
let buffer: Buffer;
if (data instanceof Buffer) {
buffer = data;
} else if (data instanceof ArrayBuffer) {
buffer = Buffer.from(data);
} else if (Array.isArray(data)) {
buffer = Buffer.concat(data);
} else {
throw new Error("Unknown message contents: " + data);
}
const frame = Frame.fromBytes(buffer);
if (frame.isError()) throw new Error(`Error: ${frame.message}\nError code: ${frame.code}`);
if (!frame.header.t || !frame.body || typeof frame.body !== "object") {
throw new Error("Invalid frame structure: " + JSON.stringify(frame, null, 2));
}
if (frame.header.t === "#commit") {
// A commit can contain no changes
if (!("blocks" in frame.body) || !(frame.body.blocks instanceof Uint8Array)) {
return {
$type: `com.atproto.sync.subscribeRepos#commit`,
...(frame.body as ComAtprotoSyncSubscribeRepos.Commit),
ops: [],
} satisfies ParsedCommit;
}
const commit = frame.body as ComAtprotoSyncSubscribeRepos.Commit;
const car = await readCar(commit.blocks);
const ops: Array<RepoOp> = commit.ops.map((op) => {
const action: "create" | "update" | "delete" = op.action as any;
if (action === "create" || action === "update") {
if (!op.cid) return;
const recordBlocks = car.blocks.get(op.cid);
if (!recordBlocks) return;
return {
action,
path: op.path,
cid: op.cid,
record: cborToLexRecord(recordBlocks),
};
} else if (action === "delete") {
return { action, path: op.path };
} else {
throw new Error(`Unknown action: ${action}`);
}
}).filter((op): op is Exclude<typeof op, undefined> => !!op);
return {
$type: "com.atproto.sync.subscribeRepos#commit",
...commit,
ops,
} satisfies ParsedCommit;
}
return { $type: `com.atproto.sync.subscribeRepos${frame.header.t}`, ...frame.body };
}
/** Sets the cursor once every `setCursorInterval` milliseconds. */
private setCursor(cursor: string) {
if (this.cursorInterval) return;
this.cursorInterval = setTimeout(() => {
this.cursor = cursor;
this.cursorInterval = undefined;
}, this.options.setCursorInterval);
}
}
/**
* Represents a record in a repository. An object with string keys & properties of any type.
*/
export type RepoRecord = ReturnType<typeof cborToLexRecord>;
/**
* Represents a `create` or `update` repository operation.
*/
export interface CreateOrUpdateOp {
action: "create" | "update";
/** The record's path in the repository. */
path: string;
/** The record's CID. */
cid: CID;
/** The record itself. */
record: RepoRecord;
}
/**
* Represents a `delete` repository operation.
*/
export interface DeleteOp {
action: "delete";
/** The record's path in the repository. */
path: string;
}
/** A repository operation. */
export type RepoOp = CreateOrUpdateOp | DeleteOp;
/**
* Represents an update of repository state.
*/
export interface ParsedCommit {
$type: "com.atproto.sync.subscribeRepos#commit";
/** The stream sequence number of this message. */
seq: number;
/** Indicates that this commit contained too many ops, or data size was too large. Consumers will need to make a separate request to get missing data. */
tooBig: boolean;
/** The repo this event comes from. */
repo: string;
/** Repo commit object CID. */
commit: CID;
/** The rev of the emitted commit. Note that this information is also in the commit object included in blocks, unless this is a tooBig event. */
rev: string;
/** The rev of the last emitted commit from this repo (if any). */
since: string | null;
/** CAR file containing relevant blocks, as a diff since the previous repo state. */
blocks: Uint8Array;
/** List of repo mutation operations in this commit (eg, records created, updated, or deleted). */
ops: Array<RepoOp>;
/** List of new blobs (by CID) referenced by records in this commit. */
blobs: CID[];
/** Timestamp of when this message was originally broadcast. */
time: string;
}