@netifyjs/netify 0.0.0-stage → 1.0.0-alpha.0

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.
Files changed (142) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +105 -2
  3. package/package.json +65 -4
  4. package/src/bootstrap/client/index.ts +191 -0
  5. package/src/bootstrap/dispatcher/index.ts +204 -0
  6. package/src/bootstrap/index.ts +22 -0
  7. package/src/bootstrap/reconnect/index.ts +334 -0
  8. package/src/bootstrap/server/index.ts +284 -0
  9. package/src/buffer/bits/index.ts +2 -0
  10. package/src/buffer/bits/reader/index.ts +64 -0
  11. package/src/buffer/bits/writer/index.ts +79 -0
  12. package/src/buffer/index.ts +1375 -0
  13. package/src/buffer/pool/index.ts +46 -0
  14. package/src/buffer/quantizer/index.ts +101 -0
  15. package/src/channel/attribute/index.ts +89 -0
  16. package/src/channel/context/index.ts +621 -0
  17. package/src/channel/group/index.ts +256 -0
  18. package/src/channel/handler/duplex/index.ts +105 -0
  19. package/src/channel/handler/inbound/index.ts +78 -0
  20. package/src/channel/handler/index.ts +135 -0
  21. package/src/channel/handler/outbound/index.ts +33 -0
  22. package/src/channel/index.ts +619 -0
  23. package/src/channel/initializer/index.ts +77 -0
  24. package/src/channel/outbound/index.ts +611 -0
  25. package/src/channel/pipeline/head/index.ts +100 -0
  26. package/src/channel/pipeline/index.ts +414 -0
  27. package/src/channel/pipeline/tail/index.ts +45 -0
  28. package/src/channel/pipeline/tracker/index.ts +120 -0
  29. package/src/channel/queue/index.ts +203 -0
  30. package/src/channel/resolved/index.ts +34 -0
  31. package/src/channel/server/index.ts +164 -0
  32. package/src/channel/shutdown/index.ts +25 -0
  33. package/src/channel/simple/index.ts +38 -0
  34. package/src/channel/transport/index.ts +74 -0
  35. package/src/channel/transport/socket/index.ts +80 -0
  36. package/src/cluster/index.ts +360 -0
  37. package/src/codec/binary/index.ts +102 -0
  38. package/src/codec/decoder/index.ts +479 -0
  39. package/src/codec/delimiter/index.ts +189 -0
  40. package/src/codec/encoder/index.ts +48 -0
  41. package/src/codec/error/index.ts +33 -0
  42. package/src/codec/fixed/index.ts +45 -0
  43. package/src/codec/http/aggregator/index.ts +236 -0
  44. package/src/codec/http/client/index.ts +120 -0
  45. package/src/codec/http/decoder/index.ts +4 -0
  46. package/src/codec/http/decoder/object/index.ts +644 -0
  47. package/src/codec/http/decoder/request/index.ts +49 -0
  48. package/src/codec/http/decoder/response/index.ts +59 -0
  49. package/src/codec/http/encoder/index.ts +3 -0
  50. package/src/codec/http/encoder/object/index.ts +196 -0
  51. package/src/codec/http/encoder/request/index.ts +24 -0
  52. package/src/codec/http/encoder/response/index.ts +26 -0
  53. package/src/codec/http/headers/index.ts +287 -0
  54. package/src/codec/http/index.ts +33 -0
  55. package/src/codec/http/message/content/index.ts +36 -0
  56. package/src/codec/http/message/full/index.ts +10 -0
  57. package/src/codec/http/message/full/request/index.ts +45 -0
  58. package/src/codec/http/message/full/response/index.ts +43 -0
  59. package/src/codec/http/message/head/index.ts +79 -0
  60. package/src/codec/http/message/index.ts +16 -0
  61. package/src/codec/http/message/last/index.ts +27 -0
  62. package/src/codec/http/message/request/index.ts +39 -0
  63. package/src/codec/http/message/response/index.ts +31 -0
  64. package/src/codec/http/method/index.ts +101 -0
  65. package/src/codec/http/server/index.ts +81 -0
  66. package/src/codec/http/status/index.ts +170 -0
  67. package/src/codec/http/version/index.ts +70 -0
  68. package/src/codec/index.ts +83 -0
  69. package/src/codec/length/index.ts +330 -0
  70. package/src/codec/line/index.ts +45 -0
  71. package/src/codec/message/decoder/index.ts +84 -0
  72. package/src/codec/message/encoder/index.ts +56 -0
  73. package/src/codec/message/index.ts +2 -0
  74. package/src/codec/msgpack/index.ts +51 -0
  75. package/src/codec/prepender/index.ts +296 -0
  76. package/src/codec/protobuf/index.ts +57 -0
  77. package/src/codec/string/decoder/index.ts +47 -0
  78. package/src/codec/string/encoder/index.ts +26 -0
  79. package/src/codec/string/index.ts +2 -0
  80. package/src/codec/websocket/client/index.ts +235 -0
  81. package/src/codec/websocket/decoder/index.ts +371 -0
  82. package/src/codec/websocket/encoder/index.ts +170 -0
  83. package/src/codec/websocket/error/index.ts +42 -0
  84. package/src/codec/websocket/frame/base/index.ts +55 -0
  85. package/src/codec/websocket/frame/binary/index.ts +24 -0
  86. package/src/codec/websocket/frame/close/index.ts +82 -0
  87. package/src/codec/websocket/frame/continuation/index.ts +31 -0
  88. package/src/codec/websocket/frame/index.ts +10 -0
  89. package/src/codec/websocket/frame/opcode/index.ts +35 -0
  90. package/src/codec/websocket/frame/ping/index.ts +24 -0
  91. package/src/codec/websocket/frame/pong/index.ts +24 -0
  92. package/src/codec/websocket/frame/text/index.ts +31 -0
  93. package/src/codec/websocket/handshake/index.ts +38 -0
  94. package/src/codec/websocket/index.ts +25 -0
  95. package/src/codec/websocket/key/index.ts +41 -0
  96. package/src/codec/websocket/protocol/index.ts +147 -0
  97. package/src/codec/websocket/server/index.ts +233 -0
  98. package/src/codec/websocket/status/index.ts +97 -0
  99. package/src/codec/websocket/upgrade/index.ts +116 -0
  100. package/src/datagram/bootstrap/index.ts +269 -0
  101. package/src/datagram/channel/index.ts +103 -0
  102. package/src/datagram/index.ts +10 -0
  103. package/src/datagram/packet/index.ts +72 -0
  104. package/src/datagram/transport/index.ts +239 -0
  105. package/src/handler/flush/index.ts +187 -0
  106. package/src/handler/idle/index.ts +295 -0
  107. package/src/handler/index.ts +22 -0
  108. package/src/handler/logging/index.ts +195 -0
  109. package/src/handler/metrics/index.ts +300 -0
  110. package/src/handler/offload/index.ts +141 -0
  111. package/src/handler/timeout/error/index.ts +29 -0
  112. package/src/handler/timeout/index.ts +3 -0
  113. package/src/handler/timeout/read/index.ts +44 -0
  114. package/src/handler/timeout/write/index.ts +89 -0
  115. package/src/handler/traffic/index.ts +259 -0
  116. package/src/index.ts +258 -0
  117. package/src/logger/index.ts +47 -0
  118. package/src/reliable/bootstrap/index.ts +154 -0
  119. package/src/reliable/cipher/index.ts +227 -0
  120. package/src/reliable/cookie/index.ts +78 -0
  121. package/src/reliable/handler/index.ts +1202 -0
  122. package/src/reliable/handshake/index.ts +144 -0
  123. package/src/reliable/index.ts +38 -0
  124. package/src/reliable/lane/index.ts +420 -0
  125. package/src/reliable/message/index.ts +102 -0
  126. package/src/reliable/packet/index.ts +117 -0
  127. package/src/reliable/peer/index.ts +929 -0
  128. package/src/reliable/registry/index.ts +107 -0
  129. package/src/serve/bootstrap/index.ts +606 -0
  130. package/src/serve/channel/index.ts +246 -0
  131. package/src/serve/index.ts +17 -0
  132. package/src/serve/outbox/index.ts +292 -0
  133. package/src/serve/transport/index.ts +96 -0
  134. package/src/serve/writer/index.ts +119 -0
  135. package/src/shard/envelope/index.ts +44 -0
  136. package/src/shard/index.ts +10 -0
  137. package/src/shard/link/index.ts +743 -0
  138. package/src/shard/map/index.ts +91 -0
  139. package/src/worker/group/index.ts +175 -0
  140. package/src/worker/index.ts +10 -0
  141. package/src/worker/pool/index.ts +235 -0
  142. package/src/worker/service/index.ts +55 -0
