@netifyjs/netify 1.0.0-alpha.1 → 1.0.0-alpha.3

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.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@netifyjs/netify",
3
3
  "description": "A Netty-inspired networking framework for Bun, for TCP, UDP, reliable UDP and WebSocket game servers",
4
- "version": "1.0.0-alpha.1",
4
+ "version": "1.0.0-alpha.3",
5
5
  "type": "module",
6
6
  "exports": {
7
7
  ".": "./src/index.ts"
@@ -413,6 +413,18 @@ export class Channel {
413
413
  )
414
414
  }
415
415
 
416
+ /**
417
+ * Queues encoded bytes without a flush or a promise
418
+ * @param bytes already encoded, nothing in the pipeline touches them
419
+ */
420
+ public writeEncodedSync(bytes: Uint8Array | ByteBuf): void {
421
+ void this.outbound.add(
422
+ bytes instanceof ByteBuf ? bytes.toUint8Array() : bytes,
423
+ null,
424
+ true,
425
+ )
426
+ }
427
+
416
428
  /**
417
429
  * Fire-and-forget version of writeAndFlushEncoded, no promise is made
418
430
  * @param bytes already encoded, nothing in the pipeline touches them
@@ -73,6 +73,21 @@ export class Cluster {
73
73
  */
74
74
  private static readonly readyMessage: string = 'netify:ready'
75
75
 
76
+ /**
77
+ * A worker that never calls ready counts as started after this long
78
+ */
79
+ private static readonly stableAfter: number = 10_000
80
+
81
+ /**
82
+ * Wait before the second quick restart
83
+ */
84
+ private static readonly firstBackoff: number = 250
85
+
86
+ /**
87
+ * Longest wait between restarts
88
+ */
89
+ private static readonly maxBackoff: number = 10_000
90
+
76
91
  /**
77
92
  * Kept for respawning workers later
78
93
  */
