@netifyjs/netify 1.0.0-alpha.3 → 1.0.0-alpha.5

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 (72) hide show
  1. package/README.md +6 -6
  2. package/package.json +1 -1
  3. package/src/bootstrap/client/index.ts +1 -1
  4. package/src/bootstrap/dispatcher/index.ts +7 -0
  5. package/src/bootstrap/reconnect/index.ts +14 -4
  6. package/src/bootstrap/server/index.ts +10 -4
  7. package/src/buffer/index.ts +229 -88
  8. package/src/buffer/quantizer/index.ts +16 -3
  9. package/src/channel/context/index.ts +18 -11
  10. package/src/channel/handler/index.ts +1 -1
  11. package/src/channel/index.ts +30 -7
  12. package/src/channel/outbound/index.ts +28 -12
  13. package/src/channel/pipeline/index.ts +45 -5
  14. package/src/channel/queue/index.ts +3 -2
  15. package/src/channel/resolved/index.ts +13 -3
  16. package/src/channel/server/index.ts +19 -10
  17. package/src/cluster/index.ts +73 -32
  18. package/src/codec/binary/index.ts +19 -0
  19. package/src/codec/decoder/index.ts +223 -83
  20. package/src/codec/delimiter/index.ts +95 -37
  21. package/src/codec/encoder/index.ts +30 -5
  22. package/src/codec/fixed/index.ts +5 -1
  23. package/src/codec/http/aggregator/index.ts +45 -16
  24. package/src/codec/http/decoder/object/index.ts +156 -40
  25. package/src/codec/http/decoder/request/index.ts +6 -2
  26. package/src/codec/http/encoder/object/index.ts +2 -7
  27. package/src/codec/http/encoder/request/index.ts +5 -0
  28. package/src/codec/http/headers/index.ts +45 -2
  29. package/src/codec/http/message/full/request/index.ts +1 -1
  30. package/src/codec/http/message/full/response/index.ts +1 -1
  31. package/src/codec/http/message/request/index.ts +14 -1
  32. package/src/codec/http/message/response/index.ts +1 -1
  33. package/src/codec/http/version/index.ts +3 -0
  34. package/src/codec/length/index.ts +66 -44
  35. package/src/codec/message/decoder/index.ts +18 -1
  36. package/src/codec/message/encoder/index.ts +85 -8
  37. package/src/codec/prepender/index.ts +4 -1
  38. package/src/codec/string/decoder/index.ts +6 -1
  39. package/src/codec/websocket/decoder/index.ts +78 -3
  40. package/src/codec/websocket/encoder/index.ts +90 -6
  41. package/src/codec/websocket/frame/base/index.ts +19 -10
  42. package/src/codec/websocket/frame/text/index.ts +2 -2
  43. package/src/codec/websocket/protocol/index.ts +12 -0
  44. package/src/datagram/bootstrap/index.ts +1 -1
  45. package/src/datagram/transport/index.ts +30 -1
  46. package/src/handler/flush/index.ts +25 -5
  47. package/src/handler/idle/index.ts +120 -26
  48. package/src/handler/logging/index.ts +13 -1
  49. package/src/handler/metrics/index.ts +49 -16
  50. package/src/handler/offload/index.ts +7 -0
  51. package/src/handler/timeout/read/index.ts +1 -1
  52. package/src/handler/timeout/write/index.ts +104 -23
  53. package/src/handler/traffic/index.ts +251 -38
  54. package/src/index.ts +1 -0
  55. package/src/reliable/cipher/index.ts +49 -5
  56. package/src/reliable/cookie/index.ts +64 -2
  57. package/src/reliable/handler/index.ts +11 -15
  58. package/src/reliable/index.ts +7 -1
  59. package/src/reliable/lane/index.ts +277 -58
  60. package/src/reliable/peer/index.ts +125 -38
  61. package/src/serve/bootstrap/index.ts +82 -135
  62. package/src/serve/channel/index.ts +84 -2
  63. package/src/serve/gate/index.ts +215 -0
  64. package/src/serve/index.ts +6 -2
  65. package/src/serve/outbox/index.ts +63 -2
  66. package/src/serve/transport/index.ts +33 -3
  67. package/src/serve/writer/index.ts +4 -3
  68. package/src/shard/gateway/index.ts +102 -29
  69. package/src/shard/link/index.ts +161 -175
  70. package/src/worker/group/index.ts +231 -13
  71. package/src/worker/pool/index.ts +100 -19
  72. package/src/worker/service/index.ts +9 -1
