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

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.1",
4
+ "version": "1.0.0-alpha.2",
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.10"
40
+ "@netifyjs/netify": ">=1.0.0-alpha.11"
41
41
  },
42
42
  "devDependencies": {
43
43
  "@eslint/js": "^10.0.1",
@@ -2,17 +2,46 @@ import {
2
2
  ByteBuf,
3
3
  ByteToMessageDecoder,
4
4
  EncoderError,
5
+ QueueFullError,
5
6
  type DecoderOptions,
6
7
  type HandlerContext,
7
8
  } from '@netifyjs/netify'
8
9
 
9
10
  import type { DirectWriter, Protocol } from '../protocol/index.ts'
11
+ import { TunnelOutlet } from '../scale/outlet/index.ts'
12
+
13
+ /**
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
+ }
10
34
 
11
35
  /**
12
36
  * Base for a protocol's pipeline handler, with the outbound half done
13
37
  * @class
14
38
  */
15
39
  export abstract class PacketCodec<O = unknown> extends ByteToMessageDecoder<O> {
40
+ /**
41
+ * Causes looked through before giving up
42
+ */
43
+ private static readonly causes: number = 8
44
+
16
45
  /**
17
46
  * The protocol that knows the wire format
18
47
  */
@@ -73,6 +102,20 @@ export abstract class PacketCodec<O = unknown> extends ByteToMessageDecoder<O> {
73
102
  return true
74
103
  }
75
104
 
105
+ /**
106
+ * Hangs up on a client too slow to take its frames
107
+ * @param context the connection
108
+ * @param error what went wrong
109
+ */
110
+ public override exceptionCaught(
111
+ context: HandlerContext,
112
+ error: unknown,
113
+ ): Promise<void> {
114
+ if (PacketCodec.overflowed(error)) void context.close()
115
+
116
+ return context.fireExceptionCaught(error)
117
+ }
118
+
76
119
  /**
77
120
  * Encodes packets and lets everything else through
78
121
  * @param context where the bytes go
@@ -119,34 +162,57 @@ export abstract class PacketCodec<O = unknown> extends ByteToMessageDecoder<O> {
119
162
  private direct(context: HandlerContext, message: unknown): boolean {
120
163
  const writer = this.straight
121
164
  const room = writer === null ? -1 : writer.measure(message)
122
- if (writer === null || room < 0 || !context.writesToSocket) return false
165
+ const staging = room < 0 ? null : PacketCodec.staging(context)
166
+ if (writer === null || staging === null) return false
123
167
 
124
- const channel = context.channel
125
- const offset = channel.reserve(room)
168
+ const offset = staging.reserve(room)
126
169
  if (offset < 0) return false
127
170
 
128
171
  let taken = -1
129
172
  try {
130
- taken = writer.write(message, channel.stagingBuffer, offset)
173
+ taken = writer.write(message, staging.stagingBuffer, offset)
131
174
  } finally {
132
- channel.commitStaged(taken < 0 ? room : room - taken)
175
+ staging.commitStaged(taken < 0 ? room : room - taken)
133
176
  }
134
177
 
135
178
  return taken >= 0
136
179
  }
137
180
 
181
+ /**
182
+ * Whether an error comes from a full outbox
183
+ * @param error what the pipeline caught
184
+ */
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
196
+ }
197
+
198
+ /**
199
+ * Where the next write can be staged directly, or null
200
+ * @param context the codec's place in the pipeline
201
+ */
202
+ public static staging(context: HandlerContext): Staging | null {
203
+ if (context.writesToSocket) return context.channel
204
+
205
+ const outlet = context.previous?.handler
206
+ return outlet instanceof TunnelOutlet ? outlet : null
207
+ }
208
+
138
209
  /**
139
210
  * Writes encoded bytes without a promise
140
211
  * @param context where the bytes go
141
212
  * @param bytes one or more whole frames
142
213
  */
143
214
  protected static put(context: HandlerContext, bytes: Uint8Array): void {
144
- if (
145
- context.writesToSocket &&
146
- PacketCodec.stage(context, bytes, 0, bytes.length)
147
- ) {
148
- return
149
- }
215
+ if (PacketCodec.stage(context, bytes, 0, bytes.length)) return
150
216
 
151
217
  context.writeSync(ByteBuf.wrap(bytes))
152
218
  }
@@ -157,19 +223,16 @@ export abstract class PacketCodec<O = unknown> extends ByteToMessageDecoder<O> {
157
223
  * @param frame one or more whole frames
158
224
  */
159
225
  protected static pass(context: HandlerContext, frame: ByteBuf): boolean {
160
- return (
161
- context.writesToSocket &&
162
- PacketCodec.stage(
163
- context,
164
- frame.array,
165
- frame.arrayOffset + frame.readerIndex,
166
- frame.readableBytes,
167
- )
226
+ return PacketCodec.stage(
227
+ context,
228
+ frame.array,
229
+ frame.arrayOffset + frame.readerIndex,
230
+ frame.readableBytes,
168
231
  )
169
232
  }
170
233
 
171
234
  /**
172
- * Copies bytes into the connection's outbound buffer, false if they don't fit
235
+ * Copies bytes into the outbound room, false if there's none
173
236
  * @param context where the bytes go
174
237
  * @param source array the bytes live in
175
238
  * @param start where they begin
@@ -181,12 +244,12 @@ export abstract class PacketCodec<O = unknown> extends ByteToMessageDecoder<O> {
181
244
  start: number,
182
245
  size: number,
183
246
  ): boolean {
184
- const channel = context.channel
185
- const offset = channel.reserve(size)
186
- if (offset < 0) return false
247
+ const staging = PacketCodec.staging(context)
248
+ const offset = staging === null ? -1 : staging.reserve(size)
249
+ if (staging === null || offset < 0) return false
187
250
 
188
- ByteBuf.copyBytes(source, start, channel.stagingBuffer, offset, size)
189
- channel.commitStaged()
251
+ ByteBuf.copyBytes(source, start, staging.stagingBuffer, offset, size)
252
+ staging.commitStaged()
190
253
 
191
254
  return true
192
255
  }
package/src/index.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  export { PacketCodec } from './codec/index.ts'
2
+ export type { Staging } from './codec/index.ts'
2
3
  export {
3
4
  Closed,
4
5
  Opened,
@@ -22,12 +23,14 @@ export { NameTable } from './names/index.ts'
22
23
  export { type DirectWriter, Protocol } from './protocol/index.ts'
23
24
  export type { Role } from './protocol/index.ts'
24
25
  export {
26
+ Batch,
25
27
  Courier,
26
28
  DatagramSwitch,
27
29
  Fanout,
28
30
  Handoff,
29
31
  Layout,
30
32
  Mesh,
33
+ Pending,
31
34
  Placement,
32
35
  SinkTransport,
33
36
  Switchboard,
@@ -37,7 +40,10 @@ export {
37
40
  TunnelTransport,
38
41
  } from './scale/index.ts'
39
42
  export type {
43
+ BatchTaken,
44
+ BatchVisitor,
40
45
  CourierBytesListener,
46
+ CourierFlusher,
41
47
  CourierListener,
42
48
  CourierResponder,
43
49
  DatagramReceiver,
@@ -49,6 +55,7 @@ export type {
49
55
  Hosted,
50
56
  MeshOptions,
51
57
  OutletSink,
58
+ PendingLoss,
52
59
  PlacementRule,
53
60
  Portable,
54
61
  Reach,
@@ -64,7 +64,9 @@ export class ParameterTable {
64
64
  * @param code parameter code
65
65
  */
66
66
  public get(code: number): PhotonValue | null {
67
- return this.held[this.codes.indexOf(code)] ?? null
67
+ const at = this.codes.indexOf(code)
68
+
69
+ return at < 0 ? null : (this.held[at] ?? null)
68
70
  }
69
71
 
70
72
  /**
@@ -37,6 +37,24 @@ export class PhotonValue {
37
37
  null,
38
38
  )
39
39
 
40
+ /**
41
+ * Lowest whole number with a kept label
42
+ */
43
+ private static readonly lowest: number = -128
44
+
45
+ /**
46
+ * Highest whole number with a kept label
47
+ */
48
+ private static readonly highest: number = 255
49
+
50
+ /**
51
+ * Labels of small whole numbers, by kind and then value
52
+ */
53
+ private static readonly labels: Map<KindId, (string | undefined)[]> = new Map<
54
+ KindId,
55
+ (string | undefined)[]
56
+ >()
57
+
40
58
  /**
41
59
  * Its exact type
42
60
  */
@@ -271,14 +289,48 @@ export class PhotonValue {
271
289
  if (this.labelled) return this.label
272
290
 
273
291
  this.labelled = true
274
- this.label =
275
- typeof data === 'object'
276
- ? null
277
- : `\0${String(this.shape.kind)}:${String(data)}`
292
+ if (typeof data === 'number') {
293
+ this.label = PhotonValue.numbered(this.shape.kind, data)
294
+ } else {
295
+ this.label =
296
+ typeof data === 'object'
297
+ ? null
298
+ : `\0${String(this.shape.kind)}:${String(data)}`
299
+ }
278
300
 
279
301
  return this.label
280
302
  }
281
303
 
304
+ /**
305
+ * The label of a number, kept for small whole ones
306
+ * @param kind its type
307
+ * @param data the number
308
+ */
309
+ private static numbered(kind: KindId, data: number): string {
310
+ const small =
311
+ Number.isInteger(data) &&
312
+ data >= PhotonValue.lowest &&
313
+ data <= PhotonValue.highest
314
+ if (!small) return `\0${String(kind)}:${String(data)}`
315
+
316
+ let labels = PhotonValue.labels.get(kind)
317
+ if (labels === undefined) {
318
+ labels = new Array<string | undefined>(
319
+ PhotonValue.highest - PhotonValue.lowest + 1,
320
+ ).fill(undefined)
321
+ PhotonValue.labels.set(kind, labels)
322
+ }
323
+
324
+ const at = data - PhotonValue.lowest
325
+ const known = labels[at]
326
+ if (known !== undefined) return known
327
+
328
+ const label = `\0${String(kind)}:${String(data)}`
329
+ labels[at] = label
330
+
331
+ return label
332
+ }
333
+
282
334
  /**
283
335
  * A byte, short, int or long as a number, or null
284
336
  */
@@ -424,6 +424,8 @@ export class GameHandler {
424
424
  * @param session the connection
425
425
  */
426
426
  private peer(session: Session<GamePeer>): GamePeer {
427
+ if (session.user !== null) return session.user
428
+
427
429
  const peer = GamePeer.of(session.channel, this.services.clock.now())
428
430
  session.user = peer
429
431
 
@@ -4,6 +4,7 @@ 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'
8
9
  import type { MessageFormat } from '../format/index.ts'
9
10
  import type { PhotonPeer } from '../peer/index.ts'
@@ -35,6 +36,20 @@ export abstract class MessageHandlerAdapter extends DuplexHandlerAdapter {
35
36
  this.format = format
36
37
  }
37
38
 
39
+ /**
40
+ * Hangs up on a client too slow to take its frames
41
+ * @param context the connection
42
+ * @param error what went wrong
43
+ */
44
+ public override exceptionCaught(
45
+ context: HandlerContext,
46
+ error: unknown,
47
+ ): Promise<void> {
48
+ if (PacketCodec.overflowed(error)) void context.close()
49
+
50
+ return context.fireExceptionCaught(error)
51
+ }
52
+
38
53
  /**
39
54
  * Sends envelopes and messages in the connection's format
40
55
  * @param context where the write goes
@@ -7,6 +7,7 @@ import {
7
7
  type HandlerContext,
8
8
  } from '@netifyjs/netify'
9
9
 
10
+ import { PacketCodec } from '../../../codec/index.ts'
10
11
  import { Frame } from '../../frame/index.ts'
11
12
  import { ServerClock } from '../clock/index.ts'
12
13
  import { TcpFraming } from '../framing/index.ts'
@@ -141,16 +142,14 @@ export abstract class TcpCodec<O = unknown> extends ByteToMessageDecoder<O> {
141
142
  */
142
143
  private staged(context: HandlerContext, frame: Frame): boolean {
143
144
  const size = TcpFraming.HEADER + frame.payload.length
144
- if (!context.writesToSocket || this.framing.refusal(size) !== null) {
145
- return false
146
- }
145
+ if (this.framing.refusal(size) !== null) return false
147
146
 
148
- const channel = context.channel
149
- const offset = channel.reserve(size)
150
- if (offset < 0) return false
147
+ const staging = PacketCodec.staging(context)
148
+ const offset = staging === null ? -1 : staging.reserve(size)
149
+ if (staging === null || offset < 0) return false
151
150
 
152
- this.framing.write(frame, channel.stagingBuffer, offset)
153
- channel.commitStaged()
151
+ this.framing.write(frame, staging.stagingBuffer, offset)
152
+ staging.commitStaged()
154
153
 
155
154
  return true
156
155
  }
@@ -0,0 +1,210 @@
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 its frames, a view into the batch
7
+ * @param from the shard that sent the batch
8
+ */
9
+ export type BatchVisitor = (id: number, bytes: Uint8Array, from: number) => void
10
+
11
+ /**
12
+ * Everything a batch held as it was taken
13
+ */
14
+ export type BatchTaken = {
15
+ /**
16
+ * Every entry, ready for the link
17
+ */
18
+ readonly bytes: Uint8Array
19
+
20
+ /**
21
+ * Sessions with bytes in it
22
+ */
23
+ readonly ids: readonly number[]
24
+ }
25
+
26
+ /**
27
+ * Session bytes bound for one shard, packed as id, size and frames
28
+ * @class
29
+ */
30
+ export class Batch {
31
+ /**
32
+ * Bytes an entry takes before its frames
33
+ */
34
+ public static readonly HEAD: number = 8
35
+
36
+ /**
37
+ * Where entries pile up
38
+ */
39
+ private readonly buffer: ByteBuf
40
+
41
+ /**
42
+ * Sessions with bytes waiting
43
+ */
44
+ private readonly ids: Set<number>
45
+
46
+ /**
47
+ * Session of the newest entry, or -1
48
+ */
49
+ private latest: number
50
+
51
+ /**
52
+ * Where the newest entry keeps its size
53
+ */
54
+ private sized: number
55
+
56
+ /**
57
+ * @param capacity room to start with
58
+ */
59
+ private constructor(capacity: number) {
60
+ this.buffer = ByteBuf.allocate(capacity)
61
+ this.ids = new Set<number>()
62
+ this.latest = -1
63
+ this.sized = 0
64
+ }
65
+
66
+ /**
67
+ * An empty batch
68
+ * @param capacity room to start with
69
+ */
70
+ public static of(capacity: number): Batch {
71
+ return new Batch(capacity)
72
+ }
73
+
74
+ /**
75
+ * Bytes waiting
76
+ */
77
+ public get size(): number {
78
+ return this.buffer.readableBytes
79
+ }
80
+
81
+ /**
82
+ * Bytes a write would add
83
+ * @param id the session
84
+ * @param size its frames
85
+ */
86
+ public cost(id: number, size: number): number {
87
+ return id === this.latest ? size : Batch.HEAD + size
88
+ }
89
+
90
+ /**
91
+ * Copies a session's frames in
92
+ * @param id the session
93
+ * @param source holds its frames
94
+ * @param start where they begin
95
+ * @param size how many bytes they take
96
+ */
97
+ public add(
98
+ id: number,
99
+ source: Uint8Array,
100
+ start: number,
101
+ size: number,
102
+ ): void {
103
+ const buffer = this.buffer
104
+
105
+ if (id === this.latest) {
106
+ buffer.setUint32(this.sized, buffer.getUint32(this.sized) + size)
107
+ } else {
108
+ buffer.writeUint32(id)
109
+ this.sized = buffer.writerIndex
110
+ buffer.writeUint32(size)
111
+ this.latest = id
112
+ this.ids.add(id)
113
+ }
114
+
115
+ buffer.ensureWritable(size)
116
+ const at = buffer.writerIndex
117
+ ByteBuf.copyBytes(
118
+ source,
119
+ start,
120
+ buffer.array,
121
+ buffer.arrayOffset + at,
122
+ size,
123
+ )
124
+ buffer.writerIndex = at + size
125
+ }
126
+
127
+ /**
128
+ * Hands over a copy of everything and starts again empty
129
+ */
130
+ public take(): BatchTaken {
131
+ const taken: BatchTaken = {
132
+ bytes: this.buffer.readBytes(this.buffer.readableBytes),
133
+ ids: [...this.ids],
134
+ }
135
+
136
+ this.clear()
137
+ return taken
138
+ }
139
+
140
+ /**
141
+ * Drops everything waiting
142
+ */
143
+ public clear(): void {
144
+ this.buffer.clear()
145
+ this.ids.clear()
146
+ this.latest = -1
147
+ this.sized = 0
148
+ }
149
+
150
+ /**
151
+ * A batch of one entry, ready for the link
152
+ * @param id the session
153
+ * @param source holds its frames
154
+ * @param start where they begin
155
+ * @param size how many bytes they take
156
+ */
157
+ public static one(
158
+ id: number,
159
+ source: Uint8Array,
160
+ start: number,
161
+ size: number,
162
+ ): Uint8Array {
163
+ const packed = new Uint8Array(Batch.HEAD + size)
164
+ const view = new DataView(packed.buffer)
165
+
166
+ view.setUint32(0, id)
167
+ view.setUint32(4, size)
168
+ ByteBuf.copyBytes(source, start, packed, Batch.HEAD, size)
169
+
170
+ return packed
171
+ }
172
+
173
+ /**
174
+ * Walks the entries of a batch that crossed the link
175
+ * @param bytes the whole batch
176
+ * @param from the shard that sent it
177
+ * @param visit gets each entry in order
178
+ */
179
+ public static read(
180
+ bytes: Uint8Array,
181
+ from: number,
182
+ visit: BatchVisitor,
183
+ ): void {
184
+ let at = 0
185
+ while (at + Batch.HEAD <= bytes.length) {
186
+ const id = Batch.word(bytes, at)
187
+ 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')
190
+
191
+ visit(id, bytes.subarray(start, end), from)
192
+ at = end
193
+ }
194
+ }
195
+
196
+ /**
197
+ * A big endian 32 bit number out of a batch
198
+ * @param bytes the batch
199
+ * @param at where the number starts
200
+ */
201
+ private static word(bytes: Uint8Array, at: number): number {
202
+ return (
203
+ (((bytes[at] ?? 0) << 24) |
204
+ ((bytes[at + 1] ?? 0) << 16) |
205
+ ((bytes[at + 2] ?? 0) << 8) |
206
+ (bytes[at + 3] ?? 0)) >>>
207
+ 0
208
+ )
209
+ }
210
+ }
@@ -137,6 +137,12 @@ type Outbox = {
137
137
  */
138
138
  export type CourierWatcher = (shard: number) => void
139
139
 
140
+ /**
141
+ * Sends anything held back for a shard before a message goes to it
142
+ * @param shard where the message is going
143
+ */
144
+ export type CourierFlusher = (shard: number) => void
145
+
140
146
  /**
141
147
  * Sends messages and questions between shards under one topic prefix
142
148
  * @class
@@ -202,6 +208,11 @@ export class Courier {
202
208
  */
203
209
  private readonly watchers: Set<CourierWatcher>
204
210
 
211
+ /**
212
+ * Run ahead of every message
213
+ */
214
+ private readonly flushers: Set<CourierFlusher>
215
+
205
216
  /**
206
217
  * Shards that answered and haven't dropped since
207
218
  */
@@ -241,6 +252,7 @@ export class Courier {
241
252
  this.outboxes = new Map<number, Outbox>()
242
253
  this.piped = new Set<string>()
243
254
  this.watchers = new Set<CourierWatcher>()
255
+ this.flushers = new Set<CourierFlusher>()
244
256
  this.reached = new Set<number>()
245
257
  this.epochs = new Map<number, number>()
246
258
  this.timer = null
@@ -346,6 +358,15 @@ export class Courier {
346
358
  return this
347
359
  }
348
360
 
361
+ /**
362
+ * Lets held back bytes go out ahead of every later message to their shard
363
+ * @param flusher sends what's held for one shard
364
+ */
365
+ public before(flusher: CourierFlusher): this {
366
+ this.flushers.add(flusher)
367
+ return this
368
+ }
369
+
349
370
  /**
350
371
  * Whether nothing is held back for a shard
351
372
  * @param shard the target
@@ -548,6 +569,8 @@ export class Courier {
548
569
  ): boolean {
549
570
  if (!this.link.isOpen) return false
550
571
 
572
+ for (const flusher of this.flushers) flusher(shard)
573
+
551
574
  const outbox = this.outboxes.get(shard)
552
575
  if (outbox !== undefined) {
553
576
  if (outbox.parked.length >= limit) return false
@@ -292,6 +292,7 @@ export class Fanout<S = unknown> {
292
292
  return
293
293
  }
294
294
 
295
+ this.tunnel.settle()
295
296
  this.gateway?.publish(this.courier.topic(topic), bytes)
296
297
  this.hand(
297
298
  shared.filter(
@@ -37,9 +37,15 @@ export class HostedChannel extends Channel {
37
37
  * @param bytes ready for the wire
38
38
  */
39
39
  public override writeEncodedSync(bytes: Uint8Array | ByteBuf): void {
40
- this.sink(
41
- bytes instanceof ByteBuf ? bytes.toUint8Array().slice() : bytes.slice(),
42
- )
40
+ if (bytes instanceof ByteBuf) {
41
+ this.sink(
42
+ bytes.array,
43
+ bytes.arrayOffset + bytes.readerIndex,
44
+ bytes.readableBytes,
45
+ )
46
+ } else {
47
+ this.sink(bytes, 0, bytes.length)
48
+ }
43
49
  }
44
50
 
45
51
  /**
@@ -1,6 +1,11 @@
1
+ export { Batch } from './batch/index.ts'
2
+ export type { BatchTaken, BatchVisitor } from './batch/index.ts'
1
3
  export { Courier } from './courier/index.ts'
4
+ export { Pending } from './pending/index.ts'
5
+ export type { PendingLoss } from './pending/index.ts'
2
6
  export type {
3
7
  CourierBytesListener,
8
+ CourierFlusher,
4
9
  CourierListener,
5
10
  CourierResponder,
6
11
  CourierWatcher,
@@ -4,22 +4,40 @@ import {
4
4
  type HandlerContext,
5
5
  } from '@netifyjs/netify'
6
6
 
7
+ import type { Staging } from '../../codec/index.ts'
8
+
7
9
  /**
8
10
  * Takes each frame a moved session writes
9
- * @param bytes a copy of one frame
11
+ * @param source holds the frame, borrowed for the call
12
+ * @param start where it begins
13
+ * @param size how many bytes it takes
10
14
  */
11
- export type OutletSink = (bytes: Uint8Array) => void
15
+ export type OutletSink = (
16
+ source: Uint8Array,
17
+ start: number,
18
+ size: number,
19
+ ) => void
12
20
 
13
21
  /**
14
22
  * Catches a moved session's frames before they reach its outbox
15
23
  * @class
16
24
  */
17
- export class TunnelOutlet extends OutboundHandlerAdapter {
25
+ export class TunnelOutlet extends OutboundHandlerAdapter implements Staging {
26
+ /**
27
+ * Room codecs write into, shared by every outlet
28
+ */
29
+ private static scratch: Uint8Array = new Uint8Array(4096)
30
+
18
31
  /**
19
32
  * Where frames go
20
33
  */
21
34
  private readonly sink: OutletSink
22
35
 
36
+ /**
37
+ * Bytes the last reserve asked for
38
+ */
39
+ private reserved: number
40
+
23
41
  /**
24
42
  * @param sink where frames go
25
43
  */
@@ -27,6 +45,40 @@ export class TunnelOutlet extends OutboundHandlerAdapter {
27
45
  super()
28
46
 
29
47
  this.sink = sink
48
+ this.reserved = 0
49
+ }
50
+
51
+ /**
52
+ * Where reserved bytes get written
53
+ */
54
+ public get stagingBuffer(): Uint8Array {
55
+ return TunnelOutlet.scratch
56
+ }
57
+
58
+ /**
59
+ * Makes room for a frame and gives where it starts
60
+ * @param size bytes the frame may take
61
+ */
62
+ public reserve(size: number): number {
63
+ if (TunnelOutlet.scratch.length < size) {
64
+ TunnelOutlet.scratch = new Uint8Array(
65
+ Math.max(size, TunnelOutlet.scratch.length * 2),
66
+ )
67
+ }
68
+
69
+ this.reserved = size
70
+ return 0
71
+ }
72
+
73
+ /**
74
+ * Sends what was written into the reserved room
75
+ * @param unused bytes of the room left over
76
+ */
77
+ public commitStaged(unused = 0): void {
78
+ const size = this.reserved - unused
79
+
80
+ this.reserved = 0
81
+ if (size > 0) this.sink(TunnelOutlet.scratch, 0, size)
30
82
  }
31
83
 
32
84
  /**
@@ -40,7 +92,7 @@ export class TunnelOutlet extends OutboundHandlerAdapter {
40
92
  ): Promise<void> {
41
93
  if (!(message instanceof ByteBuf)) return context.write(message)
42
94
 
43
- this.sink(message.readBytes(message.readableBytes))
95
+ this.drain(message)
44
96
  return Promise.resolve()
45
97
  }
46
98
 
@@ -52,7 +104,18 @@ export class TunnelOutlet extends OutboundHandlerAdapter {
52
104
  public writeSync(context: HandlerContext, message: unknown): boolean {
53
105
  if (!(message instanceof ByteBuf)) return false
54
106
 
55
- this.sink(message.readBytes(message.readableBytes))
107
+ this.drain(message)
56
108
  return true
57
109
  }
110
+
111
+ /**
112
+ * Hands the frame's unread bytes to the sink and marks them read
113
+ * @param message the frame
114
+ */
115
+ private drain(message: ByteBuf): void {
116
+ const size = message.readableBytes
117
+
118
+ this.sink(message.array, message.arrayOffset + message.readerIndex, size)
119
+ message.skipBytes(size)
120
+ }
58
121
  }
@@ -0,0 +1,165 @@
1
+ import { Batch } from '../batch/index.ts'
2
+ import type { Courier } from '../courier/index.ts'
3
+
4
+ /**
5
+ * Hears about sessions whose bytes couldn't leave
6
+ * @param shard where they were going
7
+ * @param ids the sessions
8
+ */
9
+ export type PendingLoss = (shard: number, ids: readonly number[]) => void
10
+
11
+ /**
12
+ * Session bytes held for the end of the turn, one batch per shard
13
+ * @class
14
+ */
15
+ export class Pending {
16
+ /**
17
+ * Bytes a batch may hold before it leaves early
18
+ */
19
+ private static readonly limit: number = 256 * 1024
20
+
21
+ /**
22
+ * Room a new batch starts with
23
+ */
24
+ private static readonly start: number = 4096
25
+
26
+ /**
27
+ * Carries the batches
28
+ */
29
+ private readonly courier: Courier
30
+
31
+ /**
32
+ * Short topic name the batches go out on
33
+ */
34
+ private readonly name: string
35
+
36
+ /**
37
+ * Told about bytes that were dropped
38
+ */
39
+ private readonly lost: PendingLoss
40
+
41
+ /**
42
+ * Batches by shard
43
+ */
44
+ private readonly batches: Map<number, Batch>
45
+
46
+ /**
47
+ * Shards with bytes waiting
48
+ */
49
+ private readonly waiting: Set<number>
50
+
51
+ /**
52
+ * Sends every waiting batch
53
+ */
54
+ private readonly releaser: () => void
55
+
56
+ /**
57
+ * Sends one shard's batch ahead of anything else bound there
58
+ */
59
+ private readonly early: (shard: number) => void
60
+
61
+ /**
62
+ * @param courier carries the batches
63
+ * @param name short topic name they go out on
64
+ * @param lost told about bytes that were dropped
65
+ */
66
+ private constructor(courier: Courier, name: string, lost: PendingLoss) {
67
+ this.courier = courier
68
+ this.name = name
69
+ this.lost = lost
70
+ this.batches = new Map<number, Batch>()
71
+ this.waiting = new Set<number>()
72
+ this.releaser = (): void => {
73
+ for (const shard of this.waiting) this.release(shard)
74
+ }
75
+ this.early = (shard: number): void => {
76
+ if (this.waiting.has(shard)) this.release(shard)
77
+ }
78
+
79
+ courier.before(this.early)
80
+ }
81
+
82
+ /**
83
+ * Holds bytes for one topic
84
+ * @param courier carries the batches
85
+ * @param name short topic name they go out on
86
+ * @param lost told about bytes that were dropped
87
+ */
88
+ public static of(courier: Courier, name: string, lost: PendingLoss): Pending {
89
+ return new Pending(courier, name, lost)
90
+ }
91
+
92
+ /**
93
+ * Keeps a session's bytes for the end of the turn, or sends them alone to a shard that's behind
94
+ * @param shard where they go
95
+ * @param id the session
96
+ * @param source holds whole frames, copied before this returns
97
+ * @param start where they begin
98
+ * @param size how many bytes they take
99
+ */
100
+ public hold(
101
+ shard: number,
102
+ id: number,
103
+ source: Uint8Array,
104
+ start: number,
105
+ size: number,
106
+ ): void {
107
+ if (!this.courier.clear(shard)) {
108
+ this.release(shard)
109
+
110
+ const alone = Batch.one(id, source, start, size)
111
+ if (!this.courier.sendBytes(shard, this.name, alone)) {
112
+ this.lost(shard, [id])
113
+ }
114
+
115
+ return
116
+ }
117
+
118
+ let batch = this.batches.get(shard)
119
+ if (batch === undefined) {
120
+ batch = Batch.of(Pending.start)
121
+ this.batches.set(shard, batch)
122
+ }
123
+
124
+ const full = batch.size + batch.cost(id, size) > Pending.limit
125
+ if (full && batch.size > 0) this.release(shard)
126
+
127
+ if (this.waiting.size === 0) queueMicrotask(this.releaser)
128
+ this.waiting.add(shard)
129
+ batch.add(id, source, start, size)
130
+
131
+ if (batch.size >= Pending.limit) this.release(shard)
132
+ }
133
+
134
+ /**
135
+ * Sends every waiting batch now
136
+ */
137
+ public settle(): void {
138
+ this.releaser()
139
+ }
140
+
141
+ /**
142
+ * Forgets what's held for a shard that dropped
143
+ * @param shard the one that dropped
144
+ */
145
+ public drop(shard: number): void {
146
+ this.waiting.delete(shard)
147
+ this.batches.delete(shard)
148
+ }
149
+
150
+ /**
151
+ * Sends one shard's waiting bytes
152
+ * @param shard where they go
153
+ */
154
+ private release(shard: number): void {
155
+ this.waiting.delete(shard)
156
+
157
+ const batch = this.batches.get(shard)
158
+ if (batch === undefined || batch.size === 0) return
159
+
160
+ const taken = batch.take()
161
+ if (!this.courier.sendBytes(shard, this.name, taken.bytes)) {
162
+ this.lost(shard, taken.ids)
163
+ }
164
+ }
165
+ }
@@ -11,9 +11,11 @@ import {
11
11
  export type RelayEvents = {
12
12
  /**
13
13
  * The client sent bytes
14
- * @param bytes a copy of what arrived
14
+ * @param source holds what arrived, borrowed for the call
15
+ * @param start where it begins
16
+ * @param size how many bytes arrived
15
17
  */
16
- read(bytes: Uint8Array): void
18
+ read(source: Uint8Array, start: number, size: number): void
17
19
 
18
20
  /**
19
21
  * The server is stopping
@@ -37,11 +39,6 @@ export class TunnelRelay extends InboundHandlerAdapter {
37
39
  */
38
40
  private readonly events: RelayEvents
39
41
 
40
- /**
41
- * Bound once for failed writes
42
- */
43
- private readonly refused: (error: unknown) => void
44
-
45
42
  /**
46
43
  * Where this handler sits, or null
47
44
  */
@@ -55,13 +52,6 @@ export class TunnelRelay extends InboundHandlerAdapter {
55
52
 
56
53
  this.events = events
57
54
  this.context = null
58
- this.refused = (error: unknown): void => {
59
- const context = this.context
60
- if (context === null) return
61
-
62
- void context.fireExceptionCaught(error)
63
- void context.close()
64
- }
65
55
  }
66
56
 
67
57
  /**
@@ -80,8 +70,7 @@ export class TunnelRelay extends InboundHandlerAdapter {
80
70
  const context = this.context
81
71
  if (context === null) return
82
72
 
83
- context.write(ByteBuf.wrap(bytes)).catch(this.refused)
84
- void context.flush()
73
+ context.writeAndFlushSync(ByteBuf.wrap(bytes))
85
74
  }
86
75
 
87
76
  /**
@@ -95,7 +84,14 @@ export class TunnelRelay extends InboundHandlerAdapter {
95
84
  ): void | Promise<void> {
96
85
  if (!(message instanceof ByteBuf)) return context.fireChannelRead(message)
97
86
 
98
- this.events.read(message.readBytes(message.readableBytes))
87
+ const size = message.readableBytes
88
+
89
+ this.events.read(
90
+ message.array,
91
+ message.arrayOffset + message.readerIndex,
92
+ size,
93
+ )
94
+ message.skipBytes(size)
99
95
  }
100
96
 
101
97
  /**
@@ -112,6 +108,21 @@ export class TunnelRelay extends InboundHandlerAdapter {
112
108
  return context.fireUserEventTriggered(event)
113
109
  }
114
110
 
111
+ /**
112
+ * Hangs up once frames may have gone missing
113
+ * @param context the connection
114
+ * @param error what went wrong
115
+ */
116
+ public override exceptionCaught(
117
+ context: HandlerContext,
118
+ error: unknown,
119
+ ): Promise<void> {
120
+ const fired = context.fireExceptionCaught(error)
121
+
122
+ void context.close()
123
+ return fired
124
+ }
125
+
115
126
  /**
116
127
  * Tells the session's shard the client went away
117
128
  * @param context the connection
@@ -6,7 +6,7 @@ import type { Transport } from '@netifyjs/netify'
6
6
  export type TransportEvents = {
7
7
  /**
8
8
  * The session wrote bytes
9
- * @param bytes a copy of what was written
9
+ * @param bytes a borrowed view of what was written
10
10
  */
11
11
  wrote(bytes: Uint8Array): void
12
12
 
@@ -75,7 +75,7 @@ export class TunnelTransport implements Transport {
75
75
  public write(bytes: Uint8Array): number {
76
76
  if (this.ended) return -1
77
77
 
78
- this.events.wrote(bytes.slice())
78
+ this.events.wrote(bytes)
79
79
  return bytes.length
80
80
  }
81
81
 
@@ -7,9 +7,11 @@ import {
7
7
  type Logger,
8
8
  } from '@netifyjs/netify'
9
9
 
10
+ import { Batch, type BatchVisitor } from '../batch/index.ts'
10
11
  import { Courier } from '../courier/index.ts'
11
12
  import { HostedChannel } from '../hosted/index.ts'
12
13
  import { type OutletSink, TunnelOutlet } from '../outlet/index.ts'
14
+ import { Pending } from '../pending/index.ts'
13
15
  import type { Portable, Reach } from '../portable/index.ts'
14
16
  import { TunnelRelay } from '../relay/index.ts'
15
17
  import { TunnelTransport } from '../transport/index.ts'
@@ -210,6 +212,26 @@ export class Tunnel<S = unknown> {
210
212
  */
211
213
  private readonly flusher: () => void
212
214
 
215
+ /**
216
+ * Replies waiting to go back to the clients' shards
217
+ */
218
+ private readonly downs: Pending
219
+
220
+ /**
221
+ * Client bytes waiting to go to the sessions' shards
222
+ */
223
+ private readonly ups: Pending
224
+
225
+ /**
226
+ * Hands one entry of an arriving batch to its client
227
+ */
228
+ private readonly delivering: BatchVisitor
229
+
230
+ /**
231
+ * Hands one entry of an arriving batch to its session
232
+ */
233
+ private readonly arriving: BatchVisitor
234
+
213
235
  /**
214
236
  * Last session id used
215
237
  */
@@ -236,16 +258,33 @@ export class Tunnel<S = unknown> {
236
258
 
237
259
  this.touched.clear()
238
260
  }
261
+ this.downs = Pending.of(
262
+ this.courier,
263
+ 'down',
264
+ (front: number, ids: readonly number[]): void => {
265
+ this.lose(front, ids)
266
+ },
267
+ )
268
+ this.ups = Pending.of(
269
+ this.courier,
270
+ 'up',
271
+ (_shard: number, ids: readonly number[]): void => {
272
+ this.strand(ids)
273
+ },
274
+ )
275
+ this.delivering = (id: number, bytes: Uint8Array): void => {
276
+ this.fronted.get(id)?.relay.deliver(bytes)
277
+ }
278
+ this.arriving = (id: number, bytes: Uint8Array, from: number): void => {
279
+ void this.guests.get(from)?.get(id)?.channel.handleData(bytes)
280
+ }
239
281
 
240
282
  this.courier
241
283
  .on('open', (data: unknown, from: number): void => {
242
284
  this.host(data as Opening<S>, from)
243
285
  })
244
286
  .onBytes('up', (bytes: Uint8Array, from: number): void => {
245
- void this.guests
246
- .get(from)
247
- ?.get(Tunnel.idAt(bytes, 0))
248
- ?.channel.handleData(bytes.subarray(Tunnel.ID))
287
+ Batch.read(bytes, from, this.arriving)
249
288
  })
250
289
  .on('stop', (data: unknown, from: number): void => {
251
290
  const [id, deadline] = data as Stopping
@@ -255,10 +294,8 @@ export class Tunnel<S = unknown> {
255
294
  const guest = this.guests.get(from)?.get(data as number)
256
295
  if (guest !== undefined) this.evict(guest, false)
257
296
  })
258
- .onBytes('down', (bytes: Uint8Array): void => {
259
- this.fronted
260
- .get(Tunnel.idAt(bytes, 0))
261
- ?.relay.deliver(bytes.subarray(Tunnel.ID))
297
+ .onBytes('down', (bytes: Uint8Array, from: number): void => {
298
+ Batch.read(bytes, from, this.delivering)
262
299
  })
263
300
  .onBytes('share', (bytes: Uint8Array): void => {
264
301
  this.hand(bytes)
@@ -301,8 +338,8 @@ export class Tunnel<S = unknown> {
301
338
  * Passes the client's bytes on
302
339
  * @param read what arrived
303
340
  */
304
- read: (read: Uint8Array): void => {
305
- this.up(id, read)
341
+ read: (source: Uint8Array, start: number, size: number): void => {
342
+ this.up(id, source, start, size)
306
343
  },
307
344
  /**
308
345
  * Passes on word of a server stop
@@ -377,17 +414,23 @@ export class Tunnel<S = unknown> {
377
414
  ids: number | readonly number[],
378
415
  bytes: Uint8Array,
379
416
  ): void {
380
- const sent =
381
- typeof ids === 'number'
382
- ? this.courier.sendBytes(front, 'down', Tunnel.addressed(ids, bytes))
383
- : this.courier.sendBytes(front, 'share', Tunnel.shared(ids, bytes))
384
- if (sent) return
417
+ if (typeof ids === 'number') {
418
+ this.downs.hold(front, ids, bytes, 0, bytes.length)
419
+ return
420
+ }
385
421
 
386
- const guests = this.guests.get(front)
387
- for (const id of typeof ids === 'number' ? [ids] : ids) {
388
- const guest = guests?.get(id)
389
- if (guest !== undefined) this.evict(guest, true)
422
+ if (this.courier.sendBytes(front, 'share', Tunnel.shared(ids, bytes))) {
423
+ return
390
424
  }
425
+
426
+ this.lose(front, ids)
427
+ }
428
+
429
+ /**
430
+ * Sends every waiting reply now
431
+ */
432
+ public settle(): void {
433
+ this.downs.settle()
391
434
  }
392
435
 
393
436
  /**
@@ -454,7 +497,7 @@ export class Tunnel<S = unknown> {
454
497
  * @param bytes what the session wrote
455
498
  */
456
499
  wrote: (bytes: Uint8Array): void => {
457
- this.down(from, opening.id, bytes)
500
+ this.downs.hold(from, opening.id, bytes, 0, bytes.length)
458
501
  },
459
502
  /**
460
503
  * Ends the session with its connection
@@ -464,8 +507,14 @@ export class Tunnel<S = unknown> {
464
507
  this.courier.tell(from, 'end', opening.id)
465
508
  },
466
509
  })
467
- const sink: OutletSink = (bytes: Uint8Array): void => {
468
- if (!transport.ended) this.down(from, opening.id, bytes)
510
+ const sink: OutletSink = (
511
+ source: Uint8Array,
512
+ start: number,
513
+ size: number,
514
+ ): void => {
515
+ if (!transport.ended) {
516
+ this.downs.hold(from, opening.id, source, start, size)
517
+ }
469
518
  }
470
519
  const channel = new HostedChannel(transport, sink)
471
520
  const guest: Hosted = {
@@ -499,34 +548,48 @@ export class Tunnel<S = unknown> {
499
548
  void channel.handleData(opening.bytes)
500
549
  }
501
550
 
551
+ /**
552
+ * Ends sessions whose bytes couldn't reach their client's shard
553
+ * @param front the client's shard
554
+ * @param ids the sessions there
555
+ */
556
+ private lose(front: number, ids: readonly number[]): void {
557
+ const guests = this.guests.get(front)
558
+
559
+ for (const id of ids) {
560
+ const guest = guests?.get(id)
561
+ if (guest !== undefined) this.evict(guest, true)
562
+ }
563
+ }
564
+
502
565
  /**
503
566
  * Passes a client's bytes to its session
504
567
  * @param id the session's id on this shard
505
- * @param bytes what arrived
506
- */
507
- private up(id: number, bytes: Uint8Array): void {
568
+ * @param source holds what arrived
569
+ * @param start where it begins
570
+ * @param size how many bytes arrived
571
+ */
572
+ private up(
573
+ id: number,
574
+ source: Uint8Array,
575
+ start: number,
576
+ size: number,
577
+ ): void {
508
578
  const session = this.fronted.get(id)
509
- if (session === undefined) return
510
-
511
- const sent = this.courier.sendBytes(
512
- session.shard,
513
- 'up',
514
- Tunnel.addressed(id, bytes),
515
- )
516
- if (!sent) this.cut(session, true)
579
+ if (session !== undefined) {
580
+ this.ups.hold(session.shard, id, source, start, size)
581
+ }
517
582
  }
518
583
 
519
584
  /**
520
- * Bytes with the id of their session in front
521
- * @param id the session's id on the client's shard
522
- * @param bytes whole frames
585
+ * Hangs up on clients whose bytes couldn't reach their sessions
586
+ * @param ids the clients here
523
587
  */
524
- private static addressed(id: number, bytes: Uint8Array): Uint8Array {
525
- const packed = new Uint8Array(Tunnel.ID + bytes.length)
526
- Tunnel.put(packed, 0, id)
527
- packed.set(bytes, Tunnel.ID)
528
-
529
- return packed
588
+ private strand(ids: readonly number[]): void {
589
+ for (const id of ids) {
590
+ const session = this.fronted.get(id)
591
+ if (session !== undefined) this.cut(session, true)
592
+ }
530
593
  }
531
594
 
532
595
  /**
@@ -666,6 +729,9 @@ export class Tunnel<S = unknown> {
666
729
  * @param shard the one that dropped
667
730
  */
668
731
  private abandon(shard: number): void {
732
+ this.downs.drop(shard)
733
+ this.ups.drop(shard)
734
+
669
735
  for (const session of [...this.fronted.values()]) {
670
736
  if (session.shard === shard) this.cut(session, false)
671
737
  }