@netifyjs/netify 1.0.0-alpha.3 → 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.3",
4
+ "version": "1.0.0-alpha.4",
5
5
  "type": "module",
6
6
  "exports": {
7
7
  ".": "./src/index.ts"
@@ -99,48 +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
+ /**
106
+ * Their state as it was at the handoff
107
+ */
108
+ readonly bytes: Uint8Array
109
+
105
110
  /**
106
- * What the old shard sent over
111
+ * The only shard allowed to take them
107
112
  */
108
- readonly state: unknown
113
+ readonly shard: number
109
114
 
110
115
  /**
111
- * The old shard, which has the last word on the claim
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
133
+ readonly token: string
129
134
 
130
135
  /**
131
- * Set once the new shard was allowed to claim
136
+ * The process asking
132
137
  */
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
138
+ readonly instance: string
144
139
  }
145
140
 
146
141
  /**
@@ -195,24 +190,29 @@ class ShardReceiver extends InboundHandlerAdapter<ByteBuf> {
195
190
  */
196
191
  export class ShardLink {
197
192
  /**
198
- * Topic used for handoffs
193
+ * Topic a new shard takes a handed off player on
199
194
  */
200
- public static readonly handoffTopic: string = 'netify:handoff'
195
+ public static readonly claimTopic: string = 'netify:claim'
201
196
 
202
197
  /**
203
- * Asks the old shard whether a player can still be claimed
198
+ * Topic a new shard confirms a player's arrival on
204
199
  */
205
- public static readonly confirmTopic: string = 'netify:confirm'
200
+ public static readonly settledTopic: string = 'netify:settled'
206
201
 
207
202
  /**
208
- * Tells the old shard it can drop its copy
203
+ * Topic a shard names its process on
209
204
  */
210
- public static readonly settledTopic: string = 'netify:settled'
205
+ public static readonly instanceTopic: string = 'netify:instance'
211
206
 
212
207
  /**
213
- * Asks the new shard whether it has a player
208
+ * Milliseconds between tries at a shard that's restarting
214
209
  */
215
- public static readonly holdsTopic: string = 'netify:holds'
210
+ private static readonly retryDelay: number = 50
211
+
212
+ /**
213
+ * Bytes kept free for the envelope around a handed off player
214
+ */
215
+ private static readonly envelopeSize: number = 512
216
216
 
217
217
  /**
218
218
  * This shard
@@ -259,26 +259,11 @@ export class ShardLink {
259
259
  */
260
260
  private readonly waiting: Map<number, Waiting>
261
261
 
262
- /**
263
- * Handed off players by token
264
- */
265
- private readonly arrivals: Map<string, Arrival>
266
-
267
262
  /**
268
263
  * Players sent away and not claimed yet, by token
269
264
  */
270
265
  private readonly departures: Map<string, Departure>
271
266
 
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
-
282
267
  /**
283
268
  * Outgoing connections by shard
284
269
  */
@@ -299,11 +284,21 @@ export class ShardLink {
299
284
  */
300
285
  private server: ServerChannel | null
301
286
 
287
+ /**
288
+ * Names this process, new on every start
289
+ */
290
+ private readonly instance: string
291
+
302
292
  /**
303
293
  * Last request id used
304
294
  */
305
295
  private nextId: number
306
296
 
297
+ /**
298
+ * Settles drain once every departure is gone, or null
299
+ */
300
+ private idle: PromiseWithResolvers<undefined> | null
301
+
307
302
  /**
308
303
  * Set by close
309
304
  */
@@ -323,38 +318,31 @@ export class ShardLink {
323
318
  this.listeners = new Map<string, ShardListener>()
324
319
  this.responders = new Map<string, ShardResponder>()
325
320
  this.waiting = new Map<number, Waiting>()
326
- this.arrivals = new Map<string, Arrival>()
327
321
  this.departures = new Map<string, Departure>()
328
- this.recalled = new Map<string, Timer>()
329
- this.claimed = new Map<string, Timer>()
330
322
  this.connections = new Map<number, Peer>()
331
323
  this.dirty = new Set<Peer>()
332
324
  this.server = null
325
+ this.instance = crypto.randomUUID()
333
326
  this.nextId = 0
327
+ this.idle = null
334
328
  this.closed = false
335
329
  this.flusher = (): void => {
336
- for (const peer of this.dirty) this.drain(peer)
330
+ for (const peer of this.dirty) this.transmit(peer)
337
331
  this.dirty.clear()
338
332
  }
339
333
 
340
334
  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)),
335
+ ShardLink.claimTopic,
336
+ (claim: unknown, from: number): Uint8Array | null =>
337
+ this.take(claim as Claim, from),
351
338
  )
352
- this.responders.set(ShardLink.holdsTopic, (token: unknown): boolean =>
353
- this.claimed.has(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
+ },
354
345
  )
355
- this.listeners.set(ShardLink.settledTopic, (token: unknown): void => {
356
- this.forget(String(token))
357
- })
358
346
  }
359
347
 
360
348
  /**
@@ -487,96 +475,69 @@ export class ShardLink {
487
475
  }
488
476
 
489
477
  /**
490
- * 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
491
479
  * @param shard the new shard
492
480
  * @param state anything structured clone can copy
493
481
  */
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
- )
482
+ public handoff(shard: number, state: unknown): string {
483
+ this.check(shard)
500
484
 
485
+ const bytes = this.pack(state)
486
+ const token = `${String(this.id)}.${crypto.randomUUID()}`
501
487
  const timer = setTimeout((): void => {
502
- this.departures.delete(token)
488
+ this.forget(token)
503
489
  }, this.handoffTimeout)
504
490
  timer.unref()
505
- this.departures.set(token, { state, granted: false, shard, timer })
491
+
492
+ this.departures.set(token, { bytes, shard, taker: null, timer })
506
493
  return token
507
494
  }
