-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathrelay-single.ts
673 lines (632 loc) · 22.7 KB
/
relay-single.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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
import { sleep } from "@blowater/csp";
import { newURL, parseJSON, RESTRequestFailed } from "./_helper.ts";
import { prepareNostrEvent } from "./event.ts";
import { PublicKey } from "./key.ts";
import { getRelayInformation, type RelayInformation } from "./nip11.ts";
import { NoteID } from "./nip19.ts";
import {
type _RelayResponse,
type ClientRequest_REQ,
type NostrEvent,
type NostrFilter,
NostrKind,
type RelayResponse_REQ_Message,
type Signer,
} from "./nostr.ts";
import type { Closer, EventSender, Subscriber, SubscriptionCloser } from "./relay.interface.ts";
import {
AsyncWebSocket,
CloseTwice,
type WebSocketClosedEvent,
type WebSocketError,
type WebSocketReadyState,
} from "./websocket.ts";
import * as csp from "@blowater/csp";
import { getSpaceMembers, prepareSpaceMember } from "./space-member.ts";
import { assertEquals } from "@std/assert";
import type { Event_V2, Signer_V2, SpaceMember } from "./v2.ts";
export class WebSocketClosed extends Error {
constructor(
public url: string | URL,
public state: WebSocketReadyState,
public reason?: WebSocketClosedEvent,
) {
super(`${url} is in state ${state}, code ${reason?.code}`);
this.name = WebSocketClosed.name;
}
}
export class RelayDisconnectedByClient extends Error {
constructor() {
super();
this.name = RelayDisconnectedByClient.name;
}
}
export class FailedToLookupAddress extends Error {}
export type NextMessageType = {
type: "messsage";
data: string;
} | {
type: "WebSocketClosed";
error: WebSocketClosed;
} | {
type: "RelayDisconnectedByClient";
error: RelayDisconnectedByClient;
} | {
type: "FailedToLookupAddress";
error: string;
} | {
type: "OtherError";
error: WebSocketError;
} | {
type: "open";
} | {
type: "closed";
event: WebSocketClosedEvent;
};
export type BidirectionalNetwork = {
status(): WebSocketReadyState;
untilOpen(): Promise<WebSocketClosed | undefined>;
nextMessage(): Promise<
NextMessageType
>;
send: (
str: string | ArrayBufferLike | Blob | ArrayBufferView,
) => Promise<WebSocketClosed | Error | undefined>;
close: (
code?: number,
reason?: string,
force?: boolean,
) => Promise<CloseTwice | WebSocketClosedEvent | undefined>;
};
export class SubscriptionAlreadyExist extends Error {
constructor(public subID: string, public url: string) {
super(`subscription '${subID}' already exists for ${url}`);
}
}
export type SubscriptionStream = {
filters: NostrFilter[];
chan: csp.Channel<RelayResponse_REQ_Message>;
};
/**
* [examples](./tests/example.test.ts)
*/
export class SingleRelayConnection implements Subscriber, SubscriptionCloser, EventSender, Closer {
private _isClosedByClient = false;
isClosedByClient() {
return this._isClosedByClient;
}
private subscriptionMap = new Map<
string,
SubscriptionStream
>();
readonly send_promise_resolvers = new Map<
string,
(res: { ok: boolean; message: string }) => void
>();
private error: AuthError | RelayDisconnectedByClient | undefined; // todo: check this error in public APIs
private ws: BidirectionalNetwork | undefined;
status(): WebSocketReadyState {
if (this.ws == undefined) {
return "Closed";
}
return this.ws.status();
}
private constructor(
readonly url: URL,
readonly wsCreator: (url: string, log: boolean) => BidirectionalNetwork | Error,
public log: boolean,
readonly signer?: Signer,
readonly signer_v2?: Signer_V2,
) {
(async () => {
const ws = await this.connect();
if (ws instanceof Error) {
this.error = ws;
return ws;
}
this.ws = ws;
for (;;) {
const messsage = await this.nextMessage(this.ws);
if (messsage.type == "RelayDisconnectedByClient") {
this.error = messsage.error;
// exit the coroutine
return messsage.error;
} else if (
messsage.type == "WebSocketClosed" ||
messsage.type == "FailedToLookupAddress" ||
messsage.type == "OtherError" || messsage.type == "closed"
) {
if (messsage.type != "closed") {
if (messsage.error instanceof Error) {
this.error = messsage.error;
} else if (typeof messsage.error == "string") {
this.error = new Error(messsage.error);
} else {
console.error(messsage);
this.error = new Error(messsage.error.error);
}
}
if (messsage.type == "closed") {
// https://www.rfc-editor.org/rfc/rfc6455.html#section-7.4
// https://www.iana.org/assignments/websocket/websocket.xml#close-code-number
if (messsage.event.code == 3000) {
// close all sub channels
for (const stream of this.subscriptionMap) {
const e = await this.closeSub(stream[0]);
if (e instanceof Error) {
console.error(e);
}
}
const err = new AuthError(messsage.event.reason);
// resolve all send_promise_resolvers to false
for (const [_, resolver] of this.send_promise_resolvers) {
resolver({
ok: false,
message: err.message,
});
}
return err;
}
}
if (this._isClosedByClient == false) {
console.log("connection error", messsage);
const err = await this.connect();
if (err instanceof RelayDisconnectedByClient) {
return err;
}
if (err instanceof Error) {
console.error(err);
this.error = err;
}
}
continue;
} else if (messsage.type == "open") {
if (this.log) {
console.log(`relay connection ${this.url} is openned`);
}
// the websocket is just openned
// send all the subscriptions to the relay
for (const [subID, data] of this.subscriptionMap.entries()) {
if (this.ws == undefined) {
console.error("impossible state");
break;
}
const err = await sendSubscription(this.ws, subID, ...data.filters);
if (err instanceof Error) {
console.error(err);
}
}
} else {
const relayResponse = parseJSON<_RelayResponse>(messsage.data);
if (relayResponse instanceof Error) {
console.error(relayResponse);
continue;
}
if (
relayResponse[0] === "EVENT" ||
relayResponse[0] === "EOSE"
) {
const subID = relayResponse[1];
const subscription = this.subscriptionMap.get(
subID,
);
if (subscription === undefined) {
// the subscription has been closed locally before receiving remote messages
// or the relay sends to the wrong connection
continue;
}
const chan = subscription.chan;
if (!chan.closed()) {
if (relayResponse[0] === "EOSE") {
chan.put({
type: relayResponse[0],
subID: relayResponse[1],
});
} else {
chan.put({
type: relayResponse[0],
subID: relayResponse[1],
event: relayResponse[2],
});
}
}
} else if (relayResponse[0] == "OK") {
const resolver = this.send_promise_resolvers.get(relayResponse[1]);
if (resolver) {
const ok = relayResponse[2];
const message = relayResponse[3];
resolver({ ok, message });
}
} else {
for (const sub of this.subscriptionMap.values()) {
sub.chan.put({
type: "NOTICE",
note: relayResponse[1],
});
}
console.log(url, relayResponse); // NOTICE, OK and other non-standard response types
}
}
}
})().then((res) => {
if (res instanceof RelayDisconnectedByClient) {
if (this.log) {
console.log(res);
}
return;
}
if (res instanceof Error) {
this.error = res;
} else {
console.error(res);
}
});
}
public static New(
urlString: string,
args?: {
wsCreator?: (url: string, log: boolean) => BidirectionalNetwork | Error;
connect?: boolean;
log?: boolean;
signer?: Signer; // used for authentication
signer_v2?: Signer_V2; // used for sign event v2
},
): SingleRelayConnection | TypeError {
if (args == undefined) {
args = {};
}
try {
if (!urlString.startsWith("wss://") && !urlString.startsWith("ws://")) {
urlString = "wss://" + urlString;
}
if (args.wsCreator == undefined) {
args.wsCreator = AsyncWebSocket.New;
}
const url = newURL(urlString);
if (url instanceof TypeError) {
return url;
}
return new SingleRelayConnection(
url,
args.wsCreator,
args.log || false,
args.signer,
args.signer_v2,
);
} catch (e) {
if (e instanceof Error) {
return e;
} else {
throw e; // impossible
}
}
}
async newSub(subID: string, ...filters: NostrFilter[]) {
if (this.error instanceof AuthError) {
return this.error;
}
if (this.log) {
console.log(`${this.url} registers subscription ${subID}`, ...filters);
}
const subscription = this.subscriptionMap.get(subID);
if (subscription !== undefined) {
return new SubscriptionAlreadyExist(subID, this.url.toString());
}
if (this.ws != undefined) {
const err = await sendSubscription(this.ws, subID, ...filters);
if (err instanceof Error) {
console.error(err);
}
}
const chan = csp.chan<RelayResponse_REQ_Message>();
this.subscriptionMap.set(subID, { filters, chan });
return { filters, chan };
}
async sendEvent(event: NostrEvent) {
if (this.ws == undefined) {
return new WebSocketClosed(this.url.toString(), this.status());
}
if (this.error) {
return this.error;
}
const err = await this.ws.send(JSON.stringify([
"EVENT",
event,
]));
if (err instanceof Error) {
return err;
}
const res = await new Promise<{ ok: boolean; message: string }>(
(resolve) => {
this.send_promise_resolvers.set(event.id, resolve);
},
);
if (!res.ok) {
return new RelayRejectedEvent(res.message, event);
}
return res.message;
}
async getEvent(id: NoteID | string) {
if (this.error) {
return this.error;
}
if (id instanceof NoteID) {
id = id.hex;
}
const err = await this.closeSub(id);
if (err instanceof Error) return err;
const events = await this.newSub(id, { ids: [id] });
if (events instanceof Error) {
return events;
}
for await (const msg of events.chan) {
const err = await this.closeSub(id);
if (err instanceof Error) return err;
if (msg.type == "EVENT") {
return msg.event;
} else if (msg.type == "NOTICE") {
// todo: give a concrete type
return new Error(msg.note);
} else if (msg.type == "EOSE") {
return;
}
}
}
async getReplaceableEvent(pubkey: PublicKey, kind: NostrKind) {
const subID = `${pubkey.bech32()}:${kind}`;
const err = await this.closeSub(subID);
if (err instanceof Error) return err;
const events = await this.newSub(subID, {
authors: [pubkey.hex],
kinds: [kind],
limit: 1,
});
if (events instanceof Error) {
return events;
}
for await (const msg of events.chan) {
const err = await this.closeSub(subID);
if (err instanceof Error) return err;
if (msg.type == "EVENT") {
return msg.event;
} else if (msg.type == "NOTICE") {
return new Error(msg.note);
} else if (msg.type == "EOSE") {
return;
}
}
}
async closeSub(subID: string) {
let err;
if (this.ws != undefined) {
err = await this.ws.send(JSON.stringify([
"CLOSE",
subID, // multiplex marker / channel
]));
}
const subscription = this.subscriptionMap.get(subID);
if (subscription === undefined) {
return;
}
try {
await subscription.chan.close();
} catch (e) {
if (!(e instanceof csp.CloseChannelTwiceError)) {
throw e;
}
}
this.subscriptionMap.delete(subID);
return err;
}
close = async (force?: boolean) => {
this._isClosedByClient = true;
for (const [subID, { chan }] of this.subscriptionMap.entries()) {
if (chan.closed()) {
continue;
}
await this.closeSub(subID);
}
if (this.ws) {
await this.ws.close(undefined, undefined, force ? true : false);
}
// the WebSocket constructor is async underneath but since it's too old,
// it does not have an awaitable interface so that exiting the program may cause
// unresolved event underneath
// this is a quick & dirty way for me to address it
// old browser API sucks
await csp.sleep(1);
if (this.log) {
console.log(`relay ${this.url} closed, status: ${this.status()}`);
}
};
[Symbol.asyncDispose] = () => {
return this.close();
};
isClosed(): boolean {
if (this.ws == undefined) {
return true;
}
return this.ws.status() == "Closed" || this.ws.status() == "Closing";
}
private async connect() {
if (this.error instanceof Error) {
return this.error;
}
let ws: BidirectionalNetwork | Error | undefined;
for (;;) {
if (this.log) {
console.log(`(re)connecting ${this.url}`);
}
if (this.isClosedByClient()) {
return new RelayDisconnectedByClient();
}
if (this.ws) {
const status = this.ws.status();
if (status == "Connecting" || status == "Open") {
return this.ws;
}
}
if (this.signer) {
this.url.searchParams.set(
"auth",
btoa(JSON.stringify(
await prepareNostrEvent(this.signer, {
kind: NostrKind.HTTP_AUTH,
content: "",
}),
)),
);
}
ws = this.wsCreator(this.url.toString(), this.log);
if (ws instanceof Error) {
console.error(ws.name, ws.message, ws.cause);
if (ws.name == "SecurityError") {
return ws;
}
continue;
}
break;
}
this.ws = ws;
return this.ws;
}
private async nextMessage(ws: BidirectionalNetwork): Promise<NextMessageType> {
if (this.isClosedByClient()) {
return {
type: "RelayDisconnectedByClient",
error: new RelayDisconnectedByClient(),
};
}
const message = await ws.nextMessage();
return message;
}
unstable = {
/**
* before we have relay info as events,
* let's pull it periodically to have an async iterable API
*/
getRelayInformationStream: () => {
const chan = csp.chan<Error | RelayInformation>();
(async () => {
let spaceInformation: RelayInformation | Error | undefined;
for (;;) {
if (chan.closed()) return;
const info = await this.unstable.getSpaceInformation();
if (info instanceof Error || !deepEqual(spaceInformation, info)) {
spaceInformation = info;
const err = await chan.put(info);
if (err instanceof Error) {
// the channel is closed by outside, stop the stream
return;
}
}
await sleep(3000); // every 3 sec
}
})();
return chan;
},
postEventV2: async (event: Event_V2): Promise<Error | Response> => {
const httpURL = new URL(this.url);
httpURL.protocol = httpURL.protocol == "wss:" ? "https" : "http";
try {
return await fetch(httpURL, { method: "POST", body: JSON.stringify(event) });
} catch (e) {
return e as Error;
}
},
/**
* v2 API, unstable
* add a public key to this relay as its member
*/
addSpaceMember: async (member: PublicKey | string): Promise<Error | Response> => {
if (!this.signer_v2) {
return new SignerV2NotExist();
}
const spaceMemberEvent = await prepareSpaceMember(this.signer_v2, member);
if (spaceMemberEvent instanceof Error) {
return spaceMemberEvent;
}
return await this.unstable.postEventV2(spaceMemberEvent);
},
/**
* v2 API, unstable
* a stream of space members
*/
getSpaceMembersStream: () => {
const chan = csp.chan<
RESTRequestFailed | TypeError | SyntaxError | Error | SpaceMember[]
>();
(async () => {
let spaceMembers:
| SpaceMember[]
| RESTRequestFailed
| TypeError
| SyntaxError
| Error
| undefined;
for (;;) {
if (chan.closed()) return;
const members = await getSpaceMembers(this.url);
if (members instanceof Error) {
if (members instanceof RESTRequestFailed) {
if (members.res.status == 404) {
await chan.put(members);
await chan.close();
} else {
await chan.put(members);
}
} else {
await chan.put(members);
}
} else if (!deepEqual(spaceMembers, members)) {
spaceMembers = members;
const err = await chan.put(members);
if (err instanceof Error) {
// the channel is closed by outside, stop the stream
return;
}
}
await sleep(3000); // every 3 sec
}
})();
return chan;
},
getSpaceInformation: () => {
return getRelayInformation(this.url);
},
};
}
async function sendSubscription(ws: BidirectionalNetwork, subID: string, ...filters: NostrFilter[]) {
const req: ClientRequest_REQ = ["REQ", subID, ...filters];
const err = await ws.send(JSON.stringify(req));
if (err) {
return err;
}
}
export class RelayRejectedEvent extends Error {
constructor(msg: string, public readonly event: NostrEvent) {
super(`${event.id}: ${msg}`);
this.name = RelayRejectedEvent.name;
}
}
export class AuthError extends Error {
constructor(msg: string) {
super(msg);
this.name = AuthError.name;
}
}
export class SignerV2NotExist extends Error {
constructor() {
super(`Signer V2 does not exist`);
this.name = SignerV2NotExist.name;
}
}
// deno-lint-ignore no-explicit-any
function deepEqual(a: any, b: any) {
try {
assertEquals(a, b);
return true;
} catch {
return false;
}
}