@netifyjs/netify 1.0.0-alpha.4 → 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 +15 -0
  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
@@ -23,16 +23,41 @@ export abstract class MessageToByteEncoder<T> extends OutboundHandlerAdapter {
23
23
  try {
24
24
  out = this.encode(context, message)
25
25
  } catch (error) {
26
- return Promise.reject(
27
- error instanceof EncoderError
28
- ? error
29
- : new EncoderError('Encoding failed', { cause: error }),
30
- )
26
+ return Promise.reject(MessageToByteEncoder.wrap(error))
31
27
  }
32
28
 
33
29
  return context.write(out)
34
30
  }
35
31
 
32
+ /**
33
+ * Encodes and writes without a promise, false for other messages
34
+ * @param context where the bytes get written
35
+ * @param message anything heading out
36
+ */
37
+ public writeSync(context: HandlerContext, message: unknown): boolean {
38
+ if (!this.accepts(message)) return false
39
+
40
+ let out: ByteBuf
41
+ try {
42
+ out = this.encode(context, message)
43
+ } catch (error) {
44
+ throw MessageToByteEncoder.wrap(error)
45
+ }
46
+
47
+ context.writeSync(out)
48
+ return true
49
+ }
50
+
51
+ /**
52
+ * Wraps anything thrown in an EncoderError
53
+ * @param error anything encode threw
54
+ */
55
+ private static wrap(error: unknown): EncoderError {
56
+ if (error instanceof EncoderError) return error
57
+
58
+ return new EncoderError('Encoding failed', { cause: error })
59
+ }
60
+
36
61
  /**
37
62
  * Says whether a message is one this encoder should handle
38
63
  * @param message the outbound message
@@ -18,12 +18,16 @@ export class FixedLengthFrameDecoder extends ByteToMessageDecoder<ByteBuf> {
18
18
  * @param options buffering and pooling
19
19
  */
20
20
  public constructor(frameLength: number, options: DecoderOptions = {}) {
21
- super(options)
21
+ super(ByteToMessageDecoder.sized<DecoderOptions>(options, frameLength))
22
22
 
23
23
  if (!Number.isInteger(frameLength) || frameLength <= 0) {
24
24
  throw new RangeError('Frame length is invalid')
25
25
  }
26
26
 
27
+ if (ByteToMessageDecoder.oversized(options, frameLength)) {
28
+ throw new RangeError('Frame limit is above the buffer limit')
29
+ }
30
+
27
31
  this.frameLength = frameLength
28
32
  }
29
33
 
