-
Notifications
You must be signed in to change notification settings - Fork 1
/
channel.ts
209 lines (195 loc) · 5.14 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
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
import { Queue } from "./queue.ts";
import { jsonSerializer } from "./serializers.ts";
export interface Channel<T> {
closed: Promise<void>;
signal: AbortSignal;
close(): void;
send(value: T): Promise<void>;
recv(signal?: AbortSignal): AsyncIterableIterator<T>;
}
export const link = (...signals: AbortSignal[]): AbortSignal => {
const ctrl = new AbortController();
for (const signal of signals) {
signal.addEventListener("abort", (evt) => {
if (!ctrl.signal.aborted) {
ctrl.abort(evt);
}
});
}
return ctrl.signal;
};
export class ClosedChannelError extends Error {
constructor() {
super("Channel is closed");
}
}
export const ifClosedChannel =
(cb: () => Promise<void> | void) => (err: unknown) => {
if (err instanceof ClosedChannelError) {
return cb();
}
throw err;
};
export const ignoreIfClosed = ifClosedChannel(() => {});
export const makeChan = <T>(capacity = 0): Channel<T> => {
let currentCapacity = capacity;
const queue: Queue<{ value: T; resolve: () => void }> = new Queue();
const ctrl = new AbortController();
const abortPromise = Promise.withResolvers<void>();
ctrl.signal.onabort = () => {
abortPromise.resolve();
};
const send = (value: T): Promise<void> => {
return new Promise((resolve, reject) => {
if (ctrl.signal.aborted) reject(new ClosedChannelError());
let mResolve = resolve;
if (currentCapacity > 0) {
currentCapacity--;
mResolve = () => {
currentCapacity++;
};
resolve();
}
queue.push({ value, resolve: mResolve });
});
};
const close = () => {
ctrl.abort();
};
const recv = async function* (
signal?: AbortSignal,
): AsyncIterableIterator<T> {
const linked = signal ? link(ctrl.signal, signal) : ctrl.signal;
while (true) {
if (linked.aborted) {
return;
}
try {
const next = await queue.pop({ signal: linked });
next.resolve();
yield next.value;
} catch (_err) {
if (linked.aborted) {
return;
}
throw _err;
}
}
};
return {
send,
recv,
close,
signal: ctrl.signal,
closed: abortPromise.promise,
};
};
export interface DuplexChannel<TSend, TReceive> {
in: Channel<TReceive>;
out: Channel<TSend>;
}
// deno-lint-ignore no-explicit-any
export type Message<TMessageProperties = any> = TMessageProperties & {
chunk?: Uint8Array;
};
export interface MessageSerializer<
TSend,
TReceive,
TRawFormat extends string | ArrayBufferLike | ArrayBufferView | Blob,
> {
binaryType?: BinaryType;
serialize: (
msg: Message<TSend>,
) => TRawFormat;
deserialize: (str: TRawFormat) => Message<TReceive>;
}
export const makeWebSocket = <
TSend,
TReceive,
TMessageFormat extends string | ArrayBufferLike | ArrayBufferView | Blob =
| string
| ArrayBufferLike
| ArrayBufferView
| Blob,
>(
socket: WebSocket,
_serializer?: MessageSerializer<TSend, TReceive, TMessageFormat>,
): Promise<DuplexChannel<Message<TSend>, Message<TReceive>>> => {
const serializer = _serializer ??
jsonSerializer<Message<TSend>, Message<TReceive>>();
const sendChan = makeChan<Message<TSend>>();
const recvChan = makeChan<Message<TReceive>>();
const ch = Promise.withResolvers<
DuplexChannel<Message<TSend>, Message<TReceive>>
>();
socket.binaryType = serializer.binaryType ?? "blob";
socket.onclose = () => {
sendChan.close();
recvChan.close();
};
socket.onerror = (err) => {
socket.close();
ch.reject(err);
};
socket.onmessage = async (msg) => {
if (recvChan.signal.aborted) {
return;
}
await recvChan.send(serializer.deserialize(msg.data));
};
socket.onopen = async () => {
ch.resolve({ in: recvChan, out: sendChan });
for await (const message of sendChan.recv()) {
try {
socket.send(
serializer.serialize(message),
);
} catch (_err) {
console.error("error sending message through socket", message);
}
}
socket.close();
};
return ch.promise;
};
export const makeReadableStream = (
ch: Channel<Uint8Array>,
signal?: AbortSignal,
): ReadableStream<Uint8Array> => {
return new ReadableStream({
async start(controller) {
for await (const content of ch.recv(signal)) {
controller.enqueue(content);
}
// Uncomment if necessary. this will send a signal to the controller
// if (signal?.aborted) {
// controller.error(new Error("aborted"));
// }
controller.close();
},
cancel() {
ch.close();
},
});
};
export const makeChanStream = (
stream: ReadableStream,
): Channel<Uint8Array> => {
const chan = makeChan<Uint8Array>(0); // capacity
// Consume the transformed stream to trigger the pipeline
const reader = stream.getReader();
const processStream = async () => {
while (true) {
const { done, value } = await reader.read();
if (done) break;
await chan.send(value);
}
chan.close();
};
processStream().catch((err) => {
if (!err?.target?.aborted) {
console.error("error processing stream", err);
}
});
return chan;
};