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

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 +230 -89
  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
@@ -46,23 +46,38 @@ export class WebSocketChannel extends Channel {
46
46
  */
47
47
  private spare: BinaryWebSocketFrame | null
48
48
 
49
+ /**
50
+ * Settles on the native close
51
+ */
52
+ private readonly gone: PromiseWithResolvers<undefined>
53
+
54
+ /**
55
+ * Resolves after the socket closes
56
+ */
57
+ public readonly drained: Promise<undefined>
58
+
49
59
  /**
50
60
  * Normally built by WebSocketBootstrap
51
61
  * @param socket the native socket
52
62
  * @param options same knobs as any other channel
53
63
  * @param pooled whether binary frames are reused
64
+ * @param closeTimeout drain time in ms
54
65
  */
55
66
  public constructor(
56
67
  socket: ServerWebSocket<WebSocketState>,
57
68
  options: ChannelOptions,
58
69
  pooled = true,
70
+ closeTimeout: number = WebSocketOutbox.defaultCloseTimeout,
59
71
  ) {
60
- super(new WebSocketTransport(socket), options)
72
+ const transport = new WebSocketTransport(socket)
73
+ super(transport, options)
61
74
 
62
75
  this.socket = socket
63
76
  this.pooled = pooled
64
77
  this.spare = null
65
78
  this.blocked = false
79
+ this.gone = Promise.withResolvers<undefined>()
80
+ this.drained = this.gone.promise
66
81
  this.outbox = new WebSocketOutbox(
67
82
  socket,
68
83
  options.maxPendingBytes ?? Channel.defaultMaxPendingBytes,
@@ -80,7 +95,9 @@ export class WebSocketChannel extends Channel {
80
95
  this.setBlocked(false)
81
96
  },
82
97
  },
98
+ closeTimeout,
83
99
  )
100
+ transport.bind(this.outbox)
84
101
  }
85
102
 
86
103
  /**
@@ -184,12 +201,77 @@ export class WebSocketChannel extends Channel {
184
201
  return this.outbox.sendBinary(bytes)
185
202
  }
186
203
 
204
+ /**
205
+ * Bytes waiting on a flush
206
+ */
207
+ public get unflushedBytes(): number {
208
+ return super.pendingBytes
209
+ }
210
+
211
+ /**
212
+ * Sends encoded bytes as one binary message
213
+ * @param bytes ready for the wire
214
+ */
215
+ public override writeEncoded(bytes: Uint8Array | ByteBuf): Promise<void> {
216
+ const result = this.outbox.sendBinary(
217
+ bytes instanceof ByteBuf ? bytes.toUint8Array() : bytes,
218
+ )
219
+ if (result === 'full') {
220
+ return Promise.reject(new Error('Write queue is full'))
221
+ }
222
+
223
+ return result === 'closed'
224
+ ? Promise.reject(new Error('Channel is closed'))
225
+ : resolved
226
+ }
227
+
228
+ /**
229
+ * Sends encoded bytes without a promise
230
+ * @param bytes ready for the wire
231
+ */
232
+ public override writeEncodedSync(bytes: Uint8Array | ByteBuf): void {
233
+ const result = this.outbox.sendBinary(
234
+ bytes instanceof ByteBuf ? bytes.toUint8Array() : bytes,
235
+ )
236
+ if (result !== 'full') return
237
+
238
+ void this.handleError(new Error('Write queue is full'))
239
+ }
240
+
241
+ /**
242
+ * Writes and flushes encoded bytes
243
+ * @param bytes ready for the wire
244
+ */
245
+ public override writeAndFlushEncoded(
246
+ bytes: Uint8Array | ByteBuf,
247
+ ): Promise<void> {
248
+ return this.writeEncoded(bytes)
249
+ }
250
+
251
+ /**
252
+ * Writes and flushes without a promise
253
+ * @param bytes ready for the wire
254
+ */
255
+ public override writeAndFlushEncodedSync(bytes: Uint8Array | ByteBuf): void {
256
+ this.writeEncodedSync(bytes)
257
+ }
258
+
187
259
  /**
188
260
  * Bun has room again, so send what's waiting
189
261
  */
