@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
@@ -1,4 +1,5 @@
1
1
  import { Cluster } from '../../cluster/index.ts'
2
+ import { type Logger, ConsoleLogger } from '../../logger/index.ts'
2
3
 
3
4
  /**
4
5
  * Settings for a group of server threads
@@ -28,6 +29,21 @@ export type WorkerGroupOptions = {
28
29
  * Extra arguments, they show up at the end of Bun.argv in each thread
29
30
  */
30
31
  readonly argv?: readonly string[]
32
+
33
+ /**
34
+ * Restarts dead threads
35
+ */
36
+ readonly restart?: boolean
37
+
38
+ /**
39
+ * Milliseconds a stopping thread gets
40
+ */
41
+ readonly stopTimeout?: number
42
+
43
+ /**
44
+ * Told about dead threads
45
+ */
46
+ readonly logger?: Logger
31
47
  }
32
48
 
33
49
  /**
@@ -50,6 +66,31 @@ type SharedMessage = {
50
66
  * @class
51
67
  */
52
68
  export class WorkerGroup {
69
+ /**
70
+ * Tells a thread to stop
71
+ */
72
+ private static readonly stopMessage: string = 'netify:stop'
73
+
74
+ /**
75
+ * Sent by a thread with a stop callback
76
+ */
77
+ private static readonly stoppableMessage: string = 'netify:stoppable'
78
+
79
+ /**
80
+ * A thread that lives this long counts as started
81
+ */
82
+ private static readonly stableAfter: number = 10_000
83
+
84
+ /**
85
+ * Wait before the second quick restart
86
+ */
87
+ private static readonly firstBackoff: number = 250
88
+
89
+ /**
90
+ * Longest wait between restarts
91
+ */
92
+ private static readonly maxBackoff: number = 10_000
93
+
53
94
  /**
54
95
  * Script, size and shared memory
55
96
  */
@@ -61,23 +102,73 @@ export class WorkerGroup {
61
102
  private readonly count: number
62
103
 
63
104
  /**
64
- * The running threads
105
+ * Hears about dead threads
106
+ */
107
+ private readonly logger: Logger
108
+
109
+ /**
110
+ * Thread in each slot, or null
111
+ */
112
+ private readonly threads: (Worker | null)[]
113
+
114
+ /**
115
+ * When the thread in each slot started
116
+ */
117
+ private readonly births: number[]
118
+
119
+ /**
120
+ * Quick deaths in a row, per slot
65
121
  */
66
- private readonly threads: Worker[]
122
+ private readonly crashes: number[]
67
123
 
68
124
  /**
69
- * Checks the size, nothing starts until start
125
+ * Pending restart timers, per slot
126
+ */
127
+ private readonly pending: (Timer | null)[]
128
+
129
+ /**
130
+ * Threads with a stop callback
131
+ */
132
+ private readonly stoppable: Set<Worker>
133
+
134
+ /**
135
+ * True between start and stop
136
+ */
137
+ private running: boolean
138
+
139
+ /**
140
+ * Sets up an idle group
70
141
  * @param options script, size and shared memory
71
142
  */
72
143
  public constructor(options: WorkerGroupOptions) {
144
+ const reason = WorkerGroup.refusal(options)
145
+ if (reason !== null) throw new RangeError(reason)
146
+
147
+ this.options = options
148
+ this.count = options.workers ?? navigator.hardwareConcurrency
149
+ this.logger = options.logger ?? new ConsoleLogger()
150
+ this.threads = Array.from({ length: this.count }, (): null => null)
151
+ this.births = Array.from({ length: this.count }, (): number => 0)
152
+ this.crashes = Array.from({ length: this.count }, (): number => 0)
153
+ this.pending = Array.from({ length: this.count }, (): null => null)
154
+ this.stoppable = new Set<Worker>()
155
+ this.running = false
156
+ }
157
+
158
+ /**
159
+ * Why the options are bad, or null
160
+ * @param options group settings
161
+ */
162
+ private static refusal(options: WorkerGroupOptions): string | null {
73
163
  const count = options.workers ?? navigator.hardwareConcurrency
74
- if (!Number.isInteger(count) || count < 1) {
75
- throw new RangeError('Worker count is invalid')
164
+ if (!Number.isInteger(count) || count < 1) return 'Worker count is invalid'
165
+
166
+ const timeout = options.stopTimeout
167
+ if (timeout !== undefined && (!Number.isFinite(timeout) || timeout < 0)) {
168
+ return 'Timeout is invalid'
76
169
  }
77
170
 
78
- this.options = options
79
- this.count = count
80
- this.threads = []
171
+ return null
81
172
  }
82
173
 
83
174
  /**
@@ -95,6 +186,30 @@ export class WorkerGroup {
95
186
  return promise
96
187
  }
97
188
 
189
+ /**
190
+ * Runs a callback before this thread stops
191
+ * @param callback cleanup to run
192
+ */
193
+ public static onStop(callback: () => void | Promise<void>): void {
194
+ const listener = (event: MessageEvent<unknown>): void => {
195
+ if (event.data !== WorkerGroup.stopMessage) return
196
+ removeEventListener('message', listener)
197
+ void Promise.resolve()
198
+ .then(callback)
199
+ .then(
200
+ (): void => {
201
+ process.exit(0)
202
+ },
203
+ (err: unknown): void => {
204
+ new ConsoleLogger().warn({ err }, 'Stop callback failed')
205
+ process.exit(1)
206
+ },
207
+ )
208
+ }
209
+ addEventListener('message', listener)
210
+ postMessage(WorkerGroup.stoppableMessage)
211
+ }
212
+
98
213
  /**
99
214
  * Tells our shared memory message apart from the script's own messages
100
215
  * @param data whatever the thread was sent
@@ -119,10 +234,11 @@ export class WorkerGroup {
119
234
  * Starts every thread
120
235
  */
121
236
  public start(): this {
122
- if (this.threads.length > 0) return this
237
+ if (this.running) return this
238
+ this.running = true
123
239
 
124
240
  for (let index = 0; index < this.count; index++) {
125
- this.threads.push(this.spawn(index))
241
+ this.threads[index] = this.spawn(index)
126
242
  }
127
243
 
128
244
  return this
@@ -131,10 +247,22 @@ export class WorkerGroup {
131
247
  /**
132
248
  * Stops every thread
133
249
  */
134
- public stop(): Promise<void> {
135
- for (const thread of this.threads.splice(0)) thread.terminate()
250
+ public async stop(): Promise<void> {
251
+ this.running = false
136
252
 
137
- return Promise.resolve()
253
+ for (const timer of this.pending) {
254
+ if (timer !== null) clearTimeout(timer)
255
+ }
256
+
257
+ this.pending.fill(null)
258
+
259
+ const threads = this.threads.filter(
260
+ (thread: Worker | null): thread is Worker => thread !== null,
261
+ )
262
+ this.threads.fill(null)
263
+ await Promise.all(
264
+ threads.map((thread: Worker): Promise<void> => this.retire(thread)),
265
+ )
138
266
  }
139
267
 
140
268
  /**
@@ -162,6 +290,19 @@ export class WorkerGroup {
162
290
  */
163
291
  argv: [...(this.options.argv ?? [])],
164
292
  })
293
+ thread.addEventListener('message', (event: MessageEvent<unknown>): void => {
294
+ if (event.data === WorkerGroup.stoppableMessage) {
295
+ this.stoppable.add(thread)
296
+ }
297
+ })
298
+ thread.addEventListener('error', (event: ErrorEvent): void => {
299
+ const err: unknown = event.error ?? new Error(event.message)
300
+ this.died(index, thread, err)
301
+ })
302
+ thread.addEventListener('close', (): void => {
303
+ this.died(index, thread, null)
304
+ })
305
+
165
306
  if (this.options.shared !== undefined) {
166
307
  const message: SharedMessage = {
167
308
  kind: 'netify:shared',
@@ -170,6 +311,83 @@ export class WorkerGroup {
170
311
  thread.postMessage(message)
171
312
  }
172
313
 
314
+ this.births[index] = performance.now()
173
315
  return thread
174
316
  }
317
+
318
+ /**
319
+ * Reports a dead thread and refills its slot
320
+ * @param index the thread's id
321
+ * @param thread the one that died
322
+ * @param err what killed it, or null
323
+ */
324
+ private died(index: number, thread: Worker, err: unknown): void {
325
+ this.stoppable.delete(thread)
326
+ if (this.threads[index] !== thread) return
327
+ this.threads[index] = null
328
+ thread.terminate()
329
+
330
+ if (err === null) this.logger.warn({ worker: index }, 'Worker exited')
331
+ else this.logger.warn({ err, worker: index }, 'Worker failed')
332
+
333
+ if (!this.running || this.options.restart === false) return
334
+ this.restart(index, performance.now() - (this.births[index] ?? 0))
335
+ }
336
+
337
+ /**
338
+ * Restarts a slot's thread
339
+ * @param index the slot
340
+ * @param lived ms the thread ran for
341
+ */
342
+ private restart(index: number, lived: number): void {
343
+ const crashes =
344
+ lived < WorkerGroup.stableAfter ? (this.crashes[index] ?? 0) + 1 : 1
345
+ this.crashes[index] = crashes
346
+
347
+ const delay =
348
+ crashes <= 1
349
+ ? 0
350
+ : Math.min(
351
+ WorkerGroup.maxBackoff,
352
+ WorkerGroup.firstBackoff * 2 ** (crashes - 2),
353
+ )
354
+ if (delay === 0) {
355
+ this.threads[index] = this.spawn(index)
356
+ return
357
+ }
358
+
359
+ const timer = setTimeout((): void => {
360
+ this.pending[index] = null
361
+ if (this.running && this.threads[index] === null) {
362
+ this.threads[index] = this.spawn(index)
363
+ }
364
+ }, delay)
365
+ timer.unref()
366
+ this.pending[index] = timer
367
+ }
368
+
369
+ /**
370
+ * Asks a thread to stop
371
+ * @param thread one to stop
372
+ */
373
+ private async retire(thread: Worker): Promise<void> {
374
+ if (!this.stoppable.has(thread)) {
375
+ thread.terminate()
376
+ return
377
+ }
378
+
379
+ const gone = Promise.withResolvers<undefined>()
380
+ thread.addEventListener('close', (): void => {
381
+ gone.resolve(undefined)
382
+ })
383
+ const timer = setTimeout((): void => {
384
+ thread.terminate()
385
+ gone.resolve(undefined)
386
+ }, this.options.stopTimeout ?? 10000)
387
+
388
+ thread.postMessage(WorkerGroup.stopMessage)
389
+ await gone.promise
390
+ clearTimeout(timer)
391
+ this.stoppable.delete(thread)
392
+ }
175
393
  }
@@ -81,9 +81,34 @@ export class WorkerPool<I, O> {
81
81
  public static readonly defaultMaxQueued: number = 1024
82
82
 
83
83
  /**
84
- * The threads
84
+ * Wait before a thread's second quick restart
85
85
  */
86
- private readonly workers: Worker[]
86
+ private static readonly firstBackoff: number = 250
87
+
88
+ /**
89
+ * Longest wait between restarts
90
+ */
91
+ private static readonly maxBackoff: number = 10_000
92
+
93
+ /**
94
+ * What each thread runs
95
+ */
96
+ private readonly script: string | URL
97
+
98
+ /**
99
+ * Each thread, or null
100
+ */
101
+ private readonly workers: (Worker | null)[]
102
+
103
+ /**
104
+ * Deaths in a row, per thread
105
+ */
106
+ private readonly failures: number[]
107
+
108
+ /**
109
+ * Pending restart timers, per thread
110
+ */
111
+ private readonly pending: (Timer | null)[]
87
112
 
88
113
  /**
89
114
  * Jobs in flight per worker
@@ -124,10 +149,13 @@ export class WorkerPool<I, O> {
124
149
  this.jobs = new Map<number, Job<O>>()
125
150
  this.nextId = 1
126
151
  this.closed = false
152
+ this.script = options.script
127
153
  this.load = Array.from({ length: count }, (): number => 0)
154
+ this.failures = Array.from({ length: count }, (): number => 0)
155
+ this.pending = Array.from({ length: count }, (): null => null)
128
156
  this.workers = Array.from(
129
157
  { length: count },
130
- (_: unknown, index: number): Worker => this.spawn(options.script, index),
158
+ (_: unknown, index: number): Worker => this.spawn(index),
131
159
  )
132
160
  }
133
161
 
@@ -150,12 +178,19 @@ export class WorkerPool<I, O> {
150
178
  }
151
179
 
152
180
  const worker = this.leastBusy()
153
- const id = this.nextId++
181
+ const thread = this.workers[worker] ?? null
182
+ if (thread === null) return Promise.reject(new Error('Pool has no workers'))
183
+
184
+ const request: WorkerRequest<I> = { id: this.nextId++, input }
185
+ try {
186
+ thread.postMessage(request, [...transfer])
187
+ } catch (cause) {
188
+ return Promise.reject(new Error('Input is invalid', { cause }))
189
+ }
190
+
154
191
  const job: Job<O> = { result: Promise.withResolvers<O>(), worker }
155
- this.jobs.set(id, job)
192
+ this.jobs.set(request.id, job)
156
193
  this.load[worker] = (this.load[worker] ?? 0) + 1
157
- const request: WorkerRequest<I> = { id, input }
158
- this.workers[worker]?.postMessage(request, [...transfer])
159
194
  return job.result.promise
160
195
  }
161
196
 
@@ -165,7 +200,12 @@ export class WorkerPool<I, O> {
165
200
  public close(): Promise<void> {
166
201
  this.closed = true
167
202
 
168
- for (const worker of this.workers) worker.terminate()
203
+ for (const timer of this.pending) {
204
+ if (timer !== null) clearTimeout(timer)
205
+ }
206
+
207
+ this.pending.fill(null)
208
+ for (const worker of this.workers) worker?.terminate()
169
209
  for (const job of this.jobs.values()) {
170
210
  job.result.reject(new Error('Pool is closed'))
171
211
  }
@@ -176,21 +216,58 @@ export class WorkerPool<I, O> {
176
216
 
177
217
  /**
178
218
  * Starts one thread and wires up its replies
179
- * @param script what the thread runs
180
219
  * @param index its slot in the pool
181
220
  */
182
- private spawn(script: string | URL, index: number): Worker {
183
- const worker = new Worker(script)
221
+ private spawn(index: number): Worker {
222
+ const worker = new Worker(this.script)
184
223
 
185
224
  worker.onmessage = (event: MessageEvent<WorkerReply<O>>): void => {
186
225
  this.settle(event.data)
187
226
  }
188
227
  worker.onerror = (event: ErrorEvent): void => {
189
- this.failWorker(index, new Error('Worker failed', { cause: event.error }))
228
+ const cause: unknown = event.error ?? new Error(event.message)
229
+ this.replace(index, worker, new Error('Worker failed', { cause }))
190
230
  }
231
+ worker.addEventListener('close', (): void => {
232
+ this.replace(index, worker, new Error('Worker failed'))
233
+ })
191
234
  return worker
192
235
  }
193
236
 
237
+ /**
238
+ * Swaps a dead thread for a new one
239
+ * @param index the thread's slot
240
+ * @param worker the thread that died
241
+ * @param error why it failed
242
+ */
243
+ private replace(index: number, worker: Worker, error: Error): void {
244
+ if (this.closed || this.workers[index] !== worker) return
245
+ this.workers[index] = null
246
+ worker.terminate()
247
+ this.fail(index, error)
248
+
249
+ const failures = (this.failures[index] ?? 0) + 1
250
+ this.failures[index] = failures
251
+ const delay =
252
+ failures <= 1
253
+ ? 0
254
+ : Math.min(
255
+ WorkerPool.maxBackoff,
256
+ WorkerPool.firstBackoff * 2 ** (failures - 2),
257
+ )
258
+ if (delay === 0) {
259
+ this.workers[index] = this.spawn(index)
260
+ return
261
+ }
262
+
263
+ const timer = setTimeout((): void => {
264
+ this.pending[index] = null
265
+ this.workers[index] = this.spawn(index)
266
+ }, delay)
267
+ timer.unref()
268
+ this.pending[index] = timer
269
+ }
270
+
194
271
  /**
195
272
  * Resolves or rejects the job a reply belongs to
196
273
  * @param reply what the worker sent
@@ -200,17 +277,18 @@ export class WorkerPool<I, O> {
200
277
  if (job === undefined) return
201
278
  this.jobs.delete(reply.id)
202
279
  this.load[job.worker] = (this.load[job.worker] ?? 1) - 1
280
+ this.failures[job.worker] = 0
203
281
 
204
282
  if (reply.error !== undefined) job.result.reject(new Error(reply.error))
205
283
  else job.result.resolve(reply.output as O)
206
284
  }
207
285
 
208
286
  /**
209
- * Fails every job a crashed worker had
210
- * @param index the worker's slot
287
+ * Fails every job a dead thread had
288
+ * @param index the thread's slot
211
289
  * @param error why it failed
212
290
  */
213
- private failWorker(index: number, error: Error): void {
291
+ private fail(index: number, error: Error): void {
214
292
  for (const [id, job] of this.jobs) {
215
293
  if (job.worker !== index) continue
216
294
  this.jobs.delete(id)
@@ -221,13 +299,16 @@ export class WorkerPool<I, O> {
221
299
  }
222
300
 
223
301
  /**
224
- * Slot of the worker with the fewest jobs
302
+ * Slot of the live thread with the fewest jobs, or -1
225
303
  */
226
304
  private leastBusy(): number {
227
- let best = 0
305
+ let best = -1
228
306
 
229
- for (let index = 1; index < this.load.length; index++) {
230
- if ((this.load[index] ?? 0) < (this.load[best] ?? 0)) best = index
307
+ for (let index = 0; index < this.load.length; index++) {
308
+ if (this.workers[index] === null) continue
309
+ if (best < 0 || (this.load[index] ?? 0) < (this.load[best] ?? 0)) {
310
+ best = index
311
+ }
231
312
  }
232
313
 
233
314
  return best
@@ -50,6 +50,14 @@ export class WorkerService<I, O> {
50
50
  }
51
51
  }
52
52
 
53
- postMessage(reply)
53
+ try {
54
+ postMessage(reply)
55
+ } catch {
56
+ const refusal: WorkerReply<O> = {
57
+ id: request.id,
58
+ error: 'Output is invalid',
59
+ }
60
+ postMessage(refusal)
61
+ }
54
62
  }
55
63
  }