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

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.2",
4
+ "version": "1.0.0-alpha.4",
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
@@ -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
  }
@@ -99,43 +99,43 @@ type Waiting = {
99
99
  }
100
100
 
101
101
  /**
102
- * A handed off player waiting to be claimed
102
+ * A handed off player nobody has claimed yet
103
103
  */
104
- type Arrival = {
104
+ type Departure = {
105
105
  /**
106
- * What the old shard sent over
106
+ * Their state as it was at the handoff
107
107
  */
108
- readonly state: unknown
108
+ readonly bytes: Uint8Array
109
+
110
+ /**
111
+ * The only shard allowed to take them
112
+ */
113
+ readonly shard: number
109
114
 
110
115
  /**
111
- * The old shard, told once the player is claimed
116
+ * The process that took them, or null
112
117
  */
113
- readonly from: number
118
+ taker: string | null
114
119
 
115
120
  /**
116
- * Drops it when nobody claims it
121
+ * Drops them if nobody claims in time
117
122
  */
118
123
  readonly timer: Timer
119
124
  }
120
125
 
121
126
  /**
122
- * A copy kept on the old shard until the new one confirms the claim
127
+ * What a new shard sends to take a player
123
128
  */
124
- type Departure = {
129
+ type Claim = {
125
130
  /**
126
- * What was sent over
131
+ * From handoff
127
132
  */
128
- readonly state: unknown
129
-
130
- /**
131
- * Where the player went
132
- */
133
- readonly shard: number
133
+ readonly token: string
134
134
 
135
135
  /**
136
- * Drops it once a claim can't happen any more
136
+ * The process asking
137
137
  */
138
- readonly timer: Timer
138
+ readonly instance: string
139
139
  }
140
140
 
141
141
  /**
@@ -190,19 +190,29 @@ class ShardReceiver extends InboundHandlerAdapter<ByteBuf> {
190
190
  */
191
191
  export class ShardLink {
192
192
  /**
193
- * Topic used for handoffs
193
+ * Topic a new shard takes a handed off player on
194
+ */
195
+ public static readonly claimTopic: string = 'netify:claim'
196
+
197
+ /**
198
+ * Topic a new shard confirms a player's arrival on
199
+ */
200
+ public static readonly settledTopic: string = 'netify:settled'
201
+
202
+ /**
203
+ * Topic a shard names its process on
194
204
  */
195
- public static readonly handoffTopic: string = 'netify:handoff'
205
+ public static readonly instanceTopic: string = 'netify:instance'
196
206
 
197
207
  /**
198
- * Tells the old shard a player arrived
208
+ * Milliseconds between tries at a shard that's restarting
199
209
  */
200
- public static readonly claimedTopic: string = 'netify:claimed'
210
+ private static readonly retryDelay: number = 50
201
211
 
202
212
  /**
203
- * Asks the new shard to drop a player who never arrived
213
+ * Bytes kept free for the envelope around a handed off player
204
214
  */
205
- public static readonly cancelTopic: string = 'netify:cancel'
215
+ private static readonly envelopeSize: number = 512
206
216
 
207
217
  /**
208
218
  * This shard
@@ -249,21 +259,11 @@ export class ShardLink {
249
259
  */
250
260
  private readonly waiting: Map<number, Waiting>
251
261
 
252
- /**
253
- * Handed off players by token
254
- */
255
- private readonly arrivals: Map<string, Arrival>
256
-
257
262
  /**
258
263
  * Players sent away and not claimed yet, by token
259
264
  */
260
265
  private readonly departures: Map<string, Departure>
261
266
 
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
-
267
267
  /**
268
268
  * Outgoing connections by shard
269
269
  */
@@ -284,11 +284,21 @@ export class ShardLink {
284
284
  */
285
285
  private server: ServerChannel | null
286
286
 
287
+ /**
288
+ * Names this process, new on every start
289
+ */
290
+ private readonly instance: string
291
+
287
292
  /**
288
293
  * Last request id used
289
294
  */
290
295
  private nextId: number
291
296
 
297
+ /**
298
+ * Settles drain once every departure is gone, or null
299
+ */
300
+ private idle: PromiseWithResolvers<undefined> | null
301
+
292
302
  /**
293
303
  * Set by close
294
304
  */
@@ -308,29 +318,31 @@ export class ShardLink {
308
318
  this.listeners = new Map<string, ShardListener>()
309
319
  this.responders = new Map<string, ShardResponder>()
310
320
  this.waiting = new Map<number, Waiting>()
311
- this.arrivals = new Map<string, Arrival>()
312
321
  this.departures = new Map<string, Departure>()
313
- this.claimed = new Map<string, Timer>()
314
322
  this.connections = new Map<number, Peer>()
315
323
  this.dirty = new Set<Peer>()
316
324
  this.server = null
325
+ this.instance = crypto.randomUUID()
317
326
  this.nextId = 0
327
+ this.idle = null
318
328
  this.closed = false
319
329
  this.flusher = (): void => {
320
- for (const peer of this.dirty) this.drain(peer)
330
+ for (const peer of this.dirty) this.transmit(peer)
321
331
  this.dirty.clear()
322
332
  }
323
333
 
324
334
  this.responders.set(
325
- ShardLink.handoffTopic,
326
- (state: unknown, from: number): string => this.arrive(state, from),
335
+ ShardLink.claimTopic,
336
+ (claim: unknown, from: number): Uint8Array | null =>
337
+ this.take(claim as Claim, from),
327
338
  )
328
- this.responders.set(ShardLink.cancelTopic, (token: unknown): boolean =>
329
- this.cancel(String(token)),
339
+ this.responders.set(ShardLink.instanceTopic, (): string => this.instance)
340
+ this.listeners.set(
341
+ ShardLink.settledTopic,
342
+ (token: unknown, from: number): void => {
343
+ this.settled(String(token), from)
344
+ },
330
345
  )
331
- this.listeners.set(ShardLink.claimedTopic, (token: unknown): void => {
332
- this.forget(String(token))
333
- })
334
346
  }
335
347
 
336
348
  /**
@@ -463,76 +475,69 @@ export class ShardLink {
463
475
  }
464
476
 
465
477
  /**
466
- * Moves a player's state to another shard and returns the token they claim it with
478
+ * Keeps a player's state for another shard to claim and returns their token
467
479
  * @param shard the new shard
468
480
  * @param state anything structured clone can copy
469
481
  */
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
- )
482
+ public handoff(shard: number, state: unknown): string {
483
+ this.check(shard)
476
484
 
485
+ const bytes = this.pack(state)
486
+ const token = `${String(this.id)}.${crypto.randomUUID()}`
477
487
  const timer = setTimeout((): void => {
478
- this.departures.delete(token)
488
+ this.forget(token)
479
489
  }, this.handoffTimeout)
480
490
  timer.unref()
481
- this.departures.set(token, { state, shard, timer })
491
+
492
+ this.departures.set(token, { bytes, shard, taker: null, timer })
482
493
  return token
483
494
  }
484
495
 
485
496
  /**
486
- * Takes a handed off player's state, or null if the token is unknown or expired
497
+ * Takes a handed off player from their old shard, or null
487
498
  * @param token from handoff
488
499
  */
489
- public claim<T>(token: string): T | null {
490
- const arrival = this.arrivals.get(token)
491
- if (arrival === undefined) return null
492
-
493
- clearTimeout(arrival.timer)
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)
500
+ public async claim<T>(token: string): Promise<T | null> {
501
+ const from = Number.parseInt(token, 10)
502
+ if (!Number.isInteger(from) || from < 0 || from >= this.count) return null
501
503
 
502
- if (arrival.from >= 0 && arrival.from < this.count) {
503
- this.send(arrival.from, ShardLink.claimedTopic, token)
504
- }
504
+ const claim: Claim = { token, instance: this.instance }
505
+ const bytes = await this.request<Uint8Array | null>(
506
+ from,
507
+ ShardLink.claimTopic,
508
+ claim,
509
+ )
510
+ if (bytes === null) return null
505
511
 
506
- return arrival.state as T
512
+ if (!this.closed) this.send(from, ShardLink.settledTopic, token)
513
+ return deserialize(bytes) as T
507
514
  }
508
515
 
509
516
  /**
510
- * Takes back a player who never reached their new shard, or null if they did
517
+ * Takes back a player who never arrived, or null
511
518
  * @param token from handoff
512
519
  */
513
520
  public async recall<T>(token: string): Promise<T | null> {
514
521
  const departure = this.departures.get(token)
515
522
  if (departure === undefined) return null
516
523
 
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
524
+ if (departure.taker !== null) {
525
+ const gone = await this.replaced(departure.shard, departure.taker)
526
+ if (!gone || this.departures.get(token) !== departure) return null
530
527
  }
531
528
 
532
- if (this.departures.get(token) !== departure) return null
533
-
534
529
  this.forget(token)
535
- return cancelled ? (departure.state as T) : null
530
+ return deserialize(departure.bytes) as T
531
+ }
532
+
533
+ /**
534
+ * Resolves once no handed off players are left here
535
+ */
536
+ public drain(): Promise<void> {
537
+ if (this.departures.size === 0) return Promise.resolve()
538
+
539
+ this.idle ??= Promise.withResolvers<undefined>()
540
+ return this.idle.promise
536
541
  }
537
542
 
538
543
  /**
@@ -565,15 +570,7 @@ export class ShardLink {
565
570
  this.settle(id, null, 'Link is closed')
566
571
  }
567
572
 
568
- for (const arrival of this.arrivals.values()) clearTimeout(arrival.timer)
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()
573
+ for (const token of [...this.departures.keys()]) this.forget(token)
577
574
 
578
575
  const channels = [...this.connections.values()]
579
576
  .map((peer: Peer): Channel | null => peer.channel)
@@ -684,7 +681,7 @@ export class ShardLink {
684
681
  * Sends everything queued for a connection as one frame
685
682
  * @param peer the connection
686
683
  */
687
- private drain(peer: Peer): void {
684
+ private transmit(peer: Peer): void {
688
685
  const channel = peer.channel
689
686
  const queue = peer.queue
690
687
  if (channel === null || queue.length === 0) return
@@ -755,7 +752,7 @@ export class ShardLink {
755
752
  }
756
753
 
757
754
  peer.channel = channel
758
- this.drain(peer)
755
+ this.transmit(peer)
759
756
  void channel.closed.then((): void => {
760
757
  if (this.connections.get(shard) === peer) this.lose(shard, peer)
761
758
  })
@@ -839,39 +836,76 @@ export class ShardLink {
839
836
  }
840
837
 
841
838
  /**
842
- * Stores a handed off player and returns their token
843
- * @param state what the old shard sent over
844
- * @param from the old shard
839
+ * Copies a player's state into bytes
840
+ * @param state anything structured clone can copy
845
841
  */
846
- private arrive(state: unknown, from: number): string {
847
- const token = crypto.randomUUID()
848
- const timer = setTimeout((): void => {
849
- this.arrivals.delete(token)
850
- }, this.handoffTimeout)
851
- timer.unref()
842
+ private pack(state: unknown): Uint8Array {
843
+ let bytes: Uint8Array
844
+ try {
845
+ bytes = serialize(state, { binaryType: 'nodebuffer' })
846
+ } catch (cause) {
847
+ throw new Error('State is invalid', { cause })
848
+ }
852
849
 
853
- this.arrivals.set(token, { state, from, timer })
854
- return token
850
+ if (bytes.length > this.maxMessageSize - ShardLink.envelopeSize) {
851
+ throw new RangeError('State is too large')
852
+ }
853
+
854
+ return bytes
855
+ }
856
+
857
+ /**
858
+ * Lends a player to the shard they were sent to, or null
859
+ * @param claim the token and who's asking
860
+ * @param from the shard asking
861
+ */
862
+ private take(claim: Claim, from: number): Uint8Array | null {
863
+ const departure = this.departures.get(claim.token)
864
+ if (departure?.shard !== from || departure.taker !== null) return null
865
+
866
+ departure.taker = claim.instance
867
+ return departure.bytes
855
868
  }
856
869
 
857
870
  /**
858
- * Drops a player who won't arrive, false if they already did
871
+ * Lets go of a player their new shard confirmed
859
872
  * @param token from handoff
873
+ * @param from the shard confirming
860
874
  */
861
- private cancel(token: string): boolean {
862
- if (this.claimed.has(token)) return false
875
+ private settled(token: string, from: number): void {
876
+ const departure = this.departures.get(token)
877
+ if (departure?.shard !== from || departure.taker === null) return
863
878
 
864
- const arrival = this.arrivals.get(token)
865
- if (arrival !== undefined) {
866
- clearTimeout(arrival.timer)
867
- this.arrivals.delete(token)
868
- }
879
+ this.forget(token)
880
+ }
881
+
882
+ /**
883
+ * True if a different process answers for a shard
884
+ * @param shard the shard
885
+ * @param instance the process that was there
886
+ */
887
+ private async replaced(shard: number, instance: string): Promise<boolean> {
888
+ const deadline = performance.now() + this.timeout
869
889
 
870
- return true
890
+ for (;;) {
891
+ try {
892
+ const current = await this.request<string>(
893
+ shard,
894
+ ShardLink.instanceTopic,
895
+ null,
896
+ )
897
+ return current !== instance
898
+ } catch (error) {
899
+ const down = error instanceof Error && error.message === 'Shard is down'
900
+ if (!down || performance.now() >= deadline) throw error
901
+ }
902
+
903
+ await Bun.sleep(ShardLink.retryDelay)
904
+ }
871
905
  }
872
906
 
873
907
  /**
874
- * Lets go of the copy of a player who's been claimed or recalled
908
+ * Drops a departure and settles drain after the last one
875
909
  * @param token from handoff
876
910
  */
877
911
  private forget(token: string): void {
@@ -880,5 +914,9 @@ export class ShardLink {
880
914
 
881
915
  clearTimeout(departure.timer)
882
916
  this.departures.delete(token)
917
+ if (this.departures.size > 0) return
918
+
919
+ this.idle?.resolve(undefined)
920
+ this.idle = null
883
921
  }
884
922
  }