190
262
  public override handleDrain(): void {
191
- super.handleDrain()
192
263
  this.outbox.drain()
264
+ super.handleDrain()
265
+ }
266
+
267
+ /**
268
+ * Cleans up after the socket closes
269
+ */
270
+ public override handleClose(): Promise<void> {
271
+ this.outbox.disarm()
272
+ this.gone.resolve(undefined)
273
+
274
+ return super.handleClose()
193
275
  }
194
276
 
195
277
  /**
@@ -0,0 +1,215 @@
1
+ import type { HeadersInit, Server } from 'bun'
2
+
3
+ import type { Logger } from '../../logger/index.ts'
4
+ import type { WebSocketChannel } from '../channel/index.ts'
5
+ import type { WebSocketState } from '../transport/index.ts'
6
+
7
+ /**
8
+ * What the upgrade hook decided
9
+ */
10
+ export type UpgradeVerdict =
11
+ | {
12
+ /**
13
+ * Let the client in
14
+ */
15
+ readonly accept: true
16
+
17
+ /**
18
+ * Data kept with the channel
19
+ */
20
+ readonly data?: unknown
21
+
22
+ /**
23
+ * Extra headers on the 101
24
+ */
25
+ readonly headers?: HeadersInit
26
+ }
27
+ | {
28
+ /**
29
+ * Turn the client away
30
+ */
31
+ readonly accept: false
32
+
33
+ /**
34
+ * HTTP status to answer with
35
+ */
36
+ readonly status?: number
37
+ }
38
+
39
+ /**
40
+ * Vets a request before the upgrade
41
+ */
42
+ export type UpgradeHandler = (
43
+ request: Request,
44
+ ) => UpgradeVerdict | Promise<UpgradeVerdict>
45
+
46
+ /**
47
+ * Rules for each request
48
+ */
49
+ export type UpgradeGateOptions = {
50
+ /**
51
+ * Path that upgrades, or null
52
+ */
53
+ readonly path: string | null
54
+
55
+ /**
56
+ * Open connections allowed at once
57
+ */
58
+ readonly maxConnections: number
59
+
60
+ /**
61
+ * Upgrade hook, or null
62
+ */
63
+ readonly upgrade: UpgradeHandler | null
64
+
65
+ /**
66
+ * Hears about a hook that threw
67
+ */
68
+ readonly logger: Logger
69
+
70
+ /**
71
+ * Every open channel
72
+ */
73
+ readonly children: ReadonlySet<WebSocketChannel>
74
+ }
75
+
76
+ /**
77
+ * Decides which HTTP requests get upgraded to a WebSocket
78
+ * @class
79
+ */
80
+ export class UpgradeGate {
81
+ /**
82
+ * Path, limit, hook and logger
83
+ */
84
+ private readonly options: UpgradeGateOptions
85
+
86
+ /**
87
+ * Requests waiting on the hook
88
+ */
89
+ private pending: number
90
+
91
+ /**
92
+ * Starts with nothing pending
93
+ * @param options path, limit, hook and logger
94
+ */
95
+ public constructor(options: UpgradeGateOptions) {
96
+ this.options = options
97
+ this.pending = 0
98
+ }
99
+
100
+ /**
101
+ * Upgrades matching requests, refuses the rest
102
+ * @param request incoming request
103
+ * @param server server to upgrade on
104
+ */
105
+ public handle(
106
+ request: Request,
107
+ server: Server<WebSocketState>,
108
+ ): Response | undefined | Promise<Response | undefined> {
109
+ const { path, maxConnections, upgrade, children } = this.options
110
+
111
+ const url = new URL(request.url)
112
+ if (path !== null && url.pathname !== path) {
113
+ return new Response(null, { status: 404 })
114
+ }
115
+
116
+ if (children.size + this.pending >= maxConnections) {
117
+ return new Response(null, { status: 503 })
118
+ }
119
+
120
+ if (upgrade === null) {
121
+ return UpgradeGate.accept(request, server, url, null, null)
122
+ }
123
+
124
+ return this.decide(request, server, url, upgrade)
125
+ }
126
+
127
+ /**
128
+ * Asks the upgrade hook
129
+ * @param request incoming request
130
+ * @param server server to upgrade on
131
+ * @param url the parsed request URL
132
+ * @param upgrade hook to ask
133
+ */
134
+ private async decide(
135
+ request: Request,
136
+ server: Server<WebSocketState>,
137
+ url: URL,
138
+ upgrade: UpgradeHandler,
139
+ ): Promise<Response | undefined> {
140
+ this.pending += 1
141
+
142
+ let verdict: UpgradeVerdict
143
+ try {
144
+ verdict = await upgrade(request)
145
+ } catch (error) {
146
+ this.options.logger.warn({ err: error }, 'Upgrade hook failed')
147
+ return new Response(null, { status: 500 })
148
+ } finally {
149
+ this.pending -= 1
150
+ }
151
+
152
+ if (!verdict.accept) {
153
+ return new Response(null, { status: verdict.status ?? 403 })
154
+ }
155
+
156
+ return UpgradeGate.accept(
157
+ request,
158
+ server,
159
+ url,
160
+ verdict.data ?? null,
161
+ verdict.headers ?? null,
162
+ )
163
+ }
164
+
165
+ /**
166
+ * Upgrades with the hook's data
167
+ * @param request incoming request
168
+ * @param server server to upgrade on
169
+ * @param url the parsed request URL
170
+ * @param data whatever the hook attached, or null
171
+ * @param headers extra response headers, or null
172
+ */
173
+ private static accept(
174
+ request: Request,
175
+ server: Server<WebSocketState>,
176
+ url: URL,
177
+ data: unknown,
178
+ headers: HeadersInit | null,
179
+ ): Response | undefined {
180
+ const upgraded = server.upgrade(request, {
181
+ /**
182
+ * Filled in as the socket opens
183
+ */
184
+ data: {
185
+ channel: null,
186
+ uri: url.pathname + url.search,
187
+ headers: request.headers,
188
+ subprotocol: UpgradeGate.subprotocolOf(request, headers),
189
+ data,
190
+ },
191
+ ...(headers === null ? {} : { headers }),
192
+ })
193
+ return upgraded ? undefined : new Response(null, { status: 400 })
194
+ }
195
+
196
+ /**
197
+ * Subprotocol the 101 will name, or null
198
+ * @param request incoming request
199
+ * @param headers extra response headers, or null
200
+ */
201
+ private static subprotocolOf(
202
+ request: Request,
203
+ headers: HeadersInit | null,
204
+ ): string | null {
205
+ const chosen =
206
+ headers === null
207
+ ? null
208
+ : new Headers(headers).get('sec-websocket-protocol')
209
+ if (chosen !== null) return chosen
210
+
211
+ const offered = request.headers.get('sec-websocket-protocol')
212
+ const first = offered?.split(',')[0]?.trim() ?? ''
213
+ return first === '' ? null : first
214
+ }
215
+ }
@@ -1,11 +1,15 @@
1
1
  export { WebSocketBootstrap, WebSocketServer } from './bootstrap/index.ts'
