@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,611 @@
1
+ import { protect, resolved } from '../resolved/index.ts'
2
+ import type { Transport } from '../transport/index.ts'
3
+ import type { PacketAddress } from '../../datagram/packet/index.ts'
4
+
5
+ /**
6
+ * Writes made between two flushes share one promise, which saves an allocation each
7
+ */
8
+ type Batch = {
9
+ /**
10
+ * Resolves once every write in the batch has gone out
11
+ */
12
+ readonly result: PromiseWithResolvers<undefined>
13
+
14
+ /**
15
+ * Counts down as writes finish, resolves the batch at zero
16
+ */
17
+ remaining: number
18
+ }
19
+
20
+ /**
21
+ * One write sitting in the queue
22
+ */
23
+ type Entry = {
24
+ /**
25
+ * Shrinks from the front when the socket only takes part of it
26
+ */
27
+ bytes: Uint8Array
28
+
29
+ /**
30
+ * UDP target, null for streams and connected sockets
31
+ */
32
+ readonly recipient: PacketAddress | null
33
+
34
+ /**
35
+ * Who to tell when these bytes are written
36
+ */
37
+ readonly batch: Batch
38
+ }
39
+
40
+ /**
41
+ * Backpressure limits and the hooks the buffer reports through
42
+ */
43
+ export type OutboundOptions = {
44
+ /**
45
+ * Queued bytes at which the channel stops being writable
46
+ */
47
+ readonly highWaterMark: number
48
+
49
+ /**
50
+ * Queued bytes the buffer has to drop below before it's writable again
51
+ */
52
+ readonly lowWaterMark: number
53
+
54
+ /**
55
+ * Called on each flip with the new state
56
+ */
57
+ readonly onWritabilityChanged: (writable: boolean) => void
58
+
59
+ /**
60
+ * Only way to hear about a refused sync write, since there's no promise to reject
61
+ */
62
+ readonly onSyncRefused?: (error: Error) => void
63
+
64
+ /**
65
+ * Hard cap on queued bytes, writes past it fail
66
+ */
67
+ readonly maxPendingBytes: number
68
+ }
69
+
70
+ /**
71
+ * Holds outgoing bytes until the socket has room, with water marks for backpressure
72
+ * @class
73
+ */
74
+ export class OutboundBuffer {
75
+ /**
76
+ * Dummy batch for sync writes, never settles and nobody awaits it
77
+ */
78
+ private static readonly voided: Batch = {
79
+ result: Promise.withResolvers<undefined>(),
80
+ remaining: 0,
81
+ }
82
+
83
+ /**
84
+ * Cap on how much we copy together for a single socket write
85
+ */
86
+ private static readonly gatherLimit: number = 256 * 1024
87
+
88
+ /**
89
+ * Starting size of the staging buffer
90
+ */
91
+ public static readonly stagingSize = 64 * 1024
92
+
93
+ /**
94
+ * Biggest write that goes through staging
95
+ */
96
+ public static readonly stagingLimit = 4096
97
+
98
+ /**
99
+ * Most packets handed to one batched send
100
+ */
101
+ private static readonly batchLimit = 1024
102
+
103
+ /**
104
+ * Shared across all buffers, safe because gather and write happen in one go
105
+ */
106
+ private static readonly scratch: Uint8Array = new Uint8Array(
107
+ OutboundBuffer.gatherLimit,
108
+ )
109
+
110
+ /**
111
+ * Socket we hand bytes to
112
+ */
113
+ private readonly transport: Transport
114
+
115
+ /**
116
+ * Water marks and callbacks
117
+ */
118
+ private readonly options: OutboundOptions
119
+
120
+ /**
121
+ * Written but not flushed yet, so nothing's been sent
122
+ */
123
+ private unflushed: Entry[]
124
+
125
+ /**
126
+ * Flushed and waiting for the socket to take them
127
+ */
128
+ private flushed: Entry[]
129
+
130
+ /**
131
+ * Total bytes across both queues, checked against the water marks
132
+ */
133
+ private size: number
134
+
135
+ /**
136
+ * Bytes the socket has taken so far
137
+ */
138
+ private written: number
139
+
140
+ /**
141
+ * Last state we reported through onWritabilityChanged
142
+ */
143
+ private writable: boolean
144
+
145
+ /**
146
+ * Small sync writes copied straight in, so they need no entry or array of their own
147
+ */
148
+ private staging: Uint8Array
149
+
150
+ /**
151
+ * Where the open staged run starts
152
+ */
153
+ private stagedFrom: number
154
+
155
+ /**
156
+ * Bytes of staging in use
157
+ */
158
+ private stagedTo: number
159
+
160
+ /**
161
+ * Open batch for stream writes, cleared on flush
162
+ */
163
+ private batch: Batch | null
164
+
165
+ /**
166
+ * Set by fail, after which writes are refused
167
+ */
168
+ private closed: boolean
169
+
170
+ /**
171
+ * Stops drain from re-entering itself through socket callbacks
172
+ */
173
+ private draining: boolean
174
+
175
+ /**
176
+ * The staging buffer, valid until the next reserve
177
+ */
178
+ public get stagingBuffer(): Uint8Array {
179
+ return this.staging
180
+ }
181
+
182
+ /**
183
+ * Makes room for a small sync write in staging, returns where to write it or -1 to take the normal path
184
+ * @param size bytes about to be written
185
+ */
186
+ public reserve(size: number): number {
187
+ if (this.closed || this.transport.datagram) return -1
188
+ if (size > OutboundBuffer.stagingLimit) return -1
189
+ if (this.size + size > this.options.maxPendingBytes) return -1
190
+
191
+ if (
192
+ this.stagedFrom === this.stagedTo &&
193
+ this.flushed.length === 0 &&
194
+ this.unflushed.length === 0
195
+ ) {
196
+ this.stagedFrom = 0
197
+ this.stagedTo = 0
198
+ }
199
+ if (this.stagedTo + size > this.staging.length) {
200
+ this.seal()
201
+ const busy = this.flushed.length > 0 || this.unflushed.length > 0
202
+ if (busy) this.staging = new Uint8Array(this.staging.length)
203
+ this.stagedFrom = 0
204
+ this.stagedTo = 0
205
+ }
206
+
207
+ const offset = this.stagedTo
208
+ this.stagedTo += size
209
+ this.resize(size)
210
+ return offset
211
+ }
212
+
213
+ /**
214
+ * Turns the open staged run into one entry, so later writes queue behind it
215
+ */
216
+ private seal(): void {
217
+ if (this.stagedTo === this.stagedFrom) return
218
+
219
+ this.unflushed.push({
220
+ bytes: this.staging.subarray(this.stagedFrom, this.stagedTo),
221
+ recipient: null,
222
+ batch: OutboundBuffer.voided,
223
+ })
224
+ this.stagedFrom = this.stagedTo
225
+ }
226
+
227
+ /**
228
+ * Starts empty and writable
229
+ * @param transport where bytes end up
230
+ * @param options water marks and callbacks
231
+ */
232
+ public constructor(transport: Transport, options: OutboundOptions) {
233
+ this.transport = transport
234
+ this.options = options
235
+ this.unflushed = []
236
+ this.flushed = []
237
+ this.size = 0
238
+ this.written = 0
239
+ this.writable = true
240
+ this.staging = new Uint8Array(OutboundBuffer.stagingSize)
241
+ this.stagedFrom = 0
242
+ this.stagedTo = 0
243
+ this.batch = null
244
+ this.closed = false
245
+ this.draining = false
246
+ }
247
+
248
+ /**
249
+ * False while too much is queued to write
250
+ */
251
+ public get isWritable(): boolean {
252
+ return this.writable
253
+ }
254
+
255
+ /**
256
+ * Bytes the socket has taken since the channel opened
257
+ */
258
+ public get writtenBytes(): number {
259
+ return this.written
260
+ }
261
+
262
+ /**
263
+ * Bytes queued and not yet taken by the socket
264
+ */
265
+ public get pendingBytes(): number {
266
+ return this.size
267
+ }
268
+
269
+ /**
270
+ * Holds the bytes until the next flush, the promise settles once they're sent
271
+ * @param bytes what to send
272
+ * @param recipient UDP target, or null
273
+ * @param discard skip the promise for a sync write
274
+ */
275
+ public add(
276
+ bytes: Uint8Array,
277
+ recipient: PacketAddress | null = null,
278
+ discard = false,
279
+ ): Promise<void> {
280
+ this.seal()
281
+ if (this.closed) {
282
+ return discard ? resolved : Promise.reject(new Error('Channel is closed'))
283
+ }
284
+
285
+ if (this.size + bytes.length > this.options.maxPendingBytes) {
286
+ const error = new Error('Write queue is full')
287
+ if (!discard) return Promise.reject(error)
288
+ this.options.onSyncRefused?.(error)
289
+ return resolved
290
+ }
291
+
292
+ if (discard) {
293
+ this.unflushed.push({ bytes, recipient, batch: OutboundBuffer.voided })
294
+ this.resize(bytes.length)
295
+ return resolved
296
+ }
297
+
298
+ const batch = this.join()
299
+ batch.remaining += 1
300
+ this.unflushed.push({ bytes, recipient, batch })
301
+ this.resize(bytes.length)
302
+ return batch.result.promise
303
+ }
304
+
305
+ /**
306
+ * Hands everything queued so far to the socket
307
+ */
308
+ public flush(): Promise<void> {
309
+ if (this.flushStaged()) return resolved
310
+
311
+ this.seal()
312
+ if (this.flushed.length === 0) {
313
+ const empty = this.flushed
314
+ this.flushed = this.unflushed
315
+ this.unflushed = empty
316
+ } else {
317
+ for (const entry of this.unflushed) this.flushed.push(entry)
318
+ this.unflushed.length = 0
319
+ }
320
+
321
+ this.batch = null
322
+
323
+ const last = this.lastWaited()
324
+ this.drain()
325
+ if (last === null || last.remaining === 0) return resolved
326
+ return last.result.promise
327
+ }
328
+
329
+ /**
330
+ * Writes the staged run straight from staging when nothing else is queued, true if it all went
331
+ */
332
+ private flushStaged(): boolean {
333
+ const from = this.stagedFrom
334
+ const size = this.stagedTo - from
335
+ const transport = this.transport
336
+ if (size === 0 || this.closed || this.draining) return false
337
+ if (this.unflushed.length > 0 || this.flushed.length > 0) return false
338
+ if (transport.writeRange === undefined) return false
339
+
340
+ let written: number
341
+ try {
342
+ written = transport.writeRange(this.staging, from, size)
343
+ } catch {
344
+ return false
345
+ }
346
+
347
+ if (written < 0) {
348
+ this.fail(new Error('Channel is closed'))
349
+ return true
350
+ }
351
+
352
+ this.stagedFrom = from + written
353
+ this.written += written
354
+ this.batch = null
355
+ this.resize(-written)
356
+ return written === size
357
+ }
358
+
359
+ /**
360
+ * Called again whenever the socket says it has room
361
+ */
362
+ public drain(): void {
363
+ if (this.draining || this.closed) return
364
+ this.draining = true
365
+
366
+ try {
367
+ this.write()
368
+ } finally {
369
+ this.draining = false
370
+ }
371
+ }
372
+
373
+ /**
374
+ * Closes the buffer for good and rejects anything still waiting
375
+ * @param error what every pending write gets rejected with
376
+ */
377
+ public fail(error: Error): void {
378
+ if (this.closed) return
379
+ this.closed = true
380
+ this.stagedFrom = this.stagedTo
381
+
382
+ const batches = new Set<Batch>()
383
+ for (const entry of this.flushed) batches.add(entry.batch)
384
+ for (const entry of this.unflushed) batches.add(entry.batch)
385
+ batches.delete(OutboundBuffer.voided)
386
+ this.flushed.length = 0
387
+ this.unflushed = []
388
+ this.batch = null
389
+ this.size = 0
390
+ for (const batch of batches) batch.result.reject(error)
391
+ }
392
+
393
+ /**
394
+ * Keeps going until the queue's empty or the socket pushes back
395
+ */
396
+ private write(): void {
397
+ if (this.transport.datagram && this.transport.writeBatch !== undefined) {
398
+ this.writeDatagrams()
399
+ return
400
+ }
401
+
402
+ while (this.flushed.length > 0 && !this.closed) {
403
+ const gathered = this.transport.datagram ? null : this.gather()
404
+ const progressed =
405
+ gathered === null ? this.writeOne() : this.writeMany(gathered)
406
+ if (!progressed) return
407
+ }
408
+ }
409
+
410
+ /**
411
+ * Sends flushed packets in batches, one system call each
412
+ */
413
+ private writeDatagrams(): void {
414
+ while (this.flushed.length > 0 && !this.closed) {
415
+ const flushed = this.flushed
416
+ const count = Math.min(flushed.length, OutboundBuffer.batchLimit)
417
+ const packets =
418
+ count === flushed.length ? flushed : flushed.slice(0, count)
419
+
420
+ let sent: number
421
+ try {
422
+ sent = this.transport.writeBatch?.(packets) ?? -1
423
+ } catch {
424
+ if (!this.writeOne()) return
425
+ continue
426
+ }
427
+
428
+ if (sent < 0) {
429
+ this.fail(new Error('Channel is closed'))
430
+ return
431
+ }
432
+
433
+ let bytes = 0
434
+ for (let index = 0; index < sent; index++) {
435
+ const entry = flushed[index]
436
+ if (entry === undefined) break
437
+ bytes += entry.bytes.length
438
+ OutboundBuffer.settle(entry)
439
+ }
440
+
441
+ this.resize(-bytes)
442
+ this.written += bytes
443
+ if (sent === flushed.length) flushed.length = 0
444
+ else flushed.splice(0, sent)
445
+ if (sent < count) return
446
+ }
447
+ }
448
+
449
+ /**
450
+ * Used for datagrams and big entries, true if it all went and we can keep going
451
+ */
452
+ private writeOne(): boolean {
453
+ const entry = this.flushed[0]
454
+ if (entry === undefined) return false
455
+
456
+ const written = this.attempt(entry)
457
+ if (written === null) return true
458
+ if (written < 0) {
459
+ this.fail(new Error('Channel is closed'))
460
+ return false
461
+ }
462
+
463
+ const complete = written >= entry.bytes.length
464
+ this.consume(written)
465
+ return complete
466
+ }
467
+
468
+ /**
469
+ * One syscall for lots of small writes, true if the socket took all of it
470
+ * @param bytes slice of the scratch buffer from gather
471
+ */
472
+ private writeMany(bytes: Uint8Array): boolean {
473
+ let written: number
474
+ try {
475
+ written = this.transport.write(bytes, null)
476
+ } catch (cause) {
477
+ this.fail(new Error('Write was refused', { cause }))
478
+ return false
479
+ }
480
+
481
+ if (written < 0) {
482
+ this.fail(new Error('Channel is closed'))
483
+ return false
484
+ }
485
+
486
+ this.consume(written)
487
+ return written >= bytes.length
488
+ }
489
+
490
+ /**
491
+ * Null unless at least two entries fit under the limit, else packs as many as fit
492
+ */
493
+ private gather(): Uint8Array | null {
494
+ const first = this.flushed[0]
495
+ const second = this.flushed[1]
496
+ if (first === undefined || second === undefined) return null
497
+ if (first.bytes.length + second.bytes.length > OutboundBuffer.gatherLimit) {
498
+ return null
499
+ }
500
+
501
+ let size = 0
502
+ for (const entry of this.flushed) {
503
+ if (size + entry.bytes.length > OutboundBuffer.gatherLimit) break
504
+ OutboundBuffer.scratch.set(entry.bytes, size)
505
+ size += entry.bytes.length
506
+ }
507
+
508
+ return OutboundBuffer.scratch.subarray(0, size)
509
+ }
510
+
511
+ /**
512
+ * Drops fully written entries and trims a partly written one
513
+ * @param written how many bytes the socket took
514
+ */
515
+ private consume(written: number): void {
516
+ let remaining = written
517
+ let done = 0
518
+
519
+ for (const entry of this.flushed) {
520
+ if (remaining < entry.bytes.length) {
521
+ if (remaining > 0) entry.bytes = entry.bytes.subarray(remaining)
522
+ break
523
+ }
524
+
525
+ remaining -= entry.bytes.length
526
+ done += 1
527
+ }
528
+
529
+ this.resize(-written)
530
+ this.written += written
531
+ for (let index = 0; index < done; index++) {
532
+ const entry = this.flushed[index]
533
+ if (entry !== undefined) OutboundBuffer.settle(entry)
534
+ }
535
+
536
+ if (done === this.flushed.length) this.flushed.length = 0
537
+ else this.flushed.splice(0, done)
538
+ }
539
+
540
+ /**
541
+ * Null if the transport threw, in which case only that entry is dropped
542
+ * @param entry the head of the flushed queue
543
+ */
544
+ private attempt(entry: Entry): number | null {
545
+ try {
546
+ return this.transport.write(entry.bytes, entry.recipient)
547
+ } catch (cause) {
548
+ this.flushed.shift()
549
+ this.resize(-entry.bytes.length)
550
+ const error = new Error('Write was refused', { cause })
551
+ if (entry.batch === OutboundBuffer.voided)
552
+ this.options.onSyncRefused?.(error)
553
+ else entry.batch.result.reject(error)
554
+ return null
555
+ }
556
+ }
557
+
558
+ /**
559
+ * Batches settle in order, so the last real one tells us when the flush is done
560
+ */
561
+ private lastWaited(): Batch | null {
562
+ for (let index = this.flushed.length - 1; index >= 0; index--) {
563
+ const batch = this.flushed[index]?.batch
564
+ if (batch !== undefined && batch !== OutboundBuffer.voided) return batch
565
+ }
566
+
567
+ return null
568
+ }
569
+
570
+ /**
571
+ * Reuses the open batch on streams, datagrams get a fresh one every time
572
+ */
573
+ private join(): Batch {
574
+ if (this.batch !== null) return this.batch
575
+
576
+ const batch: Batch = {
577
+ result: Promise.withResolvers<undefined>(),
578
+ remaining: 0,
579
+ }
580
+ void protect(batch.result.promise)
581
+ if (!this.transport.datagram) this.batch = batch
582
+ return batch
583
+ }
584
+
585
+ /**
586
+ * Ticks the batch down and resolves it on the last write, void ones are skipped
587
+ * @param entry one that's fully written
588
+ */
589
+ private static settle(entry: Entry): void {
590
+ if (entry.batch === OutboundBuffer.voided) return
591
+ entry.batch.remaining -= 1
592
+
593
+ if (entry.batch.remaining === 0) entry.batch.result.resolve(undefined)
594
+ }
595
+
596
+ /**
597
+ * Updates the byte count and reports if we crossed a water mark
598
+ * @param delta bytes added, negative when written
599
+ */
600
+ private resize(delta: number): void {
601
+ this.size += delta
602
+
603
+ if (this.writable && this.size > this.options.highWaterMark) {
604
+ this.writable = false
605
+ this.options.onWritabilityChanged(false)
606
+ } else if (!this.writable && this.size < this.options.lowWaterMark) {
607
+ this.writable = true
608
+ this.options.onWritabilityChanged(true)
609
+ }
610
+ }
611
+ }
@@ -0,0 +1,100 @@
1
+ import { ByteBuf } from '../../../buffer/index.ts'
2
+ import {
3
+ DatagramPacket,
4
+ type PacketAddress,
5
+ } from '../../../datagram/packet/index.ts'
6
+ import type { HandlerContext } from '../../context/index.ts'
7
+ import type { OutboundHandler } from '../../handler/index.ts'
8
+
9
+ /**
10
+ * The channel side the head hands finished bytes to
11
+ */
12
+ export type Sink = {
13
+ /**
14
+ * True for UDP, where packets keep their own recipient
15
+ */
16
+ readonly datagram: boolean
17
+
18
+ /**
19
+ * Queues the bytes without writing them yet
20
+ * @param bytes encoded output
21
+ * @param recipient UDP target, or null for the connected peer
22
+ */
23
+ send(bytes: Uint8Array, recipient: PacketAddress | null): Promise<void>
24
+
25
+ /**
26
+ * Pushes everything queued out to the socket
27
+ */
28
+ flush(): Promise<void>
29
+
30
+ /**
31
+ * Tears the channel down
32
+ */
33
+ close(): Promise<void>
34
+ }
35
+
36
+ /**
37
+ * Last stop for outbound calls, turns messages into bytes for the sink
38
+ * @class
39
+ */
40
+ export class HeadHandler implements OutboundHandler {
41
+ /**
42
+ * Where bytes end up, normally the channel itself
43
+ */
44
+ private readonly sink: Sink
45
+
46
+ /**
47
+ * Hooks the head up to its channel
48
+ * @param sink usually the channel that owns the pipeline
49
+ */
50
+ public constructor(sink: Sink) {
51
+ this.sink = sink
52
+ }
53
+
54
+ /**
55
+ * Accepts ByteBufs, raw bytes and, on UDP, packets, rejecting anything else
56
+ * @param context unused, the head has nowhere further to go
57
+ * @param message should be fully encoded by now
58
+ */
59
+ public write(context: HandlerContext, message: unknown): Promise<void> {
60
+ if (message instanceof DatagramPacket) {
61
+ if (!this.sink.datagram) {
62
+ return Promise.reject(new TypeError('Packet needs a datagram channel'))
63
+ }
64
+
65
+ return this.sink.send(message.content.toUint8Array(), message.recipient)
66
+ }
67
+
68
+ const bytes = this.bytesOf(message)
69
+ if (bytes === null) {
70
+ return Promise.reject(new TypeError('Message type is not supported'))
71
+ }
72
+
73
+ return this.sink.send(bytes, null)
74
+ }
75
+
76
+ /**
77
+ * Straight through to the sink
78
+ */
79
+ public flush(): Promise<void> {
80
+ return this.sink.flush()
81
+ }
82
+
83
+ /**
84
+ * Straight through to the sink
85
+ */
86
+ public close(): Promise<void> {
87
+ return this.sink.close()
88
+ }
89
+
90
+ /**
91
+ * Null for anything that isn't a ByteBuf or Uint8Array
92
+ * @param message an outbound message
93
+ */
94
+ private bytesOf(message: unknown): Uint8Array | null {
95
+ if (message instanceof ByteBuf) return message.toUint8Array()
96
+ if (message instanceof Uint8Array) return message
97
+
98
+ return null
99
+ }
100
+ }