508
495
 
509
496
  /**
510
- * Takes a handed off player's state once the old shard agrees, or null if the token is unknown, expired or recalled
497
+ * Takes a handed off player from their old shard, or null
511
498
  * @param token from handoff
512
499
  */
513
500
  public async claim<T>(token: string): Promise<T | null> {
514
- const arrival = this.arrivals.get(token)
515
- if (arrival === undefined) return null
516
-
517
- clearTimeout(arrival.timer)
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
- }
501
+ const from = Number.parseInt(token, 10)
502
+ if (!Number.isInteger(from) || from < 0 || from >= this.count) return null
503
+
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
542
511
 
543
- if (!this.closed) this.send(arrival.from, ShardLink.settledTopic, token)
544
- return arrival.state as T
512
+ if (!this.closed) this.send(from, ShardLink.settledTopic, token)
513
+ return deserialize(bytes) as T
545
514
  }
546
515
 
547
516
  /**
548
- * 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
549
518
  * @param token from handoff
550
519
  */
551
520
  public async recall<T>(token: string): Promise<T | null> {
552
521
  const departure = this.departures.get(token)
553
522
  if (departure === undefined) return null
554
523
 
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
- }
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
575
527
  }
576
528
 
577
529
  this.forget(token)
578
- this.remember(this.recalled, token)
579
- return departure.state as T
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
580
541
  }
581
542
 
582
543
  /**
@@ -609,17 +570,7 @@ export class ShardLink {
609
570
  this.settle(id, null, 'Link is closed')
610
571
  }
611
572
 
612
- for (const arrival of this.arrivals.values()) clearTimeout(arrival.timer)
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()
573
+ for (const token of [...this.departures.keys()]) this.forget(token)
623
574
 
624
575
  const channels = [...this.connections.values()]
625
576
  .map((peer: Peer): Channel | null => peer.channel)
@@ -730,7 +681,7 @@ export class ShardLink {
730
681
  * Sends everything queued for a connection as one frame
731
682
  * @param peer the connection
732
683
  */
733
- private drain(peer: Peer): void {
684
+ private transmit(peer: Peer): void {
734
685
  const channel = peer.channel
735
686
  const queue = peer.queue
736
687
  if (channel === null || queue.length === 0) return
@@ -801,7 +752,7 @@ export class ShardLink {
801
752
  }
802
753
 
803
754
  peer.channel = channel
804
- this.drain(peer)
755
+ this.transmit(peer)
805
756
  void channel.closed.then((): void => {
806
757
  if (this.connections.get(shard) === peer) this.lose(shard, peer)
807
758
  })
@@ -885,60 +836,76 @@ export class ShardLink {
885
836
  }
886
837
 
887
838
  /**
888
- * Keeps a handed off player until they claim
889
- * @param token their token
890
- * @param state what the old shard sent over
891
- * @param from the old shard
839
+ * Copies a player's state into bytes
840
+ * @param state anything structured clone can copy
892
841
  */
893
- private hold(token: string, state: unknown, from: number): void {
894
- const timer = setTimeout((): void => {
895
- this.arrivals.delete(token)
896
- }, this.handoffTimeout)
897
- 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
+ }
849
+
850
+ if (bytes.length > this.maxMessageSize - ShardLink.envelopeSize) {
851
+ throw new RangeError('State is too large')
852
+ }
898
853
 
899
- this.arrivals.set(token, { state, from, timer })
854
+ return bytes
900
855
  }
901
856
 
902
857
  /**
903
- * Lets the new shard keep a player, false if they were recalled
904
- * @param token from handoff
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
905
861
  */
906
- private confirm(token: string): boolean {
907
- if (this.recalled.has(token)) return false
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
908
865
 
909
- const departure = this.departures.get(token)
910
- if (departure !== undefined) departure.granted = true
911
- return true
866
+ departure.taker = claim.instance
867
+ return departure.bytes
912
868
  }
913
869
 
914
870
  /**
915
- * Takes a token back out of a set
916
- * @param tokens where it's kept
871
+ * Lets go of a player their new shard confirmed
917
872
  * @param token from handoff
873
+ * @param from the shard confirming
918
874
  */
919
- private release(tokens: Map<string, Timer>, token: string): void {
920
- const timer = tokens.get(token)
921
- if (timer === undefined) return
875
+ private settled(token: string, from: number): void {
876
+ const departure = this.departures.get(token)
877
+ if (departure?.shard !== from || departure.taker === null) return
922
878
 
923
- clearTimeout(timer)
924
- tokens.delete(token)
879
+ this.forget(token)
925
880
  }
926
881
 
927
882
  /**
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
883
+ * True if a different process answers for a shard
884
+ * @param shard the shard
885
+ * @param instance the process that was there
931
886
  */
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)
887
+ private async replaced(shard: number, instance: string): Promise<boolean> {
888
+ const deadline = performance.now() + this.timeout
889
+
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
+ }
938
905
  }
939
906
 
940
907
  /**
941
- * 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
942
909
  * @param token from handoff
943
910
  */
944
911
  private forget(token: string): void {
@@ -947,5 +914,9 @@ export class ShardLink {
947
914
 
948
915
  clearTimeout(departure.timer)
949
916
  this.departures.delete(token)
917
+ if (this.departures.size > 0) return
918
+
919
+ this.idle?.resolve(undefined)
920
+ this.idle = null
950
921
  }
951
922
  }