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

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 +229 -88
  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 +161 -175
  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
@@ -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
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
109
 
110
110
  /**
111
- * The old shard, which has the last word on the claim
111
+ * The only shard allowed to take them
112
112
  */
113
- readonly from: number
113
+ readonly shard: number
114
114
 
115
115
  /**
116
- * Drops it when nobody claims it
116
+ * The process that took them, or null
117
+ */
118
+ taker: string | null
119
+
120
+ /**
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
- * 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
133
+ readonly token: string
139
134
 
140
135
  /**
141
- * Drops it once a claim can't happen any more
136
+ * The process asking
142
137
  */
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'
206
+
207
+ /**
208
+ * Milliseconds between tries at a shard that's restarting
209
+ */
210
+ private static readonly retryDelay: number = 50
211
211
 
212
212
  /**
213
- * Asks the new shard whether it has a player
213
+ * Bytes kept free for the envelope around a handed off player
214
214
  */
215
- public static readonly holdsTopic: string = 'netify:holds'
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
  /**
@@ -396,6 +384,21 @@ export class ShardLink {
396
384
  return this
397
385
  }
398
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
+
399
402
  /**
400
403
  * Stops listening on a topic
401
404
  * @param topic the topic
@@ -487,96 +490,69 @@ export class ShardLink {
487
490
  }
488
491
 
489
492
  /**
490
- * Moves a player's state to another shard and returns the token they claim it with
493
+ * Keeps a player's state for another shard to claim and returns their token
491
494
  * @param shard the new shard
492
495
  * @param state anything structured clone can copy
493
496
  */
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
- )
497
+ public handoff(shard: number, state: unknown): string {
498
+ this.check(shard)
500
499
 
500
+ const bytes = this.pack(state)
501
+ const token = `${String(this.id)}.${crypto.randomUUID()}`
501
502
  const timer = setTimeout((): void => {
502
- this.departures.delete(token)
503
+ this.forget(token)
503
504
  }, this.handoffTimeout)
504
505
  timer.unref()
505
- this.departures.set(token, { state, granted: false, shard, timer })
506
+
507
+ this.departures.set(token, { bytes, shard, taker: null, timer })
506
508
  return token
507
509
  }
508
510
 
509
511
  /**
510
- * Takes a handed off player's state once the old shard agrees, or null if the token is unknown, expired or recalled
512
+ * Takes a handed off player from their old shard, or null
511
513
  * @param token from handoff
512
514
  */
513
515
  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
- }
516
+ const from = Number.parseInt(token, 10)
517
+ if (!Number.isInteger(from) || from < 0 || from >= this.count) return null
518
+
519
+ const claim: Claim = { token, instance: this.instance }
520
+ const bytes = await this.request<Uint8Array | null>(
521
+ from,
522
+ ShardLink.claimTopic,
523
+ claim,
524
+ )
525
+ if (bytes === null) return null
542
526
 
543
- if (!this.closed) this.send(arrival.from, ShardLink.settledTopic, token)
544
- return arrival.state as T
527
+ if (!this.closed) this.send(from, ShardLink.settledTopic, token)
528
+ return deserialize(bytes) as T
545
529
  }
546
530
 
547
531
  /**
548
- * Takes back a player who never reached their new shard, or null if they did
532
+ * Takes back a player who never arrived, or null
549
533
  * @param token from handoff
550
534
  */
551
535
  public async recall<T>(token: string): Promise<T | null> {
552
536
  const departure = this.departures.get(token)
553
537
  if (departure === undefined) return null
554
538
 
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
- }
539
+ if (departure.taker !== null) {
540
+ const gone = await this.replaced(departure.shard, departure.taker)
541
+ if (!gone || this.departures.get(token) !== departure) return null
575
542
  }
576
543
 
577
544
  this.forget(token)
578
- this.remember(this.recalled, token)
579
- return departure.state as T
545
+ return deserialize(departure.bytes) as T
546
+ }
547
+
548
+ /**
549
+ * Resolves once no handed off players are left here
550
+ */
551
+ public drain(): Promise<void> {
552
+ if (this.departures.size === 0) return Promise.resolve()
553
+
554
+ this.idle ??= Promise.withResolvers<undefined>()
555
+ return this.idle.promise
580
556
  }
581
557
 