@@ -9,7 +9,7 @@ import { DecoderError } from '../error/index.ts'
9
9
  */
10
10
  export type DecoderOptions = {
11
11
  /**
12
- * Bytes held while waiting for a whole frame, past this they're dropped, 16 MiB by default
12
+ * Most bytes held between reads
13
13
  */
14
14
  readonly maxCumulation?: number
15
15
 
@@ -42,20 +42,30 @@ export abstract class ByteToMessageDecoder<
42
42
  public static readonly defaultMaxCumulation: number = 16 * 1024 * 1024
43
43
 
44
44
  /**
45
- * Bytes held while waiting for a whole frame, past this they're dropped
45
+ * Most bytes held between reads
46
46
  */
47
47
  private readonly maxCumulation: number
48
48
 
49
49
  /**
50
- * Shared output array, so the outermost call doesn't allocate each time
50
+ * Output array for the outermost step
51
51
  */
52
- private readonly scratch: O[]
52
+ private scratch: O[]
53
53
 
54
54
  /**
55
- * Goes above one when a handler feeds bytes back in mid decode
55
+ * How deep the steps are nested
56
56
  */
57
57
  private depth: number
58
58
 
59
+ /**
60
+ * Decoding a read
61
+ */
62
+ private busy: boolean
63
+
64
+ /**
65
+ * Bytes arrived mid read
66
+ */
67
+ private fed: boolean
68
+
59
69
  /**
60
70
  * Set when a downstream handler went async during the last step
61
71
  */
@@ -72,27 +82,77 @@ export abstract class ByteToMessageDecoder<
72
82
  private position: number
73
83
 
74
84
  /**
75
- * Where frameOf gets its buffers, or null when pooling is off
85
+ * Buffer pool for frameOf, or null
76
86
  */
77
87
  private readonly pool: ByteBufPool | null
78
88
 
79
89
  /**
80
90
  * Starts with nothing buffered
91
+ * @param options buffering and pooling
81
92
  */
82
93
  public constructor(options: DecoderOptions = {}) {
83
94
  super()
84
95
 
96
+ const reason = ByteToMessageDecoder.misfit(options)
97
+ if (reason !== null) throw new RangeError(reason)
98
+
85
99
  this.maxCumulation =
86
100
  options.maxCumulation ?? ByteToMessageDecoder.defaultMaxCumulation
87
101
  this.cumulation = null
88
102
  this.scratch = []
89
103
  this.depth = 0
104
+ this.busy = false
105
+ this.fed = false
90
106
  this.waiting = null
91
107
  this.batch = null
92
108
  this.position = 0
93
109
  this.pool = options.pooled === false ? null : new ByteBufPool()
94
110
  }
95
111
 
112
+ /**
113
+ * What's wrong with the buffer limit, or null
114
+ * @param options what the caller passed in
115
+ */
116
+ private static misfit(options: DecoderOptions): string | null {
117
+ const limit =
118
+ options.maxCumulation ?? ByteToMessageDecoder.defaultMaxCumulation
119
+
120
+ if (!Number.isInteger(limit) || limit <= 0) return 'Buffer limit is invalid'
121
+ if (limit > ByteBuf.defaultMaxCapacity) return 'Buffer limit is too large'
122
+
123
+ return null
124
+ }
125
+
126
+ /**
127
+ * Options with a limit that fits one frame
128
+ * @param options what the caller passed in
129
+ * @param frame the biggest frame plus whatever ends it
130
+ */
131
+ protected static sized<T extends DecoderOptions>(
132
+ options: T,
133
+ frame: number,
134
+ ): T {
135
+ if (options.maxCumulation !== undefined) return options
136
+ if (!(frame > ByteToMessageDecoder.defaultMaxCumulation)) return options
137
+
138
+ return {
139
+ ...options,
140
+ /**
141
+ * Fits the biggest frame
142
+ */
143
+ maxCumulation: Math.min(Math.ceil(frame), ByteBuf.defaultMaxCapacity),
144
+ }
145
+ }
146
+
147
+ /**
148
+ * Frame too big to ever buffer
149
+ * @param options what the caller passed in
150
+ * @param frame the biggest frame plus whatever ends it
151
+ */
152
+ protected static oversized(options: DecoderOptions, frame: number): boolean {
153
+ return frame > (options.maxCumulation ?? ByteBuf.defaultMaxCapacity)
154
+ }
155
+
96
156
  /**
97
157
  * A frame over part of input, pooled when that's on
98
158
  * @param input the buffer being decoded
@@ -137,6 +197,37 @@ export abstract class ByteToMessageDecoder<
137
197
  if (message instanceof ByteBuf && message.pooled) message.release()
138
198
  }
139
199
 
200
+ /**
201
+ * Releases the frame after its handler, or null
202
+ * @param result what the handler returned
203
+ * @param message the frame it was given
204
+ */
205
+ private static after(
206
+ result: Promise<void>,
207
+ message: unknown,
208
+ ): Promise<void> | null {
209
+ if (result !== resolved) return ByteToMessageDecoder.held(result, message)
210
+
211
+ ByteToMessageDecoder.recycle(message)
212
+ return null
213
+ }
214
+
215
+ /**
216
+ * Releases the frame after an async handler
217
+ * @param result what the handler returned
218
+ * @param message the frame it was given
219
+ */
220
+ private static async held(
221
+ result: Promise<void>,
222
+ message: unknown,
223
+ ): Promise<void> {
224
+ try {
225
+ await result
226
+ } finally {
227
+ ByteToMessageDecoder.recycle(message)
228
+ }
229
+ }
230
+
140
231
  /**
141
232
  * How many buffered bytes haven't been consumed yet
142
233
  */
@@ -145,7 +236,7 @@ export abstract class ByteToMessageDecoder<
145
236
  }
