@netifyjs/netify 1.0.0-alpha.4 → 1.0.0-alpha.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/README.md +6 -6
  2. package/package.json +1 -1
  3. package/src/bootstrap/client/index.ts +1 -1
  4. package/src/bootstrap/dispatcher/index.ts +7 -0
  5. package/src/bootstrap/reconnect/index.ts +14 -4
  6. package/src/bootstrap/server/index.ts +10 -4
  7. package/src/buffer/index.ts +229 -88
  8. package/src/buffer/quantizer/index.ts +16 -3
  9. package/src/channel/context/index.ts +18 -11
  10. package/src/channel/handler/index.ts +1 -1
  11. package/src/channel/index.ts +30 -7
  12. package/src/channel/outbound/index.ts +28 -12
  13. package/src/channel/pipeline/index.ts +45 -5
  14. package/src/channel/queue/index.ts +3 -2
  15. package/src/channel/resolved/index.ts +13 -3
  16. package/src/channel/server/index.ts +19 -10
  17. package/src/cluster/index.ts +73 -32
  18. package/src/codec/binary/index.ts +19 -0
  19. package/src/codec/decoder/index.ts +223 -83
  20. package/src/codec/delimiter/index.ts +95 -37
  21. package/src/codec/encoder/index.ts +30 -5
  22. package/src/codec/fixed/index.ts +5 -1
  23. package/src/codec/http/aggregator/index.ts +45 -16
  24. package/src/codec/http/decoder/object/index.ts +156 -40
  25. package/src/codec/http/decoder/request/index.ts +6 -2
  26. package/src/codec/http/encoder/object/index.ts +2 -7
  27. package/src/codec/http/encoder/request/index.ts +5 -0
  28. package/src/codec/http/headers/index.ts +45 -2
  29. package/src/codec/http/message/full/request/index.ts +1 -1
  30. package/src/codec/http/message/full/response/index.ts +1 -1
  31. package/src/codec/http/message/request/index.ts +14 -1
  32. package/src/codec/http/message/response/index.ts +1 -1
  33. package/src/codec/http/version/index.ts +3 -0
  34. package/src/codec/length/index.ts +66 -44
  35. package/src/codec/message/decoder/index.ts +18 -1
  36. package/src/codec/message/encoder/index.ts +85 -8
  37. package/src/codec/prepender/index.ts +4 -1
  38. package/src/codec/string/decoder/index.ts +6 -1
  39. package/src/codec/websocket/decoder/index.ts +78 -3
  40. package/src/codec/websocket/encoder/index.ts +90 -6
  41. package/src/codec/websocket/frame/base/index.ts +19 -10
  42. package/src/codec/websocket/frame/text/index.ts +2 -2
  43. package/src/codec/websocket/protocol/index.ts +12 -0
  44. package/src/datagram/bootstrap/index.ts +1 -1
  45. package/src/datagram/transport/index.ts +30 -1
  46. package/src/handler/flush/index.ts +25 -5
  47. package/src/handler/idle/index.ts +120 -26
  48. package/src/handler/logging/index.ts +13 -1
  49. package/src/handler/metrics/index.ts +49 -16
  50. package/src/handler/offload/index.ts +7 -0
  51. package/src/handler/timeout/read/index.ts +1 -1
  52. package/src/handler/timeout/write/index.ts +104 -23
  53. package/src/handler/traffic/index.ts +251 -38
  54. package/src/index.ts +1 -0
  55. package/src/reliable/cipher/index.ts +49 -5
  56. package/src/reliable/cookie/index.ts +64 -2
  57. package/src/reliable/handler/index.ts +11 -15
  58. package/src/reliable/index.ts +7 -1
  59. package/src/reliable/lane/index.ts +277 -58
  60. package/src/reliable/peer/index.ts +125 -38
  61. package/src/serve/bootstrap/index.ts +82 -135
  62. package/src/serve/channel/index.ts +84 -2
  63. package/src/serve/gate/index.ts +215 -0
  64. package/src/serve/index.ts +6 -2
  65. package/src/serve/outbox/index.ts +63 -2
  66. package/src/serve/transport/index.ts +33 -3
  67. package/src/serve/writer/index.ts +4 -3
  68. package/src/shard/gateway/index.ts +102 -29
  69. package/src/shard/link/index.ts +15 -0
  70. package/src/worker/group/index.ts +231 -13
  71. package/src/worker/pool/index.ts +100 -19
  72. package/src/worker/service/index.ts +9 -1