582
558
  /**
@@ -609,17 +585,7 @@ export class ShardLink {
609
585
  this.settle(id, null, 'Link is closed')
610
586
  }
611
587
 
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()
588
+ for (const token of [...this.departures.keys()]) this.forget(token)
623
589
 
624
590
  const channels = [...this.connections.values()]
625
591
  .map((peer: Peer): Channel | null => peer.channel)
@@ -730,7 +696,7 @@ export class ShardLink {
730
696
  * Sends everything queued for a connection as one frame
731
697
  * @param peer the connection
732
698
  */
733
- private drain(peer: Peer): void {
699
+ private transmit(peer: Peer): void {
734
700
  const channel = peer.channel
735
701
  const queue = peer.queue
736
702
  if (channel === null || queue.length === 0) return
@@ -801,7 +767,7 @@ export class ShardLink {
801
767
  }
802
768
 
803
769
  peer.channel = channel
804
- this.drain(peer)
770
+ this.transmit(peer)
805
771
  void channel.closed.then((): void => {
806
772
  if (this.connections.get(shard) === peer) this.lose(shard, peer)
807
773
  })
@@ -885,60 +851,76 @@ export class ShardLink {
885
851
  }
886
852
 
887
853
  /**
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
854
+ * Copies a player's state into bytes
855
+ * @param state anything structured clone can copy
892
856
  */
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()
857
+ private pack(state: unknown): Uint8Array {
858
+ let bytes: Uint8Array
859
+ try {
860
+ bytes = serialize(state, { binaryType: 'nodebuffer' })
861
+ } catch (cause) {
862
+ throw new Error('State is invalid', { cause })
863
+ }
898
864
 
899
- this.arrivals.set(token, { state, from, timer })
865
+ if (bytes.length > this.maxMessageSize - ShardLink.envelopeSize) {
866
+ throw new RangeError('State is too large')
867
+ }
868
+
869
+ return bytes
900
870
  }
901
871
 
902
872
  /**
903
- * Lets the new shard keep a player, false if they were recalled
904
- * @param token from handoff
873
+ * Lends a player to the shard they were sent to, or null
874
+ * @param claim the token and who's asking
875
+ * @param from the shard asking
905
876
  */
906
- private confirm(token: string): boolean {
907
- if (this.recalled.has(token)) return false
877
+ private take(claim: Claim, from: number): Uint8Array | null {
878
+ const departure = this.departures.get(claim.token)
879
+ if (departure?.shard !== from || departure.taker !== null) return null
908
880
 
909
- const departure = this.departures.get(token)
910
- if (departure !== undefined) departure.granted = true
911
- return true
881
+ departure.taker = claim.instance
882
+ return departure.bytes
912
883
  }
913
884
 
914
885
  /**
915
- * Takes a token back out of a set
916
- * @param tokens where it's kept
886
+ * Lets go of a player their new shard confirmed
917
887
  * @param token from handoff
888
+ * @param from the shard confirming
918
889
  */
919
- private release(tokens: Map<string, Timer>, token: string): void {
920
- const timer = tokens.get(token)
921
- if (timer === undefined) return
890
+ private settled(token: string, from: number): void {
891
+ const departure = this.departures.get(token)
892
+ if (departure?.shard !== from || departure.taker === null) return
922
893
 
923
- clearTimeout(timer)
924
- tokens.delete(token)
894
+ this.forget(token)
925
895
  }
926
896
 
927
897
  /**
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
898
+ * True if a different process answers for a shard
899
+ * @param shard the shard
900
+ * @param instance the process that was there
931
901
  */
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)
902
+ private async replaced(shard: number, instance: string): Promise<boolean> {
903
+ const deadline = performance.now() + this.timeout
904
+
905
+ for (;;) {
906
+ try {
907
+ const current = await this.request<string>(
908
+ shard,
909
+ ShardLink.instanceTopic,
910
+ null,
911
+ )
912
+ return current !== instance
913
+ } catch (error) {
914
+ const down = error instanceof Error && error.message === 'Shard is down'
915
+ if (!down || performance.now() >= deadline) throw error
916
+ }
917
+
918
+ await Bun.sleep(ShardLink.retryDelay)
919
+ }
938
920
  }
939
921
 
940
922
  /**
941
- * Lets go of the copy of a player who's been claimed or recalled
923
+ * Drops a departure and settles drain after the last one
942
924
  * @param token from handoff
943
925
  */
944
926
  private forget(token: string): void {
@@ -947,5 +929,9 @@ export class ShardLink {
947
929
 
948
930
  clearTimeout(departure.timer)
949
931
  this.departures.delete(token)
932
+ if (this.departures.size > 0) return
933
+
934
+ this.idle?.resolve(undefined)
935
+ this.idle = null
950
936
  }
951
937
  }