146
237
 
147
238
  /**
148
- * Buffers the bytes and decodes as many messages as they allow
239
+ * Buffers bytes and decodes what it can
149
240
  * @param context where decoded messages go
150
241
  * @param message anything that isn't a ByteBuf passes straight through
151
242
  */
@@ -155,23 +246,26 @@ export abstract class ByteToMessageDecoder<
155
246
  ): Promise<void> {
156
247
  if (!(message instanceof ByteBuf)) return context.fireChannelRead(message)
157
248
 
158
- const input = this.cumulate(message)
249
+ this.cumulate(message)
250
+ if (this.busy) {
251
+ this.fed = true
252
+ return resolved
253
+ }
254
+
255
+ this.busy = true
159
256
  let running: Promise<void>
160
257
  try {
161
- running = this.run(context, input, false)
258
+ running = this.run(context, false)
162
259
  } catch (error) {
163
- this.compact(input)
260
+ this.conclude()
164
261
  throw error
165
262
  }
166
263
 
167
- if (running === resolved) {
168
- this.compact(input)
169
- return resolved
170
- }
264
+ if (running !== resolved) return running
171
265
 
172
- return running.finally((): void => {
173
- this.compact(input)
174
- })
266
+ const full = this.conclude()
267
+ if (full !== null) throw full
268
+ return resolved
175
269
  }
176
270
 
177
271
  /**
@@ -179,18 +273,25 @@ export abstract class ByteToMessageDecoder<
179
273
  * @param context the handler's context
180
274
  */
