@netifyjs/protocol 1.0.0-alpha.2 → 1.0.0-beta.1

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 (183) hide show
  1. package/package.json +2 -2
  2. package/src/codec/index.ts +82 -157
  3. package/src/dispatch/dispatcher/index.ts +116 -33
  4. package/src/dispatch/session/index.ts +9 -3
  5. package/src/index.ts +2 -4
  6. package/src/photon/balancing/codec/index.ts +27 -53
  7. package/src/photon/balancing/format/authenticate/request/index.ts +52 -6
  8. package/src/photon/balancing/format/friends/request/index.ts +21 -5
  9. package/src/photon/balancing/format/game/create/request/index.ts +45 -8
  10. package/src/photon/balancing/format/game/debug/request/index.ts +19 -4
  11. package/src/photon/balancing/format/game/join/request/index.ts +65 -13
  12. package/src/photon/balancing/format/game/list/request/index.ts +29 -3
  13. package/src/photon/balancing/format/game/random/request/index.ts +58 -10
  14. package/src/photon/balancing/format/groups/request/index.ts +19 -3
  15. package/src/photon/balancing/format/index.ts +7 -0
  16. package/src/photon/balancing/format/leave/request/index.ts +19 -3
  17. package/src/photon/balancing/format/lobby/join/request/index.ts +23 -3
  18. package/src/photon/balancing/format/lobby/stats/request/index.ts +19 -3
  19. package/src/photon/balancing/format/once/request/index.ts +31 -8
  20. package/src/photon/balancing/format/properties/get/request/index.ts +31 -4
  21. package/src/photon/balancing/format/properties/set/request/index.ts +36 -7
  22. package/src/photon/balancing/format/raise/request/index.ts +76 -10
  23. package/src/photon/balancing/format/reader/index.ts +75 -6
  24. package/src/photon/balancing/format/regions/request/index.ts +16 -1
  25. package/src/photon/balancing/format/rpc/request/index.ts +26 -3
  26. package/src/photon/balancing/format/settings/request/index.ts +15 -2
  27. package/src/photon/balancing/format/shared/credentials/index.ts +77 -33
  28. package/src/photon/balancing/format/shared/lobby/index.ts +41 -5
  29. package/src/photon/balancing/format/shared/options/index.ts +56 -24
  30. package/src/photon/balancing/format/table/index.ts +399 -0
  31. package/src/photon/balancing/index.ts +11 -1
  32. package/src/photon/balancing/travel/index.ts +15 -12
  33. package/src/photon/binary/v18/index.ts +26 -1
  34. package/src/photon/binary/value/index.ts +52 -3
  35. package/src/photon/client/connection/index.ts +6 -6
  36. package/src/photon/cluster/back/index.ts +32 -45
  37. package/src/photon/cluster/dresser/index.ts +7 -8
  38. package/src/photon/cluster/front/index.ts +25 -49
  39. package/src/photon/cluster/grid/index.ts +1 -1
  40. package/src/photon/cluster/mover/index.ts +12 -12
  41. package/src/photon/cluster/press/index.ts +2 -18
  42. package/src/photon/cluster/route/game/index.ts +9 -11
  43. package/src/photon/cluster/route/master/index.ts +15 -34
  44. package/src/photon/cluster/route/name/index.ts +4 -21
  45. package/src/photon/cluster/seat/game/index.ts +6 -26
  46. package/src/photon/cluster/seat/master/index.ts +1 -1
  47. package/src/photon/cluster/sessions/index.ts +5 -6
  48. package/src/photon/cluster/spread/index.ts +8 -147
  49. package/src/photon/enet/client/index.ts +1 -8
  50. package/src/photon/enet/gateway/index.ts +5 -15
  51. package/src/photon/enet/index.ts +1 -1
  52. package/src/photon/enet/link/index.ts +34 -15
  53. package/src/photon/enet/outbound/index.ts +279 -0
  54. package/src/photon/enet/peer/index.ts +59 -0
  55. package/src/photon/enet/transport/index.ts +8 -24
  56. package/src/photon/game/admission/index.ts +353 -0
  57. package/src/photon/game/bag/index.ts +13 -0
  58. package/src/photon/game/broadcast/index.ts +79 -0
  59. package/src/photon/game/editor/index.ts +446 -0
  60. package/src/photon/game/gate/index.ts +9 -8
  61. package/src/photon/game/handler/index.ts +30 -3
  62. package/src/photon/game/history/index.ts +234 -0
  63. package/src/photon/game/hooked/index.ts +16 -15
  64. package/src/photon/game/index.ts +12 -1
  65. package/src/photon/game/lifecycle/index.ts +193 -0
  66. package/src/photon/game/peer/index.ts +1 -10
  67. package/src/photon/game/properties/index.ts +342 -0
  68. package/src/photon/game/room/index.ts +435 -1793
  69. package/src/photon/game/rooms/index.ts +2 -1
  70. package/src/photon/game/seats/index.ts +237 -0
  71. package/src/photon/game/server/index.ts +12 -2
  72. package/src/photon/game/services/index.ts +41 -0
  73. package/src/photon/game/settings/index.ts +22 -0
  74. package/src/photon/game/snapshot/index.ts +133 -0
  75. package/src/photon/game/throttle/index.ts +60 -0
  76. package/src/photon/game/touch/index.ts +2 -5
  77. package/src/photon/game/venue/index.ts +31 -0
  78. package/src/photon/master/application/index.ts +7 -0
  79. package/src/photon/master/gate/index.ts +12 -8
  80. package/src/photon/master/handler/index.ts +36 -748
  81. package/src/photon/master/index.ts +5 -0
  82. package/src/photon/master/list/sql/index.ts +37 -3
  83. package/src/photon/master/listing/index.ts +133 -0
  84. package/src/photon/master/lobby/index.ts +9 -0
  85. package/src/photon/master/login/index.ts +424 -0
  86. package/src/photon/master/matchmaking/index.ts +282 -0
  87. package/src/photon/master/query/index.ts +45 -0
  88. package/src/photon/master/redirect/index.ts +8 -7
  89. package/src/photon/master/services/index.ts +35 -0
  90. package/src/photon/master/settings/index.ts +44 -0
  91. package/src/photon/master/sql/cost/index.ts +263 -0
  92. package/src/photon/master/sql/index.ts +1 -0
  93. package/src/photon/message/binary/index.ts +35 -1
  94. package/src/photon/message/client/index.ts +14 -11
  95. package/src/photon/message/format/index.ts +9 -0
  96. package/src/photon/message/handler/index.ts +48 -63
  97. package/src/photon/message/pipeline/index.ts +12 -12
  98. package/src/photon/message/server/index.ts +87 -43
  99. package/src/photon/message/watch/index.ts +127 -15
  100. package/src/photon/server/config/index.ts +5 -0
  101. package/src/photon/server/deferral/index.ts +57 -0
  102. package/src/photon/server/host/index.ts +36 -10
  103. package/src/photon/server/index.ts +1 -0
  104. package/src/photon/server/listeners/index.ts +11 -0
  105. package/src/photon/tcp/client/index.ts +1 -1
  106. package/src/photon/tcp/codec/index.ts +41 -38
  107. package/src/photon/tcp/framing/index.ts +24 -4
  108. package/src/photon/tcp/server/index.ts +4 -4
  109. package/src/photon/websocket/bridge/index.ts +16 -20
  110. package/src/photon/websocket/message/index.ts +27 -39
  111. package/src/photon/websocket/path/index.ts +2 -5
  112. package/src/scale/batch/index.ts +14 -6
  113. package/src/scale/fanout/index.ts +6 -6
  114. package/src/scale/index.ts +2 -4
  115. package/src/scale/outbound/index.ts +192 -0
  116. package/src/scale/relay/index.ts +24 -16
  117. package/src/scale/sink/index.ts +6 -11
  118. package/src/scale/transport/index.ts +27 -44
  119. package/src/scale/tunnel/index.ts +56 -86
  120. package/src/smartfox/common/bluebox/gateway/index.ts +401 -0
  121. package/src/smartfox/common/bluebox/index.ts +4 -0
  122. package/src/smartfox/{x2 → common}/bluebox/transport/index.ts +36 -23
  123. package/src/smartfox/common/index.ts +5 -0
  124. package/src/smartfox/common/strikes/index.ts +74 -0
  125. package/src/smartfox/pro/bluebox/index.ts +176 -4
  126. package/src/smartfox/pro/codec/index.ts +8 -7
  127. package/src/smartfox/pro/escalation/index.ts +28 -20
  128. package/src/smartfox/pro/flood/index.ts +2 -2
  129. package/src/smartfox/pro/format/extension/raw/index.ts +12 -2
  130. package/src/smartfox/pro/handler/chat/index.ts +11 -8
  131. package/src/smartfox/pro/handler/login/index.ts +2 -25
  132. package/src/smartfox/pro/handler/shared/index.ts +4 -3
  133. package/src/smartfox/pro/index.ts +11 -5
  134. package/src/smartfox/pro/login/gate/index.ts +166 -0
  135. package/src/smartfox/pro/login/index.ts +1 -0
  136. package/src/smartfox/pro/moderation/index.ts +220 -0
  137. package/src/smartfox/pro/options/index.ts +5 -5
  138. package/src/smartfox/pro/protocol/index.ts +62 -8
  139. package/src/smartfox/pro/web/index.ts +33 -26
  140. package/src/smartfox/pro/zone/index.ts +59 -282
  141. package/src/smartfox/pro/zones/index.ts +3 -3
  142. package/src/smartfox/x2/bluebox/index.ts +149 -4
  143. package/src/smartfox/x2/chat/index.ts +9 -19
  144. package/src/smartfox/x2/codec/index.ts +34 -40
  145. package/src/smartfox/x2/config/index.ts +6 -1
  146. package/src/smartfox/x2/data/array/index.ts +96 -60
  147. package/src/smartfox/x2/data/object/index.ts +144 -82
  148. package/src/smartfox/x2/data/serializer/index.ts +41 -23
  149. package/src/smartfox/x2/flood/gate/index.ts +19 -13
  150. package/src/smartfox/x2/format/buddy/init/response/index.ts +4 -3
  151. package/src/smartfox/x2/format/find/rooms/response/index.ts +4 -3
  152. package/src/smartfox/x2/format/find/users/response/index.ts +4 -3
  153. package/src/smartfox/x2/format/group/subscribe/response/index.ts +4 -3
  154. package/src/smartfox/x2/format/login/response/index.ts +4 -3
  155. package/src/smartfox/x2/format/mmo/position/response/index.ts +8 -6
  156. package/src/smartfox/x2/format/room/join/response/index.ts +4 -3
  157. package/src/smartfox/x2/games/index.ts +35 -8
  158. package/src/smartfox/x2/hall/index.ts +0 -6
  159. package/src/smartfox/x2/handler/session/index.ts +1 -1
  160. package/src/smartfox/x2/index.ts +8 -3
  161. package/src/smartfox/x2/member/index.ts +10 -3
  162. package/src/smartfox/x2/packet/login/response/index.ts +12 -0
  163. package/src/smartfox/x2/protocol/index.ts +11 -1
  164. package/src/smartfox/x2/rooms/index.ts +1 -2
  165. package/src/smartfox/x2/sessions/index.ts +6 -0
  166. package/src/smartfox/x2/udp/index.ts +61 -24
  167. package/src/smartfox/x2/web/index.ts +35 -17
  168. package/src/smartfox/x2/websocket/index.ts +18 -36
  169. package/src/smartfox/x2/zone/index.ts +77 -28
  170. package/src/smartfox/x2/zones/index.ts +17 -5
  171. package/src/photon/enet/handler/index.ts +0 -65
  172. package/src/scale/hosted/index.ts +0 -68
  173. package/src/scale/outlet/index.ts +0 -121
  174. package/src/smartfox/pro/bluebox/gateway/index.ts +0 -310
  175. package/src/smartfox/pro/bluebox/session/index.ts +0 -63
  176. package/src/smartfox/pro/bluebox/transport/index.ts +0 -104
  177. package/src/smartfox/x2/bluebox/gateway/index.ts +0 -315
  178. /package/src/smartfox/{x2 → common}/bluebox/session/index.ts +0 -0
  179. /package/src/smartfox/{pro → common}/counters/index.ts +0 -0
  180. /package/src/smartfox/{pro → common}/counters/memory/index.ts +0 -0
  181. /package/src/smartfox/{pro → common}/counters/offender/index.ts +0 -0
  182. /package/src/smartfox/{pro → common}/counters/store/index.ts +0 -0
  183. /package/src/smartfox/{pro → common}/sequence/index.ts +0 -0
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@netifyjs/protocol",
3
3
  "description": "Ready-made game server protocols for Netify, starting with SmartFoxServer Pro and 2X",