@@ -0,0 +1,479 @@
1
+ import { InboundHandlerAdapter } from '../../channel/handler/inbound/index.ts'
2
+ import { ByteBuf, ByteBufPool } from '../../buffer/index.ts'
3
+ import type { HandlerContext } from '../../channel/context/index.ts'
4
+ import { resolved } from '../../channel/resolved/index.ts'
5
+ import { DecoderError } from '../error/index.ts'
6
+
7
+ /**
8
+ * Limits shared by every byte decoder
9
+ */
10
+ export type DecoderOptions = {
11
+ /**
12
+ * Bytes held while waiting for a whole frame, past this they're dropped, 16 MiB by default
13
+ */
14
+ readonly maxCumulation?: number
15
+
16
+ /**
17
+ * Hands frames out from a pool and takes them back once channelRead settles, true by default
18
+ */
19
+ readonly pooled?: boolean
20
+ }
21
+
22
+ /**
23
+ * How the loop carries on after one decode pass
24
+ */
25
+ type After = 'continue' | 'stop' | 'stuck'
26
+
27
+ /**
28
+ * Base for decoders that buffer raw bytes until a whole message is in
29
+ * @class
30
+ */
31
+ export abstract class ByteToMessageDecoder<
32
+ O = unknown,
33
+ > extends InboundHandlerAdapter {
34
+ /**
35
+ * Bytes held over from earlier reads, or null once drained
36
+ */
37
+ private cumulation: ByteBuf | null
38
+
39
+ /**
40
+ * 16 MiB of undecoded bytes before we give up on the peer
41
+ */
42
+ public static readonly defaultMaxCumulation: number = 16 * 1024 * 1024
43
+
44
+ /**
45
+ * Bytes held while waiting for a whole frame, past this they're dropped
46
+ */
47
+ private readonly maxCumulation: number
48
+
49
+ /**
50
+ * Shared output array, so the outermost call doesn't allocate each time
51
+ */
52
+ private readonly scratch: O[]
53
+
54
+ /**
55
+ * Goes above one when a handler feeds bytes back in mid decode
56
+ */
57
+ private depth: number
58
+
59
+ /**
60
+ * Set when a downstream handler went async during the last step
61
+ */
62
+ private waiting: Promise<void> | null
63
+
64
+ /**
65
+ * Messages from the outermost step still being delivered, or null
66
+ */
67
+ private batch: readonly O[] | null
68
+
69
+ /**
70
+ * How many of batch have been handed on
71
+ */
72
+ private position: number
73
+
74
+ /**
75
+ * Where frameOf gets its buffers, or null when pooling is off
76
+ */
77
+ private readonly pool: ByteBufPool | null
78
+
79
+ /**
80
+ * Starts with nothing buffered
81
+ */
82
+ public constructor(options: DecoderOptions = {}) {
83
+ super()
84
+
85
+ this.maxCumulation =
86
+ options.maxCumulation ?? ByteToMessageDecoder.defaultMaxCumulation
87
+ this.cumulation = null
88
+ this.scratch = []
89
+ this.depth = 0
90
+ this.waiting = null
91
+ this.batch = null
92
+ this.position = 0
93
+ this.pool = options.pooled === false ? null : new ByteBufPool()
94
+ }
95
+
96
+ /**
97
+ * A frame over part of input, pooled when that's on
98
+ * @param input the buffer being decoded
99
+ * @param index where the frame starts in input
100
+ * @param size bytes in the frame
101
+ */
102
+ protected frameOf(input: ByteBuf, index: number, size: number): ByteBuf {
103
+ const pool = this.pool
104
+ if (pool === null || this.depth > 1) return input.slice(index, size)
105
+
106
+ return input.sliceInto(index, size, pool.take() ?? ByteBuf.forPool(pool))
107
+ }
108
+
109
+ /**
110
+ * Reads a frame off the front of input, pooled when that's on
111
+ * @param input the buffer being decoded
112
+ * @param size bytes in the frame
113
+ */
114
+ protected takeFrame(input: ByteBuf, size: number): ByteBuf {
115
+ const frame = this.frameOf(input, input.readerIndex, size)
116
+
117
+ input.skipBytes(size)
118
+ return frame
119
+ }
120
+
121
+ /**
122
+ * Gives back every frame from index on, once the rest won't be delivered
123
+ * @param out the step's messages
124
+ * @param index first one to give back
125
+ */
126
+ private static recycleFrom(out: readonly unknown[], index: number): void {
127
+ for (let at = index; at < out.length; at++) {
128
+ ByteToMessageDecoder.recycle(out[at])
129
+ }
130
+ }
131
+
132
+ /**
133
+ * Gives a delivered frame back to its pool
134
+ * @param message what was delivered
135
+ */
136
+ private static recycle(message: unknown): void {
137
+ if (message instanceof ByteBuf && message.pooled) message.release()
138
+ }
139
+
140
+ /**
141
+ * How many buffered bytes haven't been consumed yet
142
+ */
143
+ protected get pendingBytes(): number {
144
+ return this.cumulation?.readableBytes ?? 0
145
+ }
146
+
147
+ /**
148
+ * Buffers the bytes and decodes as many messages as they allow
149
+ * @param context where decoded messages go
150
+ * @param message anything that isn't a ByteBuf passes straight through
151
+ */
152
+ public override channelRead(
153
+ context: HandlerContext,
154
+ message: unknown,
155
+ ): Promise<void> {
156
+ if (!(message instanceof ByteBuf)) return context.fireChannelRead(message)
157
+
158
+ const input = this.cumulate(message)
159
+ let running: Promise<void>
160
+ try {
161
+ running = this.run(context, input, false)
162
+ } catch (error) {
163
+ this.compact(input)
164
+ throw error
165
+ }
166
+
167
+ if (running === resolved) {
168
+ this.compact(input)
169
+ return resolved
170
+ }
171
+
172
+ return running.finally((): void => {
173
+ this.compact(input)
174
+ })
175
+ }
176
+
177
+ /**
178
+ * Gives decodeLast a go at the leftovers before passing the close on
179
+ * @param context the handler's context
180
+ */
181
+ public override channelInactive(context: HandlerContext): Promise<void> {
182
+ const input = this.cumulation
183
+ this.cumulation = null
184
+
185
+ let running: Promise<void>
186
+ try {
187
+ running = input === null ? resolved : this.run(context, input, true)
188
+ } catch (error) {
189
+ running = Promise.reject(ByteToMessageDecoder.wrap(error))
190
+ }
191
+
192
+ if (running === resolved) return context.fireChannelInactive()
193
+ return running.finally((): Promise<void> => context.fireChannelInactive())
194
+ }
195
+
196
+ /**
197
+ * Hands any leftover bytes to the next handler when this one is removed
198
+ * @param context where the leftovers go
199
+ */
200
+ public handlerRemoved(context: HandlerContext): Promise<void> {
201
+ const input = this.cumulation
202
+ this.cumulation = null
203
+
204
+ const batch = this.batch
205
+ if (
206
+ batch !== null &&
207
+ input !== null &&
208
+ this.position < batch.length &&
209
+ this.rewind?.(input, batch[this.position] as O) === true
210
+ ) {
211
+ this.batch = null
212
+ }
213
+
214
+ return input?.isReadable() === true
215
+ ? context.fireChannelRead(input)
216
+ : resolved
217
+ }
218
+
219
+ /**
220
+ * Pull as many whole messages out of the buffer as you can, leaving partial ones
221
+ * @param context the handler's context
222
+ * @param input bytes gathered so far
223
+ * @param out push finished messages here
224
+ */
225
+ protected abstract decode(
226
+ context: HandlerContext,
227
+ input: ByteBuf,
228
+ out: O[],
229
+ ): void
230
+
231
+ /**
232
+ * Moves the reader back to where a message from the last decode started, false if it can't
233
+ * @param input the buffer that decode read from
234
+ * @param message the first one not handed on
235
+ */
236
+ protected rewind?(input: ByteBuf, message: O): boolean
237
+
238
+ /**
239
+ * Called once the channel closes, defaults to a normal decode
240
+ * @param context the handler's context
241
+ * @param input whatever was left in the buffer
242
+ * @param out push finished messages here
243
+ */
244
+ protected decodeLast(
245
+ context: HandlerContext,
246
+ input: ByteBuf,
247
+ out: O[],
248
+ ): void {
249
+ this.decode(context, input, out)
250
+ }
251
+
252
+ /**
253
+ * Adopts the first buffer as is and appends later ones to it
254
+ * @param message the freshly read chunk
255
+ */
256
+ private cumulate(message: ByteBuf): ByteBuf {
257
+ if (this.cumulation === null) {
258
+ this.cumulation = message.detach()
259
+ return message
260
+ }
261
+
262
+ if (
263
+ this.cumulation.readableBytes + message.readableBytes >
264
+ this.maxCumulation
265
+ ) {
266
+ this.cumulation = null
267
+ throw new DecoderError('Buffer is full')
268
+ }
269
+ this.cumulation.writeBytes(message)
270
+ return this.cumulation
271
+ }
272
+
273
+ /**
274
+ * Keeps decoding until there's nothing left, only going async if a handler does
275
+ * @param context passed through to decode
276
+ * @param input the buffer being worked through
277
+ * @param last true when draining after close
278
+ */
279
+ private run(
280
+ context: HandlerContext,
281
+ input: ByteBuf,
282
+ last: boolean,
283
+ ): Promise<void> {
284
+ for (;;) {
285
+ const after = this.step(context, input, last)
286
+ const waiting = this.waiting
287
+ if (waiting !== null) {
288
+ this.waiting = null
289
+ return this.resume(waiting, after, context, input, last)
290
+ }
291
+
292
+ if (after === 'stuck') throw new DecoderError('Decoder did not read')
293
+ if (after === 'stop' || !input.isReadable()) return resolved
294
+ }
295
+ }
296
+
297
+ /**
298
+ * The async half of run, picked up after a handler returned a promise
299
+ * @param waiting the pending delivery to wait for first
300
+ * @param after what the step that went async decided
301
+ * @param context passed through to decode
302
+ * @param input the buffer being worked through
303
+ * @param last true when draining after close
304
+ */
305
+ private async resume(
306
+ waiting: Promise<void>,
307
+ after: After,
308
+ context: HandlerContext,
309
+ input: ByteBuf,
310
+ last: boolean,
311
+ ): Promise<void> {
312
+ let pending: Promise<void> | null = waiting
313
+ let next = after
314
+
315
+ for (;;) {
316
+ if (pending !== null) await pending
317
+ if (next === 'stuck') throw new DecoderError('Decoder did not read')
318
+ if (next === 'stop') return
319
+ next = this.step(context, input, last)
320
+ pending = this.waiting
321
+ this.waiting = null
322
+ }
323
+ }
324
+
325
+ /**
326
+ * One decode call plus delivery of whatever it produced
327
+ * @param context passed through to decode
328
+ * @param input the buffer being worked through
329
+ * @param last uses decodeLast when true
330
+ */
331
+ private step(context: HandlerContext, input: ByteBuf, last: boolean): After {
332
+ if (!input.isReadable() || (!last && this.cumulation !== input)) {
333
+ return 'stop'
334
+ }
335
+
336
+ const before = input.readableBytes
337
+ const out: O[] = this.depth === 0 ? this.scratch : []
338
+ out.length = 0
339
+ let failure: DecoderError | null = null
340
+ this.depth += 1
341
+ try {
342
+ if (last) this.decodeLast(context, input, out)
343
+ else this.decode(context, input, out)
344
+ } catch (error) {
345
+ failure = ByteToMessageDecoder.wrap(error)
346
+ }
347
+
348
+ const progressed = input.readableBytes !== before
349
+ const produced = out.length
350
+ try {
351
+ this.waiting = this.deliver(context, out, failure)
352
+ } finally {
353
+ this.depth -= 1
354
+ }
355
+
356
+ return ByteToMessageDecoder.next(progressed, produced, failure)
357
+ }
358
+
359
+ /**
360
+ * Read nothing but produced messages means the decoder is stuck
361
+ * @param progressed whether the reader index moved
362
+ * @param produced how many messages came out
363
+ * @param failure what decode threw, or null
364
+ */
365
+ private static next(
366
+ progressed: boolean,
367
+ produced: number,
368
+ failure: DecoderError | null,
369
+ ): After {
370
+ if (progressed) return 'continue'
371
+ if (failure !== null || produced === 0) return 'stop'
372
+
373
+ return 'stuck'
374
+ }
375
+
376
+ /**
377
+ * Makes sure whatever was thrown ends up as a DecoderError
378
+ * @param error anything decode threw
379
+ */
380
+ private static wrap(error: unknown): DecoderError {
381
+ if (error instanceof DecoderError) return error
382
+
383
+ return new DecoderError('Decoding failed', { cause: error })
384
+ }
385
+
386
+ /**
387
+ * Fires each message then any error, falling back to async when a handler awaits
388
+ * @param context where to fire them
389
+ * @param out messages from this step
390
+ * @param failure reported after the messages, or null
391
+ */
392
+ private deliver(
393
+ context: HandlerContext,
394
+ out: readonly O[],
395
+ failure: DecoderError | null,
396
+ ): Promise<void> | null {
397
+ const outermost = this.depth === 1
398
+ if (outermost) this.batch = out
399
+
400
+ for (let index = 0; index < out.length; index++) {
401
+ if (outermost) this.position = index + 1
402
+ const message = out[index]
403
+ const result = context.fireChannelRead(message)
404
+ if (outermost && this.batch !== out) {
405
+ ByteToMessageDecoder.recycleFrom(out, index)
406
+ return null
407
+ }
408
+
409
+ if (result !== resolved) {
410
+ return this.deliverLater(result, context, out, index + 1, failure)
411
+ }
412
+
413
+ ByteToMessageDecoder.recycle(message)
414
+ }
415
+
416
+ if (outermost) this.batch = null
417
+ if (failure === null) return null
418
+
419
+ const reported = context.fireExceptionCaught(failure)
420
+ return reported === resolved ? null : reported
421
+ }
422
+
423
+ /**
424
+ * Delivers the rest one at a time once a handler went async
425
+ * @param first the promise that broke the sync run
426
+ * @param context where to fire them
427
+ * @param out messages from this step
428
+ * @param start first message not yet delivered
429
+ * @param failure reported at the end, or null
430
+ */
431
+ private async deliverLater(
432
+ first: Promise<void>,
433
+ context: HandlerContext,
434
+ out: readonly O[],
435
+ start: number,
436
+ failure: DecoderError | null,
437
+ ): Promise<void> {
438
+ const tracked = this.batch === out
439
+ await first
440
+ if (tracked && this.batch !== out) {
441
+ ByteToMessageDecoder.recycleFrom(out, start - 1)
442
+ return
443
+ }
444
+
445
+ ByteToMessageDecoder.recycle(out[start - 1])
446
+
447
+ for (let index = start; index < out.length; index++) {
448
+ if (tracked) this.position = index + 1
449
+ const message = out[index]
450
+ await context.fireChannelRead(message)
451
+ if (tracked && this.batch !== out) {
452
+ ByteToMessageDecoder.recycleFrom(out, index)
453
+ return
454
+ }
455
+
456
+ ByteToMessageDecoder.recycle(message)
457
+ }
458
+
459
+ if (tracked) this.batch = null
460
+ if (failure !== null) await context.fireExceptionCaught(failure)
461
+ }
462
+
463
+ /**
464
+ * Frees the buffer once empty, or copies it down once half of it is already read
465
+ * @param input left alone if a newer buffer replaced it
466
+ */
467
+ private compact(input: ByteBuf): void {
468
+ if (this.cumulation !== input) return
469
+
470
+ if (!input.isReadable()) {
471
+ this.cumulation = null
472
+ } else if (
473
+ input.readerIndex > 0 &&
474
+ input.readerIndex >= input.capacity / 2
475
+ ) {
476
+ this.cumulation = input.copy()
477
+ }
478
+ }
479
+ }
@@ -0,0 +1,189 @@
1
+ import type { HandlerContext } from '../../channel/context/index.ts'
2
+ import { ByteToMessageDecoder, type DecoderOptions } from '../decoder/index.ts'
3
+ import { DecoderError } from '../error/index.ts'
4
+ import type { ByteBuf } from '../../buffer/index.ts'
5
+
6
+ /**
7
+ * Settings for DelimiterBasedFrameDecoder
8
+ */
9
+ export type DelimiterOptions = DecoderOptions & {
10
+ /**
11
+ * Frames longer than this get thrown away
12
+ */
13
+ readonly maxFrameLength: number
14
+
15
+ /**
16
+ * Any of these marks the end of a frame
17
+ */
18
+ readonly delimiters: readonly Uint8Array[]
19
+
20
+ /**
21
+ * Leaves the delimiter off the frame, on by default
22
+ */
23
+ readonly stripDelimiter?: boolean
24
+ }
25
+
26
+ /**
27
+ * Where a delimiter turned up and which one it was
28
+ */
29
+ type Match = {
30
+ /**
31
+ * Position in the buffer, not relative to the reader
32
+ */
33
+ readonly index: number
34
+
35
+ /**
36
+ * Which delimiter matched
37
+ */
38
+ readonly delimiter: Uint8Array
39
+ }
40
+
41
+ /**
42
+ * Cuts frames at whichever delimiter comes first
43
+ * @class
44
+ */
45
+ export class DelimiterBasedFrameDecoder extends ByteToMessageDecoder<ByteBuf> {
46
+ /**
47
+ * Handy preset for NUL terminated frames
48
+ */
49
+ public static readonly nulDelimiter: readonly Uint8Array[] = [
50
+ Uint8Array.of(0),
51
+ ]
52
+
53
+ /**
54
+ * Preset for lines, CRLF listed first so it wins over a bare LF
55
+ */
56
+ public static readonly lineDelimiter: readonly Uint8Array[] = [
57
+ Uint8Array.of(13, 10),
58
+ Uint8Array.of(10),
59
+ ]
60
+
61
+ /**
62
+ * Frame length cap, not counting the delimiter
63
+ */
64
+ private readonly maxFrameLength: number
65
+
66
+ /**
67
+ * Delimiters to look for
68
+ */
69
+ private readonly delimiters: readonly Uint8Array[]
70
+
71
+ /**
72
+ * Whether frames come out without their delimiter
73
+ */
74
+ private readonly stripDelimiter: boolean
75
+
76
+ /**
77
+ * Set after an overflow, until we've skipped to the next delimiter
78
+ */
79
+ private discarding: boolean
80
+
81
+ /**
82
+ * Sets up a decoder for the given delimiters
83
+ * @param options delimiters and length cap
84
+ */
85
+ public constructor(options: DelimiterOptions) {
86
+ super(options)
87
+
88
+ const reason = DelimiterBasedFrameDecoder.refusal(options)
89
+ if (reason !== null) throw new RangeError(reason)
90
+
91
+ this.maxFrameLength = options.maxFrameLength
92
+ this.delimiters = options.delimiters
93
+ this.stripDelimiter = options.stripDelimiter ?? true
94
+ this.discarding = false
95
+ }
96
+
97
+ /**
98
+ * Rejects a bad length cap or missing and empty delimiters
99
+ * @param options what the caller passed in
100
+ */
101
+ private static refusal(options: DelimiterOptions): string | null {
102
+ if (!Number.isInteger(options.maxFrameLength)) {
103
+ return 'Frame length is invalid'
104
+ }
105
+
106
+ if (options.maxFrameLength <= 0) return 'Frame length is invalid'
107
+ if (options.delimiters.length === 0) return 'Delimiter is missing'
108
+ if (
109
+ options.delimiters.some((value: Uint8Array): boolean => !value.length)
110
+ ) {
111
+ return 'Delimiter is empty'
112
+ }
113
+
114
+ return null
115
+ }
116
+
117
+ /**
118
+ * Pulls out the frame before the nearest delimiter
119
+ * @param context unused here
120
+ * @param input bytes gathered so far
121
+ * @param out where finished frames go
122
+ */
123
+ protected decode(
124
+ context: HandlerContext,
125
+ input: ByteBuf,
126
+ out: ByteBuf[],
127
+ ): void {
128
+ const match = this.nearest(input)
129
+
130
+ if (match === null) {
131
+ this.overflow(input)
132
+ return
133
+ }
134
+
135
+ const frameLength = match.index - input.readerIndex
136
+ const delimiterLength = match.delimiter.length
137
+ if (this.discarding) {
138
+ this.discarding = false
139
+ input.skipBytes(frameLength + delimiterLength)
140
+ return
141
+ }
142
+
143
+ if (frameLength > this.maxFrameLength) {
144
+ input.skipBytes(frameLength + delimiterLength)
145
+ throw new DecoderError('Frame is too large')
146
+ }
147
+
148
+ if (this.stripDelimiter) {
149
+ out.push(this.takeFrame(input, frameLength))
150
+ input.skipBytes(delimiterLength)
151
+ } else {
152
+ out.push(this.takeFrame(input, frameLength + delimiterLength))
153
+ }
154
+ }
155
+
156
+ /**
157
+ * Picks the delimiter that shows up earliest
158
+ * @param input bytes to search
159
+ */
160
+ private nearest(input: ByteBuf): Match | null {
161
+ let match: Match | null = null
162
+
163
+ for (const delimiter of this.delimiters) {
164
+ const index = input.indexOf(delimiter)
165
+ if (index !== -1 && (match === null || index < match.index)) {
166
+ match = { index, delimiter }
167
+ }
168
+ }
169
+
170
+ return match
171
+ }
172
+
173
+ /**
174
+ * With no delimiter in sight, throws everything away once it's over the cap
175
+ * @param input bytes with no delimiter yet
176
+ */
177
+ private overflow(input: ByteBuf): void {
178
+ if (this.discarding) {
179
+ input.skipBytes(input.readableBytes)
180
+ return
181
+ }
182
+
183
+ if (input.readableBytes <= this.maxFrameLength) return
184
+
185
+ this.discarding = true
186
+ input.skipBytes(input.readableBytes)
187
+ throw new DecoderError('Frame is too large')
188
+ }
189
+ }
@@ -0,0 +1,48 @@
1
+ import { OutboundHandlerAdapter } from '../../channel/handler/outbound/index.ts'
2
+ import type { HandlerContext } from '../../channel/context/index.ts'
3
+ import { EncoderError } from '../error/index.ts'
4
+ import type { ByteBuf } from '../../buffer/index.ts'
5
+
6
+ /**
7
+ * Base for encoders that turn one kind of message into a ByteBuf
8
+ * @class
9
+ */
10
+ export abstract class MessageToByteEncoder<T> extends OutboundHandlerAdapter {
11
+ /**
12
+ * Encodes messages it accepts and lets the rest through untouched
13
+ * @param context where the bytes get written
14
+ * @param message anything heading out
15
+ */
16
+ public override write(
17
+ context: HandlerContext,
18
+ message: unknown,
19
+ ): Promise<void> {
20
+ if (!this.accepts(message)) return context.write(message)
21
+
22
+ let out: ByteBuf
23
+ try {
24
+ out = this.encode(context, message)
25
+ } catch (error) {
26
+ return Promise.reject(
27
+ error instanceof EncoderError
28
+ ? error
29
+ : new EncoderError('Encoding failed', { cause: error }),
30
+ )
31
+ }
32
+
33
+ return context.write(out)
34
+ }
35
+
36
+ /**
37
+ * Says whether a message is one this encoder should handle
38
+ * @param message the outbound message
39
+ */
40
+ protected abstract accepts(message: unknown): message is T
41
+
42
+ /**
43
+ * Turns an accepted message into bytes, throw to fail the write
44
+ * @param context the handler's context
45
+ * @param message one that passed accepts
46
+ */
47
+ protected abstract encode(context: HandlerContext, message: T): ByteBuf
48
+ }