-
Notifications
You must be signed in to change notification settings - Fork 0
/
channel.ts
67 lines (62 loc) · 1.75 KB
/
channel.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
import { Event } from "https://deno.land/x/[email protected]/event.ts";
import { Queue } from "https://deno.land/x/[email protected]/mod.ts";
import {
compress,
decompress,
init,
} from "https://deno.land/x/[email protected]/deno/zstd.ts";
await init();
const encoder = new TextEncoder();
const decoder = new TextDecoder();
export interface Channel<Send, Recv> {
send: (data: Send) => void;
recv: () => Promise<Recv>;
closed: Event;
ready: Event;
close: () => void;
}
export const asChannel = async <Send, Recv>(
socket: WebSocket,
): Promise<Channel<Send, Recv>> => {
const ready = new Event();
const recv = new Queue<Uint8Array>();
const closed = new Event();
socket.addEventListener("open", () => {
ready.set();
});
socket.addEventListener("close", (event) => {
console.log("closed", event.reason, event.code, event.type);
closed.set();
});
socket.addEventListener("message", (event) => {
recv.push(event.data);
});
socket.addEventListener("error", (event) => {
console.log("error", event);
});
await Promise.race([ready.wait(), closed.wait()]);
return {
close: () => {
closed.set();
socket.close();
},
send: (data: Send) => {
if (!closed.is_set()) {
const stringifiedData = JSON.stringify(data);
const buffer = encoder.encode(stringifiedData);
const compressed = compress(buffer, 10);
socket.send(compressed.buffer);
} else {
console.log("close was set on send");
throw new Error("close was set on send");
}
},
recv: async () => {
const received = await recv.pop();
const str = decoder.decode(decompress(new Uint8Array(received)));
return received ? JSON.parse(str) : received;
},
closed,
ready,
};
};