@netifyjs/protocol 1.0.0-alpha.2 → 1.0.0-alpha.3

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/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-alpha.3",
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-alpha.12"
41
41
  },
42
42
  "devDependencies": {
43
43
  "@eslint/js": "^10.0.1",
@@ -1,8 +1,10 @@
1
1
  import {
2
+ AttributeKey,
2
3
  ByteBuf,
3
4
  ByteToMessageDecoder,
4
5
  EncoderError,
5
6
  QueueFullError,
7
+ type Channel,
6
8
  type DecoderOptions,
7
9
  type HandlerContext,
8
10
  } from '@netifyjs/netify'
@@ -42,6 +44,27 @@ export abstract class PacketCodec<O = unknown> extends ByteToMessageDecoder<O> {
42
44
  */
43
45
  private static readonly causes: number = 8
44
46
 
47
+ /**
48
+ * Where a channel keeps its codec
49
+ */
50
+ private static readonly key: AttributeKey<PacketCodec> =
51
+ new AttributeKey<PacketCodec>('netify:protocol:codec')
52
+
53
+ /**
54
+ * Its place in the pipeline, or null
55
+ */
56
+ private context: HandlerContext | null
57
+
58
+ /**
59
+ * Pipeline version the last check of what follows belongs to
60
+ */
61
+ private checked: number
62
+
63
+ /**
64
+ * Whether no outbound handler follows it
65
+ */
66
+ private last: boolean
67
+
45
68
  /**
46
69
  * The protocol that knows the wire format
47
70
  */
@@ -73,6 +96,78 @@ export abstract class PacketCodec<O = unknown> extends ByteToMessageDecoder<O> {
73
96
  this.straight = protocol.straight()
74
97
  this.starts = []
75
98
  this.produced = []
99
+ this.context = null
100
+ this.checked = -1
101
+ this.last = false
102
+ }
103
+
104
+ /**
105
+ * The codec a channel was set up with, or null
106
+ * @param channel the connection
107
+ */
108
+ public static on(channel: Channel): PacketCodec | null {
109
+ return channel.attributes.get<PacketCodec>(PacketCodec.key)
110
+ }
111
+
112
+ /**
113
+ * Whether it still sits in a pipeline
114
+ */
115
+ public get attached(): boolean {
116
+ return this.context !== null
117
+ }
118
+
119
+ /**
120
+ * Remembers where it sits and puts itself on the channel
121
+ * @param context its place in the pipeline
122
+ */
123
+ public handlerAdded(context: HandlerContext): void {
124
+ this.context = context
125
+ this.checked = -1
126
+ context.channel.attributes.set<PacketCodec>(PacketCodec.key, this)
127
+ }
128
+
129
+ /**
130
+ * Takes itself off the channel and hands on leftover bytes
131
+ * @param context its place in the pipeline
132
+ */
133
+ public override handlerRemoved(context: HandlerContext): Promise<void> {
134
+ this.context = null
135
+
136
+ const attributes = context.channel.attributes
137
+ if (attributes.get<PacketCodec>(PacketCodec.key) === this) {
138
+ attributes.delete<PacketCodec>(PacketCodec.key)
139
+ }
140
+
141
+ return super.handlerRemoved(context)
142
+ }
143
+
144
+ /**
145
+ * Encodes a packet without walking the pipeline, false if something else has to see it
146
+ * @param packet anything heading out
147
+ */
148
+ public send(packet: unknown): boolean {
149
+ const context = this.context
150
+ if (context === null) return false
151
+
152
+ const version = context.pipeline.version
153
+ if (this.checked !== version) {
154
+ this.checked = version
155
+ this.last = PacketCodec.alone(context)
156
+ }
157
+
158
+ return this.last && this.writeSync(context, packet)
159
+ }
160
+
161
+ /**
162
+ * Whether no outbound handler sits between it and the tail
163
+ * @param context its place in the pipeline
164
+ */
165
+ private static alone(context: HandlerContext): boolean {
166
+ for (let next = context.next; next !== null; next = next.next) {
167
+ if ('write' in next.handler) return false
168
+ }
169
+
170
+ return true
76
171
  }
77
172
 
78
173
  /**
@@ -1,4 +1,8 @@
1
- import { InboundHandlerAdapter, type HandlerContext } from '@netifyjs/netify'
1
+ import {
2
+ InboundHandlerAdapter,
3
+ type Channel,
4
+ type HandlerContext,
5
+ } from '@netifyjs/netify'
2
6
 
3
7
  import { Tunnel } from '../../scale/tunnel/index.ts'
4
8
  import { Closed, Opened } from '../event/index.ts'
@@ -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>()
@@ -113,7 +123,23 @@ export class PacketDispatcher<U = unknown> extends InboundHandlerAdapter {
113
123
  const bound = this.lastKeys?.get((message as Keyed).route) ?? this.lastTyped
114
124
  if (bound === null) return context.fireChannelRead(message)
115
125
 
116
- return bound(Session.of<U>(context.channel), message)
126
+ const session = this.session(context.channel)
127
+ session.reading = true
128
+ return bound(session, message)
129
+ }
130
+
131
+ /**
132
+ * Sends everything the read's handlers wrote in one flush
133
+ * @param context the connection
134
+ */
135
+ public override channelReadComplete(context: HandlerContext): Promise<void> {
136
+ const session = this.session(context.channel)
137
+ if (session.reading) {
138
+ session.reading = false
139
+ void context.channel.flush()
140
+ }
141
+
142
+ return context.fireChannelReadComplete()
117
143
  }
118
144
 
119
145
  /**
@@ -135,6 +161,8 @@ export class PacketDispatcher<U = unknown> extends InboundHandlerAdapter {
135
161
  public override async channelInactive(
136
162
  context: HandlerContext,
137
163
  ): Promise<void> {
164
+ if (this.lastSession?.channel === context.channel) this.lastSession = null
165
+
138
166
  await this.emit(context, Closed.now())
139
167
  await context.fireChannelInactive()
140
168
  }
@@ -169,6 +197,19 @@ export class PacketDispatcher<U = unknown> extends InboundHandlerAdapter {
169
197
  }
170
198
  }
171
199
 
200
+ /**
201
+ * A connection's session, looked up once for a run of reads
202
+ * @param channel the connection
203
+ */
204
+ private session(channel: Channel): Session<U> {
205
+ const last = this.lastSession
206
+ if (last !== null && last.channel === channel) return last
207
+
208
+ const session = Session.of<U>(channel)
209
+ this.lastSession = session
210
+ return session
211
+ }
212
+
172
213
  /**
173
214
  * Files one method under its packet class and key
174
215
  * @param handler the instance it runs on
@@ -1,5 +1,7 @@
1
1
  import { AttributeKey, type Channel } from '@netifyjs/netify'
2
2
 
3
+ import { PacketCodec } from '../../codec/index.ts'
4
+
3
5
  /**
4
6
  * One connection and whoever is logged in on it
5
7
  * @class
@@ -21,6 +23,16 @@ export class Session<U = unknown> {
21
23
  */
22
24
  public user: U | null
23
25
 
26
+ /**
27
+ * Whether a read is under way, and its sends wait for one flush at the end
28
+ */
29
+ public reading: boolean
30
+
31
+ /**
32
+ * Codec sends go straight to, or null
33
+ */
34
+ private codec: PacketCodec | null
35
+
24
36
  /**
25
37
  * Starts with nobody logged in
26
38
  * @param channel the connection underneath
@@ -28,6 +40,8 @@ export class Session<U = unknown> {
28
40
  private constructor(channel: Channel) {
29
41
  this.channel = channel
30
42
  this.user = null
43
+ this.reading = false
44
+ this.codec = null
31
45
  }
32
46
 
33
47
  /**
@@ -48,7 +62,17 @@ export class Session<U = unknown> {
48
62
  * @param packet anything the codec knows how to encode
49
63
  */
50
64
  public send(packet: unknown): void {
51
- this.channel.writeAndFlushSync(packet)
65
+ if (this.codec?.attached !== true) {
66
+ this.codec = PacketCodec.on(this.channel)
67
+ }
68
+
69
+ if (this.codec?.send(packet) === true) {
70
+ if (!this.reading) void this.channel.flush()
71
+ return
72
+ }
73
+
74
+ if (this.reading) this.channel.writeSync(packet)
75
+ else this.channel.writeAndFlushSync(packet)
52
76
  }
53
77
 
54
78
  /**
@@ -261,6 +261,11 @@ const Code = {
261
261
  * @class
262
262
  */
263
263
  export class Protocol18 extends BinaryProtocolAdapter {
264
+ /**
265
+ * Longest text read straight away through the name cache
266
+ */
267
+ private static readonly named: number = 24
268
+
264
269
  /**
265
270
  * Custom type codes below this go out in the slim form
266
271
  */
@@ -376,7 +381,7 @@ export class Protocol18 extends BinaryProtocolAdapter {
376
381
  case Code.DOUBLE_ZERO:
377
382
  return PhotonValue.double(0)
378
383
  case Code.STRING:
379
- return PhotonValue.string(this.decodeString(buffer))
384
+ return this.decodeText(buffer)
380
385
  case Code.BYTE_ARRAY:
381
386
  return PhotonValue.bytes(this.decodeBytes(buffer))
382
387
  case Code.CUSTOM:
@@ -392,6 +397,13 @@ export class Protocol18 extends BinaryProtocolAdapter {
392
397
  * @param buffer where it goes
393
398
  */
394
399
  protected encodeValue(value: PhotonValue, buffer: ByteBuf): void {
400
+ const spelt = value.spelling
401
+ if (spelt !== null) {
402
+ buffer.writeUint8(Code.STRING)
403
+ this.encodeBytes(spelt, buffer)
404
+ return
405
+ }
406
+
395
407
  const data = value.data
396
408
 
397
409
  switch (value.shape.kind) {
@@ -606,6 +618,19 @@ export class Protocol18 extends BinaryProtocolAdapter {
606
618
  return BigInt.asIntN(64, (raw >> 1n) ^ -(raw & 1n))
607
619
  }
608
620
 
621
+ /**
622
+ * Reads a string value, keeping a long one as bytes until it's read
623
+ * @param buffer bytes to read from
624
+ */
625
+ private decodeText(buffer: ByteBuf): PhotonValue {
626
+ const size = this.size(this.decodeCount(buffer), buffer)
627
+ if (size <= Protocol18.named) {
628
+ return PhotonValue.string(this.names.read(size, buffer))
629
+ }
630
+
631
+ return PhotonValue.text(buffer.readBytes(size))
632
+ }
633
+
609
634
  /**
610
635
  * Reads a string with its length
611
636
  * @param buffer bytes to read from
@@ -55,15 +55,30 @@ export class PhotonValue {
55
55
  (string | undefined)[]
56
56
  >()
57
57
 
58
+ /**
59
+ * Turns kept UTF-8 bytes into text
60
+ */
61
+ private static readonly utf8: TextDecoder = new TextDecoder()
62
+
58
63
  /**
59
64
  * Its exact type
60
65
  */
61
66
  public readonly shape: Shape
62
67
 
63
68
  /**
64
- * What it holds
69
+ * What it holds, once it's been read
70
+ */
71
+ private held: PhotonData
72
+
73
+ /**
74
+ * UTF-8 bytes of a text that came off the wire, or null
65
75
  */
66
- public readonly data: PhotonData
76
+ private spelt: Uint8Array | null
77
+
78
+ /**
79
+ * Whether the text still has to be read out of its bytes
80
+ */
81
+ private waiting: boolean
67
82
 
68
83
  /**
69
84
  * What tables file it under once it's been worked out, or null
@@ -81,11 +96,33 @@ export class PhotonValue {
81
96
  */
82
97
  private constructor(shape: Shape, data: PhotonData) {
83
98
  this.shape = shape
84
- this.data = data
99
+ this.held = data
100
+ this.spelt = null
101
+ this.waiting = false
85
102
  this.label = null
86
103
  this.labelled = false
87
104
  }
88
105
 
106
+ /**
107
+ * What it holds
108
+ */
109
+ public get data(): PhotonData {
110
+ const spelt = this.spelt
111
+ if (this.waiting && spelt !== null) {
112
+ this.held = PhotonValue.utf8.decode(spelt)
113
+ this.waiting = false
114
+ }
115
+
116
+ return this.held
117
+ }
118
+
119
+ /**
120
+ * UTF-8 bytes of a text read off the wire, or null
121
+ */
122
+ public get spelling(): Uint8Array | null {
123
+ return this.spelt
124
+ }
125
+
89
126
  /**
90
127
  * A value of any shape
91
128
  * @param shape its exact type
@@ -177,6 +214,18 @@ export class PhotonValue {
177
214
  return new PhotonValue(Shape.string(), value)
178
215
  }
179
216
 
217
+ /**
218
+ * A text kept as its UTF-8 bytes until something reads it
219
+ * @param bytes the text as UTF-8, owned by the value from now on
220
+ */
221
+ public static text(bytes: Uint8Array): PhotonValue {
222
+ const value = new PhotonValue(Shape.string(), '')
223
+ value.spelt = bytes
224
+ value.waiting = true
225
+
226
+ return value
227
+ }
228
+
180
229
  /**
181
230
  * Raw bytes
182
231
  * @param value what to hold
@@ -146,6 +146,24 @@ export class BinaryFormat implements MessageFormat {
146
146
  )
147
147
  }
148
148
 
149
+ /**
150
+ * A clear message serialised into the shared scratch, or null
151
+ * @param message what to send
152
+ * @param peer the connection it leaves on
153
+ */
154
+ public scratch(message: WireMessage, peer: PhotonPeer): ByteBuf | null {
155
+ if (
156
+ message.type === MessageType.INIT ||
157
+ message.type === MessageType.INIT_RESPONSE ||
158
+ message.body instanceof Uint8Array ||
159
+ (message.encrypted && peer.cipher !== null)
160
+ ) {
161
+ return null
162
+ }
163
+
164
+ return BinaryFormat.fill(message, peer, true)
165
+ }
166
+
149
167
  /**
150
168
  * The frame for a message, or null
151
169
  * @param message what to send
@@ -266,6 +284,22 @@ export class BinaryFormat implements MessageFormat {
266
284
  const body = message.body
267
285
  if (body instanceof Uint8Array) return body
268
286
 
287
+ const buffer = BinaryFormat.fill(message, peer, headed)
288
+ return buffer.readBytes(buffer.readableBytes)
289
+ }
290
+
291
+ /**
292
+ * Serialises a message into the shared scratch
293
+ * @param message what to send, with a body to serialise
294
+ * @param peer the connection it leaves on
295
+ * @param headed whether the magic byte and type go first
296
+ */
297
+ private static fill(
298
+ message: WireMessage,
299
+ peer: PhotonPeer,
300
+ headed: boolean,
301
+ ): ByteBuf {
302
+ const body = message.body
269
303
  const serialiser = BinaryFormat.serialiser(peer)
270
304
  const buffer = BinaryFormat.scratch.clear()
271
305
  if (headed) buffer.writeUint8(BinaryFormat.MAGIC).writeUint8(message.type)
@@ -284,6 +318,6 @@ export class BinaryFormat implements MessageFormat {
284
318
  throw new Error('Message has no body')
285
319
  }
286
320
 
287
- return buffer.readBytes(buffer.readableBytes)
321
+ return buffer
288
322
  }
289
323
  }
@@ -1,3 +1,5 @@
1
+ import type { ByteBuf } from '@netifyjs/netify'
2
+
1
3
  import type { PhotonPeer } from '../peer/index.ts'
2
4
  import type { WireMessage } from '../wire/index.ts'
3
5
 
@@ -18,4 +20,11 @@ export type MessageFormat = {
18
20
  * @param peer the connection it leaves on
19
21
  */
20
22
  encode(message: WireMessage, peer: PhotonPeer): unknown
23
+
24
+ /**
25
+ * Encodes a message into room shared by every connection, or null
26
+ * @param message what to send
27
+ * @param peer the connection it leaves on
28
+ */
29
+ scratch?(message: WireMessage, peer: PhotonPeer): ByteBuf | null
21
30
  }
@@ -6,6 +6,7 @@ import {
6
6
 
7
7
  import { PacketCodec } from '../../../codec/index.ts'
8
8
  import { Envelope } from '../../envelope/index.ts'
9
+ import { TcpCodec } from '../../tcp/codec/index.ts'
9
10
  import type { MessageFormat } from '../format/index.ts'
10
11
  import type { PhotonPeer } from '../peer/index.ts'
11
12
  import { WireMessage } from '../wire/index.ts'
@@ -80,6 +81,7 @@ export abstract class MessageHandlerAdapter extends DuplexHandlerAdapter {
80
81
  public writeSync(context: HandlerContext, message: unknown): boolean {
81
82
  const wire = MessageHandlerAdapter.wire(message)
82
83
  if (wire === null) return false
84
+ if (this.staged(context, wire)) return true
83
85
 
84
86
  let unit: unknown
85
87
  try {
@@ -163,6 +165,31 @@ export abstract class MessageHandlerAdapter extends DuplexHandlerAdapter {
163
165
  : null
164
166
  }
165
167
 
168
+ /**
169
+ * Frames a clear message straight into the socket's outbound bytes, or false
170
+ * @param context the handler's place in the pipeline
171
+ * @param message what to send
172
+ */
173
+ private staged(context: HandlerContext, message: WireMessage): boolean {
174
+ const codec = context.previous
175
+ const handler = codec?.handler
176
+ if (codec === null || !(handler instanceof TcpCodec)) return false
177
+ if (this.refusal(message) !== null) return false
178
+
179
+ const bytes = this.format.scratch?.(message, this.peer) ?? null
180
+ return (
181
+ bytes !== null &&
182
+ handler.stage(
183
+ codec,
184
+ message.channel,
185
+ message.delivery,
186
+ bytes.array,
187
+ bytes.arrayOffset + bytes.readerIndex,
188
+ bytes.readableBytes,
189
+ )
190
+ )
191
+ }
192
+
166
193
  /**
167
194
  * What the transport sends for a message, or null
168
195
  * @param message what the application wrote
@@ -1,30 +1,165 @@
1
- import { type HandlerContext, IdleStateHandler } from '@netifyjs/netify'
1
+ import {
2
+ IdleStateEvent,
3
+ InboundHandlerAdapter,
4
+ type HandlerContext,
5
+ } from '@netifyjs/netify'
2
6
 
3
7
  /**
4
- * Notices a client that stopped sending, without a promise per write
8
+ * Notices a client that stopped sending, and stays out of the way of writes
5
9
  * @class
6
10
  */
7
- export class QuietWatch extends IdleStateHandler {
11
+ export class QuietWatch extends InboundHandlerAdapter {
12
+ /**
13
+ * Time allowed between received data in ms
14
+ */
15
+ private readonly timeout: number
16
+
17
+ /**
18
+ * Pending check, or null
19
+ */
20
+ private timer: Timer | null
21
+
22
+ /**
23
+ * Clock time the last read ended
24
+ */
25
+ private lastRead: number
26
+
27
+ /**
28
+ * Whether a read is under way
29
+ */
30
+ private reading: boolean
31
+
32
+ /**
33
+ * Whether the next idle event is the first of this quiet spell
34
+ */
35
+ private first: boolean
36
+
8
37
  /**
9
38
  * @param timeout time allowed between received data in ms
10
39
  */
11
40
  public constructor(timeout: number) {
12
- super({
13
- /**
14
- * Time allowed between received data
15
- */
16
- readerIdle: timeout,
17
- })
41
+ super()
42
+
43
+ this.timeout = timeout
44
+ this.timer = null
45
+ this.lastRead = 0
46
+ this.reading = false
47
+ this.first = true
48
+ }
49
+
50
+ /**
51
+ * Starts watching a connection that's already up
52
+ * @param context its place in the pipeline
53
+ */
54
+ public handlerAdded(context: HandlerContext): void {
55
+ if (context.channel.isActive) this.start(context)
56
+ }
57
+
58
+ /**
59
+ * Stops watching
60
+ */
61
+ public handlerRemoved(): void {
62
+ this.stop()
63
+ }
64
+
65
+ /**
66
+ * Starts watching once the connection is up
67
+ * @param context the connection
68
+ */
69
+ public override channelActive(context: HandlerContext): Promise<void> {
70
+ this.start(context)
71
+
72
+ return context.fireChannelActive()
73
+ }
74
+
75
+ /**
76
+ * Stops watching once the connection is gone
77
+ * @param context the connection
78
+ */
79
+ public override channelInactive(context: HandlerContext): Promise<void> {
80
+ this.stop()
81
+
82
+ return context.fireChannelInactive()
83
+ }
84
+
85
+ /**
86
+ * Notes that the client spoke
87
+ * @param context the connection
88
+ * @param message what arrived
89
+ */
90
+ public override channelRead(
91
+ context: HandlerContext,
92
+ message: unknown,
93
+ ): void | Promise<void> {
94
+ this.reading = true
95
+ this.first = true
96
+
97
+ return context.fireChannelRead(message)
98
+ }
99
+
100
+ /**
101
+ * Notes when the client last spoke
102
+ * @param context the connection
103
+ */
104
+ public override channelReadComplete(context: HandlerContext): Promise<void> {
105
+ this.reading = false
106
+ this.lastRead = performance.now()
107
+
108
+ return context.fireChannelReadComplete()
109
+ }
110
+
111
+ /**
112
+ * Starts the clock
113
+ * @param context the connection
114
+ */
115
+ private start(context: HandlerContext): void {
116
+ if (this.timer !== null) return
117
+
118
+ this.lastRead = performance.now()
119
+ this.reading = false
120
+ this.first = true
121
+ this.schedule(context, this.timeout)
122
+ }
123
+
124
+ /**
125
+ * Stops the clock
126
+ */
127
+ private stop(): void {
128
+ if (this.timer !== null) clearTimeout(this.timer)
129
+ this.timer = null
18
130
  }
19
131
 
20
132
  /**
21
- * Passes a write on untouched
22
- * @param context where the write goes
23
- * @param message what's being written
133
+ * Looks again after a while
134
+ * @param context the connection
135
+ * @param delay how long to wait in ms
24
136
  */
25
- public writeSync(context: HandlerContext, message: unknown): boolean {
26
- context.writeSync(message)
137
+ private schedule(context: HandlerContext, delay: number): void {
138
+ const timer = setTimeout((): void => {
139
+ void context.channel.execute((): Promise<void> => this.check(context))
140
+ }, delay)
141
+ timer.unref()
142
+
143
+ this.timer = timer
144
+ }
145
+
146
+ /**
147
+ * Raises an idle event if the client has been quiet too long
148
+ * @param context the connection
149
+ */
150
+ private async check(context: HandlerContext): Promise<void> {
151
+ if (this.timer === null) return
152
+
153
+ const remaining = this.timeout - (performance.now() - this.lastRead)
154
+ if (this.reading || remaining > 0) {
155
+ this.schedule(context, this.reading ? this.timeout : remaining)
156
+ return
157
+ }
158
+
159
+ this.schedule(context, this.timeout)
27
160
 
28
- return true
161
+ const first = this.first
162
+ this.first = false
163
+ await context.fireUserEventTriggered(new IdleStateEvent('reader', first))
29
164
  }
30
165
  }
@@ -224,6 +224,11 @@ export type PhotonConfig = {
224
224
  */
225
225
  readonly udp?: EnetOptions
226
226
 
227
+ /**
228
+ * Milliseconds TCP and WebSocket writes wait to go out together, off by default
229
+ */
230
+ readonly flushDelay?: number
231
+
227
232
  /**
228
233
  * Runs the waits of the Game Servers, the wall clock by default
229
234
  */
@@ -550,6 +550,10 @@ export class PhotonServer {
550
550
  * Timing and limits of reliable UDP
551
551
  */
552
552
  udp: this.config.udp ?? {},
553
+ /**
554
+ * Off unless the config asks for it
555
+ */
556
+ flushDelay: this.config.flushDelay ?? 0,
553
557
  logger: this.config.logger,
554
558
  })
555
559
 
@@ -60,6 +60,11 @@ export type ListenOptions = {
60
60
  */
61
61
  readonly udp: EnetOptions
62
62
 
63
+ /**
64
+ * Milliseconds stream writes wait to go out together, 0 for none
65
+ */
66
+ readonly flushDelay: number
67
+
63
68
  /**
64
69
  * Hears about a socket buffer the system wouldn't grant
65
70
  */
@@ -233,6 +238,12 @@ export class Listeners {
233
238
  */
234
239
  reusePort: options.reusePort,
235
240
  })
241
+ .childOptions({
242
+ /**
243
+ * Lets writes build up before they go out
244
+ */
245
+ flushDelay: options.flushDelay,
246
+ })
236
247
  .childHandler(setup)
237
248
  .bind({
238
249
  ...(options.hostname === undefined
@@ -8,7 +8,7 @@ import {
8
8
  } from '@netifyjs/netify'
9
9
 
10
10
  import { PacketCodec } from '../../../codec/index.ts'
11
- import { Frame } from '../../frame/index.ts'
11
+ import { type DeliveryMode, Frame } from '../../frame/index.ts'
12
12
  import { ServerClock } from '../clock/index.ts'
13
13
  import { TcpFraming } from '../framing/index.ts'
14
14
 
@@ -135,6 +135,38 @@ export abstract class TcpCodec<O = unknown> extends ByteToMessageDecoder<O> {
135
135
  throw new DecoderError(reason)
136
136
  }
137
137
 
138
+ /**
139
+ * Frames payload bytes straight into the socket's outbound bytes, or false
140
+ * @param context the codec's place in the pipeline
141
+ * @param channel the message's channel
142
+ * @param delivery how it's delivered
143
+ * @param source holds the payload, copied before this returns
144
+ * @param start where it begins
145
+ * @param length how many bytes it takes
146
+ */
147
+ public stage(
148
+ context: HandlerContext,
149
+ channel: number,
150
+ delivery: DeliveryMode,
151
+ source: Uint8Array,
152
+ start: number,
153
+ length: number,
154
+ ): boolean {
155
+ const size = TcpFraming.HEADER + length
156
+ if (this.framing.refusal(size) !== null) return false
157
+
158
+ const staging = PacketCodec.staging(context)
159
+ const offset = staging === null ? -1 : staging.reserve(size)
160
+ if (staging === null || offset < 0) return false
161
+
162
+ const target = staging.stagingBuffer
163
+ this.framing.head(channel, delivery, length, target, offset)
164
+ ByteBuf.copyBytes(source, start, target, offset + TcpFraming.HEADER, length)
165
+ staging.commitStaged()
166
+
167
+ return true
168
+ }
169
+
138
170
  /**
139
171
  * Frames a message straight into the socket's outbound bytes, or false
140
172
  * @param context where the bytes go
@@ -94,16 +94,36 @@ export class TcpFraming {
94
94
  * @param offset where it starts in the target
95
95
  */
96
96
  public write(frame: Frame, target: Uint8Array, offset: number): void {
97
- const size = TcpFraming.HEADER + frame.payload.length
97
+ const payload = frame.payload
98
+
99
+ this.head(frame.channel, frame.delivery, payload.length, target, offset)
100
+ target.set(payload, offset + TcpFraming.HEADER)
101
+ }
102
+
103
+ /**
104
+ * Writes a header for a payload that follows it
105
+ * @param channel the message's channel
106
+ * @param delivery how it's delivered
107
+ * @param length bytes of payload
108
+ * @param target where it goes
109
+ * @param offset where the header starts
110
+ */
111
+ public head(
112
+ channel: number,
113
+ delivery: DeliveryMode,
114
+ length: number,
115
+ target: Uint8Array,
116
+ offset: number,
117
+ ): void {
118
+ const size = TcpFraming.HEADER + length
98
119
 
99
120
  target[offset] = TcpFraming.MAGIC
100
121
  target[offset + 1] = size >>> 24
101
122
  target[offset + 2] = size >>> 16
102
123
  target[offset + 3] = size >>> 8
103
124
  target[offset + 4] = size
104
- target[offset + 5] = frame.channel
105
- target[offset + 6] = frame.delivery
106
- target.set(frame.payload, offset + TcpFraming.HEADER)
125
+ target[offset + 5] = channel
126
+ target[offset + 6] = delivery
107
127
  }
108
128
 
109
129
  /**
@@ -3,10 +3,18 @@ import { ByteBuf } from '@netifyjs/netify'
3
3
  /**
4
4
  * Hears one session's share of a batch
5
5
  * @param id the session on the client's shard
6
- * @param bytes its frames, a view into the batch
6
+ * @param bytes the whole batch, borrowed for the call
7
+ * @param start where the session's frames begin
8
+ * @param size how many bytes they take
7
9
  * @param from the shard that sent the batch
8
10
  */
9
- export type BatchVisitor = (id: number, bytes: Uint8Array, from: number) => void
11
+ export type BatchVisitor = (
12
+ id: number,
13
+ bytes: Uint8Array,
14
+ start: number,
15
+ size: number,
16
+ from: number,
17
+ ) => void
10
18
 
11
19
  /**
12
20
  * Everything a batch held as it was taken
@@ -185,11 +193,11 @@ export class Batch {
185
193
  while (at + Batch.HEAD <= bytes.length) {
186
194
  const id = Batch.word(bytes, at)
187
195
  const start = at + Batch.HEAD
188
- const end = start + Batch.word(bytes, at + 4)
189
- if (end > bytes.length) throw new Error('Batch is cut short')
196
+ const size = Batch.word(bytes, at + 4)
197
+ if (start + size > bytes.length) throw new Error('Batch is cut short')
190
198
 
191
- visit(id, bytes.subarray(start, end), from)
192
- at = end
199
+ visit(id, bytes, start, size, from)
200
+ at = start + size
193
201
  }
194
202
  }
195
203
 
@@ -64,13 +64,32 @@ export class TunnelRelay extends InboundHandlerAdapter {
64
64
 
65
65
  /**
66
66
  * Writes bytes from the session's shard to the client
67
- * @param bytes whole frames
67
+ * @param source holds whole frames and is never written again
68
+ * @param start where they begin
69
+ * @param size how many bytes they take
68
70
  */
69
- public deliver(bytes: Uint8Array): void {
71
+ public deliver(source: Uint8Array, start: number, size: number): void {
70
72
  const context = this.context
71
73
  if (context === null) return
72
74
 
73
- context.writeAndFlushSync(ByteBuf.wrap(bytes))
75
+ const channel = context.channel
76
+ const offset = context.writesToSocket ? channel.reserve(size) : -1
77
+ if (offset < 0) {
78
+ context.writeAndFlushSync(
79
+ new ByteBuf(
80
+ source,
81
+ size,
82
+ ByteBuf.defaultMaxCapacity,
83
+ start,
84
+ start + size,
85
+ ),
86
+ )
87
+ return
88
+ }
89
+
90
+ ByteBuf.copyBytes(source, start, channel.stagingBuffer, offset, size)
91
+ channel.commitStaged()
92
+ channel.flushEncoded()
74
93
  }
75
94
 
76
95
  /**
@@ -1,5 +1,6 @@
1
1
  import {
2
2
  AttributeKey,
3
+ ByteBuf,
3
4
  ShutdownEvent,
4
5
  type Channel,
5
6
  type ChannelHandler,
@@ -272,11 +273,34 @@ export class Tunnel<S = unknown> {
272
273
  this.strand(ids)
273
274
  },
274
275
  )
275
- this.delivering = (id: number, bytes: Uint8Array): void => {
276
- this.fronted.get(id)?.relay.deliver(bytes)
276
+ this.delivering = (
277
+ id: number,
278
+ bytes: Uint8Array,
279
+ start: number,
280
+ size: number,
281
+ ): void => {
282
+ this.fronted.get(id)?.relay.deliver(bytes, start, size)
277
283
  }
278
- this.arriving = (id: number, bytes: Uint8Array, from: number): void => {
279
- void this.guests.get(from)?.get(id)?.channel.handleData(bytes)
284
+ this.arriving = (
285
+ id: number,
286
+ bytes: Uint8Array,
287
+ start: number,
288
+ size: number,
289
+ from: number,
290
+ ): void => {
291
+ const guest = this.guests.get(from)?.get(id)
292
+ if (guest === undefined) return
293
+
294
+ void guest.channel.handleMessage(
295
+ new ByteBuf(
296
+ bytes,
297
+ size,
298
+ ByteBuf.defaultMaxCapacity,
299
+ start,
300
+ start + size,
301
+ ),
302
+ size,
303
+ )
280
304
  }
281
305
 
282
306
  this.courier
@@ -651,7 +675,7 @@ export class Tunnel<S = unknown> {
651
675
  if (session === undefined) continue
652
676
 
653
677
  if (session.reach === 'socket') this.share(session.channel, bytes)
654
- else session.relay.deliver(bytes)
678
+ else session.relay.deliver(bytes, 0, bytes.length)
655
679
  }
656
680
  }
657
681
 
@@ -117,7 +117,9 @@ export class SmartFox2XCodec extends PacketCodec<object> {
117
117
  * Puts the protocol's gate behind this codec
118
118
  * @param context the connection
119
119
  */
120
- public handlerAdded(context: HandlerContext): void {
120
+ public override handlerAdded(context: HandlerContext): void {
121
+ super.handlerAdded(context)
122
+
121
123
  const gate = this.protocol.gate
122
124
  if (gate === null) return
123
125