2
2
  export type {
3
- UpgradeHandler,
4
- UpgradeVerdict,
5
3
  WebSocketBindOptions,
6
4
  WebSocketBootstrapOptions,
7
5
  } from './bootstrap/index.ts'
8
6
  export { WebSocketChannel } from './channel/index.ts'
7
+ export { UpgradeGate } from './gate/index.ts'
8
+ export type {
9
+ UpgradeGateOptions,
10
+ UpgradeHandler,
11
+ UpgradeVerdict,
12
+ } from './gate/index.ts'
9
13
  export { WebSocketOutbox } from './outbox/index.ts'
10
14
  export type {
11
15
  OutboxEvents,
@@ -70,6 +70,11 @@ export type OutboxEvents = {
70
70
  * @class
71
71
  */
72
72
  export class WebSocketOutbox {
73
+ /**
74
+ * Default close wait in ms
75
+ */
76
+ public static readonly defaultCloseTimeout: number = 10_000
77
+
73
78
  /**
74
79
  * The native socket
75
80
  */
@@ -110,16 +115,33 @@ export class WebSocketOutbox {
110
115
  */
111
116
  private backed: boolean
112
117
 
118
+ /**
119
+ * A close is on its way
120
+ */
121
+ private closing: boolean
122
+
123
+ /**
124
+ * Close wait in ms
125
+ */
126
+ private readonly closeTimeout: number
127
+
128
+ /**
129
+ * Backstop for a stuck close, or null
130
+ */
131
+ private timer: Timer | null
132
+
113
133
  /**
114
134
  * Starts empty
115
135
  * @param socket the native socket
116
136
  * @param limit most bytes allowed to wait
117
137
  * @param events backed up and cleared hooks
138
+ * @param closeTimeout close wait in ms
118
139
  */
119
140
  public constructor(
120
141
  socket: ServerWebSocket<WebSocketState>,
121
142
  limit: number,
122
143
  events: OutboxEvents,
144
+ closeTimeout: number = WebSocketOutbox.defaultCloseTimeout,
123
145
  ) {
124
146
  this.socket = socket
125
147
  this.limit = limit
@@ -129,6 +151,9 @@ export class WebSocketOutbox {
129
151
  this.queuedBytes = 0
130
152
  this.written = 0
131
153
  this.backed = false
154
+ this.closing = false
155
+ this.closeTimeout = closeTimeout
156
+ this.timer = null
132
157
  }
133
158
 
134
159
  /**
@@ -150,7 +175,7 @@ export class WebSocketOutbox {
150
175
  * @param bytes what to send
151
176
  */
152
177
  public sendBinary(bytes: Uint8Array): SendResult {
153
- if (this.socket.readyState !== 1) return 'closed'
178
+ if (this.closing || this.socket.readyState !== 1) return 'closed'
154
179
  if (this.backed || this.head < this.queue.length) {
155
180
  return this.enqueue({ kind: 'binary', bytes })
156
181
  }
@@ -171,7 +196,9 @@ export class WebSocketOutbox {
171
196
  * @param message what to send
172
197
  */
173
198
  public send(message: OutgoingMessage): SendResult {
174
- if (this.socket.readyState !== 1) return 'closed'
199
+ if (this.closing || this.socket.readyState !== 1) return 'closed'
200
+ if (message.kind === 'close')
201
+ return this.close(message.code, message.reason)
175
202
  if (this.backed || this.head < this.queue.length) {
176
203
  return this.enqueue(message)
177
204
  }
@@ -187,6 +214,39 @@ export class WebSocketOutbox {
187
214
  return this.enqueue(message)
188
215
  }
189
216
 
217
+ /**
218
+ * Closes after the queue drains
219
+ * @param code close status
220
+ * @param reason close reason
221
+ */
222
+ public close(code: number, reason: string): SendResult {
223
+ if (this.closing || this.socket.readyState !== 1) return 'closed'
224
+ this.closing = true
225
+
226
+ if (this.backed || this.head < this.queue.length) {
227
+ this.queue.push({ kind: 'close', code, reason })
228
+ this.timer = setTimeout((): void => {
229
+ this.timer = null
230
+ this.socket.terminate()
231
+ }, this.closeTimeout)
232
+ this.timer.unref()
233
+ return 'queued'
234
+ }
235
+
236
+ this.socket.close(code, reason)
237
+ return 'sent'
238
+ }
239
+
240
+ /**
241
+ * Stops waiting on a queued close
242
+ */
243
+ public disarm(): void {
244
+ if (this.timer === null) return
245
+
246
+ clearTimeout(this.timer)
247
+ this.timer = null
248
+ }
249
+
190
250
  /**
191
251
  * Bun has room again, so send what's waiting until it pushes back
192
252
  */
@@ -239,6 +299,7 @@ export class WebSocketOutbox {
239
299
  status = socket.pong(message.bytes)
240
300
  break
241
301
  case 'close':
302
+ this.disarm()
242
303
  socket.close(message.code, message.reason)
243
304
  return 'sent'
244
305
  }
@@ -2,6 +2,7 @@ import type { ServerWebSocket } from 'bun'
2
2
 
3
3
  import type { Transport } from '../../channel/transport/index.ts'
4
4
  import type { WebSocketChannel } from '../channel/index.ts'
5
+ import type { WebSocketOutbox } from '../outbox/index.ts'
5
6
 
6
7
  /**
7
8
  * What each native WebSocket carries, the channel is filled in once it opens
@@ -22,6 +23,11 @@ export type WebSocketState = {
22
23
  */
23
24
  readonly headers: Headers
24
25
 
26
+ /**
27
+ * Subprotocol the 101 response named, or null
28
+ */
29
+ readonly subprotocol: string | null
30
+
25
31
  /**
26
32
  * Whatever the upgrade hook attached, or null
27
33
  */
@@ -48,6 +54,11 @@ export class WebSocketTransport implements Transport {
48
54
  */
49
55
  public readonly socket: ServerWebSocket<WebSocketState>
50
56
 
57
+ /**
58
+ * Queued sends and close, or null
59
+ */
60
+ private outbox: WebSocketOutbox | null
61
+
51
62
  /**
52
63
  * Wraps the socket
53
64
  * @param socket the native socket
@@ -56,6 +67,15 @@ export class WebSocketTransport implements Transport {
56
67
  this.datagram = true
57
68
  this.remotePort = 0
58
69
  this.socket = socket
70
+ this.outbox = null
71
+ }
72
+
73
+ /**
74
+ * Sends through an outbox
75
+ * @param outbox where writes queue
76
+ */
77
+ public bind(outbox: WebSocketOutbox): void {
78
+ this.outbox = outbox
59
79
  }
60
80
 
61
81
  /**
@@ -66,18 +86,28 @@ export class WebSocketTransport implements Transport {
66
86
  }
67
87
 
68
88
  /**
69
- * Sends one binary message, Bun queues it under backpressure
89
+ * Sends one binary message through the outbox
70
90
  * @param bytes the message
71
91
  */
72
92
  public write(bytes: Uint8Array): number {
73
- return this.socket.sendBinary(bytes) === 0 ? -1 : bytes.length
93
+ const outbox = this.outbox
94
+ if (outbox === null) {
95
+ const status = this.socket.sendBinary(bytes)
96
+ return status === 0 && bytes.length > 0 ? -1 : bytes.length
97
+ }
98
+
99
+ const result = outbox.sendBinary(bytes)
100
+ if (result === 'full') throw new Error('Write queue is full')
101
+
102
+ return result === 'closed' ? -1 : bytes.length
74
103
  }
75
104
 
76
105
  /**
77
106
  * Closes with a normal status
78
107
  */
79
108
  public end(): void {
80
- this.socket.close()
109
+ if (this.outbox === null) this.socket.close(1000, '')
110
+ else this.outbox.close(1000, '')
81
111
  }
82
112
 
83
113
  /**
@@ -111,9 +111,10 @@ export class WebSocketFrameWriter extends OutboundHandlerAdapter {
111
111
  }
112
112
 
113
113
  /**
114
- * Bun sends as it goes, so there's nothing to flush
114
+ * Flushes parked bytes
115
+ * @param context where the flush carries on
115
116
  */
116
- public override flush(): Promise<void> {
117
- return resolved
117
+ public override flush(context: HandlerContext): Promise<void> {
118
+ return this.channel.unflushedBytes > 0 ? context.flush() : resolved
118
119
  }
119
120
  }