@@ -139,14 +139,14 @@ export class MetricsHandler extends InboundHandlerAdapter<unknown> {
139
139
  private closed: number
140
140
 
141
141
  /**
142
- * Bytes read by channels that have closed
142
+ * Bytes read by channels no longer watched
143
143
  */
144
- private closedRead: number
144
+ private leftRead: number
145
145
 
146
146
  /**
147
- * Bytes written by channels that have closed
147
+ * Bytes written by channels no longer watched
148
148
  */
149
- private closedWritten: number
149
+ private leftWritten: number
150
150
 
151
151
  /**
152
152
  * Messages read
@@ -185,21 +185,36 @@ export class MetricsHandler extends InboundHandlerAdapter<unknown> {
185
185
  }
186
186
  this.opened = 0
187
187
  this.closed = 0
188
- this.closedRead = 0
189
- this.closedWritten = 0
188
+ this.leftRead = 0
189
+ this.leftWritten = 0
190
190
  this.messages = 0
191
191
  this.spent = 0
192
192
  this.timed = 0
193
193
  this.slowest = 0
194
194
  }
195
195
 
196
+ /**
197
+ * Picks up a channel that was already open
198
+ * @param context its pipeline slot
199
+ */
200
+ public handlerAdded(context: HandlerContext): void {
201
+ if (context.channel.isActive) this.join(context.channel)
202
+ }
203
+
204
+ /**
205
+ * Stops watching the channel
206
+ * @param context its pipeline slot
207
+ */
208
+ public handlerRemoved(context: HandlerContext): void {
209
+ this.leave(context.channel)
210
+ }
211
+
196
212
  /**
197
213
  * Counts a new channel
198
214
  * @param context the channel's context
199
215
  */
200
216
  public override channelActive(context: HandlerContext): Promise<void> {
201
- this.live.add(context.channel)
202
- this.opened += 1
217
+ this.join(context.channel)
203
218
 
204
219
  return context.fireChannelActive()
205
220
  }
@@ -209,12 +224,7 @@ export class MetricsHandler extends InboundHandlerAdapter<unknown> {
209
224
  * @param context the channel's context
210
225
  */
211
226
  public override channelInactive(context: HandlerContext): Promise<void> {
212
- const channel = context.channel
213
- if (this.live.delete(channel)) {
214
- this.closed += 1
215
- this.closedRead += channel.bytesRead
216
- this.closedWritten += channel.bytesWritten
217
- }
227
+ if (this.leave(context.channel)) this.closed += 1
218
228
 
219
229
  return context.fireChannelInactive()
220
230
  }
@@ -249,8 +259,8 @@ export class MetricsHandler extends InboundHandlerAdapter<unknown> {
249
259
  public snapshot(): MetricsSnapshot {
250
260
  const now = performance.now()
251
261
 
252
- let bytesRead = this.closedRead
253
- let bytesWritten = this.closedWritten
262
+ let bytesRead = this.leftRead
263
+ let bytesWritten = this.leftWritten
254
264
  let pendingBytes = 0
255
265
  for (const channel of this.live) {
256
266
  bytesRead += channel.bytesRead
@@ -286,6 +296,29 @@ export class MetricsHandler extends InboundHandlerAdapter<unknown> {
286
296
  return snapshot
287
297
  }
288
298
 
299
+ /**
300
+ * Starts watching a channel
301
+ * @param channel one to watch
302
+ */
303
+ private join(channel: Channel): void {
304
+ if (this.live.has(channel)) return
305
+
306
+ this.live.add(channel)
307
+ this.opened += 1
308
+ }
309
+
310
+ /**
311
+ * Stops watching, false if it wasn't
312
+ * @param channel one to drop
313
+ */
314
+ private leave(channel: Channel): boolean {
315
+ if (!this.live.delete(channel)) return false
316
+
317
+ this.leftRead += channel.bytesRead
318
+ this.leftWritten += channel.bytesWritten
319
+ return true
320
+ }
321
+
289
322
  /**
290
323
  * Adds one timed message
291
324
  * @param start when it began
@@ -73,6 +73,11 @@ export class OffloadHandler<I, O> extends InboundHandlerAdapter {
73
73
  this.inFlight = 0
74
74
  }
75
75
 
76
+ /**
77
+ * Catches a refused job
78
+ */
79
+ private static readonly ignore: () => undefined = (): undefined => undefined
80
+
76
81
  /**
77
82
  * Starts the job now, delivers its result after everything before it
78
83
  * @param context where results go
@@ -89,6 +94,8 @@ export class OffloadHandler<I, O> extends InboundHandlerAdapter {
89
94
  }
90
95
 
91
96
  const job = this.pool.run(message)
97
+ void job.catch(OffloadHandler.ignore)
98
+
92
99
  this.inFlight += 1
93
100
  const delivered = this.after(context, async (): Promise<void> => {
94
101
  try {
@@ -13,7 +13,7 @@ export class ReadTimeoutHandler extends IdleStateHandler {
13
13
  private fired: boolean
14
14
 
15
15
  /**
16
- * Throws a RangeError unless the timeout is a positive finite number
16
+ * Closes connections that go quiet
17
17
  * @param timeout how long reads can stay quiet, in ms
18
18
  */
19
19
  public constructor(timeout: number) {
@@ -1,21 +1,52 @@
1
1
  import { OutboundHandlerAdapter } from '../../../channel/handler/outbound/index.ts'
2
+ import { resolved } from '../../../channel/resolved/index.ts'
2
3
  import { WriteTimeoutError } from '../error/index.ts'
3
4
  import type { HandlerContext } from '../../../channel/context/index.ts'
4
5
 
5
6
  /**
6
- * Raises an error and closes the channel when a write takes too long
7
+ * A pending write or batch
8
+ */
9
+ type Deadline = {
10
+ /**
11
+ * Deadline from performance.now()
12
+ */
13
+ readonly at: number
14
+
15
+ /**
16
+ * Still waiting on the write
17
+ */
18
+ open: boolean
19
+ }
20
+
21
+ /**
22
+ * Closes the channel on a slow write
7
23
  * @class
8
24
  */
9
25
  export class WriteTimeoutHandler extends OutboundHandlerAdapter {
26
+ /**
27
+ * Longest timeout a timer can hold, in ms
28
+ */
29
+ public static readonly longest: number = 2 ** 31 - 1
30
+
10
31
  /**
11
32
  * How long each write gets, in ms
12
33
  */
13
34
  private readonly timeout: number
14
35
 
15
36
  /**
16
- * One timer per write still in flight
37
+ * Writes still in flight, oldest first
38
+ */
39
+ private readonly deadlines: Deadline[]
40
+
41
+ /**
42
+ * Timer for the oldest deadline, or null
17
43
  */
18
- private readonly timers: Set<Timer>
44
+ private timer: Timer | null
45
+
46
+ /**
47
+ * Last write promise hooked, or null
48
+ */
49
+ private tracked: Promise<void> | null
19
50
 
20
51
  /**
21
52
  * Set after the first timeout so we only raise it once
@@ -23,23 +54,25 @@ export class WriteTimeoutHandler extends OutboundHandlerAdapter {
23
54
  private fired: boolean
24
55
 
25
56
  /**
26
- * Throws a RangeError unless the timeout is a positive finite number
57
+ * Closes connections on slow writes
27
58
  * @param timeout how long a single write can take, in ms
28
59
  */
29
60
  public constructor(timeout: number) {
30
61
  super()
31
62
 
32
- if (!Number.isFinite(timeout) || timeout <= 0) {
63
+ if (!(timeout > 0 && timeout <= WriteTimeoutHandler.longest)) {
33
64
  throw new RangeError('Timeout is invalid')
34
65
  }
35
66
 
36
67
  this.timeout = timeout
37
- this.timers = new Set<Timer>()
68
+ this.deadlines = []
69
+ this.timer = null
70
+ this.tracked = null
38
71
  this.fired = false
39
72
  }
40
73
 
41
74
  /**
42
- * Starts a timer that's cleared when the write settles
75
+ * Puts a deadline on the write
43
76
  * @param context where the write gets passed on
44
77
  * @param message what to send
45
78
  */
@@ -48,29 +81,77 @@ export class WriteTimeoutHandler extends OutboundHandlerAdapter {
48
81
  message: unknown,
49
82
  ): Promise<void> {
50
83
  const promise = context.write(message)
84
+ if (promise === resolved || promise === this.tracked) return promise
51
85
 
52
- const timer = setTimeout((): void => {
53
- this.timers.delete(timer)
54
- this.expire(context)
55
- }, this.timeout)
56
- timer.unref()
57
- this.timers.add(timer)
58
-
59
- void promise
60
- .finally((): void => {
61
- clearTimeout(timer)
62
- this.timers.delete(timer)
63
- })
64
- .catch((): undefined => undefined)
86
+ this.tracked = promise
87
+ this.trim()
88
+ const deadline: Deadline = {
89
+ at: performance.now() + this.timeout,
90
+ open: true,
91
+ }
92
+ const settle = (): void => {
93
+ deadline.open = false
94
+ }
95
+
96
+ this.deadlines.push(deadline)
97
+ void promise.then(settle, settle)
98
+ if (this.timer === null) this.arm(context, this.timeout)
65
99
  return promise
66
100
  }
67
101
 
68
102
  /**
69
- * Clears any timers left so they can't fire after we're gone
103
+ * Drops the timer and every deadline
70
104
  */
71
105
  public handlerRemoved(): void {
72
- for (const timer of this.timers) clearTimeout(timer)
73
- this.timers.clear()
106
+ if (this.timer !== null) clearTimeout(this.timer)
107
+
108
+ this.timer = null
109
+ this.tracked = null
110
+ this.deadlines.length = 0
111
+ }
112
+
113
+ /**
114
+ * Forgets the settled writes at the front
115
+ */
116
+ private trim(): void {
117
+ const deadlines = this.deadlines
118
+
119
+ while (deadlines[0]?.open === false) deadlines.shift()
120
+ }
121
+
122
+ /**
123
+ * Arms the timer
124
+ * @param context where the writes went
125
+ * @param delay ms to the oldest deadline
126
+ */
127
+ private arm(context: HandlerContext, delay: number): void {
128
+ const timer = setTimeout((): void => {
129
+ this.timer = null
130
+ this.sweep(context)
131
+ }, delay)
132
+ timer.unref()
133
+
134
+ this.timer = timer
135
+ }
136
+
137
+ /**
138
+ * Times out the oldest write if it's overdue
139
+ * @param context where the writes went
140
+ */
141
+ private sweep(context: HandlerContext): void {
142
+ this.trim()
143
+
144
+ const oldest = this.deadlines[0]
145
+ if (oldest === undefined) return
146
+
147
+ const remaining = oldest.at - performance.now()
148
+ if (remaining > 0) {
149
+ this.arm(context, remaining)
150
+ return
151
+ }
152
+
153
+ this.deadlines.length = 0
154
+ this.expire(context)
74
155
  }
75
156
 
76
157
  /**
@@ -2,7 +2,6 @@ import { ByteBuf } from '../../buffer/index.ts'
2
2
  import type { Channel } from '../../channel/index.ts'
3
3
  import type { HandlerContext } from '../../channel/context/index.ts'
4
4
  import { DuplexHandlerAdapter } from '../../channel/handler/duplex/index.ts'
5
- import { resolved } from '../../channel/resolved/index.ts'
6
5
  import { DatagramPacket } from '../../datagram/packet/index.ts'
7
6
  import { WebSocketFrame } from '../../codec/websocket/frame/base/index.ts'
8
7
 
@@ -26,6 +25,61 @@ export type TrafficShapingOptions = {
26
25
  readonly maxDelay?: number
27
26
  }
28
27
 
28
+ /**
29
+ * A write waiting for its turn
30
+ */
31
+ type Held = {
32
+ /**
33
+ * What to send
34
+ */
35
+ readonly message: unknown
36
+
37
+ /**
38
+ * Release time from performance.now()
39
+ */
40
+ readonly due: number
41
+
42
+ /**
43
+ * Settles the caller's promise
44
+ */
45
+ readonly result: PromiseWithResolvers<undefined>
46
+ }
47
+
48
+ /**
49
+ * One channel's state
50
+ */
51
+ type Lane = {
52
+ /**
53
+ * Where held reads and writes carry on
54
+ */
55
+ readonly context: HandlerContext
56
+
57
+ /**
58
+ * Writes waiting, oldest first
59
+ */
60
+ readonly held: Held[]
61
+
62
+ /**
63
+ * Bytes read as of the last message
64
+ */
65
+ seen: number
66
+
67
+ /**
68
+ * Timer for the oldest held write, or null
69
+ */
70
+ timer: Timer | null
71
+
72
+ /**
73
+ * A flush is owed
74
+ */
75
+ flush: boolean
76
+
77
+ /**
78
+ * Ends a read delay early, or null
79
+ */
80
+ wake: (() => void) | null
81
+ }
82
+
29
83
  /**
30
84
  * Spends bytes against a rate and says how long to wait
31
85
  * @class
@@ -84,6 +138,11 @@ export class TokenBucket {
84
138
  * @class
85
139
  */
86
140
  export class TrafficShapingHandler extends DuplexHandlerAdapter {
141
+ /**
142
+ * Read delay check interval in ms
143
+ */
144
+ private static readonly poll: number = 100
145
+
87
146
  /**
88
147
  * The read bucket
89
148
  */
@@ -100,19 +159,14 @@ export class TrafficShapingHandler extends DuplexHandlerAdapter {
100
159
  private readonly maxDelay: number
101
160
 
102
161
  /**
103
- * Bytes each channel had read when last seen
162
+ * State for each channel
104
163
  */
105
- private readonly seen: WeakMap<Channel, number>
164
+ private readonly lanes: Map<Channel, Lane>
106
165
 
107
166
  /**
108
- * Delayed writes still waiting, by channel
167
+ * Writes held across every channel
109
168
  */
110
- private readonly waiting: WeakMap<Channel, number>
111
-
112
- /**
113
- * Channels that asked for a flush while writes were waiting
114
- */
115
- private readonly flushes: WeakSet<Channel>
169
+ private waiting: number
116
170
 
117
171
  /**
118
172
  * Sets the limits
@@ -129,9 +183,8 @@ export class TrafficShapingHandler extends DuplexHandlerAdapter {
129
183
  this.reads = new TokenBucket(options.readLimit ?? 0)
130
184
  this.writes = new TokenBucket(options.writeLimit ?? 0)
131
185
  this.maxDelay = maxDelay
132
- this.seen = new WeakMap<Channel, number>()
133
- this.waiting = new WeakMap<Channel, number>()
134
- this.flushes = new WeakSet<Channel>()
186
+ this.lanes = new Map<Channel, Lane>()
187
+ this.waiting = 0
135
188
  }
136
189
 
137
190
  /**
@@ -148,6 +201,33 @@ export class TrafficShapingHandler extends DuplexHandlerAdapter {
148
201
  return 0
149
202
  }
150
203
 
204
+ /**
205
+ * Sends held writes on in order
206
+ * @param context old slot to write through
207
+ */
208
+ public handlerRemoved(context: HandlerContext): void {
209
+ const lane = this.lanes.get(context.channel)
210
+ if (lane === undefined) return
211
+
212
+ this.lanes.delete(context.channel)
213
+ if (lane.timer !== null) clearTimeout(lane.timer)
214
+
215
+ lane.timer = null
216
+ this.forward(lane, lane.held.length)
217
+ lane.wake?.()
218
+ }
219
+
220
+ /**
221
+ * Fails held writes and stops the timers
222
+ * @param context channel going away
223
+ */
224
+ public override channelInactive(context: HandlerContext): Promise<void> {
225
+ const lane = this.lanes.get(context.channel)
226
+ if (lane !== undefined) this.drop(lane)
227
+
228
+ return context.fireChannelInactive()
229
+ }
230
+
151
231
  /**
152
232
  * Holds the message until the read rate allows it
153
233
  * @param context the channel's context
@@ -157,15 +237,17 @@ export class TrafficShapingHandler extends DuplexHandlerAdapter {
157
237
  context: HandlerContext,
158
238
  message: unknown,
159
239
  ): Promise<void> {
160
- const channel = context.channel
161
- const total = channel.bytesRead
162
- const bytes = total - (this.seen.get(channel) ?? 0)
163
- this.seen.set(channel, total)
240
+ if (this.reads.limit === 0) return context.fireChannelRead(message)
241
+
242
+ const lane = this.lanes.get(context.channel) ?? this.open(context)
243
+ const total = context.channel.bytesRead
244
+ const bytes = total - lane.seen
245
+ lane.seen = total
164
246
 
165
247
  const wait = this.delay(this.reads.take(bytes))
166
248
  if (wait === 0) return context.fireChannelRead(message)
167
249
 
168
- return Bun.sleep(wait).then((): Promise<void> =>
250
+ return this.pause(lane, wait).then((): Promise<void> =>
169
251
  context.fireChannelRead(message),
170
252
  )
171
253
  }
@@ -179,46 +261,177 @@ export class TrafficShapingHandler extends DuplexHandlerAdapter {
179
261
  context: HandlerContext,
180
262
  message: unknown,
181
263
  ): Promise<void> {
182
- const channel = context.channel
264
+ if (this.writes.limit === 0) return context.write(message)
265
+
183
266
  const wait = this.delay(
184
267
  this.writes.take(TrafficShapingHandler.sizeOf(message)),
185
268
  )
186
- if (wait === 0 && (this.waiting.get(channel) ?? 0) === 0) {
269
+ if (wait === 0 && this.waiting === 0) return context.write(message)
270
+
271
+ const lane = this.lanes.get(context.channel)
272
+ if (wait === 0 && (lane === undefined || lane.held.length === 0)) {
187
273
  return context.write(message)
188
274
  }
189
275
 
190
- if (message instanceof ByteBuf) message.detach()
191
-
192
- this.waiting.set(channel, (this.waiting.get(channel) ?? 0) + 1)
193
- return Bun.sleep(wait).then((): Promise<void> =>
194
- this.release(context, message),
195
- )
276
+ return this.hold(lane ?? this.open(context), message, wait)
196
277
  }
197
278
 
198
279
  /**
199
- * Waits for held writes before flushing
280
+ * Passes the flush on
200
281
  * @param context the channel's context
201
282
  */
202
283
  public override flush(context: HandlerContext): Promise<void> {
203
- if ((this.waiting.get(context.channel) ?? 0) === 0) return context.flush()
284
+ if (this.waiting === 0) return context.flush()
204
285
 
205
- this.flushes.add(context.channel)
206
- return resolved
286
+ const lane = this.lanes.get(context.channel)
287
+ if (lane !== undefined && lane.held.length > 0) lane.flush = true
288
+ return context.flush()
207
289
  }
208
290
 
209
291
  /**
210
- * Sends a held write and the flush that was asked for meanwhile
292
+ * Starts keeping state for a channel
211
293
  * @param context the channel's context
294
+ */
295
+ private open(context: HandlerContext): Lane {
296
+ const lane: Lane = {
297
+ context,
298
+ held: [],
299
+ seen: 0,
300
+ timer: null,
301
+ flush: false,
302
+ wake: null,
303
+ }
304
+
305
+ this.lanes.set(context.channel, lane)
306
+ return lane
307
+ }
308
+
309
+ /**
310
+ * Queues a write
311
+ * @param lane the channel's state
212
312
  * @param message the message
313
+ * @param wait milliseconds the bucket asked for
213
314
  */
214
- private release(context: HandlerContext, message: unknown): Promise<void> {
215
- const channel = context.channel
216
- const left = (this.waiting.get(channel) ?? 1) - 1
217
- this.waiting.set(channel, left)
315
+ private hold(lane: Lane, message: unknown, wait: number): Promise<void> {
316
+ if (message instanceof ByteBuf) message.detach()
317
+
318
+ const last = lane.held[lane.held.length - 1]
319
+ const due = Math.max(performance.now() + wait, last?.due ?? 0)
320
+ const result = Promise.withResolvers<undefined>()
321
+ lane.held.push({ message, due, result })
322
+ this.waiting += 1
323
+ if (lane.timer === null) this.arm(lane, wait)
324
+
325
+ return result.promise
326
+ }
327
+
328
+ /**
329
+ * Arms the lane's timer
330
+ * @param lane the channel's state
331
+ * @param delay milliseconds to the oldest held write
332
+ */
333
+ private arm(lane: Lane, delay: number): void {
334
+ lane.timer = setTimeout((): void => {
335
+ lane.timer = null
336
+ this.release(lane)
337
+ }, delay)
338
+ }
339
+
340
+ /**
341
+ * Sends every held write that's due
342
+ * @param lane the channel's state
343
+ */
344
+ private release(lane: Lane): void {
345
+ const now = performance.now() + 1
346
+
347
+ let count = 0
348
+ for (const entry of lane.held) {
349
+ if (entry.due > now) break
350
+ count += 1
351
+ }
352
+
353
+ this.forward(lane, count)
354
+
355
+ const next = lane.held[0]
356
+ if (next !== undefined) {
357
+ this.arm(lane, Math.max(1, next.due - now))
358
+ return
359
+ }
360
+
361
+ if (this.reads.limit === 0) this.lanes.delete(lane.context.channel)
362
+ }
363
+
364
+ /**
365
+ * Passes the oldest held writes on
366
+ * @param lane the channel's state
367
+ * @param count how many to send
368
+ */
369
+ private forward(lane: Lane, count: number): void {
370
+ const context = lane.context
371
+ const entries = lane.held.splice(0, count)
372
+ this.waiting -= entries.length
373
+
374
+ for (const entry of entries) {
375
+ context.write(entry.message).then(
376
+ (): void => {
377
+ entry.result.resolve(undefined)
378
+ },
379
+ (error: unknown): void => {
380
+ entry.result.reject(error)
381
+ },
382
+ )
383
+ }
384
+
385
+ if (lane.flush && entries.length > 0) void context.flush()
386
+ if (lane.held.length === 0) lane.flush = false
387
+ }
388
+
389
+ /**
390
+ * Fails everything still held
391
+ * @param lane the channel's state
392
+ */
393
+ private drop(lane: Lane): void {
394
+ this.lanes.delete(lane.context.channel)
395
+ if (lane.timer !== null) clearTimeout(lane.timer)
396
+
397
+ lane.timer = null
398
+ this.waiting -= lane.held.length
399
+ for (const entry of lane.held.splice(0)) {
400
+ entry.result.reject(new Error('Channel is closed'))
401
+ }
402
+
403
+ lane.wake?.()
404
+ }
405
+
406
+ /**
407
+ * Waits out a read delay
408
+ * @param lane the channel's state
409
+ * @param wait how long in ms
410
+ */
411
+ private pause(lane: Lane, wait: number): Promise<void> {
412
+ const result = Promise.withResolvers<undefined>()
413
+ const until = performance.now() + wait
414
+
415
+ let timer: Timer | null = null
416
+ const done = (): void => {
417
+ if (timer !== null) clearTimeout(timer)
418
+
419
+ lane.wake = null
420
+ result.resolve(undefined)
421
+ }
422
+ const tick = (): void => {
423
+ const left = until - performance.now()
424
+ if (left <= 0 || !lane.context.channel.isActive) {
425
+ done()
426
+ return
427
+ }
428
+
429
+ timer = setTimeout(tick, Math.min(left, TrafficShapingHandler.poll))
430
+ }
218
431
 
219
- const written = context.write(message)
220
- if (left === 0 && this.flushes.delete(channel)) void context.flush()
221
- return written
432
+ lane.wake = done
433
+ tick()
434
+ return result.promise
222
435
  }
223
436
 
224
437
  /**
package/src/index.ts CHANGED
@@ -150,6 +150,7 @@ export type {
150
150
  Deliver,
151
151
  Delivery,
152
152
  DisconnectReason,
153
+ LaneLimits,
153
154
  LaneOptions,
154
155
  Outgoing,
155
156
  PeerOptions,