@@ -98,6 +113,21 @@ export class Cluster {
98
113
  */
99
114
  private readonly readiness: Map<Worker, PromiseWithResolvers<boolean>>
100
115
 
116
+ /**
117
+ * When each worker started, until it says it's ready
118
+ */
119
+ private readonly births: Map<Worker, number>
120
+
121
+ /**
122
+ * Quick crashes in a row, per slot
123
+ */
124
+ private readonly crashes: number[]
125
+
126
+ /**
127
+ * Restarts waiting out their backoff, per slot
128
+ */
129
+ private readonly pending: (Timer | null)[]
130
+
101
131
  /**
102
132
  * Cleared by stop so exiting workers aren't brought back
103
133
  */
@@ -116,6 +146,9 @@ export class Cluster {
116
146
  this.name = crypto.randomUUID().slice(0, 8)
117
147
  this.processes = Array.from({ length: this.count }, (): null => null)
118
148
  this.readiness = new Map<Worker, PromiseWithResolvers<boolean>>()
149
+ this.births = new Map<Worker, number>()
150
+ this.crashes = Array.from({ length: this.count }, (): number => 0)
151
+ this.pending = Array.from({ length: this.count }, (): null => null)
119
152
  this.running = false
120
153
  }
121
154
 
@@ -232,6 +265,12 @@ export class Cluster {
232
265
  public async stop(): Promise<void> {
233
266
  this.running = false
234
267
 
268
+ for (const timer of this.pending) {
269
+ if (timer !== null) clearTimeout(timer)
270
+ }
271
+
272
+ this.pending.fill(null)
273
+
235
274
  const children = this.processes.filter(
236
275
  (child: Worker | null): child is Worker => child !== null,
237
276
  )
@@ -304,6 +343,8 @@ export class Cluster {
304
343
  ipc: (message: unknown): void => {
305
344
  if (message === Cluster.readyMessage) {
306
345
  this.readiness.get(child)?.resolve(true)
346
+ this.births.delete(child)
347
+ this.crashes[index] = 0
307
348
  }
308
349
  },
309
350
  /**
@@ -312,18 +353,54 @@ export class Cluster {
312
353
  onExit: (): void => {
313
354
  this.readiness.get(child)?.resolve(false)
314
355
  this.readiness.delete(child)
356
+ const born = this.births.get(child)
357
+ this.births.delete(child)
315
358
  if (this.processes[index] !== child) return
316
359
  this.processes[index] = null
317
360
  if (this.running && this.options.restart !== false) {
318
- this.processes[index] = this.spawn(index)
361
+ this.restart(
362
+ index,
363
+ born === undefined ? Infinity : performance.now() - born,
364
+ )
319
365
  }
320
366
  },
321
367
  })
322
368
 
323
369
  this.readiness.set(child, Promise.withResolvers<boolean>())
370
+ this.births.set(child, performance.now())
324
371
  return child
325
372
  }
326
373
 
374
+ /**
375
+ * Brings a crashed worker back, waiting longer each time it dies before it's ready
376
+ * @param index the slot
377
+ * @param lived ms the worker ran for
378
+ */
379
+ private restart(index: number, lived: number): void {
380
+ const crashes =
381
+ lived < Cluster.stableAfter ? (this.crashes[index] ?? 0) + 1 : 1
382
+ this.crashes[index] = crashes
383
+
384
+ const delay =
385
+ crashes <= 1
386
+ ? 0
387
+ : Math.min(
388
+ Cluster.maxBackoff,
389
+ Cluster.firstBackoff * 2 ** (crashes - 2),
390
+ )
391
+ if (delay === 0) {
392
+ this.processes[index] = this.spawn(index)
393
+ return
394
+ }
395
+
396
+ this.pending[index] = setTimeout((): void => {
397
+ this.pending[index] = null
398
+ if (this.running && this.processes[index] === null) {
399
+ this.processes[index] = this.spawn(index)
400
+ }
401
+ }, delay)
402
+ }
403
+
327
404
  /**
328
405
  * Waits for a worker to call ready, up to the ready timeout
329
406
  * @param child the worker
@@ -28,6 +28,16 @@ export class Gateway {
28
28
  */
29
29
  private readonly groups: Map<string, ChannelGroup>
30
30
 
31
+ /**
32
+ * Channels written to since the last flush
33
+ */
34
+ private readonly touched: Set<Channel>
35
+
36
+ /**
37
+ * Flushes every touched channel once, bound for queueMicrotask
38
+ */
39
+ private readonly flusher: () => void
40
+
31
41
  /**
32
42
  * Starts listening for publishes from other shards
33
43
  * @param link the shard's link
@@ -35,6 +45,11 @@ export class Gateway {
35
45
  public constructor(link: ShardLink) {
36
46
  this.link = link
37
47
  this.groups = new Map<string, ChannelGroup>()
48
+ this.touched = new Set<Channel>()
49
+ this.flusher = (): void => {
50
+ for (const channel of this.touched) void channel.flush()
51
+ this.touched.clear()
52
+ }
38
53
 
39
54
  link.on(Gateway.topic, (data: unknown): void => {
40
55
  const [topic, bytes] = data as Publication
@@ -114,6 +129,13 @@ export class Gateway {
114
129
  return 0
115
130
  }
116
131
 
117
- return group.broadcastSync(bytes)
132
+ if (this.touched.size === 0) queueMicrotask(this.flusher)
133
+
134
+ for (const channel of group) {
135
+ channel.writeEncodedSync(bytes)
136
+ this.touched.add(channel)
137
+ }
138
+
139
+ return group.size
118
140
  }
119
141
  }
@@ -107,12 +107,42 @@ type Arrival = {
107
107
  */
108
108
  readonly state: unknown
109
109
 
110
+ /**
111
+ * The old shard, which has the last word on the claim
112
+ */
113
+ readonly from: number
114
+
110
115
  /**
111
116
  * Drops it when nobody claims it
112
117
  */
113
118
  readonly timer: Timer
114
119
  }
115
120
 
121
+ /**
122
+ * A copy kept on the old shard until the new one confirms the claim
123
+ */
124
+ type Departure = {
125
+ /**
126
+ * What was sent over
127
+ */
128
+ readonly state: unknown
129
+
130
+ /**
131
+ * Set once the new shard was allowed to claim
132
+ */
133
+ granted: boolean
134
+
135
+ /**
136
+ * Where the player went
137
+ */
138
+ readonly shard: number
139
+
140
+ /**
141
+ * Drops it once a claim can't happen any more
142
+ */
143
+ readonly timer: Timer
144
+ }
145
+
116
146
  /**
117
147
  * A connection to another shard, or one being made
118
148
  */
@@ -169,6 +199,21 @@ export class ShardLink {
169
199
  */
170
200
  public static readonly handoffTopic: string = 'netify:handoff'
171
201
 
202
+ /**
203
+ * Asks the old shard whether a player can still be claimed
204
+ */
205
+ public static readonly confirmTopic: string = 'netify:confirm'
206
+
207
+ /**
208
+ * Tells the old shard it can drop its copy
209
+ */
210
+ public static readonly settledTopic: string = 'netify:settled'
211
+
212
+ /**
213
+ * Asks the new shard whether it has a player
214
+ */
215
+ public static readonly holdsTopic: string = 'netify:holds'
216
+
172
217
  /**
173
218
  * This shard
174
219
  */
@@ -219,6 +264,21 @@ export class ShardLink {
219
264
  */
220
265
  private readonly arrivals: Map<string, Arrival>
221
266
 
267
+ /**
268
+ * Players sent away and not claimed yet, by token
269
+ */
270
+ private readonly departures: Map<string, Departure>
271
+
272
+ /**
273
+ * Tokens recalled here lately, so the new shard can't claim them after all
274
+ */
275
+ private readonly recalled: Map<string, Timer>
276
+
277
+ /**
278
+ * Tokens claimed here lately, for the old shard to ask about
279
+ */
280
+ private readonly claimed: Map<string, Timer>
281
+
222
282
  /**
223
283
  * Outgoing connections by shard
224
284
  */
@@ -264,6 +324,9 @@ export class ShardLink {
264
324
  this.responders = new Map<string, ShardResponder>()
265
325
  this.waiting = new Map<number, Waiting>()
266
326
  this.arrivals = new Map<string, Arrival>()
327
+ this.departures = new Map<string, Departure>()
328
+ this.recalled = new Map<string, Timer>()
329
+ this.claimed = new Map<string, Timer>()
267
330
  this.connections = new Map<number, Peer>()
268
331
  this.dirty = new Set<Peer>()
269
332
  this.server = null
@@ -274,9 +337,24 @@ export class ShardLink {
274
337
  this.dirty.clear()
275
338
  }
276
339
 
277
- this.responders.set(ShardLink.handoffTopic, (state: unknown): string =>
278
- this.arrive(state),
340
+ this.responders.set(
341
+ ShardLink.handoffTopic,
342
+ (state: unknown, from: number): string => {
343
+ const token = crypto.randomUUID()
344
+
345
+ this.hold(token, state, from)
346
+ return token
347
+ },
348
+ )
349
+ this.responders.set(ShardLink.confirmTopic, (token: unknown): boolean =>
350
+ this.confirm(String(token)),
279
351
  )
352
+ this.responders.set(ShardLink.holdsTopic, (token: unknown): boolean =>
353
+ this.claimed.has(String(token)),
354
+ )
355
+ this.listeners.set(ShardLink.settledTopic, (token: unknown): void => {
356
+ this.forget(String(token))
357
+ })
280
358
  }
281
359
 
282
360
  /**
@@ -413,23 +491,94 @@ export class ShardLink {
413
491
  * @param shard the new shard
414
492
  * @param state anything structured clone can copy
415
493
  */
416
- public handoff(shard: number, state: unknown): Promise<string> {
417
- return this.request<string>(shard, ShardLink.handoffTopic, state)
494
+ public async handoff(shard: number, state: unknown): Promise<string> {
495
+ const token = await this.request<string>(
496
+ shard,
497
+ ShardLink.handoffTopic,
498
+ state,
499
+ )
500
+
501
+ const timer = setTimeout((): void => {
502
+ this.departures.delete(token)
503
+ }, this.handoffTimeout)
504
+ timer.unref()
505
+ this.departures.set(token, { state, granted: false, shard, timer })
506
+ return token
418
507
  }
419
508
 
420
509
  /**
421
- * Takes a handed off player's state, or null if the token is unknown or expired
510
+ * Takes a handed off player's state once the old shard agrees, or null if the token is unknown, expired or recalled
422
511
  * @param token from handoff
423
512
  */
424
- public claim<T>(token: string): T | null {
513
+ public async claim<T>(token: string): Promise<T | null> {
425
514
  const arrival = this.arrivals.get(token)
426
515
  if (arrival === undefined) return null
427
516
 
428
517
  clearTimeout(arrival.timer)
429
518
  this.arrivals.delete(token)
519
+ this.remember(this.claimed, token)
520
+
521
+ let allowed: boolean
522
+ try {
523
+ allowed = await this.request<boolean>(
524
+ arrival.from,
525
+ ShardLink.confirmTopic,
526
+ token,
527
+ )
528
+ } catch (error) {
529
+ if (!(error instanceof Error) || error.message !== 'Shard is down') {
530
+ this.release(this.claimed, token)
531
+ this.hold(token, arrival.state, arrival.from)
532
+ throw error
533
+ }
534
+
535
+ allowed = true
536
+ }
537
+
538
+ if (!allowed) {
539
+ this.release(this.claimed, token)
540
+ return null
541
+ }
542
+
543
+ if (!this.closed) this.send(arrival.from, ShardLink.settledTopic, token)
430
544
  return arrival.state as T
431
545
  }
432
546
 
547
+ /**
548
+ * Takes back a player who never reached their new shard, or null if they did
549
+ * @param token from handoff
550
+ */
551
+ public async recall<T>(token: string): Promise<T | null> {
552
+ const departure = this.departures.get(token)
553
+ if (departure === undefined) return null
554
+
555
+ if (departure.granted) {
556
+ let held: boolean
557
+ try {
558
+ held = await this.request<boolean>(
559
+ departure.shard,
560
+ ShardLink.holdsTopic,
561
+ token,
562
+ )
563
+ } catch (error) {
564
+ if (!(error instanceof Error) || error.message !== 'Shard is down') {
565
+ throw error
566
+ }
567
+
568
+ held = false
569
+ }
570
+
571
+ if (held || this.departures.get(token) !== departure) {
572
+ this.forget(token)
573
+ return null
574
+ }
575
+ }
576
+
577
+ this.forget(token)
578
+ this.remember(this.recalled, token)
579
+ return departure.state as T
580
+ }
581
+
433
582
  /**
434
583
  * Handles a message that came in from another shard
435
584
  * @param message what was decoded
@@ -462,6 +611,15 @@ export class ShardLink {
462
611
 
463
612
  for (const arrival of this.arrivals.values()) clearTimeout(arrival.timer)
464
613
  this.arrivals.clear()
614
+ for (const departure of this.departures.values()) {
615
+ clearTimeout(departure.timer)
616
+ }
617
+
618
+ this.departures.clear()
619
+ for (const timer of this.recalled.values()) clearTimeout(timer)
620
+ this.recalled.clear()
621
+ for (const timer of this.claimed.values()) clearTimeout(timer)
622
+ this.claimed.clear()
465
623
 
466
624
  const channels = [...this.connections.values()]
467
625
  .map((peer: Peer): Channel | null => peer.channel)
@@ -631,7 +789,7 @@ export class ShardLink {
631
789
  }
632
790
 
633
791
  /**
634
- * Sends the backlog on a new connection and forgets it once it closes
792
+ * Sends the backlog on a new connection and fails its requests once it closes
635
793
  * @param shard the shard
636
794
  * @param peer the connection record
637
795
  * @param channel the new channel
@@ -645,7 +803,7 @@ export class ShardLink {
645
803
  peer.channel = channel
646
804
  this.drain(peer)
647
805
  void channel.closed.then((): void => {
648
- if (this.connections.get(shard) === peer) this.connections.delete(shard)
806
+ if (this.connections.get(shard) === peer) this.lose(shard, peer)
649
807
  })
650
808
  }
651
809
 
@@ -727,17 +885,67 @@ export class ShardLink {
727
885
  }
728
886
 
729
887
  /**
730
- * Stores a handed off player and returns their token
888
+ * Keeps a handed off player until they claim
889
+ * @param token their token
731
890
  * @param state what the old shard sent over
891
+ * @param from the old shard
732
892
  */
733
- private arrive(state: unknown): string {
734
- const token = crypto.randomUUID()
893
+ private hold(token: string, state: unknown, from: number): void {
735
894
  const timer = setTimeout((): void => {
736
895
  this.arrivals.delete(token)
737
896
  }, this.handoffTimeout)
738
897
  timer.unref()
739
898
 
740
- this.arrivals.set(token, { state, timer })
741
- return token
899
+ this.arrivals.set(token, { state, from, timer })
900
+ }
901
+
902
+ /**
903
+ * Lets the new shard keep a player, false if they were recalled
904
+ * @param token from handoff
905
+ */
906
+ private confirm(token: string): boolean {
907
+ if (this.recalled.has(token)) return false
908
+
909
+ const departure = this.departures.get(token)
910
+ if (departure !== undefined) departure.granted = true
911
+ return true
912
+ }
913
+
914
+ /**
915
+ * Takes a token back out of a set
916
+ * @param tokens where it's kept
917
+ * @param token from handoff
918
+ */
919
+ private release(tokens: Map<string, Timer>, token: string): void {
920
+ const timer = tokens.get(token)
921
+ if (timer === undefined) return
922
+
923
+ clearTimeout(timer)
924
+ tokens.delete(token)
925
+ }
926
+
927
+ /**
928
+ * Keeps a token in a set until claims and recalls on it can't happen any more
929
+ * @param tokens where to keep it
930
+ * @param token from handoff
931
+ */
932
+ private remember(tokens: Map<string, Timer>, token: string): void {
933
+ const timer = setTimeout((): void => {
934
+ tokens.delete(token)
935
+ }, this.handoffTimeout)
936
+ timer.unref()
937
+ tokens.set(token, timer)
938
+ }
939
+
940
+ /**
941
+ * Lets go of the copy of a player who's been claimed or recalled
942
+ * @param token from handoff
943
+ */
944
+ private forget(token: string): void {
945
+ const departure = this.departures.get(token)
946
+ if (departure === undefined) return
947
+
948
+ clearTimeout(departure.timer)
949
+ this.departures.delete(token)
742
950
  }
743
951
  }