@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.
@@ -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
  /**
@@ -74,14 +64,32 @@ export class TunnelRelay extends InboundHandlerAdapter {
74
64
 
75
65
  /**
76
66
  * Writes bytes from the session's shard to the client
77
- * @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
78
70
  */
79
- public deliver(bytes: Uint8Array): void {
71
+ public deliver(source: Uint8Array, start: number, size: number): void {
80
72
  const context = this.context
81
73
  if (context === null) return
82
74
 
83
- context.write(ByteBuf.wrap(bytes)).catch(this.refused)
84
- void context.flush()
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()
85
93
  }
86
94
 
87
95
  /**
@@ -95,7 +103,14 @@ export class TunnelRelay extends InboundHandlerAdapter {
95
103
  ): void | Promise<void> {
96
104
  if (!(message instanceof ByteBuf)) return context.fireChannelRead(message)
97
105
 
98
- this.events.read(message.readBytes(message.readableBytes))
106
+ const size = message.readableBytes
107
+
108
+ this.events.read(
109
+ message.array,
110
+ message.arrayOffset + message.readerIndex,
111
+ size,
112
+ )
113
+ message.skipBytes(size)
99
114
  }
100
115
 
101
116
  /**
@@ -112,6 +127,21 @@ export class TunnelRelay extends InboundHandlerAdapter {
112
127
  return context.fireUserEventTriggered(event)
113
128
  }
114
129
 
130
+ /**
131
+ * Hangs up once frames may have gone missing
132
+ * @param context the connection
133
+ * @param error what went wrong
134
+ */
135
+ public override exceptionCaught(
136
+ context: HandlerContext,
137
+ error: unknown,
138
+ ): Promise<void> {
139
+ const fired = context.fireExceptionCaught(error)
140
+
141
+ void context.close()
142
+ return fired
143
+ }
144
+
115
145
  /**
116
146
  * Tells the session's shard the client went away
117
147
  * @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