@netifyjs/netify 1.0.0-alpha.4 → 1.0.0-alpha.6

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 +230 -89
  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
@@ -1,5 +1,4 @@
1
1
  import { ByteBuf } from '../../buffer/index.ts'
2
- import { ChannelGroup } from '../../channel/group/index.ts'
3
2
  import type { Channel } from '../../channel/index.ts'
4
3
  import type { ShardLink } from '../link/index.ts'
5
4
 
@@ -26,7 +25,12 @@ export class Gateway {
26
25
  /**
27
26
  * This shard's subscribers, by topic
28
27
  */
29
- private readonly groups: Map<string, ChannelGroup>
28
+ private readonly topics: Map<string, Set<Channel>>
29
+
30
+ /**
31
+ * Topics each open channel is on
32
+ */
33
+ private readonly channels: Map<Channel, Set<string>>
30
34
 
31
35
  /**
32
36
  * Channels written to since the last flush
@@ -39,18 +43,29 @@ export class Gateway {
39
43
  private readonly flusher: () => void
40
44
 
41
45
  /**
42
- * Starts listening for publishes from other shards
46
+ * Closed yet
47
+ */
48
+ private closed: boolean
49
+
50
+ /**
51
+ * Listens for publishes from other shards
43
52
  * @param link the shard's link
44
53
  */
45
54
  public constructor(link: ShardLink) {
55
+ if (link.listens(Gateway.topic)) {
56
+ throw new Error('Link already has a gateway')
57
+ }
58
+
46
59
  this.link = link
47
- this.groups = new Map<string, ChannelGroup>()
60
+ this.topics = new Map<string, Set<Channel>>()
61
+ this.channels = new Map<Channel, Set<string>>()
48
62
  this.touched = new Set<Channel>()
49
63
  this.flusher = (): void => {
50
- for (const channel of this.touched) void channel.flush()
64
+ for (const channel of this.touched) channel.flushEncoded()
51
65
  this.touched.clear()
52
66
  }
53
67
 
68
+ this.closed = false
54
69
  link.on(Gateway.topic, (data: unknown): void => {
55
70
  const [topic, bytes] = data as Publication
56
71
  this.deliver(topic, bytes)
@@ -63,13 +78,18 @@ export class Gateway {
63
78
  * @param topic any name, like a zone id
64
79
  */
65
80
  public subscribe(channel: Channel, topic: string): void {
66
- let group = this.groups.get(topic)
67
- if (group === undefined) {
68
- group = new ChannelGroup()
69
- this.groups.set(topic, group)
81
+ const joined = this.channels.get(channel) ?? this.watch(channel)
82
+ if (joined.has(topic)) return
83
+
84
+ joined.add(topic)
85
+
86
+ const members = this.topics.get(topic)
87
+ if (members === undefined) {
88
+ this.topics.set(topic, new Set<Channel>([channel]))
89
+ return
70
90
  }
71
91
 
72
- group.add(channel)
92
+ members.add(channel)
73
93
  }
74
94
 
75
95
  /**
@@ -78,11 +98,9 @@ export class Gateway {
78
98
  * @param topic the topic
79
99
  */
80
100
  public unsubscribe(channel: Channel, topic: string): boolean {
81
- const group = this.groups.get(topic)
82
- if (group === undefined) return false
101
+ const removed = this.channels.get(channel)?.delete(topic) ?? false
102
+ if (removed) this.leave(channel, topic)
83
103
 
84
- const removed = group.remove(channel)
85
- if (group.size === 0) this.groups.delete(topic)
86
104
  return removed
87
105
  }
88
106
 
@@ -92,7 +110,7 @@ export class Gateway {
92
110
  * @param topic the topic
93
111
  */
94
112
  public isSubscribed(channel: Channel, topic: string): boolean {
95
- return this.groups.get(topic)?.has(channel) ?? false
113
+ return this.channels.get(channel)?.has(topic) ?? false
96
114
  }
97
115
 
98
116
  /**
@@ -100,42 +118,97 @@ export class Gateway {
100
118
  * @param topic the topic
101
119
  */
102
120
  public subscriberCount(topic: string): number {
103
- return this.groups.get(topic)?.size ?? 0
121
+ return this.topics.get(topic)?.size ?? 0
104
122
  }
105
123
 
106
124
  /**
107
- * Sends encoded bytes to subscribers everywhere
125
+ * Topics with a local channel on them
126
+ */
127
+ public get topicCount(): number {
128
+ return this.topics.size
129
+ }
130
+
131
+ /**
132
+ * Copies the bytes to every local subscriber
108
133
  * @param topic the topic
109
134
  * @param bytes a whole frame, skipping the pipelines
110
135
  */
111
136
  public publish(topic: string, bytes: Uint8Array | ByteBuf): number {
112
- const shared = bytes instanceof ByteBuf ? bytes.toUint8Array() : bytes
137
+ const shared = new Uint8Array(
138
+ bytes instanceof ByteBuf ? bytes.toUint8Array() : bytes,
139
+ )
113
140
 
114
- this.link.broadcast(Gateway.topic, [topic, shared])
141
+ if (this.link.isOpen) this.link.broadcast(Gateway.topic, [topic, shared])
115
142
  return this.deliver(topic, shared)
116
143
  }
117
144
 
118
145
  /**
119
- * Writes to this shard's subscribers and forgets topics nobody's on
146
+ * Stops listening and frees the link
147
+ */
148
+ public close(): void {
149
+ if (this.closed) return
150
+ this.closed = true
151
+
152
+ this.link.off(Gateway.topic)
153
+ this.topics.clear()
154
+ this.channels.clear()
155
+ }
156
+
157
+ /**
158
+ * Starts tracking a channel
159
+ * @param channel a connection on this shard
160
+ */
161
+ private watch(channel: Channel): Set<string> {
162
+ const joined = new Set<string>()
163
+ this.channels.set(channel, joined)
164
+
165
+ void channel.closed.then((): void => {
166
+ this.forget(channel)
167
+ })
168
+ return joined
169
+ }
170
+
171
+ /**
172
+ * Takes a closed channel off everything
173
+ * @param channel just closed
174
+ */
175
+ private forget(channel: Channel): void {
176
+ const joined = this.channels.get(channel)
177
+ if (joined === undefined) return
178
+
179
+ this.channels.delete(channel)
180
+ for (const topic of joined) this.leave(channel, topic)
181
+ }
182
+
183
+ /**
184
+ * Takes a member off a topic
185
+ * @param channel who's leaving
186
+ * @param topic what it leaves
187
+ */
188
+ private leave(channel: Channel, topic: string): void {
189
+ const members = this.topics.get(topic)
190
+ if (members === undefined) return
191
+
192
+ members.delete(channel)
193
+ if (members.size === 0) this.topics.delete(topic)
194
+ }
195
+
196
+ /**
197
+ * Writes to this shard's subscribers
120
198
  * @param topic the topic
121
199
  * @param bytes the frame
122
200
  */
123
201
  private deliver(topic: string, bytes: Uint8Array): number {
124
- const group = this.groups.get(topic)
125
- if (group === undefined) return 0
126
-
127
- if (group.size === 0) {
128
- this.groups.delete(topic)
129
- return 0
130
- }
202
+ const members = this.topics.get(topic)
203
+ if (members === undefined) return 0
131
204
 
132
205
  if (this.touched.size === 0) queueMicrotask(this.flusher)
133
206
 
134
- for (const channel of group) {
207
+ for (const channel of members) {
135
208
  channel.writeEncodedSync(bytes)
136
209
  this.touched.add(channel)
137
210
  }
138
211
 
139
- return group.size
212
+ return members.size
140
213
  }
141
214
  }
@@ -384,6 +384,21 @@ export class ShardLink {
384
384
  return this
385
385
  }
386
386
 
387
+ /**
388
+ * False after close
389
+ */
390
+ public get isOpen(): boolean {
391
+ return !this.closed
392
+ }
393
+
394
+ /**
395
+ * Whether a topic has a listener
396
+ * @param topic name to look up
397
+ */
398
+ public listens(topic: string): boolean {
399
+ return this.listeners.has(topic)
400
+ }
401
+
387
402
  /**
388
403
  * Stops listening on a topic
389
404
  * @param topic the topic
@@ -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
  }