@@ -30,15 +30,25 @@ export class HttpObjectAggregator extends InboundHandlerAdapter {
30
30
  private message: HttpMessage | null
31
31
 
32
32
  /**
33
- * Body bytes collected so far
33
+ * Body so far, or null
34
34
  */
35
- private content: ByteBuf
35
+ private content: ByteBuf | null
36
+
37
+ /**
38
+ * Body size from the head
39
+ */
40
+ private expected: number
36
41
 
37
42
  /**
38
43
  * Set while skipping the rest of a body that was too big
39
44
  */
40
45
  private discarding: boolean
41
46
 
47
+ /**
48
+ * Already sent a 413
49
+ */
50
+ private refused: boolean
51
+
42
52
  /**
43
53
  * Sets up an aggregator with a body size cap
44
54
  * @param maxContentLength bodies past this many bytes get a 413
@@ -52,12 +62,14 @@ export class HttpObjectAggregator extends InboundHandlerAdapter {
52
62
 
53
63
  this.maxContentLength = maxContentLength
54
64
  this.message = null
55
- this.content = ByteBuf.allocate(0)
65
+ this.content = null
66
+ this.expected = 0
56
67
  this.discarding = false
68
+ this.refused = false
57
69
  }
58
70
 
59
71
  /**
60
- * Collects heads and chunks, letting full messages and anything else straight through
72
+ * Collects heads and chunks into full messages
61
73
  * @param context where full messages go
62
74
  * @param message whatever the decoder produced
63
75
  */
@@ -65,6 +77,7 @@ export class HttpObjectAggregator extends InboundHandlerAdapter {
65
77
  context: HandlerContext,
66
78
  message: unknown,
67
79
  ): Promise<void> {
80
+ if (this.refused) return resolved
68
81
  if (
69
82
  message instanceof FullHttpRequest ||
70
83
  message instanceof FullHttpResponse
@@ -83,7 +96,7 @@ export class HttpObjectAggregator extends InboundHandlerAdapter {
83
96
  */
84
97
  public override channelInactive(context: HandlerContext): Promise<void> {
85
98
  this.message = null
86
- this.content = ByteBuf.allocate(0)
99
+ this.content = null
87
100
 
88
101
  return context.fireChannelInactive()
89
102
  }
@@ -110,7 +123,8 @@ export class HttpObjectAggregator extends InboundHandlerAdapter {
110
123
  }
111
124
 
112
125
  this.message = message
113
- this.content = ByteBuf.allocate(length ?? 0)
126
+ this.content = null
127
+ this.expected = length ?? 0
114
128
  return resolved
115
129
  }
116
130
 
@@ -128,47 +142,58 @@ export class HttpObjectAggregator extends InboundHandlerAdapter {
128
142
 
129
143
  const message = this.message
130
144
  if (message === null) return context.fireChannelRead(content)
131
- const size = this.content.readableBytes + content.content.readableBytes
145
+ const size =
146
+ (this.content?.readableBytes ?? 0) + content.content.readableBytes
132
147
  if (size > this.maxContentLength) {
133
148
  this.message = null
134
149
  return this.oversized(context, message, !last)
135
150
  }
136
151
 
137
152
  if (content.content.isReadable()) {
153
+ this.content ??= ByteBuf.allocate(Math.max(this.expected, size))
138
154
  this.content.writeBytes(content.content)
139
155
  }
140
156
 
141
157
  if (!(content instanceof LastHttpContent)) return resolved
142
158
 
143
- const full = this.complete(message, content.trailers)
159
+ const full = this.complete(
160
+ message,
161
+ this.content ?? ByteBuf.allocate(0),
162
+ content.trailers,
163
+ )
144
164
  this.message = null
145
- this.content = ByteBuf.allocate(0)
165
+ this.content = null
146
166
  return context.fireChannelRead(full)
147
167
  }
148
168
 
149
169
  /**
150
170
  * Puts the full message together, swapping chunked encoding for a Content-Length
151
171
  * @param message head we've been collecting for
172
+ * @param content the whole body
152
173
  * @param trailers from the last chunk
153
174
  */
154
175
  private complete(
155
176
  message: HttpMessage,
177
+ content: ByteBuf,
156
178
  trailers: HttpHeaders,
157
179
  ): FullHttpMessage {
158
180
  const full =
159
181
  message instanceof HttpResponse
160
182
  ? new FullHttpResponse(
161
183
  message.status,
162
- this.content,
184
+ content,
163
185
  message.version,
164
186
  message.headers,
165
187
  trailers,
166
188
  )
167
- : this.completeRequest(message, trailers)
189
+ : HttpObjectAggregator.completeRequest(message, content, trailers)
190
+
191
+ if (full.headers.has('transfer-encoding') && full.isChunked()) {
192
+ full.headers.remove('transfer-encoding')
193
+ }
168
194
 
169
- if (full.isChunked()) full.headers.remove('transfer-encoding')
170
195
  if (!full.headers.has('content-length')) {
171
- full.setContentLength(this.content.readableBytes)
196
+ full.setContentLength(content.readableBytes)
172
197
  }
173
198
 
174
199
  return full
@@ -177,10 +202,12 @@ export class HttpObjectAggregator extends InboundHandlerAdapter {
177
202
  /**
178
203
  * Request half of complete
179
204
  * @param message should be a request head
205
+ * @param content the whole body
180
206
  * @param trailers from the last chunk
181
207
  */
182
- private completeRequest(
208
+ private static completeRequest(
183
209
  message: HttpMessage,
210
+ content: ByteBuf,
184
211
  trailers: HttpHeaders,
185
212
  ): FullHttpRequest {
186
213
  if (!(message instanceof HttpRequest)) {
@@ -190,7 +217,7 @@ export class HttpObjectAggregator extends InboundHandlerAdapter {
190
217
  return new FullHttpRequest(
191
218
  message.method,
192
219
  message.uri,
193
- this.content,
220
+ content,
194
221
  message.version,
195
222
  message.headers,
196
223
  trailers,
@@ -220,11 +247,13 @@ export class HttpObjectAggregator extends InboundHandlerAdapter {
220
247
  discard: boolean,
221
248
  ): Promise<void> {
222
249
  this.discarding = discard
223
- this.content = ByteBuf.allocate(0)
250
+ this.content = null
224
251
  if (!(message instanceof HttpRequest)) {
225
252
  throw new DecoderError('Content is too large')
226
253
  }
227
254
 
255
+ this.refused = true
256
+
228
257
  const response = new FullHttpResponse(
229
258
  HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE,
230
259
  )
@@ -24,7 +24,7 @@ export type HttpDecoderOptions = {
24
24
  readonly maxHeaderSize?: number
25
25
 
26
26
  /**
27
- * Biggest chunk size we'll accept, 8192 by default
27
+ * Biggest chunk piece passed on
28
28
  */
29
29
  readonly maxChunkSize?: number
30
30
  }
@@ -80,7 +80,7 @@ export abstract class HttpObjectDecoder extends ByteToMessageDecoder<HttpObject>
80
80
  private readonly maxHeaderSize: number
81
81
 
82
82
  /**
83
- * Cap on any one chunk
83
+ * Biggest chunk piece passed on
84
84
  */
85
85
  private readonly maxChunkSize: number
86
86
 
@@ -114,6 +114,16 @@ export abstract class HttpObjectDecoder extends ByteToMessageDecoder<HttpObject>
114
114
  */
115
115
  private pendingValue: string
116
116
 
117
+ /**
118
+ * Joined Content-Length values, or null
119
+ */
120
+ private lengths: string | null
121
+
122
+ /**
123
+ * Joined Transfer-Encoding values, or null
124
+ */
125
+ private codings: string | null
126
+
117
127
  /**
118
128
  * Bytes left in a fixed body or the current chunk
119
129
  */
@@ -142,6 +152,8 @@ export abstract class HttpObjectDecoder extends ByteToMessageDecoder<HttpObject>
142
152
  this.headerSize = 0
143
153
  this.pendingName = null
144
154
  this.pendingValue = ''
155
+ this.lengths = null
156
+ this.codings = null
145
157
  this.remaining = 0
146
158
  }
147
159
 
@@ -259,7 +271,7 @@ export abstract class HttpObjectDecoder extends ByteToMessageDecoder<HttpObject>
259
271
  private ending(): LastHttpContent | DecoderError | null {
260
272
  switch (this.state) {
261
273
  case 'untilClose':
262
- this.finish()
274
+ this.endMessage()
263
275
  return new LastHttpContent()
264
276
  case 'initial':
265
277
  case 'upgraded':
@@ -317,7 +329,7 @@ export abstract class HttpObjectDecoder extends ByteToMessageDecoder<HttpObject>
317
329
  this.maxInitialLineLength,
318
330
  'Line is too long',
319
331
  )
320
- if (line === null || line.trim() === '') return
332
+ if (line === null || line === '') return
321
333
 
322
334
  const message = this.createMessage(line)
323
335
  this.message = message
@@ -390,8 +402,12 @@ export abstract class HttpObjectDecoder extends ByteToMessageDecoder<HttpObject>
390
402
  * @param line continuation starting with a space or tab
391
403
  */
392
404
  private foldHeader(line: string): void {
393
- const value = line.trim()
394
- if (this.pendingName === null) throw new DecoderError('Header is invalid')
405
+ const value = HttpHeaders.trim(line)
406
+ const name = this.pendingName
407
+ if (name === null || HttpObjectDecoder.isFraming(name)) {
408
+ throw new DecoderError('Header is invalid')
409
+ }
410
+
395
411
  if (!HttpHeaders.isValidValue(value)) {
396
412
  throw new DecoderError('Header is invalid')
397
413
  }
@@ -406,7 +422,7 @@ export abstract class HttpObjectDecoder extends ByteToMessageDecoder<HttpObject>
406
422
  private startHeader(line: string): void {
407
423
  const colon = line.indexOf(':')
408
424
  const name = line.slice(0, Math.max(colon, 0))
409
- const value = line.slice(colon + 1).trim()
425
+ const value = HttpHeaders.trim(line.slice(colon + 1))
410
426
  if (colon <= 0 || !HttpHeaders.isValidName(name)) {
411
427
  throw new DecoderError('Header is invalid')
412
428
  }
@@ -423,13 +439,33 @@ export abstract class HttpObjectDecoder extends ByteToMessageDecoder<HttpObject>
423
439
  * Moves the pending header into the block
424
440
  */
425
441
  private commitHeader(): void {
426
- if (this.pendingName === null) return
442
+ const name = this.pendingName
443
+ if (name === null) return
444
+ const value = this.pendingValue
427
445
 
428
- this.headers.append(this.pendingName, this.pendingValue)
446
+ this.headers.append(name, value)
447
+ if (this.state === 'headers') this.noteFraming(name, value)
429
448
  this.pendingName = null
430
449
  this.pendingValue = ''
431
450
  }
432
451
 
452
+ /**
453
+ * Keeps the body framing headers
454
+ * @param name header name as sent
455
+ * @param value header value
456
+ */
457
+ private noteFraming(name: string, value: string): void {
458
+ const size = name.length
459
+ if (size !== 14 && size !== 17) return
460
+
461
+ const key = name.toLowerCase()
462
+ if (key === 'content-length') {
463
+ this.lengths = this.lengths === null ? value : `${this.lengths},${value}`
464
+ } else if (key === 'transfer-encoding') {
465
+ this.codings = this.codings === null ? value : `${this.codings},${value}`
466
+ }
467
+ }
468
+
433
469
  /**
434
470
  * Emits the head or trailers and picks how to read the body
435
471
  * @param out where they go
@@ -437,7 +473,7 @@ export abstract class HttpObjectDecoder extends ByteToMessageDecoder<HttpObject>
437
473
  private endHeaderBlock(out: HttpObject[]): void {
438
474
  if (this.state === 'trailers') {
439
475
  out.push(new LastHttpContent(new Uint8Array(0), this.headers))
440
- this.finish()
476
+ this.endMessage()
441
477
  return
442
478
  }
443
479
 
@@ -454,33 +490,40 @@ export abstract class HttpObjectDecoder extends ByteToMessageDecoder<HttpObject>
454
490
  this.state = 'untilClose'
455
491
  } else {
456
492
  out.push(new LastHttpContent())
457
- this.finish()
493
+ this.endMessage()
458
494
  if (this.isSwitchingProtocols(message)) this.state = 'upgraded'
459
495
  }
460
496
  }
461
497
 
498
+ /**
499
+ * Content-Length or Transfer-Encoding
500
+ * @param name header name in any case
501
+ */
502
+ private static isFraming(name: string): boolean {
503
+ const key = name.toLowerCase()
504
+
505
+ return key === 'content-length' || key === 'transfer-encoding'
506
+ }
507
+
462
508
  /**
463
509
  * Chunked beats Content-Length, and responses with neither read until close
464
510
  * @param message head to look at
465
511
  */
466
512
  private bodyMode(message: HttpMessage): BodyMode {
467
513
  if (this.isContentAlwaysEmpty(message)) return 'none'
468
- if (message.isChunked()) {
469
- message.headers.remove('content-length')
470
- return 'chunked'
471
- }
472
514
 
473
- if (message.headers.has('transfer-encoding')) {
474
- if (message instanceof HttpRequest) {
475
- throw new DecoderError('Transfer encoding is unsupported')
476
- }
477
-
478
- return 'close'
515
+ const lengths = this.lengths
516
+ const codings = this.codings
517
+ if (codings !== null) {
518
+ return HttpObjectDecoder.codedMode(
519
+ message,
520
+ HttpObjectDecoder.readCodings(codings),
521
+ lengths !== null,
522
+ )
479
523
  }
480
524
 
481
- const length = this.readContentLength(message)
482
- if (length !== null) {
483
- this.remaining = length
525
+ if (lengths !== null) {
526
+ this.remaining = HttpObjectDecoder.readContentLength(lengths)
484
527
  return 'fixed'
485
528
  }
486
529
 
@@ -488,25 +531,93 @@ export abstract class HttpObjectDecoder extends ByteToMessageDecoder<HttpObject>
488
531
  }
489
532
 
490
533
  /**
491
- * Every Content-Length has to agree, or the message is refused
492
- * @param message head to look at
534
+ * Picks the body mode for Transfer-Encoding
535
+ * @param message head carrying Transfer-Encoding
536
+ * @param chunked chunked is the final coding
537
+ * @param sized also had a Content-Length
493
538
  */
494
- private readContentLength(message: HttpMessage): number | null {
495
- const values = message.headers.tokens('content-length')
496
- const first = values[0]
497
- if (first === undefined) return null
539
+ private static codedMode(
540
+ message: HttpMessage,
541
+ chunked: boolean,
542
+ sized: boolean,
543
+ ): BodyMode {
544
+ const request = message instanceof HttpRequest
545
+ if (request && !(chunked && message.version.keepAliveDefault)) {
546
+ throw new DecoderError('Transfer encoding is unsupported')
547
+ }
548
+
549
+ if (!chunked) return 'close'
550
+ if (!sized) return 'chunked'
551
+
552
+ message.headers.remove('content-length')
553
+ if (request && !message.headers.hasToken('connection', 'close')) {
554
+ message.headers.add('Connection', 'close')
555
+ }
556
+
557
+ return 'chunked'
558
+ }
559
+
560
+ /**
561
+ * Chunked is the final coding
562
+ * @param codings the header values joined by commas
563
+ */
564
+ private static readCodings(codings: string): boolean {
565
+ if (codings === 'chunked') return true
566
+
567
+ const parts = codings.split(',')
568
+ let first = -1
569
+ for (let index = 0; index < parts.length; index++) {
570
+ const coding = HttpHeaders.trim(parts[index] ?? '')
571
+ if (!HttpHeaders.isValidName(coding)) {
572
+ throw new DecoderError('Transfer encoding is invalid')
573
+ }
574
+
575
+ if (first === -1 && coding.toLowerCase() === 'chunked') first = index
576
+ }
577
+
578
+ return first === parts.length - 1
579
+ }
580
+
581
+ /**
582
+ * Reads one agreed Content-Length
583
+ * @param lengths the header values joined by commas
584
+ */
585
+ private static readContentLength(lengths: string): number {
586
+ let first: string | null = null
587
+ for (const part of lengths.includes(',') ? lengths.split(',') : [lengths]) {
588
+ const digits = HttpHeaders.trim(part)
589
+ if (!HttpObjectDecoder.isLength(digits, first)) {
590
+ throw new DecoderError('Content length is invalid')
591
+ }
592
+
593
+ first = digits
594
+ }
498
595
 
499
596
  const length = Number(first)
500
- const valid = values.every(
501
- (value: string): boolean => /^\d+$/.test(value) && value === first,
502
- )
503
- if (!valid || !Number.isSafeInteger(length)) {
597
+ if (!Number.isSafeInteger(length)) {
504
598
  throw new DecoderError('Content length is invalid')
505
599
  }
506
600
 
507
601
  return length
508
602
  }
509
603
 
604
+ /**
605
+ * Digits matching the earlier length
606
+ * @param digits one Content-Length member
607
+ * @param first the earlier member, or null
608
+ */
609
+ private static isLength(digits: string, first: string | null): boolean {
610
+ if (first !== null) return digits === first
611
+ if (digits === '') return false
612
+
613
+ for (let index = 0; index < digits.length; index++) {
614
+ const code = digits.charCodeAt(index)
615
+ if (code < 0x30 || code > 0x39) return false
616
+ }
617
+
618
+ return true
619
+ }
620
+
510
621
  /**
511
622
  * Passes on what has arrived, ending with LastHttpContent once it's all in
512
623
  * @param input bytes gathered so far
@@ -524,7 +635,7 @@ export abstract class HttpObjectDecoder extends ByteToMessageDecoder<HttpObject>
524
635
  }
525
636
 
526
637
  out.push(new LastHttpContent(content))
527
- this.finish()
638
+ this.endMessage()
528
639
  }
529
640
 
530
641
  /**
@@ -539,13 +650,12 @@ export abstract class HttpObjectDecoder extends ByteToMessageDecoder<HttpObject>
539
650
  )
540
651
  if (line === null) return
541
652
 
542
- const text = (line.split(';')[0] ?? '').trim()
653
+ const text = HttpHeaders.trim(line.split(';')[0] ?? '')
543
654
  if (!/^[0-9a-fA-F]{1,13}$/.test(text)) {
544
655
  throw new DecoderError('Chunk size is invalid')
545
656
  }
546
657
 
547
658
  const size = Number.parseInt(text, 16)
548
- if (size > this.maxChunkSize) throw new DecoderError('Chunk is too large')
549
659
 
550
660
  if (size === 0) {
551
661
  this.begin(new HttpHeaders(), 'trailers')
@@ -557,12 +667,16 @@ export abstract class HttpObjectDecoder extends ByteToMessageDecoder<HttpObject>
557
667
  }
558
668
 
559
669
  /**
560
- * Passes chunk bytes on as they arrive
670
+ * Passes chunk bytes on in pieces
561
671
  * @param input bytes gathered so far
562
672
  * @param out body chunks go here
563
673
  */
564
674
  private readChunkData(input: ByteBuf, out: HttpObject[]): void {
565
- const size = Math.min(this.remaining, input.readableBytes)
675
+ const size = Math.min(
676
+ this.remaining,
677
+ input.readableBytes,
678
+ this.maxChunkSize,
679
+ )
566
680
  if (size === 0) return
567
681
 
568
682
  out.push(new HttpContent(input.readSlice(size)))
@@ -603,13 +717,15 @@ export abstract class HttpObjectDecoder extends ByteToMessageDecoder<HttpObject>
603
717
  this.headerSize = 0
604
718
  this.pendingName = null
605
719
  this.pendingValue = ''
720
+ this.lengths = null
721
+ this.codings = null
606
722
  this.state = state
607
723
  }
608
724
 
609
725
  /**
610
726
  * Back to waiting for a first line
611
727
  */
612
- private finish(): void {
728
+ private endMessage(): void {
613
729
  this.state = 'initial'
614
730
  this.message = null
615
731
  this.remaining = 0
@@ -20,11 +20,15 @@ export class HttpRequestDecoder extends HttpObjectDecoder {
20
20
  * @param line first line of the request
21
21
  */
22
22
  protected createMessage(line: string): HttpRequest {
23
- const match = HttpRequestDecoder.pattern.exec(line.trimStart())
23
+ const match = HttpRequestDecoder.pattern.exec(line)
24
24
  const method = match?.[1]
25
25
  const uri = match?.[2]
26
26
  const version = HttpVersion.parse(match?.[3] ?? '')
27
- if (method === undefined || uri === undefined) {
27
+ if (
28
+ method === undefined ||
29
+ uri === undefined ||
30
+ !HttpRequest.isValidUri(uri)
31
+ ) {
28
32
  throw new DecoderError('Request line is invalid')
29
33
  }
30
34
 
@@ -131,9 +131,7 @@ export abstract class HttpObjectEncoder<
131
131
  }
132
132
  if (!this.acceptsMessage(message) || message.isChunked()) return false
133
133
 
134
- let head = `${this.initialLine(message)}\r\n`
135
- for (const [name, value] of message.headers) head += `${name}: ${value}\r\n`
136
- head += '\r\n'
134
+ const head = `${this.initialLine(message)}\r\n${message.headers.serialize()}\r\n`
137
135
  if (!HttpObjectEncoder.isAscii(head)) return false
138
136
 
139
137
  const body = message.content
@@ -175,10 +173,7 @@ export abstract class HttpObjectEncoder<
175
173
  * @param headers headers or trailers
176
174
  */
177
175
  private writeHeaders(out: ByteBuf, headers: HttpHeaders): void {
178
- let text = ''
179
-
180
- for (const [name, value] of headers) text += `${name}: ${value}\r\n`
181
- out.writeString(`${text}\r\n`)
176
+ out.writeString(`${headers.serialize()}\r\n`)
182
177
  }
183
178
 
184
179
  /**
@@ -1,3 +1,4 @@
1
+ import { EncoderError } from '../../../error/index.ts'
1
2
  import { HttpRequest } from '../../message/request/index.ts'
2
3
  import { HttpObjectEncoder } from '../object/index.ts'
3
4
 
@@ -19,6 +20,10 @@ export class HttpRequestEncoder extends HttpObjectEncoder<HttpRequest> {
19
20
  * @param message head being written
20
21
  */
21
22
  protected initialLine(message: HttpRequest): string {
23
+ if (!HttpRequest.isValidUri(message.uri)) {
24
+ throw new EncoderError('Request target is invalid')
25
+ }
26
+
22
27
  return `${message.method.name} ${message.uri} ${message.version.text}`
23
28
  }
24
29
  }