4
- "version": "1.0.0-alpha.2",
4
+ "version": "1.0.0-beta.1",
5
5
  "type": "module",
6
6
  "exports": {
7
7
  ".": "./src/index.ts",
@@ -37,7 +37,7 @@
37
37
  "url": "https://github.com/netifyjs/protocol/issues"
38
38
  },
39
39
  "peerDependencies": {
40
- "@netifyjs/netify": ">=1.0.0-alpha.11"
40
+ "@netifyjs/netify": ">=1.0.0-beta.1"
41
41
  },
42
42
  "devDependencies": {
43
43
  "@eslint/js": "^10.0.1",
@@ -1,56 +1,39 @@
1
1
  import {
2
+ AttributeKey,
2
3
  ByteBuf,
3
4
  ByteToMessageDecoder,
4
5
  EncoderError,
5
- QueueFullError,
6
+ type Channel,
6
7
  type DecoderOptions,
7
8
  type HandlerContext,
9
+ type OutboundHandler,
8
10
  } from '@netifyjs/netify'
9
11
 
10
12
  import type { DirectWriter, Protocol } from '../protocol/index.ts'
11
- import { TunnelOutlet } from '../scale/outlet/index.ts'
12
13
 
13
14
  /**
14
- * Takes encoded bytes written straight into its room
15
- */
16
- export type Staging = {
17
- /**
18
- * Where reserved bytes get written
19
- */
20
- readonly stagingBuffer: Uint8Array
21
-
22
- /**
23
- * Makes room and gives where it starts, or -1
24
- * @param size bytes to make room for
25
- */
26
- reserve(size: number): number
27
-
28
- /**
29
- * Sends what was written into the reserved room
30
- * @param unused bytes of the room left over
31
- */
32
- commitStaged(unused?: number): void
33
- }
34
-
35
- /**
36
- * Base for a protocol's pipeline handler, with the outbound half done
15
+ * Base for a protocol's pipeline handler, decoding packets in and encoding them out
37
16
  * @class
38
17
  */
39
- export abstract class PacketCodec<O = unknown> extends ByteToMessageDecoder<O> {
18
+ export abstract class PacketCodec<O = unknown>
19
+ extends ByteToMessageDecoder<O>
20
+ implements OutboundHandler
21
+ {
40
22
  /**
41
- * Causes looked through before giving up
23
+ * Where a channel keeps its codec
42
24
  */
43
- private static readonly causes: number = 8
25
+ private static readonly key: AttributeKey<PacketCodec> =
26
+ new AttributeKey<PacketCodec>('netify:protocol:codec')
44
27
 
45
28
  /**
46
29
  * The protocol that knows the wire format
47
30
  */
48
- private readonly speaks: Protocol
31
+ protected readonly protocol: Protocol
49
32
 
50
33
  /**
51
34
  * Writes some packets straight into the outbound bytes, or null
52
35
  */
53
- private readonly straight: DirectWriter | null
36
+ private readonly direct: DirectWriter | null
54
37
 
55
38
  /**
56
39
  * Where each packet of the last decode began
@@ -69,51 +52,39 @@ export abstract class PacketCodec<O = unknown> extends ByteToMessageDecoder<O> {
69
52
  protected constructor(protocol: Protocol, options: DecoderOptions = {}) {
70
53
  super(options)
71
54
 
72
- this.speaks = protocol
73
- this.straight = protocol.straight()
55
+ this.protocol = protocol
56
+ this.direct = protocol.straight()
74
57
  this.starts = []
75
58
  this.produced = []
76
59
  }
77
60
 
78
61
  /**
79
- * Adds a decoded packet and notes where its bytes began
80
- * @param out where finished packets go
81
- * @param packet what was decoded
82
- * @param start reader index of its first byte
62
+ * The codec a channel was set up with, or null
63
+ * @param channel the connection
83
64
  */
84
- protected push(out: O[], packet: O, start: number): void {
85
- if (out.length === 0) this.starts.length = 0
86
-
87
- this.produced = out
88
- this.starts.push(start)
89
- out.push(packet)
65
+ public static on(channel: Channel): PacketCodec | null {
66
+ return channel.attributes.get<PacketCodec>(PacketCodec.key)
90
67
  }
91
68
 
92
69
  /**
93
- * Moves the reader back to a packet that was decoded and not handed on
94
- * @param input the buffer the packet came from
95
- * @param message the first packet not handed on
70
+ * Puts itself on the channel
71
+ * @param context its place in the pipeline
96
72
  */
97
- protected override rewind(input: ByteBuf, message: O): boolean {
98
- const start = this.starts[this.produced.indexOf(message)]
99
- if (start === undefined) return false
100
-
101
- input.readerIndex = start
102
- return true
73
+ public handlerAdded(context: HandlerContext): void {
74
+ context.channel.attributes.set<PacketCodec>(PacketCodec.key, this)
103
75
  }
104
76
 
105
77
  /**
106
- * Hangs up on a client too slow to take its frames
107
- * @param context the connection
108
- * @param error what went wrong
78
+ * Takes itself off the channel and hands on leftover bytes
79
+ * @param context its place in the pipeline
109
80
  */
110
- public override exceptionCaught(
111
- context: HandlerContext,
112
- error: unknown,
113
- ): Promise<void> {
114
- if (PacketCodec.overflowed(error)) void context.close()
81
+ public override handlerRemoved(context: HandlerContext): void {
82
+ const attributes = context.channel.attributes
83
+ if (attributes.get<PacketCodec>(PacketCodec.key) === this) {
84
+ attributes.delete<PacketCodec>(PacketCodec.key)
85
+ }
115
86
 
116
- return context.fireExceptionCaught(error)
87
+ super.handlerRemoved(context)
117
88
  }
118
89
 
119
90
  /**
@@ -121,136 +92,90 @@ export abstract class PacketCodec<O = unknown> extends ByteToMessageDecoder<O> {
121
92
  * @param context where the bytes go
122
93
  * @param message anything heading out
123
94
  */
124
- public write(context: HandlerContext, message: unknown): Promise<void> {
125
- let bytes: Uint8Array | null
126
- try {
127
- bytes = this.speaks.encode(message)
128
- } catch (cause) {
129
- return Promise.reject(new EncoderError('Encoding failed', { cause }))
95
+ public write(context: HandlerContext, message: unknown): void {
96
+ if (message instanceof ByteBuf || message instanceof Uint8Array) {
97
+ context.write(message)
98
+ return
130
99
  }
131
100
 
132
- return context.write(bytes === null ? message : ByteBuf.wrap(bytes))
133
- }
134
-
135
- /**
136
- * Encodes and writes without a promise, false for other messages
137
- * @param context where the bytes go
138
- * @param message anything heading out
139
- */
140
- public writeSync(context: HandlerContext, message: unknown): boolean {
141
- if (message instanceof ByteBuf) return PacketCodec.pass(context, message)
142
- if (this.direct(context, message)) return true
101
+ if (context.writesToSocket && this.stage(context, message)) return
143
102
 
144
103
  let bytes: Uint8Array | null
145
104
  try {
146
- bytes = this.speaks.encode(message)
105
+ bytes = this.protocol.encode(message)
147
106
  } catch (cause) {
148
107
  throw new EncoderError('Encoding failed', { cause })
149
108
  }
150
109
 
151
- if (bytes === null) return false
152
- PacketCodec.put(context, bytes)
153
-
154
- return true
110
+ context.write(bytes ?? message)
155
111
  }
156
112
 
157
113
  /**
158
- * Lets the protocol write a packet straight into the outbound bytes, or false
159
- * @param context where the bytes go
160
- * @param message anything heading out
114
+ * Passes a flush on
115
+ * @param context where it goes
161
116
  */
162
- private direct(context: HandlerContext, message: unknown): boolean {
163
- const writer = this.straight
164
- const room = writer === null ? -1 : writer.measure(message)
165
- const staging = room < 0 ? null : PacketCodec.staging(context)
166
- if (writer === null || staging === null) return false
167
-
168
- const offset = staging.reserve(room)
169
- if (offset < 0) return false
170
-
171
- let taken = -1
172
- try {
173
- taken = writer.write(message, staging.stagingBuffer, offset)
174
- } finally {
175
- staging.commitStaged(taken < 0 ? room : room - taken)
176
- }
177
-
178
- return taken >= 0
117
+ public flush(context: HandlerContext): void {
118
+ context.flush()
179
119
  }
180
120
 
181
121
  /**
182
- * Whether an error comes from a full outbox
183
- * @param error what the pipeline caught
122
+ * Passes a close on
123
+ * @param context where it goes
184
124
  */
185
- public static overflowed(error: unknown): boolean {
186
- let current: unknown = error
187
-
188
- for (let step = 0; step < PacketCodec.causes; step++) {
189
- if (current instanceof QueueFullError) return true
190
- if (!(current instanceof Error)) return false
191
-
192
- current = current.cause
193
- }
194
-
195
- return false
125
+ public close(context: HandlerContext): void {
126
+ void context.close()
196
127
  }
197
128
 
198
129
  /**
199
- * Where the next write can be staged directly, or null
200
- * @param context the codec's place in the pipeline
130
+ * Adds a decoded packet and notes where its bytes began
131
+ * @param out where finished packets go
132
+ * @param packet what was decoded
133
+ * @param start reader index of its first byte
201
134
  */
202
- public static staging(context: HandlerContext): Staging | null {
203
- if (context.writesToSocket) return context.channel
135
+ protected push(out: O[], packet: O, start: number): void {
136
+ if (out.length === 0) this.starts.length = 0
204
137
 
205
- const outlet = context.previous?.handler
206
- return outlet instanceof TunnelOutlet ? outlet : null
138
+ this.produced = out
139
+ this.starts.push(start)
140
+ out.push(packet)
207
141
  }
208
142
 
209
143
  /**
210
- * Writes encoded bytes without a promise
211
- * @param context where the bytes go
212
- * @param bytes one or more whole frames
144
+ * Moves the reader back to a packet that was decoded and not handed on
145
+ * @param input the buffer the packet came from
146
+ * @param message the first packet not handed on
213
147
  */
214
- protected static put(context: HandlerContext, bytes: Uint8Array): void {
215
- if (PacketCodec.stage(context, bytes, 0, bytes.length)) return
148
+ protected override rewind(input: ByteBuf, message: O): boolean {
149
+ const start = this.starts[this.produced.indexOf(message)]
150
+ if (start === undefined) return false
216
151
 
217
- context.writeSync(ByteBuf.wrap(bytes))
152
+ input.readerIndex = start
153
+ return true
218
154
  }
219
155
 
220
156
  /**
221
- * Writes a buffer of encoded bytes straight to the socket, false if a handler has to see it
222
- * @param context where the bytes go
223
- * @param frame one or more whole frames
157
+ * Writes a packet straight into the channel's staging slab, false if it can't
158
+ * @param context next to the socket
159
+ * @param message anything heading out
224
160
  */
225
- protected static pass(context: HandlerContext, frame: ByteBuf): boolean {
226
- return PacketCodec.stage(
227
- context,
228
- frame.array,
229
- frame.arrayOffset + frame.readerIndex,
230
- frame.readableBytes,
231
- )
232
- }
161
+ private stage(context: HandlerContext, message: unknown): boolean {
162
+ const writer = this.direct
163
+ const room = writer === null ? -1 : writer.measure(message)
164
+ if (writer === null || room < 0) return false
233
165
 
234
- /**
235
- * Copies bytes into the outbound room, false if there's none
236
- * @param context where the bytes go
237
- * @param source array the bytes live in
238
- * @param start where they begin
239
- * @param size how many there are
240
- */
241
- private static stage(
242
- context: HandlerContext,
243
- source: Uint8Array,
244
- start: number,
245
- size: number,
246
- ): boolean {
247
- const staging = PacketCodec.staging(context)
248
- const offset = staging === null ? -1 : staging.reserve(size)
249
- if (staging === null || offset < 0) return false
166
+ const channel = context.channel
167
+ const offset = channel.reserve(room)
168
+ if (offset < 0) return false
250
169
 
251
- ByteBuf.copyBytes(source, start, staging.stagingBuffer, offset, size)
252
- staging.commitStaged()
170
+ let taken = -1
171
+ try {
172
+ taken = writer.write(message, channel.stagingBuffer, offset)
173
+ } catch (cause) {
174
+ throw new EncoderError('Encoding failed', { cause })
175
+ } finally {
176
+ channel.commit(taken < 0 ? room : room - taken)
177
+ }
253
178
 
254
- return true
179
+ return taken >= 0
255
180
  }
256
181
  }
@@ -1,6 +1,10 @@
1
- import { InboundHandlerAdapter, type HandlerContext } from '@netifyjs/netify'
1
+ import {
2
+ InboundHandlerAdapter,
3
+ type Channel,
4
+ type HandlerContext,
5
+ type Outcome,
6
+ } from '@netifyjs/netify'
2
7
 
3
- import { Tunnel } from '../../scale/tunnel/index.ts'
4
8
  import { Closed, Opened } from '../event/index.ts'
5
9
  import { Routes, type Keyed, type Route } from '../route/index.ts'
6
10
  import { Session } from '../session/index.ts'
@@ -8,7 +12,7 @@ import { Session } from '../session/index.ts'
8
12
  /**
9
13
  * A handler method tied to its instance
10
14
  */
11
- type Bound = (session: Session, packet: unknown) => void | Promise<void>
15
+ type Bound = (session: Session, packet: unknown) => Outcome
12
16
 
13
17
  /**
14
18
  * Hands each packet to the method decorated for it
@@ -45,6 +49,11 @@ export class PacketDispatcher<U = unknown> extends InboundHandlerAdapter {
45
49
  */
46
50
  private lastTyped: Bound | null
47
51
 
52
+ /**
53
+ * Session of the last connection read, or null
54
+ */
55
+ private lastSession: Session<U> | null
56
+
48
57
  /**
49
58
  * Starts with no handlers
50
59
  */
@@ -54,6 +63,7 @@ export class PacketDispatcher<U = unknown> extends InboundHandlerAdapter {
54
63
  this.lastType = null
55
64
  this.lastKeys = null
56
65
  this.lastTyped = null
66
+ this.lastSession = null
57
67
 
58
68
  this.events = new Map<unknown, Bound[]>()
59
69
  this.typed = new Map<unknown, Bound>()
@@ -68,20 +78,26 @@ export class PacketDispatcher<U = unknown> extends InboundHandlerAdapter {
68
78
  }
69
79
 
70
80
  /**
71
- * Registers every decorated method of a handler, up its prototype chain
81
+ * Registers every decorated method of a handler, calling its most derived version
72
82
  * @param handler an instance with decorated methods
73
83
  */
74
84
  public add<T extends object>(handler: T): this {
85
+ const seen = new Set<string>()
75
86
  let prototype: unknown = Object.getPrototypeOf(handler)
76
87
 
77
88
  while (typeof prototype === 'object' && prototype !== null) {
78
89
  for (const name of Object.getOwnPropertyNames(prototype)) {
90
+ if (seen.has(name)) continue
91
+
79
92
  const method: unknown = Object.getOwnPropertyDescriptor(
80
93
  prototype,
81
94
  name,
82
95
  )?.value
83
96
  const route = Routes.shared.find(method)
84
- if (route !== null) this.register(handler, route)
97
+ if (route === null) continue
98
+
99
+ seen.add(name)
100
+ this.register(handler, name, route)
85
101
  }
86
102
 
87
103
  prototype = Object.getPrototypeOf(prototype)
@@ -95,12 +111,10 @@ export class PacketDispatcher<U = unknown> extends InboundHandlerAdapter {
95
111
  * @param context the connection
96
112
  * @param message a decoded packet
97
113
  */
98
- public override channelRead(
99
- context: HandlerContext,
100
- message: unknown,
101
- ): void | Promise<void> {
114
+ public override channelRead(context: HandlerContext, message: unknown): void {
102
115
  if (typeof message !== 'object' || message === null) {
103
- return context.fireChannelRead(message)
116
+ context.fireChannelRead(message)
117
+ return
104
118
  }
105
119
 
106
120
  const type: unknown = message.constructor
@@ -111,32 +125,34 @@ export class PacketDispatcher<U = unknown> extends InboundHandlerAdapter {
111
125
  }
112
126
 
113
127
  const bound = this.lastKeys?.get((message as Keyed).route) ?? this.lastTyped
114
- if (bound === null) return context.fireChannelRead(message)
128
+ if (bound === null) {
129
+ context.fireChannelRead(message)
130
+ return
131
+ }
115
132
 
116
- return bound(Session.of<U>(context.channel), message)
133
+ const outcome = bound(this.session(context.channel), message)
134
+ if (outcome instanceof Promise) PacketDispatcher.hold(context, outcome)
117
135
  }
118
136
 
119
137
  /**
120
138
  * Tells listeners a connection came up, once across shards
121
139
  * @param context the connection
122
140
  */
123
- public override async channelActive(context: HandlerContext): Promise<void> {
124
- if (!Tunnel.carries(context.channel)) {
125
- await this.emit(context, Opened.now())
126
- }
141
+ public override channelActive(context: HandlerContext): void {
142
+ if (!this.session(context.channel).moved) this.emit(context, Opened.now())
127
143
 
128
- await context.fireChannelActive()
144
+ context.fireChannelActive()
129
145
  }
130
146
 
131
147
  /**
132
148
  * Tells listeners a connection went away
133
149
  * @param context the connection
134
150
  */
135
- public override async channelInactive(
136
- context: HandlerContext,
137
- ): Promise<void> {
138
- await this.emit(context, Closed.now())
139
- await context.fireChannelInactive()
151
+ public override channelInactive(context: HandlerContext): void {
152
+ this.emit(context, Closed.now())
153
+ if (this.lastSession?.channel === context.channel) this.lastSession = null
154
+
155
+ context.fireChannelInactive()
140
156
  }
141
157
 
142
158
  /**
@@ -144,12 +160,33 @@ export class PacketDispatcher<U = unknown> extends InboundHandlerAdapter {
144
160
  * @param context the connection
145
161
  * @param event whatever an earlier handler raised
146
162
  */
147
- public override async userEventTriggered(
163
+ public override userEventTriggered(
148
164
  context: HandlerContext,
149
165
  event: unknown,
150
- ): Promise<void> {
151
- await this.emit(context, event)
152
- await context.fireUserEventTriggered(event)
166
+ ): void {
167
+ this.emit(context, event)
168
+ context.fireUserEventTriggered(event)
169
+ }
170
+
171
+ /**
172
+ * Holds later reads back while an async handler runs
173
+ * @param context the connection
174
+ * @param outcome what the handler is still doing
175
+ */
176
+ private static hold(context: HandlerContext, outcome: Promise<void>): void {
177
+ const channel = context.channel
178
+ const paused = channel.isActive
179
+
180
+ if (paused) channel.pauseReads()
181
+ outcome.then(
182
+ (): void => {
183
+ if (paused) channel.resumeReads()
184
+ },
185
+ (error: unknown): void => {
186
+ if (paused) channel.resumeReads()
187
+ context.fireExceptionCaught(error)
188
+ },
189
+ )
153
190
  }
154
191
 
155
192
  /**
@@ -157,25 +194,69 @@ export class PacketDispatcher<U = unknown> extends InboundHandlerAdapter {
157
194
  * @param context the connection
158
195
  * @param event what happened
159
196
  */
160
- private async emit(context: HandlerContext, event: unknown): Promise<void> {
197
+ private emit(context: HandlerContext, event: unknown): void {
161
198
  if (typeof event !== 'object' || event === null) return
162
199
 
163
200
  const listeners = this.events.get(event.constructor)
164
201
  if (listeners === undefined) return
165
202
 
166
- const session = Session.of<U>(context.channel)
167
- for (const listener of listeners) {
168
- await listener(session, event)
203
+ const session = this.session(context.channel)
204
+ const rest = PacketDispatcher.run(listeners, 0, session, event)
205
+ if (rest !== null) PacketDispatcher.hold(context, rest)
206
+ }
207
+
208
+ /**
209
+ * Calls listeners from one on, waiting for any that return a promise
210
+ * @param listeners every listener of the event
211
+ * @param from the first one to call
212
+ * @param session the connection's session
213
+ * @param event what happened
214
+ */
215
+ private static run(
216
+ listeners: readonly Bound[],
217
+ from: number,
218
+ session: Session,
219
+ event: unknown,
220
+ ): Promise<void> | null {
221
+ for (let index = from; index < listeners.length; index++) {
222
+ const outcome = listeners[index]?.(session, event)
223
+ if (!(outcome instanceof Promise)) continue
224
+
225
+ return outcome.then(
226
+ (): Promise<void> | undefined =>
227
+ PacketDispatcher.run(listeners, index + 1, session, event) ??
228
+ undefined,
229
+ )
169
230
  }
231
+
232
+ return null
233
+ }
234
+
235
+ /**
236
+ * A connection's session, looked up once for a run of reads
237
+ * @param channel the connection
238
+ */
239
+ private session(channel: Channel): Session<U> {
240
+ const last = this.lastSession
241
+ if (last !== null && last.channel === channel) return last
242
+
243
+ const session = Session.of<U>(channel)
244
+ this.lastSession = session
245
+ return session
170
246
  }
171
247
 
172
248
  /**
173
249
  * Files one method under its packet class and key
174
250
  * @param handler the instance it runs on
251
+ * @param name the method's name, looked up on the instance
175
252
  * @param route what the method answers to
176
253
  */
177
- private register(handler: object, route: Route): void {
178
- const bound: Bound = route.method.bind(handler)
254
+ private register(handler: object, name: string, route: Route): void {
255
+ const method: unknown = Reflect.get(handler, name)
256
+ const bound: Bound =
257
+ typeof method === 'function'
258
+ ? (method as Route['method']).bind(handler)
259
+ : route.method.bind(handler)
179
260
  this.lastType = null
180
261
 
181
262
  if (route.event) {
@@ -186,8 +267,10 @@ export class PacketDispatcher<U = unknown> extends InboundHandlerAdapter {
186
267
  }
187
268
 
188
269
  if (route.key === null) {
189
- if (this.typed.has(route.type))
270
+ if (this.typed.has(route.type)) {
190
271
  throw new Error('Packet is already handled')
272
+ }
273
+
191
274
  this.typed.set(route.type, bound)
192
275
  return
193
276
  }
@@ -21,6 +21,11 @@ export class Session<U = unknown> {
21
21
  */
22
22
  public user: U | null
23
23
 
24
+ /**
25
+ * Whether it came over from another shard with its state
26
+ */
27
+ public moved: boolean
28
+
24
29
  /**
25
30
  * Starts with nobody logged in
26
31
  * @param channel the connection underneath
@@ -28,6 +33,7 @@ export class Session<U = unknown> {
28
33
  private constructor(channel: Channel) {
29
34
  this.channel = channel
30
35
  this.user = null
36
+ this.moved = false
31
37
  }
32
38
 
33
39
  /**
@@ -44,15 +50,15 @@ export class Session<U = unknown> {
44
50
  }
45
51
 
46
52
  /**
47
- * Sends a packet through the pipeline
53
+ * Sends a packet through the pipeline, going out at the end of the read or turn
48
54
  * @param packet anything the codec knows how to encode
49
55
  */
50
56
  public send(packet: unknown): void {
51
- this.channel.writeAndFlushSync(packet)
57
+ this.channel.writeAndFlush(packet)
52
58
  }
53
59
 
54
60
  /**
55
- * Hangs up
61
+ * Hangs up once what's queued has gone out
56
62
  */
57
63
  public close(): Promise<void> {
58
64
  return this.channel.close()
package/src/index.ts CHANGED
@@ -1,5 +1,4 @@
1
1
  export { PacketCodec } from './codec/index.ts'
2
- export type { Staging } from './codec/index.ts'
3
2
  export {
4
3
  Closed,
5
4
  Opened,
@@ -35,7 +34,7 @@ export {
35
34
  SinkTransport,
36
35
  Switchboard,
37
36
  Tunnel,
38
- TunnelOutlet,
37
+ TunnelOutbound,
39
38
  TunnelRelay,
40
39
  TunnelTransport,
41
40
  } from './scale/index.ts'
@@ -54,13 +53,12 @@ export type {
54
53
  HandoffReturn,
55
54
  Hosted,
56
55
  MeshOptions,
57
- OutletSink,
58
56
  PendingLoss,
59
57
  PlacementRule,
60
58
  Portable,
61
59
  Reach,
62
60
  RelayEvents,
63
61
  SwitchboardLocal,
64
- TransportEvents,
65
62
  TunnelOptions,
63
+ TunnelSink,
66
64
  } from './scale/index.ts'