@netifyjs/protocol 1.0.0-alpha.1 → 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.
@@ -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
  }
@@ -4,7 +4,9 @@ import {
4
4
  type HandlerContext,
5
5
  } from '@netifyjs/netify'
6
6
 
7
+ import { PacketCodec } from '../../../codec/index.ts'
7
8
  import { Envelope } from '../../envelope/index.ts'
9
+ import { TcpCodec } from '../../tcp/codec/index.ts'
8
10
  import type { MessageFormat } from '../format/index.ts'
9
11
  import type { PhotonPeer } from '../peer/index.ts'
10
12
  import { WireMessage } from '../wire/index.ts'
@@ -35,6 +37,20 @@ export abstract class MessageHandlerAdapter extends DuplexHandlerAdapter {
35
37
  this.format = format
36
38
  }
37
39
 
40
+ /**
41
+ * Hangs up on a client too slow to take its frames
42
+ * @param context the connection
43
+ * @param error what went wrong
44
+ */
45
+ public override exceptionCaught(
46
+ context: HandlerContext,
47
+ error: unknown,
48
+ ): Promise<void> {
49
+ if (PacketCodec.overflowed(error)) void context.close()
50
+
51
+ return context.fireExceptionCaught(error)
52
+ }
53
+
38
54
  /**
39
55
  * Sends envelopes and messages in the connection's format
40
56
  * @param context where the write goes
@@ -65,6 +81,7 @@ export abstract class MessageHandlerAdapter extends DuplexHandlerAdapter {
65
81
  public writeSync(context: HandlerContext, message: unknown): boolean {
66
82
  const wire = MessageHandlerAdapter.wire(message)
67
83
  if (wire === null) return false
84
+ if (this.staged(context, wire)) return true
68
85
 
69
86
  let unit: unknown
70
87
  try {
@@ -148,6 +165,31 @@ export abstract class MessageHandlerAdapter extends DuplexHandlerAdapter {
148
165
  : null
149
166
  }
150
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
+
151
193
  /**
152
194
  * What the transport sends for a message, or null
153
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
@@ -7,7 +7,8 @@ import {
7
7
  type HandlerContext,
8
8
  } from '@netifyjs/netify'
9
9
 
10
- import { Frame } from '../../frame/index.ts'
10
+ import { PacketCodec } from '../../../codec/index.ts'
11
+ import { type DeliveryMode, Frame } from '../../frame/index.ts'
11
12
  import { ServerClock } from '../clock/index.ts'
12
13
  import { TcpFraming } from '../framing/index.ts'
13
14
 
@@ -134,6 +135,38 @@ export abstract class TcpCodec<O = unknown> extends ByteToMessageDecoder<O> {
134
135
  throw new DecoderError(reason)
135
136
  }
136
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
+
137
170
  /**
138
171
  * Frames a message straight into the socket's outbound bytes, or false
139
172
  * @param context where the bytes go
@@ -141,16 +174,14 @@ export abstract class TcpCodec<O = unknown> extends ByteToMessageDecoder<O> {
141
174
  */
142
175
  private staged(context: HandlerContext, frame: Frame): boolean {
143
176
  const size = TcpFraming.HEADER + frame.payload.length
144
- if (!context.writesToSocket || this.framing.refusal(size) !== null) {
145
- return false
146
- }
177
+ if (this.framing.refusal(size) !== null) return false
147
178
 
148
- const channel = context.channel
149
- const offset = channel.reserve(size)
150
- if (offset < 0) return false
179
+ const staging = PacketCodec.staging(context)
180
+ const offset = staging === null ? -1 : staging.reserve(size)
181
+ if (staging === null || offset < 0) return false
151
182
 
152
- this.framing.write(frame, channel.stagingBuffer, offset)
153
- channel.commitStaged()
183
+ this.framing.write(frame, staging.stagingBuffer, offset)
184
+ staging.commitStaged()
154
185
 
155
186
  return true
156
187
  }
