@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,300 @@
1
+ import type { Channel } from '../../channel/index.ts'
2
+ import type { HandlerContext } from '../../channel/context/index.ts'
3
+ import { InboundHandlerAdapter } from '../../channel/handler/inbound/index.ts'
4
+ import { resolved } from '../../channel/resolved/index.ts'
5
+
6
+ /**
7
+ * Settings for MetricsHandler
8
+ */
9
+ export type MetricsOptions = {
10
+ /**
11
+ * Times the handlers after this one, off by default
12
+ */
13
+ readonly timing?: boolean
14
+ }
15
+
16
+ /**
17
+ * Counters for every channel the handler has seen
18
+ */
19
+ export type MetricsSnapshot = {
20
+ /**
21
+ * Channels open now
22
+ */
23
+ readonly connections: number
24
+
25
+ /**
26
+ * Channels opened since the start
27
+ */
28
+ readonly opened: number
29
+
30
+ /**
31
+ * Channels closed since the start
32
+ */
33
+ readonly closed: number
34
+
35
+ /**
36
+ * Bytes read from sockets since the start
37
+ */
38
+ readonly bytesRead: number
39
+
40
+ /**
41
+ * Bytes sockets have taken since the start
42
+ */
43
+ readonly bytesWritten: number
44
+
45
+ /**
46
+ * Messages that reached the handler since the start
47
+ */
48
+ readonly messagesRead: number
49
+
50
+ /**
51
+ * Bytes queued for open sockets now
52
+ */
53
+ readonly pendingBytes: number
54
+
55
+ /**
56
+ * Milliseconds since the last snapshot
57
+ */
58
+ readonly elapsed: number
59
+
60
+ /**
61
+ * Bytes read per second since the last snapshot
62
+ */
63
+ readonly readRate: number
64
+
65
+ /**
66
+ * Bytes written per second since the last snapshot
67
+ */
68
+ readonly writeRate: number
69
+
70
+ /**
71
+ * Messages per second since the last snapshot
72
+ */
73
+ readonly messageRate: number
74
+
75
+ /**
76
+ * Average microseconds per message in later handlers since the last snapshot, 0 without timing
77
+ */
78
+ readonly averageTime: number
79
+
80
+ /**
81
+ * Slowest message in microseconds since the last snapshot, 0 without timing
82
+ */
83
+ readonly slowestTime: number
84
+ }
85
+
86
+ /**
87
+ * Totals kept between snapshots
88
+ */
89
+ type Totals = {
90
+ /**
91
+ * When it was taken
92
+ */
93
+ at: number
94
+
95
+ /**
96
+ * Bytes read
97
+ */
98
+ bytesRead: number
99
+
100
+ /**
101
+ * Bytes written
102
+ */
103
+ bytesWritten: number
104
+
105
+ /**
106
+ * Messages read
107
+ */
108
+ messagesRead: number
109
+ }
110
+
111
+ /**
112
+ * Counts connections, bytes and messages for every channel it's added to
113
+ * @class
114
+ */
115
+ export class MetricsHandler extends InboundHandlerAdapter<unknown> {
116
+ /**
117
+ * Whether later handlers are timed
118
+ */
119
+ private readonly timing: boolean
120
+
121
+ /**
122
+ * Channels open now
123
+ */
124
+ private readonly live: Set<Channel>
125
+
126
+ /**
127
+ * Totals at the last snapshot
128
+ */
129
+ private readonly last: Totals
130
+
131
+ /**
132
+ * Channels opened
133
+ */
134
+ private opened: number
135
+
136
+ /**
137
+ * Channels closed
138
+ */
139
+ private closed: number
140
+
141
+ /**
142
+ * Bytes read by channels that have closed
143
+ */
144
+ private closedRead: number
145
+
146
+ /**
147
+ * Bytes written by channels that have closed
148
+ */
149
+ private closedWritten: number
150
+
151
+ /**
152
+ * Messages read
153
+ */
154
+ private messages: number
155
+
156
+ /**
157
+ * Microseconds spent in later handlers since the last snapshot
158
+ */
159
+ private spent: number
160
+
161
+ /**
162
+ * Messages timed since the last snapshot
163
+ */
164
+ private timed: number
165
+
166
+ /**
167
+ * Slowest message since the last snapshot in microseconds
168
+ */
169
+ private slowest: number
170
+
171
+ /**
172
+ * Sets up empty counters, add it first in each pipeline
173
+ * @param options timing switch
174
+ */
175
+ public constructor(options: MetricsOptions = {}) {
176
+ super()
177
+
178
+ this.timing = options.timing ?? false
179
+ this.live = new Set<Channel>()
180
+ this.last = {
181
+ at: performance.now(),
182
+ bytesRead: 0,
183
+ bytesWritten: 0,
184
+ messagesRead: 0,
185
+ }
186
+ this.opened = 0
187
+ this.closed = 0
188
+ this.closedRead = 0
189
+ this.closedWritten = 0
190
+ this.messages = 0
191
+ this.spent = 0
192
+ this.timed = 0
193
+ this.slowest = 0
194
+ }
195
+
196
+ /**
197
+ * Counts a new channel
198
+ * @param context the channel's context
199
+ */
200
+ public override channelActive(context: HandlerContext): Promise<void> {
201
+ this.live.add(context.channel)
202
+ this.opened += 1
203
+
204
+ return context.fireChannelActive()
205
+ }
206
+
207
+ /**
208
+ * Moves a closed channel's bytes into the totals
209
+ * @param context the channel's context
210
+ */
211
+ public override channelInactive(context: HandlerContext): Promise<void> {
212
+ const channel = context.channel
213
+ if (this.live.delete(channel)) {
214
+ this.closed += 1
215
+ this.closedRead += channel.bytesRead
216
+ this.closedWritten += channel.bytesWritten
217
+ }
218
+
219
+ return context.fireChannelInactive()
220
+ }
221
+
222
+ /**
223
+ * Counts the message and times the handlers after this one when asked to
224
+ * @param context the channel's context
225
+ * @param message the message
226
+ */
227
+ public override channelRead(
228
+ context: HandlerContext,
229
+ message: unknown,
230
+ ): Promise<void> {
231
+ this.messages += 1
232
+ if (!this.timing) return context.fireChannelRead(message)
233
+
234
+ const start = performance.now()
235
+ const result = context.fireChannelRead(message)
236
+ if (result === resolved) {
237
+ this.record(start)
238
+ return result
239
+ }
240
+
241
+ return result.finally((): void => {
242
+ this.record(start)
243
+ })
244
+ }
245
+
246
+ /**
247
+ * Reads every counter and starts the next rate window
248
+ */
249
+ public snapshot(): MetricsSnapshot {
250
+ const now = performance.now()
251
+
252
+ let bytesRead = this.closedRead
253
+ let bytesWritten = this.closedWritten
254
+ let pendingBytes = 0
255
+ for (const channel of this.live) {
256
+ bytesRead += channel.bytesRead
257
+ bytesWritten += channel.bytesWritten
258
+ pendingBytes += channel.pendingBytes
259
+ }
260
+
261
+ const elapsed = now - this.last.at
262
+ const seconds = elapsed > 0 ? elapsed / 1000 : 1
263
+ const snapshot: MetricsSnapshot = {
264
+ connections: this.live.size,
265
+ opened: this.opened,
266
+ closed: this.closed,
267
+ bytesRead,
268
+ bytesWritten,
269
+ messagesRead: this.messages,
270
+ pendingBytes,
271
+ elapsed,
272
+ readRate: (bytesRead - this.last.bytesRead) / seconds,
273
+ writeRate: (bytesWritten - this.last.bytesWritten) / seconds,
274
+ messageRate: (this.messages - this.last.messagesRead) / seconds,
275
+ averageTime: this.timed > 0 ? this.spent / this.timed : 0,
276
+ slowestTime: this.slowest,
277
+ }
278
+
279
+ this.last.at = now
280
+ this.last.bytesRead = bytesRead
281
+ this.last.bytesWritten = bytesWritten
282
+ this.last.messagesRead = this.messages
283
+ this.spent = 0
284
+ this.timed = 0
285
+ this.slowest = 0
286
+ return snapshot
287
+ }
288
+
289
+ /**
290
+ * Adds one timed message
291
+ * @param start when it began
292
+ */
293
+ private record(start: number): void {
294
+ const micros = (performance.now() - start) * 1000
295
+
296
+ this.spent += micros
297
+ this.timed += 1
298
+ if (micros > this.slowest) this.slowest = micros
299
+ }
300
+ }
@@ -0,0 +1,141 @@
1
+ import type { HandlerContext } from '../../channel/context/index.ts'
2
+ import { InboundHandlerAdapter } from '../../channel/handler/inbound/index.ts'
3
+ import { resolved } from '../../channel/resolved/index.ts'
4
+ import type { WorkerPool } from '../../worker/pool/index.ts'
5
+
6
+ /**
7
+ * Settings for handing work to a pool
8
+ */
9
+ export type OffloadOptions<I, O> = {
10
+ /**
11
+ * The worker threads that do the work
12
+ */
13
+ readonly pool: WorkerPool<I, O>
14
+
15
+ /**
16
+ * Picks the messages worth sending off, the rest pass straight through
17
+ * @param message whatever came in
18
+ */
19
+ readonly accepts: (message: unknown) => message is I
20
+
21
+ /**
22
+ * Jobs one connection can have running before reads pause, 16 by default
23
+ */
24
+ readonly maxInFlight?: number
25
+ }
26
+
27
+ /**
28
+ * Runs heavy work on worker threads and passes results on in arrival order
29
+ * @class
30
+ */
31
+ export class OffloadHandler<I, O> extends InboundHandlerAdapter {
32
+ /**
33
+ * 16 jobs per connection before we push back on the socket
34
+ */
35
+ public static readonly defaultMaxInFlight: number = 16
36
+
37
+ /**
38
+ * Where the work runs
39
+ */
40
+ private readonly pool: WorkerPool<I, O>
41
+
42
+ /**
43
+ * Which messages go to the pool
44
+ */
45
+ private readonly takes: (message: unknown) => message is I
46
+
47
+ /**
48
+ * Cap on running jobs for this connection
49
+ */
50
+ private readonly maxInFlight: number
51
+
52
+ /**
53
+ * Settles once everything handed on so far has been delivered
54
+ */
55
+ private tail: Promise<void>
56
+
57
+ /**
58
+ * Jobs started and not yet delivered
59
+ */
60
+ private inFlight: number
61
+
62
+ /**
63
+ * Make one per connection, the pool can be shared
64
+ * @param options pool, filter and in-flight cap
65
+ */
66
+ public constructor(options: OffloadOptions<I, O>) {
67
+ super()
68
+
69
+ this.pool = options.pool
70
+ this.takes = options.accepts
71
+ this.maxInFlight = options.maxInFlight ?? OffloadHandler.defaultMaxInFlight
72
+ this.tail = resolved
73
+ this.inFlight = 0
74
+ }
75
+
76
+ /**
77
+ * Starts the job now, delivers its result after everything before it
78
+ * @param context where results go
79
+ * @param message whatever came in
80
+ */
81
+ public override channelRead(
82
+ context: HandlerContext,
83
+ message: unknown,
84
+ ): void | Promise<void> {
85
+ if (!this.takes(message)) {
86
+ return this.after(context, (): Promise<void> =>
87
+ context.fireChannelRead(message),
88
+ )
89
+ }
90
+
91
+ const job = this.pool.run(message)
92
+ this.inFlight += 1
93
+ const delivered = this.after(context, async (): Promise<void> => {
94
+ try {
95
+ await context.fireChannelRead(await job)
96
+ } finally {
97
+ this.inFlight -= 1
98
+ }
99
+ })
100
+ return this.inFlight >= this.maxInFlight ? delivered : undefined
101
+ }
102
+
103
+ /**
104
+ * Lines up behind pending results so a flush here covers them, without blocking reads
105
+ * @param context where to pass it
106
+ */
107
+ public override channelReadComplete(context: HandlerContext): void {
108
+ void this.after(context, (): Promise<void> =>
109
+ context.fireChannelReadComplete(),
110
+ )
111
+ }
112
+
113
+ /**
114
+ * Delivers what's pending before passing deactivation on
115
+ * @param context where to pass it
116
+ */
117
+ public override channelInactive(context: HandlerContext): Promise<void> {
118
+ return this.after(context, (): Promise<void> =>
119
+ context.fireChannelInactive(),
120
+ )
121
+ }
122
+
123
+ /**
124
+ * Queues a step behind everything already handed on, errors go to the pipeline
125
+ * @param context where errors get reported
126
+ * @param step what to run once it's this step's turn
127
+ */
128
+ private after(
129
+ context: HandlerContext,
130
+ step: () => Promise<void>,
131
+ ): Promise<void> {
132
+ const next = this.tail
133
+ .then(step)
134
+ .catch((error: unknown): Promise<void> =>
135
+ context.fireExceptionCaught(error),
136
+ )
137
+
138
+ this.tail = next
139
+ return next
140
+ }
141
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Thrown down the pipeline when the peer goes quiet for too long
3
+ * @class
4
+ */
5
+ export class ReadTimeoutError extends Error {
6
+ /**
7
+ * Fixed message and name, nothing to configure
8
+ */
9
+ public constructor() {
10
+ super('Read timed out')
11
+
12
+ this.name = 'ReadTimeoutError'
13
+ }
14
+ }
15
+
16
+ /**
17
+ * Thrown down the pipeline when a write hangs past its deadline
18
+ * @class
19
+ */
20
+ export class WriteTimeoutError extends Error {
21
+ /**
22
+ * Same deal as the read one, fixed message and name
23
+ */
24
+ public constructor() {
25
+ super('Write timed out')
26
+
27
+ this.name = 'WriteTimeoutError'
28
+ }
29
+ }
@@ -0,0 +1,3 @@
1
+ export { ReadTimeoutError, WriteTimeoutError } from './error/index.ts'
2
+ export { ReadTimeoutHandler } from './read/index.ts'
3
+ export { WriteTimeoutHandler } from './write/index.ts'
@@ -0,0 +1,44 @@
1
+ import { IdleStateHandler, type IdleStateEvent } from '../../idle/index.ts'
2
+ import { ReadTimeoutError } from '../error/index.ts'
3
+ import type { HandlerContext } from '../../../channel/context/index.ts'
4
+
5
+ /**
6
+ * Raises an error and closes the channel when nothing is read in time
7
+ * @class
8
+ */
9
+ export class ReadTimeoutHandler extends IdleStateHandler {
10
+ /**
11
+ * Set after the first timeout so we only raise it once
12
+ */
13
+ private fired: boolean
14
+
15
+ /**
16
+ * Throws a RangeError unless the timeout is a positive finite number
17
+ * @param timeout how long reads can stay quiet, in ms
18
+ */
19
+ public constructor(timeout: number) {
20
+ if (!Number.isFinite(timeout) || timeout <= 0) {
21
+ throw new RangeError('Timeout is invalid')
22
+ }
23
+
24
+ super({ readerIdle: timeout })
25
+
26
+ this.fired = false
27
+ }
28
+
29
+ /**
30
+ * Fires a ReadTimeoutError then closes, ignoring writer idleness
31
+ * @param context where the error gets fired from
32
+ * @param event which side went idle
33
+ */
34
+ protected override async channelIdle(
35
+ context: HandlerContext,
36
+ event: IdleStateEvent,
37
+ ): Promise<void> {
38
+ if (this.fired || event.state !== 'reader') return
39
+ this.fired = true
40
+
41
+ await context.fireExceptionCaught(new ReadTimeoutError())
42
+ await context.close()
43
+ }
44
+ }
@@ -0,0 +1,89 @@
1
+ import { OutboundHandlerAdapter } from '../../../channel/handler/outbound/index.ts'
2
+ import { WriteTimeoutError } from '../error/index.ts'
3
+ import type { HandlerContext } from '../../../channel/context/index.ts'
4
+
5
+ /**
6
+ * Raises an error and closes the channel when a write takes too long
7
+ * @class
8
+ */
9
+ export class WriteTimeoutHandler extends OutboundHandlerAdapter {
10
+ /**
11
+ * How long each write gets, in ms
12
+ */
13
+ private readonly timeout: number
14
+
15
+ /**
16
+ * One timer per write still in flight
17
+ */
18
+ private readonly timers: Set<Timer>
19
+
20
+ /**
21
+ * Set after the first timeout so we only raise it once
22
+ */
23
+ private fired: boolean
24
+
25
+ /**
26
+ * Throws a RangeError unless the timeout is a positive finite number
27
+ * @param timeout how long a single write can take, in ms
28
+ */
29
+ public constructor(timeout: number) {
30
+ super()
31
+
32
+ if (!Number.isFinite(timeout) || timeout <= 0) {
33
+ throw new RangeError('Timeout is invalid')
34
+ }
35
+
36
+ this.timeout = timeout
37
+ this.timers = new Set<Timer>()
38
+ this.fired = false
39
+ }
40
+
41
+ /**
42
+ * Starts a timer that's cleared when the write settles
43
+ * @param context where the write gets passed on
44
+ * @param message what to send
45
+ */
46
+ public override write(
47
+ context: HandlerContext,
48
+ message: unknown,
49
+ ): Promise<void> {
50
+ const promise = context.write(message)
51
+
52
+ const timer = setTimeout((): void => {
53
+ this.timers.delete(timer)
54
+ this.expire(context)
55
+ }, this.timeout)
56
+ timer.unref()
57
+ this.timers.add(timer)
58
+
59
+ void promise
60
+ .finally((): void => {
61
+ clearTimeout(timer)
62
+ this.timers.delete(timer)
63
+ })
64
+ .catch((): undefined => undefined)
65
+ return promise
66
+ }
67
+
68
+ /**
69
+ * Clears any timers left so they can't fire after we're gone
70
+ */
71
+ public handlerRemoved(): void {
72
+ for (const timer of this.timers) clearTimeout(timer)
73
+ this.timers.clear()
74
+ }
75
+
76
+ /**
77
+ * Fires a WriteTimeoutError on the channel's executor, then closes
78
+ * @param context the context the slow write went through
79
+ */
80
+ private expire(context: HandlerContext): void {
81
+ if (this.fired) return
82
+ this.fired = true
83
+
84
+ void context.channel.execute(async (): Promise<void> => {
85
+ await context.fireExceptionCaught(new WriteTimeoutError())
86
+ await context.close()
87
+ })
88
+ }
89
+ }