@netifyjs/netify 0.0.0-stage → 1.0.0-alpha.1
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/LICENSE +21 -0
- package/README.md +105 -2
- package/package.json +65 -4
- package/src/bootstrap/client/index.ts +191 -0
- package/src/bootstrap/dispatcher/index.ts +204 -0
- package/src/bootstrap/index.ts +22 -0
- package/src/bootstrap/reconnect/index.ts +334 -0
- package/src/bootstrap/server/index.ts +284 -0
- package/src/buffer/bits/index.ts +2 -0
- package/src/buffer/bits/reader/index.ts +64 -0
- package/src/buffer/bits/writer/index.ts +79 -0
- package/src/buffer/index.ts +1375 -0
- package/src/buffer/pool/index.ts +46 -0
- package/src/buffer/quantizer/index.ts +101 -0
- package/src/channel/attribute/index.ts +89 -0
- package/src/channel/context/index.ts +621 -0
- package/src/channel/group/index.ts +256 -0
- package/src/channel/handler/duplex/index.ts +105 -0
- package/src/channel/handler/inbound/index.ts +78 -0
- package/src/channel/handler/index.ts +135 -0
- package/src/channel/handler/outbound/index.ts +33 -0
- package/src/channel/index.ts +619 -0
- package/src/channel/initializer/index.ts +77 -0
- package/src/channel/outbound/index.ts +611 -0
- package/src/channel/pipeline/head/index.ts +100 -0
- package/src/channel/pipeline/index.ts +414 -0
- package/src/channel/pipeline/tail/index.ts +45 -0
- package/src/channel/pipeline/tracker/index.ts +120 -0
- package/src/channel/queue/index.ts +203 -0
- package/src/channel/resolved/index.ts +34 -0
- package/src/channel/server/index.ts +164 -0
- package/src/channel/shutdown/index.ts +25 -0
- package/src/channel/simple/index.ts +38 -0
- package/src/channel/transport/index.ts +74 -0
- package/src/channel/transport/socket/index.ts +80 -0
- package/src/cluster/index.ts +360 -0
- package/src/codec/binary/index.ts +102 -0
- package/src/codec/decoder/index.ts +479 -0
- package/src/codec/delimiter/index.ts +189 -0
- package/src/codec/encoder/index.ts +48 -0
- package/src/codec/error/index.ts +33 -0
- package/src/codec/fixed/index.ts +45 -0
- package/src/codec/http/aggregator/index.ts +236 -0
- package/src/codec/http/client/index.ts +120 -0
- package/src/codec/http/decoder/index.ts +4 -0
- package/src/codec/http/decoder/object/index.ts +644 -0
- package/src/codec/http/decoder/request/index.ts +49 -0
- package/src/codec/http/decoder/response/index.ts +59 -0
- package/src/codec/http/encoder/index.ts +3 -0
- package/src/codec/http/encoder/object/index.ts +196 -0
- package/src/codec/http/encoder/request/index.ts +24 -0
- package/src/codec/http/encoder/response/index.ts +26 -0
- package/src/codec/http/headers/index.ts +287 -0
- package/src/codec/http/index.ts +33 -0
- package/src/codec/http/message/content/index.ts +36 -0
- package/src/codec/http/message/full/index.ts +10 -0
- package/src/codec/http/message/full/request/index.ts +45 -0
- package/src/codec/http/message/full/response/index.ts +43 -0
- package/src/codec/http/message/head/index.ts +79 -0
- package/src/codec/http/message/index.ts +16 -0
- package/src/codec/http/message/last/index.ts +27 -0
- package/src/codec/http/message/request/index.ts +39 -0
- package/src/codec/http/message/response/index.ts +31 -0
- package/src/codec/http/method/index.ts +101 -0
- package/src/codec/http/server/index.ts +81 -0
- package/src/codec/http/status/index.ts +170 -0
- package/src/codec/http/version/index.ts +70 -0
- package/src/codec/index.ts +83 -0
- package/src/codec/length/index.ts +330 -0
- package/src/codec/line/index.ts +45 -0
- package/src/codec/message/decoder/index.ts +84 -0
- package/src/codec/message/encoder/index.ts +56 -0
- package/src/codec/message/index.ts +2 -0
- package/src/codec/msgpack/index.ts +51 -0
- package/src/codec/prepender/index.ts +296 -0
- package/src/codec/protobuf/index.ts +57 -0
- package/src/codec/string/decoder/index.ts +47 -0
- package/src/codec/string/encoder/index.ts +26 -0
- package/src/codec/string/index.ts +2 -0
- package/src/codec/websocket/client/index.ts +235 -0
- package/src/codec/websocket/decoder/index.ts +371 -0
- package/src/codec/websocket/encoder/index.ts +170 -0
- package/src/codec/websocket/error/index.ts +42 -0
- package/src/codec/websocket/frame/base/index.ts +55 -0
- package/src/codec/websocket/frame/binary/index.ts +24 -0
- package/src/codec/websocket/frame/close/index.ts +82 -0
- package/src/codec/websocket/frame/continuation/index.ts +31 -0
- package/src/codec/websocket/frame/index.ts +10 -0
- package/src/codec/websocket/frame/opcode/index.ts +35 -0
- package/src/codec/websocket/frame/ping/index.ts +24 -0
- package/src/codec/websocket/frame/pong/index.ts +24 -0
- package/src/codec/websocket/frame/text/index.ts +31 -0
- package/src/codec/websocket/handshake/index.ts +38 -0
- package/src/codec/websocket/index.ts +25 -0
- package/src/codec/websocket/key/index.ts +41 -0
- package/src/codec/websocket/protocol/index.ts +147 -0
- package/src/codec/websocket/server/index.ts +233 -0
- package/src/codec/websocket/status/index.ts +97 -0
- package/src/codec/websocket/upgrade/index.ts +116 -0
- package/src/datagram/bootstrap/index.ts +269 -0
- package/src/datagram/channel/index.ts +103 -0
- package/src/datagram/index.ts +10 -0
- package/src/datagram/packet/index.ts +72 -0
- package/src/datagram/transport/index.ts +239 -0
- package/src/handler/flush/index.ts +187 -0
- package/src/handler/idle/index.ts +295 -0
- package/src/handler/index.ts +22 -0
- package/src/handler/logging/index.ts +195 -0
- package/src/handler/metrics/index.ts +300 -0
- package/src/handler/offload/index.ts +141 -0
- package/src/handler/timeout/error/index.ts +29 -0
- package/src/handler/timeout/index.ts +3 -0
- package/src/handler/timeout/read/index.ts +44 -0
- package/src/handler/timeout/write/index.ts +89 -0
- package/src/handler/traffic/index.ts +259 -0
- package/src/index.ts +258 -0
- package/src/logger/index.ts +47 -0
- package/src/reliable/bootstrap/index.ts +154 -0
- package/src/reliable/cipher/index.ts +227 -0
- package/src/reliable/cookie/index.ts +78 -0
- package/src/reliable/handler/index.ts +1202 -0
- package/src/reliable/handshake/index.ts +144 -0
- package/src/reliable/index.ts +38 -0
- package/src/reliable/lane/index.ts +420 -0
- package/src/reliable/message/index.ts +102 -0
- package/src/reliable/packet/index.ts +117 -0
- package/src/reliable/peer/index.ts +929 -0
- package/src/reliable/registry/index.ts +107 -0
- package/src/serve/bootstrap/index.ts +606 -0
- package/src/serve/channel/index.ts +246 -0
- package/src/serve/index.ts +17 -0
- package/src/serve/outbox/index.ts +292 -0
- package/src/serve/transport/index.ts +96 -0
- package/src/serve/writer/index.ts +119 -0
- package/src/shard/envelope/index.ts +44 -0
- package/src/shard/gateway/index.ts +119 -0
- package/src/shard/index.ts +11 -0
- package/src/shard/link/index.ts +743 -0
- package/src/shard/map/index.ts +91 -0
- package/src/worker/group/index.ts +175 -0
- package/src/worker/index.ts +10 -0
- package/src/worker/pool/index.ts +235 -0
- package/src/worker/service/index.ts +55 -0
|
@@ -0,0 +1,360 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What to run and how many copies
|
|
3
|
+
*/
|
|
4
|
+
export type ClusterOptions = {
|
|
5
|
+
/**
|
|
6
|
+
* Path to the entry file, run with bun
|
|
7
|
+
*/
|
|
8
|
+
readonly script: string
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Defaults to one per CPU core
|
|
12
|
+
*/
|
|
13
|
+
readonly workers?: number
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* On by default, set false to let crashed workers stay dead
|
|
17
|
+
*/
|
|
18
|
+
readonly restart?: boolean
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Appended after the script path
|
|
22
|
+
*/
|
|
23
|
+
readonly argv?: readonly string[]
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Merged over the parent's environment
|
|
27
|
+
*/
|
|
28
|
+
readonly env?: Readonly<Record<string, string>>
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* How long a stopping worker gets before it's killed in milliseconds, 10000 by default
|
|
32
|
+
*/
|
|
33
|
+
readonly stopTimeout?: number
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* How long reload waits for a new worker to call ready in milliseconds, 10000 by default
|
|
37
|
+
*/
|
|
38
|
+
readonly readyTimeout?: number
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* How reload replaces each worker
|
|
43
|
+
*/
|
|
44
|
+
export type ReloadOrder = 'start-first' | 'stop-first'
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Whatever Bun.spawn hands back
|
|
48
|
+
*/
|
|
49
|
+
type Worker = ReturnType<typeof Bun.spawn>
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Forks the same script a few times so they can all listen on one port
|
|
53
|
+
* @class
|
|
54
|
+
*/
|
|
55
|
+
export class Cluster {
|
|
56
|
+
/**
|
|
57
|
+
* Env var a worker reads to find its own index
|
|
58
|
+
*/
|
|
59
|
+
public static readonly workerVariable: string = 'NETIFY_WORKER'
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Env var a worker reads to find the cluster size
|
|
63
|
+
*/
|
|
64
|
+
public static readonly countVariable: string = 'NETIFY_WORKERS'
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Env var a worker reads to find which cluster it's in
|
|
68
|
+
*/
|
|
69
|
+
public static readonly clusterVariable: string = 'NETIFY_CLUSTER'
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* What a worker sends once it's listening
|
|
73
|
+
*/
|
|
74
|
+
private static readonly readyMessage: string = 'netify:ready'
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Kept for respawning workers later
|
|
78
|
+
*/
|
|
79
|
+
private readonly options: ClusterOptions
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Resolved worker count, fixed for the cluster's lifetime
|
|
83
|
+
*/
|
|
84
|
+
private readonly count: number
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Random name shared by every worker in this cluster
|
|
88
|
+
*/
|
|
89
|
+
private readonly name: string
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* One slot per worker index, null while nothing is running there
|
|
93
|
+
*/
|
|
94
|
+
private readonly processes: (Worker | null)[]
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Settles when a worker calls ready, true if it did in time
|
|
98
|
+
*/
|
|
99
|
+
private readonly readiness: Map<Worker, PromiseWithResolvers<boolean>>
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Cleared by stop so exiting workers aren't brought back
|
|
103
|
+
*/
|
|
104
|
+
private running: boolean
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Doesn't spawn anything yet, call start for that
|
|
108
|
+
* @param options script, worker count and restart policy
|
|
109
|
+
*/
|
|
110
|
+
public constructor(options: ClusterOptions) {
|
|
111
|
+
const reason = Cluster.refusal(options)
|
|
112
|
+
if (reason !== null) throw new RangeError(reason)
|
|
113
|
+
|
|
114
|
+
this.options = options
|
|
115
|
+
this.count = options.workers ?? navigator.hardwareConcurrency
|
|
116
|
+
this.name = crypto.randomUUID().slice(0, 8)
|
|
117
|
+
this.processes = Array.from({ length: this.count }, (): null => null)
|
|
118
|
+
this.readiness = new Map<Worker, PromiseWithResolvers<boolean>>()
|
|
119
|
+
this.running = false
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Checks the worker count and timeouts
|
|
124
|
+
* @param options what the caller passed in
|
|
125
|
+
*/
|
|
126
|
+
private static refusal(options: ClusterOptions): string | null {
|
|
127
|
+
const count = options.workers ?? navigator.hardwareConcurrency
|
|
128
|
+
if (!Number.isInteger(count) || count < 1) return 'Worker count is invalid'
|
|
129
|
+
|
|
130
|
+
for (const timeout of [options.stopTimeout, options.readyTimeout]) {
|
|
131
|
+
if (timeout !== undefined && (!Number.isFinite(timeout) || timeout < 0)) {
|
|
132
|
+
return 'Timeout is invalid'
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
return null
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Call from inside a worker to find out which one you are, null if not in a cluster
|
|
141
|
+
*/
|
|
142
|
+
public static get workerId(): number | null {
|
|
143
|
+
const value = Bun.env[Cluster.workerVariable]
|
|
144
|
+
|
|
145
|
+
return value === undefined ? null : Number(value)
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* How many siblings this worker has, null if not in a cluster
|
|
150
|
+
*/
|
|
151
|
+
public static get workerCount(): number | null {
|
|
152
|
+
const value = Bun.env[Cluster.countVariable]
|
|
153
|
+
|
|
154
|
+
return value === undefined ? null : Number(value)
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Name of the cluster this worker is in, null if not in a cluster
|
|
159
|
+
*/
|
|
160
|
+
public static get clusterId(): string | null {
|
|
161
|
+
return Bun.env[Cluster.clusterVariable] ?? null
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Tells the parent this worker is listening and exits if the parent goes, call it after bind
|
|
166
|
+
*/
|
|
167
|
+
public static ready(): void {
|
|
168
|
+
if (process.send === undefined) return
|
|
169
|
+
|
|
170
|
+
process.send(Cluster.readyMessage)
|
|
171
|
+
process.once('disconnect', (): void => {
|
|
172
|
+
process.exit(0)
|
|
173
|
+
})
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* Runs a callback when the parent stops this worker, then exits
|
|
178
|
+
* @param callback usually a graceful shutdown
|
|
179
|
+
*/
|
|
180
|
+
public static onStop(callback: () => void | Promise<void>): void {
|
|
181
|
+
process.once('SIGTERM', (): void => {
|
|
182
|
+
void Promise.resolve()
|
|
183
|
+
.then(callback)
|
|
184
|
+
.finally((): void => {
|
|
185
|
+
process.exit(0)
|
|
186
|
+
})
|
|
187
|
+
})
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* Configured worker count, not how many are alive right now
|
|
192
|
+
*/
|
|
193
|
+
public get size(): number {
|
|
194
|
+
return this.count
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* True between start and stop
|
|
199
|
+
*/
|
|
200
|
+
public get isRunning(): boolean {
|
|
201
|
+
return this.running
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* Spawns every worker, does nothing if already started
|
|
206
|
+
*/
|
|
207
|
+
public start(): this {
|
|
208
|
+
if (this.running) return this
|
|
209
|
+
this.running = true
|
|
210
|
+
|
|
211
|
+
for (let index = 0; index < this.count; index++) {
|
|
212
|
+
this.processes[index] = this.spawn(index)
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
return this
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* Waits until every worker has called ready, or the ready timeout passes
|
|
220
|
+
*/
|
|
221
|
+
public async whenReady(): Promise<void> {
|
|
222
|
+
await Promise.all(
|
|
223
|
+
this.processes
|
|
224
|
+
.filter((child: Worker | null): child is Worker => child !== null)
|
|
225
|
+
.map((child: Worker): Promise<void> => this.waitReady(child)),
|
|
226
|
+
)
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* Stops every worker, killing any still running after the stop timeout
|
|
231
|
+
*/
|
|
232
|
+
public async stop(): Promise<void> {
|
|
233
|
+
this.running = false
|
|
234
|
+
|
|
235
|
+
const children = this.processes.filter(
|
|
236
|
+
(child: Worker | null): child is Worker => child !== null,
|
|
237
|
+
)
|
|
238
|
+
this.processes.fill(null)
|
|
239
|
+
await Promise.all(
|
|
240
|
+
children.map((child: Worker): Promise<void> => this.retire(child)),
|
|
241
|
+
)
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* Replaces every worker one at a time so the server never goes down
|
|
246
|
+
* @param order start-first for shared ports, stop-first when each worker has its own
|
|
247
|
+
*/
|
|
248
|
+
public async reload(order: ReloadOrder = 'start-first'): Promise<void> {
|
|
249
|
+
if (!this.running) throw new Error('Cluster is not running')
|
|
250
|
+
|
|
251
|
+
for (let index = 0; index < this.count; index++) {
|
|
252
|
+
const old = this.processes[index] ?? null
|
|
253
|
+
|
|
254
|
+
if (order === 'stop-first') {
|
|
255
|
+
this.processes[index] = null
|
|
256
|
+
if (old !== null) await this.retire(old)
|
|
257
|
+
const fresh = this.spawn(index)
|
|
258
|
+
this.processes[index] = fresh
|
|
259
|
+
await this.waitReady(fresh)
|
|
260
|
+
} else {
|
|
261
|
+
const fresh = this.spawn(index)
|
|
262
|
+
await this.waitReady(fresh)
|
|
263
|
+
this.processes[index] = fresh
|
|
264
|
+
if (old !== null) await this.retire(old)
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* Launches one worker with its index in the environment
|
|
271
|
+
* @param index which slot it fills, passed through as NETIFY_WORKER
|
|
272
|
+
*/
|
|
273
|
+
private spawn(index: number): Worker {
|
|
274
|
+
const child: Worker = Bun.spawn({
|
|
275
|
+
/**
|
|
276
|
+
* Runs the worker script with Bun, plus any extra args
|
|
277
|
+
*/
|
|
278
|
+
cmd: ['bun', this.options.script, ...(this.options.argv ?? [])],
|
|
279
|
+
/**
|
|
280
|
+
* Our env plus the worker's index, the cluster size and its name
|
|
281
|
+
*/
|
|
282
|
+
env: {
|
|
283
|
+
...Bun.env,
|
|
284
|
+
...this.options.env,
|
|
285
|
+
[Cluster.workerVariable]: String(index),
|
|
286
|
+
[Cluster.countVariable]: String(this.count),
|
|
287
|
+
[Cluster.clusterVariable]: this.name,
|
|
288
|
+
},
|
|
289
|
+
/**
|
|
290
|
+
* Workers don't read from us
|
|
291
|
+
*/
|
|
292
|
+
stdin: 'ignore',
|
|
293
|
+
/**
|
|
294
|
+
* Worker output shows up in our terminal
|
|
295
|
+
*/
|
|
296
|
+
stdout: 'inherit',
|
|
297
|
+
/**
|
|
298
|
+
* Same for errors
|
|
299
|
+
*/
|
|
300
|
+
stderr: 'inherit',
|
|
301
|
+
/**
|
|
302
|
+
* Notes when a worker says it's ready
|
|
303
|
+
*/
|
|
304
|
+
ipc: (message: unknown): void => {
|
|
305
|
+
if (message === Cluster.readyMessage) {
|
|
306
|
+
this.readiness.get(child)?.resolve(true)
|
|
307
|
+
}
|
|
308
|
+
},
|
|
309
|
+
/**
|
|
310
|
+
* Brings it back unless we're stopping or restarts are off
|
|
311
|
+
*/
|
|
312
|
+
onExit: (): void => {
|
|
313
|
+
this.readiness.get(child)?.resolve(false)
|
|
314
|
+
this.readiness.delete(child)
|
|
315
|
+
if (this.processes[index] !== child) return
|
|
316
|
+
this.processes[index] = null
|
|
317
|
+
if (this.running && this.options.restart !== false) {
|
|
318
|
+
this.processes[index] = this.spawn(index)
|
|
319
|
+
}
|
|
320
|
+
},
|
|
321
|
+
})
|
|
322
|
+
|
|
323
|
+
this.readiness.set(child, Promise.withResolvers<boolean>())
|
|
324
|
+
return child
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/**
|
|
328
|
+
* Waits for a worker to call ready, up to the ready timeout
|
|
329
|
+
* @param child the worker
|
|
330
|
+
*/
|
|
331
|
+
private async waitReady(child: Worker): Promise<void> {
|
|
332
|
+
const readiness = this.readiness.get(child)
|
|
333
|
+
if (readiness === undefined) return
|
|
334
|
+
|
|
335
|
+
const timeout = this.options.readyTimeout ?? 10000
|
|
336
|
+
const timer = setTimeout((): void => {
|
|
337
|
+
readiness.resolve(false)
|
|
338
|
+
}, timeout)
|
|
339
|
+
await readiness.promise
|
|
340
|
+
clearTimeout(timer)
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/**
|
|
344
|
+
* Asks a worker to stop and kills it after the stop timeout
|
|
345
|
+
* @param child the worker
|
|
346
|
+
*/
|
|
347
|
+
private async retire(child: Worker): Promise<void> {
|
|
348
|
+
if (child.exitCode !== null || child.killed) {
|
|
349
|
+
await child.exited
|
|
350
|
+
return
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
child.kill('SIGTERM')
|
|
354
|
+
const timer = setTimeout((): void => {
|
|
355
|
+
child.kill('SIGKILL')
|
|
356
|
+
}, this.options.stopTimeout ?? 10000)
|
|
357
|
+
await child.exited
|
|
358
|
+
clearTimeout(timer)
|
|
359
|
+
}
|
|
360
|
+
}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { ByteBuf } from '../../buffer/index.ts'
|
|
2
|
+
import type { HandlerContext } from '../../channel/context/index.ts'
|
|
3
|
+
import { DuplexHandlerAdapter } from '../../channel/handler/duplex/index.ts'
|
|
4
|
+
import { DecoderError, EncoderError } from '../error/index.ts'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* How to turn your messages into bytes and back
|
|
8
|
+
*/
|
|
9
|
+
export type BinaryCodecOptions<T> = {
|
|
10
|
+
/**
|
|
11
|
+
* Turns a message into bytes, FlatBuffers builders and the like go here
|
|
12
|
+
* @param message what's being sent
|
|
13
|
+
*/
|
|
14
|
+
readonly encode: (message: T) => Uint8Array
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Turns one whole frame back into a message, the bytes are a view so copy before keeping them
|
|
18
|
+
* @param bytes one frame
|
|
19
|
+
*/
|
|
20
|
+
readonly decode: (bytes: Uint8Array) => T
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Picks the outbound messages this codec encodes, others pass straight through
|
|
24
|
+
* @param message whatever is being written
|
|
25
|
+
*/
|
|
26
|
+
readonly accepts: (message: unknown) => message is T
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Encodes and decodes whole frames with any binary format, put a framer in front of it
|
|
31
|
+
* @class
|
|
32
|
+
*/
|
|
33
|
+
export class BinaryCodec<T> extends DuplexHandlerAdapter {
|
|
34
|
+
/**
|
|
35
|
+
* Message to bytes
|
|
36
|
+
*/
|
|
37
|
+
private readonly encoder: (message: T) => Uint8Array
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Bytes to message
|
|
41
|
+
*/
|
|
42
|
+
private readonly decoder: (bytes: Uint8Array) => T
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Which writes are ours
|
|
46
|
+
*/
|
|
47
|
+
private readonly takes: (message: unknown) => message is T
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Wraps your encode and decode functions
|
|
51
|
+
* @param options encode, decode and accepts
|
|
52
|
+
*/
|
|
53
|
+
public constructor(options: BinaryCodecOptions<T>) {
|
|
54
|
+
super()
|
|
55
|
+
|
|
56
|
+
this.encoder = options.encode
|
|
57
|
+
this.decoder = options.decode
|
|
58
|
+
this.takes = options.accepts
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Decodes a frame without copying it first
|
|
63
|
+
* @param context where messages go
|
|
64
|
+
* @param message a frame from the framer
|
|
65
|
+
*/
|
|
66
|
+
public override channelRead(
|
|
67
|
+
context: HandlerContext,
|
|
68
|
+
message: unknown,
|
|
69
|
+
): void | Promise<void> {
|
|
70
|
+
if (!(message instanceof ByteBuf)) return context.fireChannelRead(message)
|
|
71
|
+
|
|
72
|
+
let decoded: T
|
|
73
|
+
try {
|
|
74
|
+
decoded = this.decoder(message.toUint8Array())
|
|
75
|
+
} catch (cause) {
|
|
76
|
+
throw new DecoderError('Decoding failed', { cause })
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
return context.fireChannelRead(decoded)
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Encodes our messages, lets everything else through
|
|
84
|
+
* @param context where bytes go
|
|
85
|
+
* @param message whatever is being written
|
|
86
|
+
*/
|
|
87
|
+
public override write(
|
|
88
|
+
context: HandlerContext,
|
|
89
|
+
message: unknown,
|
|
90
|
+
): Promise<void> {
|
|
91
|
+
if (!this.takes(message)) return context.write(message)
|
|
92
|
+
|
|
93
|
+
let bytes: Uint8Array
|
|
94
|
+
try {
|
|
95
|
+
bytes = this.encoder(message)
|
|
96
|
+
} catch (cause) {
|
|
97
|
+
return Promise.reject(new EncoderError('Encoding failed', { cause }))
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
return context.write(bytes)
|
|
101
|
+
}
|
|
102
|
+
}
|