181
275
  public override channelInactive(context: HandlerContext): Promise<void> {
182
- const input = this.cumulation
183
- this.cumulation = null
276
+ const nested = this.busy
277
+ this.busy = true
184
278
 
185
279
  let running: Promise<void>
186
280
  try {
187
- running = input === null ? resolved : this.run(context, input, true)
281
+ running = this.run(context, true)
188
282
  } catch (error) {
189
283
  running = Promise.reject(ByteToMessageDecoder.wrap(error))
190
284
  }
191
285
 
192
- if (running === resolved) return context.fireChannelInactive()
193
- return running.finally((): Promise<void> => context.fireChannelInactive())
286
+ if (running === resolved) {
287
+ this.shut(nested)
288
+ return context.fireChannelInactive()
289
+ }
290
+
291
+ return running.finally((): Promise<void> => {
292
+ this.shut(nested)
293
+ return context.fireChannelInactive()
294
+ })
194
295
  }
195
296
 
196
297
  /**
@@ -253,44 +354,54 @@ export abstract class ByteToMessageDecoder<
253
354
  * Adopts the first buffer as is and appends later ones to it
254
355
  * @param message the freshly read chunk
255
356
  */
256
- private cumulate(message: ByteBuf): ByteBuf {
257
- if (this.cumulation === null) {
357
+ private cumulate(message: ByteBuf): void {
358
+ const held = this.cumulation
359
+ if (held === null) {
258
360
  this.cumulation = message.detach()
259
- return message
361
+ return
260
362
  }
261
363
 
262
- if (
263
- this.cumulation.readableBytes + message.readableBytes >
264
- this.maxCumulation
265
- ) {
266
- this.cumulation = null
267
- throw new DecoderError('Buffer is full')
364
+ if (held.writerIndex + message.readableBytes > held.maxCapacity) {
365
+ this.cumulation = ByteToMessageDecoder.merge(held, message)
366
+ return
268
367
  }
269
- this.cumulation.writeBytes(message)
270
- return this.cumulation
368
+
369
+ held.writeBytes(message)
370
+ }
371
+
372
+ /**
373
+ * Merges both into a new buffer
374
+ * @param held what was buffered
375
+ * @param message the freshly read chunk
376
+ */
377
+ private static merge(held: ByteBuf, message: ByteBuf): ByteBuf {
378
+ const size = held.readableBytes + message.readableBytes
379
+ const merged = ByteBuf.allocate(
380
+ size,
381
+ Math.max(size, ByteBuf.defaultMaxCapacity),
382
+ )
383
+
384
+ merged.writeBytes(held, held.readerIndex, held.readableBytes)
385
+ return merged.writeBytes(message)
271
386
  }
272
387
 
273
388
  /**
274
389
  * Keeps decoding until there's nothing left, only going async if a handler does
275
390
  * @param context passed through to decode
276
- * @param input the buffer being worked through
277
391
  * @param last true when draining after close
278
392
  */
279
- private run(
280
- context: HandlerContext,
281
- input: ByteBuf,
282
- last: boolean,
283
- ): Promise<void> {
393
+ private run(context: HandlerContext, last: boolean): Promise<void> {
284
394
  for (;;) {
285
- const after = this.step(context, input, last)
395
+ const after = this.step(context, last)
286
396
  const waiting = this.waiting
287
397
  if (waiting !== null) {
288
398
  this.waiting = null
289
- return this.resume(waiting, after, context, input, last)
399
+ return this.resume(waiting, after, context, last)
290
400
  }
291
401
 
292
402
  if (after === 'stuck') throw new DecoderError('Decoder did not read')
293
- if (after === 'stop' || !input.isReadable()) return resolved
403
+ if (this.fed) this.fed = false
404
+ else if (after === 'stop' || this.pendingBytes === 0) return resolved
294
405
  }
295
406
  }
296
407
 
@@ -299,39 +410,46 @@ export abstract class ByteToMessageDecoder<
299
410
  * @param waiting the pending delivery to wait for first
300
411
  * @param after what the step that went async decided
301
412
  * @param context passed through to decode
302
- * @param input the buffer being worked through
303
413
  * @param last true when draining after close
304
414
  */
305
415
  private async resume(
306
416
  waiting: Promise<void>,
307
417
  after: After,
308
418
  context: HandlerContext,
309
- input: ByteBuf,
310
419
  last: boolean,
311
420
  ): Promise<void> {
312
421
  let pending: Promise<void> | null = waiting
313
422
  let next = after
314
423
 
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
424
+ try {
425
+ for (;;) {
426
+ if (pending !== null) await pending
427
+ if (next === 'stuck') throw new DecoderError('Decoder did not read')
428
+ if (next === 'stop' && !this.fed) break
429
+
430
+ this.fed = false
431
+ next = this.step(context, last)
432
+ pending = this.waiting
433
+ this.waiting = null
434
+ }
435
+ } catch (error) {
436
+ if (!last) this.conclude()
437
+ throw error
322
438
  }
439
+
440
+ if (last) return
441
+ const full = this.conclude()
442
+ if (full !== null) throw full
323
443
  }
324
444
 
325
445
  /**
326
446
  * One decode call plus delivery of whatever it produced
327
447
  * @param context passed through to decode
328
- * @param input the buffer being worked through
329
448
  * @param last uses decodeLast when true
330
449
  */
331
- private step(context: HandlerContext, input: ByteBuf, last: boolean): After {
332
- if (!input.isReadable() || (!last && this.cumulation !== input)) {
333
- return 'stop'
334
- }
450
+ private step(context: HandlerContext, last: boolean): After {
451
+ const input = this.cumulation
452
+ if (input?.isReadable() !== true) return 'stop'
335
453
 
336
454
  const before = input.readableBytes
337
455
  const out: O[] = this.depth === 0 ? this.scratch : []
@@ -394,26 +512,27 @@ export abstract class ByteToMessageDecoder<
394
512
  out: readonly O[],
395
513
  failure: DecoderError | null,
396
514
  ): Promise<void> | null {
397
- const outermost = this.depth === 1
398
- if (outermost) this.batch = out
515
+ const tracked = this.depth === 1 && this.batch === null
516
+ if (tracked) this.batch = out
399
517
 
400
518
  for (let index = 0; index < out.length; index++) {
401
- if (outermost) this.position = index + 1
519
+ if (tracked) this.position = index + 1
402
520
  const message = out[index]
403
521
  const result = context.fireChannelRead(message)
404
- if (outermost && this.batch !== out) {
405
- ByteToMessageDecoder.recycleFrom(out, index)
406
- return null
522
+ if (tracked && this.batch !== out) {
523
+ ByteToMessageDecoder.recycleFrom(out, index + 1)
524
+ return ByteToMessageDecoder.after(result, message)
407
525
  }
408
526
 
409
527
  if (result !== resolved) {
528
+ if (out === this.scratch) this.scratch = []
410
529
  return this.deliverLater(result, context, out, index + 1, failure)
411
530
  }
412
531
 
413
532
  ByteToMessageDecoder.recycle(message)
414
533
  }
415
534
 
416
- if (outermost) this.batch = null
535
+ if (tracked) this.batch = null
417
536
  if (failure === null) return null
418
537
 
419
538
  const reported = context.fireExceptionCaught(failure)
@@ -436,44 +555,65 @@ export abstract class ByteToMessageDecoder<
436
555
  failure: DecoderError | null,
437
556
  ): Promise<void> {
438
557
  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)
558
+ try {
559
+ await first
451
560
  if (tracked && this.batch !== out) {
452
- ByteToMessageDecoder.recycleFrom(out, index)
561
+ ByteToMessageDecoder.recycleFrom(out, start - 1)
453
562
  return
454
563
  }
455
564
 
456
- ByteToMessageDecoder.recycle(message)
565
+ ByteToMessageDecoder.recycle(out[start - 1])
566
+
567
+ for (let index = start; index < out.length; index++) {
568
+ if (tracked) this.position = index + 1
569
+ const message = out[index]
570
+ await context.fireChannelRead(message)
571
+ if (tracked && this.batch !== out) {
572
+ ByteToMessageDecoder.recycleFrom(out, index)
573
+ return
574
+ }
575
+
576
+ ByteToMessageDecoder.recycle(message)
577
+ }
578
+ } finally {
579
+ if (tracked && this.batch === out) this.batch = null
457
580
  }
458
581
 
459
- if (tracked) this.batch = null
460
582
  if (failure !== null) await context.fireExceptionCaught(failure)
461
583
  }
462
584
 
463
585
  /**
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
586
+ * Ends a read, the overflow error or null
466
587
  */
467
- private compact(input: ByteBuf): void {
468
- if (this.cumulation !== input) return
588
+ private conclude(): DecoderError | null {
589
+ this.busy = false
590
+ this.fed = false
469
591
 
470
- if (!input.isReadable()) {
592
+ const input = this.cumulation
593
+ if (input === null) return null
594
+
595
+ const held = input.readableBytes
596
+ if (held === 0) {
597
+ this.cumulation = null
598
+ } else if (held > this.maxCumulation) {
471
599
  this.cumulation = null
600
+ return new DecoderError('Buffer is full')
472
601
  } else if (
473
602
  input.readerIndex > 0 &&
474
603
  input.readerIndex >= input.capacity / 2
475
604
  ) {
476
605
  this.cumulation = input.copy()
477
606
  }
607
+
608
+ return null
609
+ }
610
+
611
+ /**
612
+ * Ends the last run and drops the rest
613
+ * @param nested whether a read was still going
614
+ */
615
+ private shut(nested: boolean): void {
616
+ this.cumulation = null
617
+ this.busy = nested
478
618
  }
479
619
  }
@@ -23,21 +23,6 @@ export type DelimiterOptions = DecoderOptions & {
23
23
  readonly stripDelimiter?: boolean
24
24
  }
25
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
26
  /**
42
27
  * Cuts frames at whichever delimiter comes first
43
28
  * @class
@@ -78,27 +63,68 @@ export class DelimiterBasedFrameDecoder extends ByteToMessageDecoder<ByteBuf> {
78
63
  */
79
64
  private discarding: boolean
80
65
 
66
+ /**
67
+ * Tail bytes that might start a delimiter
68
+ */
69
+ private readonly tail: number
70
+
71
+ /**
72
+ * Delimiter that ended the last frame
73
+ */
74
+ private matched: Uint8Array
75
+
76
+ /**
77
+ * Its index in the list
78
+ */
79
+ private lead: number
80
+
81
81
  /**
82
82
  * Sets up a decoder for the given delimiters
83
83
  * @param options delimiters and length cap
84
84
  */
85
85
  public constructor(options: DelimiterOptions) {
86
- super(options)
87
-
88
- const reason = DelimiterBasedFrameDecoder.refusal(options)
86
+ const longest = DelimiterBasedFrameDecoder.longest(options.delimiters)
87
+ super(
88
+ ByteToMessageDecoder.sized<DelimiterOptions>(
89
+ options,
90
+ options.maxFrameLength + longest,
91
+ ),
92
+ )
93
+
94
+ const reason = DelimiterBasedFrameDecoder.refusal(options, longest)
89
95
  if (reason !== null) throw new RangeError(reason)
90
96
 
91
97
  this.maxFrameLength = options.maxFrameLength
92
98
  this.delimiters = options.delimiters
93
99
  this.stripDelimiter = options.stripDelimiter ?? true
94
100
  this.discarding = false
101
+ this.tail = longest - 1
102
+ this.matched = options.delimiters[0] ?? Uint8Array.of(0)
103
+ this.lead = 0
104
+ }
105
+
106
+ /**
107
+ * Length of the longest delimiter
108
+ * @param delimiters the ones to look for
109
+ */
110
+ private static longest(delimiters: readonly Uint8Array[]): number {
111
+ let longest = 0
112
+ for (const delimiter of delimiters) {
113
+ if (delimiter.length > longest) longest = delimiter.length
114
+ }
115
+
116
+ return longest
95
117
  }
96
118
 
97
119
  /**
98
120
  * Rejects a bad length cap or missing and empty delimiters
99
121
  * @param options what the caller passed in
122
+ * @param longest length of the longest delimiter
100
123
  */
101
- private static refusal(options: DelimiterOptions): string | null {
124
+ private static refusal(
125
+ options: DelimiterOptions,
126
+ longest: number,
127
+ ): string | null {
102
128
  if (!Number.isInteger(options.maxFrameLength)) {
103
129
  return 'Frame length is invalid'
104
130
  }
@@ -111,6 +137,12 @@ export class DelimiterBasedFrameDecoder extends ByteToMessageDecoder<ByteBuf> {
111
137
  return 'Delimiter is empty'
112
138
  }
113
139
 
140
+ if (
141
+ ByteToMessageDecoder.oversized(options, options.maxFrameLength + longest)
142
+ ) {
143
+ return 'Frame limit is above the buffer limit'
144
+ }
145
+
114
146
  return null
115
147
  }
116
148
 
@@ -125,15 +157,14 @@ export class DelimiterBasedFrameDecoder extends ByteToMessageDecoder<ByteBuf> {
125
157
  input: ByteBuf,
126
158
  out: ByteBuf[],
127
159
  ): void {
128
- const match = this.nearest(input)
129
-
130
- if (match === null) {
160
+ const index = this.nearest(input)
161
+ if (index === -1) {
131
162
  this.overflow(input)
132
163
  return
133
164
  }
134
165
 
135
- const frameLength = match.index - input.readerIndex
136
- const delimiterLength = match.delimiter.length
166
+ const frameLength = index - input.readerIndex
167
+ const delimiterLength = this.matched.length
137
168
  if (this.discarding) {
138
169
  this.discarding = false
139
170
  input.skipBytes(frameLength + delimiterLength)
@@ -154,36 +185,63 @@ export class DelimiterBasedFrameDecoder extends ByteToMessageDecoder<ByteBuf> {
154
185
  }
155
186
 
156
187
  /**
157
- * Picks the delimiter that shows up earliest
188
+ * Start of the earliest delimiter, or -1
158
189
  * @param input bytes to search
159
190
  */
160
- private nearest(input: ByteBuf): Match | null {
161
- let match: Match | null = null
191
+ private nearest(input: ByteBuf): number {
192
+ const delimiters = this.delimiters
193
+ const lead = this.lead
194
+ let best = input.indexOf(this.matched)
195
+
196
+ for (let rank = 0; rank < delimiters.length; rank++) {
197
+ const delimiter = delimiters[rank]
198
+ if (delimiter === undefined || rank === lead) continue
199
+
200
+ const index = this.earlier(input, delimiter, best, rank < this.lead)
201
+ if (index === -1) continue
162
202
 
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
- }
203
+ best = index
204
+ this.matched = delimiter
205
+ this.lead = rank
168
206
  }
169
207
 
170
- return match
208
+ return best
209
+ }
210
+
211
+ /**
212
+ * Start of a delimiter beating the best so far, or -1
213
+ * @param input bytes to search
214
+ * @param delimiter what to look for
215
+ * @param best where the best match starts, or -1
216
+ * @param ties whether a tie counts
217
+ */
218
+ private earlier(
219
+ input: ByteBuf,
220
+ delimiter: Uint8Array,
221
+ best: number,
222
+ ties: boolean,
223
+ ): number {
224
+ if (best === -1) return input.indexOf(delimiter)
225
+
226
+ const end = best + delimiter.length - (ties ? 0 : 1)
227
+ return input.indexOf(delimiter, input.readerIndex, end)
171
228
  }
172
229
 
173
230
  /**
174
- * With no delimiter in sight, throws everything away once it's over the cap
231
+ * Skips an oversized frame
175
232
  * @param input bytes with no delimiter yet
176
233
  */
177
234
  private overflow(input: ByteBuf): void {
235
+ const spare = input.readableBytes - this.tail
178
236
  if (this.discarding) {
179
- input.skipBytes(input.readableBytes)
237
+ if (spare > 0) input.skipBytes(spare)
180
238
  return
181
239
  }
182
240
 
183
- if (input.readableBytes <= this.maxFrameLength) return
241
+ if (spare <= this.maxFrameLength) return
184
242
 
185
243
  this.discarding = true
186
- input.skipBytes(input.readableBytes)
244
+ input.skipBytes(spare)
187
245
  throw new DecoderError('Frame is too large')
188
246
  }
189
247
  }