@@ -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
  /**
@@ -0,0 +1,218 @@
1
+ import { ByteBuf } from '@netifyjs/netify'
2
+
3
+ /**
4
+ * Hears one session's share of a batch
5
+ * @param id the session on the client's shard
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
9
+ * @param from the shard that sent the batch
10
+ */
11
+ export type BatchVisitor = (
12
+ id: number,
13
+ bytes: Uint8Array,
14
+ start: number,
15
+ size: number,
16
+ from: number,
17
+ ) => void
18
+
19
+ /**
20
+ * Everything a batch held as it was taken
21
+ */
22
+ export type BatchTaken = {
23
+ /**
24
+ * Every entry, ready for the link
25
+ */
26
+ readonly bytes: Uint8Array
27
+
28
+ /**
29
+ * Sessions with bytes in it
30
+ */
31
+ readonly ids: readonly number[]
32
+ }
33
+
34
+ /**
35
+ * Session bytes bound for one shard, packed as id, size and frames
36
+ * @class
37
+ */
38
+ export class Batch {
39
+ /**
40
+ * Bytes an entry takes before its frames
41
+ */
42
+ public static readonly HEAD: number = 8
43
+
44
+ /**
45
+ * Where entries pile up
46
+ */
47
+ private readonly buffer: ByteBuf
48
+
49
+ /**
50
+ * Sessions with bytes waiting
51
+ */
52
+ private readonly ids: Set<number>
53
+
54
+ /**
55
+ * Session of the newest entry, or -1
56
+ */
57
+ private latest: number
58
+
59
+ /**
60
+ * Where the newest entry keeps its size
61
+ */
62
+ private sized: number
63
+
64
+ /**
65
+ * @param capacity room to start with
66
+ */
67
+ private constructor(capacity: number) {
68
+ this.buffer = ByteBuf.allocate(capacity)
69
+ this.ids = new Set<number>()
70
+ this.latest = -1
71
+ this.sized = 0
72
+ }
73
+
74
+ /**
75
+ * An empty batch
76
+ * @param capacity room to start with
77
+ */
78
+ public static of(capacity: number): Batch {
79
+ return new Batch(capacity)
80
+ }
81
+
82
+ /**
83
+ * Bytes waiting
84
+ */
85
+ public get size(): number {
86
+ return this.buffer.readableBytes
87
+ }
88
+
89
+ /**
90
+ * Bytes a write would add
91
+ * @param id the session
92
+ * @param size its frames
93
+ */
94
+ public cost(id: number, size: number): number {
95
+ return id === this.latest ? size : Batch.HEAD + size
96
+ }
97
+
98
+ /**
99
+ * Copies a session's frames in
100
+ * @param id the session
101
+ * @param source holds its frames
102
+ * @param start where they begin
103
+ * @param size how many bytes they take
104
+ */
105
+ public add(
106
+ id: number,
107
+ source: Uint8Array,
108
+ start: number,
109
+ size: number,
110
+ ): void {
111
+ const buffer = this.buffer
112
+
113
+ if (id === this.latest) {
114
+ buffer.setUint32(this.sized, buffer.getUint32(this.sized) + size)
115
+ } else {
116
+ buffer.writeUint32(id)
117
+ this.sized = buffer.writerIndex
118
+ buffer.writeUint32(size)
119
+ this.latest = id
120
+ this.ids.add(id)
121
+ }
122
+
123
+ buffer.ensureWritable(size)
124
+ const at = buffer.writerIndex
125
+ ByteBuf.copyBytes(
126
+ source,
127
+ start,
128
+ buffer.array,
129
+ buffer.arrayOffset + at,
130
+ size,
131
+ )
132
+ buffer.writerIndex = at + size
133
+ }
134
+
135
+ /**
136
+ * Hands over a copy of everything and starts again empty
137
+ */
138
+ public take(): BatchTaken {
139
+ const taken: BatchTaken = {
140
+ bytes: this.buffer.readBytes(this.buffer.readableBytes),
141
+ ids: [...this.ids],
142
+ }
143
+
144
+ this.clear()
145
+ return taken
146
+ }
147
+
148
+ /**
149
+ * Drops everything waiting
150
+ */
151
+ public clear(): void {
152
+ this.buffer.clear()
153
+ this.ids.clear()
154
+ this.latest = -1
155
+ this.sized = 0
156
+ }
157
+
158
+ /**
159
+ * A batch of one entry, ready for the link
160
+ * @param id the session
161
+ * @param source holds its frames
162
+ * @param start where they begin
163
+ * @param size how many bytes they take
164
+ */
165
+ public static one(
166
+ id: number,
167
+ source: Uint8Array,
168
+ start: number,
169
+ size: number,
170
+ ): Uint8Array {
171
+ const packed = new Uint8Array(Batch.HEAD + size)
172
+ const view = new DataView(packed.buffer)
173
+
174
+ view.setUint32(0, id)
175
+ view.setUint32(4, size)
176
+ ByteBuf.copyBytes(source, start, packed, Batch.HEAD, size)
177
+
178
+ return packed
179
+ }
180
+
181
+ /**
182
+ * Walks the entries of a batch that crossed the link
183
+ * @param bytes the whole batch
184
+ * @param from the shard that sent it
185
+ * @param visit gets each entry in order
186
+ */
187
+ public static read(
188
+ bytes: Uint8Array,
189
+ from: number,
190
+ visit: BatchVisitor,
191
+ ): void {
192
+ let at = 0
193
+ while (at + Batch.HEAD <= bytes.length) {
194
+ const id = Batch.word(bytes, at)
195
+ const start = at + Batch.HEAD
196
+ const size = Batch.word(bytes, at + 4)
197
+ if (start + size > bytes.length) throw new Error('Batch is cut short')
198
+
199
+ visit(id, bytes, start, size, from)
200
+ at = start + size
201
+ }
202
+ }
203
+
204
+ /**
205
+ * A big endian 32 bit number out of a batch
206
+ * @param bytes the batch
207
+ * @param at where the number starts
208
+ */
209
+ private static word(bytes: Uint8Array, at: number): number {
210
+ return (
211
+ (((bytes[at] ?? 0) << 24) |
212
+ ((bytes[at + 1] ?? 0) << 16) |
213
+ ((bytes[at + 2] ?? 0) << 8) |
214
+ (bytes[at + 3] ?? 0)) >>>
215
+ 0
216
+ )
217
+ }
218
+ }