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

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.2",
5
5
  "type": "module",
6
6
  "exports": {
7
7
  ".": "./src/index.ts"
@@ -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
@@ -107,12 +107,37 @@ type Arrival = {
107
107
  */
108
108
  readonly state: unknown
109
109
 
110
+ /**
111
+ * The old shard, told once the player is claimed
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
+ * Where the player went
132
+ */
133
+ readonly shard: number
134
+
135
+ /**
136
+ * Drops it once a claim can't happen any more
137
+ */
138
+ readonly timer: Timer
139
+ }
140
+
116
141
  /**
117
142
  * A connection to another shard, or one being made
118
143
  */
@@ -169,6 +194,16 @@ export class ShardLink {
169
194
  */
170
195
  public static readonly handoffTopic: string = 'netify:handoff'
171
196
 
197
+ /**
198
+ * Tells the old shard a player arrived
199
+ */
200
+ public static readonly claimedTopic: string = 'netify:claimed'
201
+
202
+ /**
203
+ * Asks the new shard to drop a player who never arrived
204
+ */
205
+ public static readonly cancelTopic: string = 'netify:cancel'
206
+
172
207
  /**
173
208
  * This shard
174
209
  */
@@ -219,6 +254,16 @@ export class ShardLink {
219
254
  */
220
255
  private readonly arrivals: Map<string, Arrival>
221
256
 
257
+ /**
258
+ * Players sent away and not claimed yet, by token
259
+ */
260
+ private readonly departures: Map<string, Departure>
261
+
262
+ /**
263
+ * Tokens claimed here lately, so a late recall can't bring the player back twice
264
+ */
265
+ private readonly claimed: Map<string, Timer>
266
+
222
267
  /**
223
268
  * Outgoing connections by shard
224
269
  */
@@ -264,6 +309,8 @@ export class ShardLink {
264
309
  this.responders = new Map<string, ShardResponder>()
265
310
  this.waiting = new Map<number, Waiting>()
266
311
  this.arrivals = new Map<string, Arrival>()
312
+ this.departures = new Map<string, Departure>()
313
+ this.claimed = new Map<string, Timer>()
267
314
  this.connections = new Map<number, Peer>()
268
315
  this.dirty = new Set<Peer>()
269
316
  this.server = null
@@ -274,9 +321,16 @@ export class ShardLink {
274
321
  this.dirty.clear()
275
322
  }
276
323
 
277
- this.responders.set(ShardLink.handoffTopic, (state: unknown): string =>
278
- this.arrive(state),
324
+ this.responders.set(
325
+ ShardLink.handoffTopic,
326
+ (state: unknown, from: number): string => this.arrive(state, from),
327
+ )
328
+ this.responders.set(ShardLink.cancelTopic, (token: unknown): boolean =>
329
+ this.cancel(String(token)),
279
330
  )
331
+ this.listeners.set(ShardLink.claimedTopic, (token: unknown): void => {
332
+ this.forget(String(token))
333
+ })
280
334
  }
281
335
 
282
336
  /**
@@ -413,8 +467,19 @@ export class ShardLink {
413
467
  * @param shard the new shard
414
468
  * @param state anything structured clone can copy
415
469
  */
416
- public handoff(shard: number, state: unknown): Promise<string> {
417
- return this.request<string>(shard, ShardLink.handoffTopic, state)
470
+ public async handoff(shard: number, state: unknown): Promise<string> {
471
+ const token = await this.request<string>(
472
+ shard,
473
+ ShardLink.handoffTopic,
474
+ state,
475
+ )
476
+
477
+ const timer = setTimeout((): void => {
478
+ this.departures.delete(token)
479
+ }, this.handoffTimeout)
480
+ timer.unref()
481
+ this.departures.set(token, { state, shard, timer })
482
+ return token
418
483
  }
419
484
 
420
485
  /**
@@ -427,9 +492,49 @@ export class ShardLink {
427
492
 
428
493
  clearTimeout(arrival.timer)
429
494
  this.arrivals.delete(token)
495
+
496
+ const timer = setTimeout((): void => {
497
+ this.claimed.delete(token)
498
+ }, this.handoffTimeout)
499
+ timer.unref()
500
+ this.claimed.set(token, timer)
501
+
502
+ if (arrival.from >= 0 && arrival.from < this.count) {
503
+ this.send(arrival.from, ShardLink.claimedTopic, token)
504
+ }
505
+
430
506
  return arrival.state as T
431
507
  }
432
508
 
509
+ /**
510
+ * Takes back a player who never reached their new shard, or null if they did
511
+ * @param token from handoff
512
+ */
513
+ public async recall<T>(token: string): Promise<T | null> {
514
+ const departure = this.departures.get(token)
515
+ if (departure === undefined) return null
516
+
517
+ let cancelled: boolean
518
+ try {
519
+ cancelled = await this.request<boolean>(
520
+ departure.shard,
521
+ ShardLink.cancelTopic,
522
+ token,
523
+ )
524
+ } catch (error) {
525
+ if (!(error instanceof Error) || error.message !== 'Shard is down') {
526
+ throw error
527
+ }
528
+
529
+ cancelled = true
530
+ }
531
+
532
+ if (this.departures.get(token) !== departure) return null
533
+
534
+ this.forget(token)
535
+ return cancelled ? (departure.state as T) : null
536
+ }
537
+
433
538
  /**
434
539
  * Handles a message that came in from another shard
435
540
  * @param message what was decoded
@@ -462,6 +567,13 @@ export class ShardLink {
462
567
 
463
568
  for (const arrival of this.arrivals.values()) clearTimeout(arrival.timer)
464
569
  this.arrivals.clear()
570
+ for (const departure of this.departures.values()) {
571
+ clearTimeout(departure.timer)
572
+ }
573
+
574
+ this.departures.clear()
575
+ for (const timer of this.claimed.values()) clearTimeout(timer)
576
+ this.claimed.clear()
465
577
 
466
578
  const channels = [...this.connections.values()]
467
579
  .map((peer: Peer): Channel | null => peer.channel)
@@ -631,7 +743,7 @@ export class ShardLink {
631
743
  }
632
744
 
633
745
  /**
634
- * Sends the backlog on a new connection and forgets it once it closes
746
+ * Sends the backlog on a new connection and fails its requests once it closes
635
747
  * @param shard the shard
636
748
  * @param peer the connection record
637
749
  * @param channel the new channel
@@ -645,7 +757,7 @@ export class ShardLink {
645
757
  peer.channel = channel
646
758
  this.drain(peer)
647
759
  void channel.closed.then((): void => {
648
- if (this.connections.get(shard) === peer) this.connections.delete(shard)
760
+ if (this.connections.get(shard) === peer) this.lose(shard, peer)
649
761
  })
650
762
  }
651
763
 
@@ -729,15 +841,44 @@ export class ShardLink {
729
841
  /**
730
842
  * Stores a handed off player and returns their token
731
843
  * @param state what the old shard sent over
844
+ * @param from the old shard
732
845
  */
733
- private arrive(state: unknown): string {
846
+ private arrive(state: unknown, from: number): string {
734
847
  const token = crypto.randomUUID()
735
848
  const timer = setTimeout((): void => {
736
849
  this.arrivals.delete(token)
737
850
  }, this.handoffTimeout)
738
851
  timer.unref()
739
852
 
740
- this.arrivals.set(token, { state, timer })
853
+ this.arrivals.set(token, { state, from, timer })
741
854
  return token
742
855
  }
856
+
857
+ /**
858
+ * Drops a player who won't arrive, false if they already did
859
+ * @param token from handoff
860
+ */
861
+ private cancel(token: string): boolean {
862
+ if (this.claimed.has(token)) return false
863
+
864
+ const arrival = this.arrivals.get(token)
865
+ if (arrival !== undefined) {
866
+ clearTimeout(arrival.timer)
867
+ this.arrivals.delete(token)
868
+ }
869
+
870
+ return true
871
+ }
872
+
873
+ /**
874
+ * Lets go of the copy of a player who's been claimed or recalled
875
+ * @param token from handoff
876
+ */
877
+ private forget(token: string): void {
878
+ const departure = this.departures.get(token)
879
+ if (departure === undefined) return
880
+
881
+ clearTimeout(departure.timer)
882
+ this.departures.delete(token)
883
+ }
743
884
  }