@netifyjs/netify 0.0.0-stage → 1.0.0-alpha.1

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 (143) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +105 -2
  3. package/package.json +65 -4
  4. package/src/bootstrap/client/index.ts +191 -0
  5. package/src/bootstrap/dispatcher/index.ts +204 -0
  6. package/src/bootstrap/index.ts +22 -0
  7. package/src/bootstrap/reconnect/index.ts +334 -0
  8. package/src/bootstrap/server/index.ts +284 -0
  9. package/src/buffer/bits/index.ts +2 -0
  10. package/src/buffer/bits/reader/index.ts +64 -0
  11. package/src/buffer/bits/writer/index.ts +79 -0
  12. package/src/buffer/index.ts +1375 -0
  13. package/src/buffer/pool/index.ts +46 -0
  14. package/src/buffer/quantizer/index.ts +101 -0
  15. package/src/channel/attribute/index.ts +89 -0
  16. package/src/channel/context/index.ts +621 -0
  17. package/src/channel/group/index.ts +256 -0
  18. package/src/channel/handler/duplex/index.ts +105 -0
  19. package/src/channel/handler/inbound/index.ts +78 -0
  20. package/src/channel/handler/index.ts +135 -0
  21. package/src/channel/handler/outbound/index.ts +33 -0
  22. package/src/channel/index.ts +619 -0
  23. package/src/channel/initializer/index.ts +77 -0
  24. package/src/channel/outbound/index.ts +611 -0
  25. package/src/channel/pipeline/head/index.ts +100 -0
  26. package/src/channel/pipeline/index.ts +414 -0
  27. package/src/channel/pipeline/tail/index.ts +45 -0
  28. package/src/channel/pipeline/tracker/index.ts +120 -0
  29. package/src/channel/queue/index.ts +203 -0
  30. package/src/channel/resolved/index.ts +34 -0
  31. package/src/channel/server/index.ts +164 -0
  32. package/src/channel/shutdown/index.ts +25 -0
  33. package/src/channel/simple/index.ts +38 -0
  34. package/src/channel/transport/index.ts +74 -0
  35. package/src/channel/transport/socket/index.ts +80 -0
  36. package/src/cluster/index.ts +360 -0
  37. package/src/codec/binary/index.ts +102 -0
  38. package/src/codec/decoder/index.ts +479 -0
  39. package/src/codec/delimiter/index.ts +189 -0
  40. package/src/codec/encoder/index.ts +48 -0
  41. package/src/codec/error/index.ts +33 -0
  42. package/src/codec/fixed/index.ts +45 -0
  43. package/src/codec/http/aggregator/index.ts +236 -0
  44. package/src/codec/http/client/index.ts +120 -0
  45. package/src/codec/http/decoder/index.ts +4 -0
  46. package/src/codec/http/decoder/object/index.ts +644 -0
  47. package/src/codec/http/decoder/request/index.ts +49 -0
  48. package/src/codec/http/decoder/response/index.ts +59 -0
  49. package/src/codec/http/encoder/index.ts +3 -0
  50. package/src/codec/http/encoder/object/index.ts +196 -0
  51. package/src/codec/http/encoder/request/index.ts +24 -0
  52. package/src/codec/http/encoder/response/index.ts +26 -0
  53. package/src/codec/http/headers/index.ts +287 -0
  54. package/src/codec/http/index.ts +33 -0
  55. package/src/codec/http/message/content/index.ts +36 -0
  56. package/src/codec/http/message/full/index.ts +10 -0
  57. package/src/codec/http/message/full/request/index.ts +45 -0
  58. package/src/codec/http/message/full/response/index.ts +43 -0
  59. package/src/codec/http/message/head/index.ts +79 -0
  60. package/src/codec/http/message/index.ts +16 -0
  61. package/src/codec/http/message/last/index.ts +27 -0
  62. package/src/codec/http/message/request/index.ts +39 -0
  63. package/src/codec/http/message/response/index.ts +31 -0
  64. package/src/codec/http/method/index.ts +101 -0
  65. package/src/codec/http/server/index.ts +81 -0
  66. package/src/codec/http/status/index.ts +170 -0
  67. package/src/codec/http/version/index.ts +70 -0
  68. package/src/codec/index.ts +83 -0
  69. package/src/codec/length/index.ts +330 -0
  70. package/src/codec/line/index.ts +45 -0
  71. package/src/codec/message/decoder/index.ts +84 -0
  72. package/src/codec/message/encoder/index.ts +56 -0
  73. package/src/codec/message/index.ts +2 -0
  74. package/src/codec/msgpack/index.ts +51 -0
  75. package/src/codec/prepender/index.ts +296 -0
  76. package/src/codec/protobuf/index.ts +57 -0
  77. package/src/codec/string/decoder/index.ts +47 -0
  78. package/src/codec/string/encoder/index.ts +26 -0
  79. package/src/codec/string/index.ts +2 -0
  80. package/src/codec/websocket/client/index.ts +235 -0
  81. package/src/codec/websocket/decoder/index.ts +371 -0
  82. package/src/codec/websocket/encoder/index.ts +170 -0
  83. package/src/codec/websocket/error/index.ts +42 -0
  84. package/src/codec/websocket/frame/base/index.ts +55 -0
  85. package/src/codec/websocket/frame/binary/index.ts +24 -0
  86. package/src/codec/websocket/frame/close/index.ts +82 -0
  87. package/src/codec/websocket/frame/continuation/index.ts +31 -0
  88. package/src/codec/websocket/frame/index.ts +10 -0
  89. package/src/codec/websocket/frame/opcode/index.ts +35 -0
  90. package/src/codec/websocket/frame/ping/index.ts +24 -0
  91. package/src/codec/websocket/frame/pong/index.ts +24 -0
  92. package/src/codec/websocket/frame/text/index.ts +31 -0
  93. package/src/codec/websocket/handshake/index.ts +38 -0
  94. package/src/codec/websocket/index.ts +25 -0
  95. package/src/codec/websocket/key/index.ts +41 -0
  96. package/src/codec/websocket/protocol/index.ts +147 -0
  97. package/src/codec/websocket/server/index.ts +233 -0
  98. package/src/codec/websocket/status/index.ts +97 -0
  99. package/src/codec/websocket/upgrade/index.ts +116 -0
  100. package/src/datagram/bootstrap/index.ts +269 -0
  101. package/src/datagram/channel/index.ts +103 -0
  102. package/src/datagram/index.ts +10 -0
  103. package/src/datagram/packet/index.ts +72 -0
  104. package/src/datagram/transport/index.ts +239 -0
  105. package/src/handler/flush/index.ts +187 -0
  106. package/src/handler/idle/index.ts +295 -0
  107. package/src/handler/index.ts +22 -0
  108. package/src/handler/logging/index.ts +195 -0
  109. package/src/handler/metrics/index.ts +300 -0
  110. package/src/handler/offload/index.ts +141 -0
  111. package/src/handler/timeout/error/index.ts +29 -0
  112. package/src/handler/timeout/index.ts +3 -0
  113. package/src/handler/timeout/read/index.ts +44 -0
  114. package/src/handler/timeout/write/index.ts +89 -0
  115. package/src/handler/traffic/index.ts +259 -0
  116. package/src/index.ts +258 -0
  117. package/src/logger/index.ts +47 -0
  118. package/src/reliable/bootstrap/index.ts +154 -0
  119. package/src/reliable/cipher/index.ts +227 -0
  120. package/src/reliable/cookie/index.ts +78 -0
  121. package/src/reliable/handler/index.ts +1202 -0
  122. package/src/reliable/handshake/index.ts +144 -0
  123. package/src/reliable/index.ts +38 -0
  124. package/src/reliable/lane/index.ts +420 -0
  125. package/src/reliable/message/index.ts +102 -0
  126. package/src/reliable/packet/index.ts +117 -0
  127. package/src/reliable/peer/index.ts +929 -0
  128. package/src/reliable/registry/index.ts +107 -0
  129. package/src/serve/bootstrap/index.ts +606 -0
  130. package/src/serve/channel/index.ts +246 -0
  131. package/src/serve/index.ts +17 -0
  132. package/src/serve/outbox/index.ts +292 -0
  133. package/src/serve/transport/index.ts +96 -0
  134. package/src/serve/writer/index.ts +119 -0
  135. package/src/shard/envelope/index.ts +44 -0
  136. package/src/shard/gateway/index.ts +119 -0
  137. package/src/shard/index.ts +11 -0
  138. package/src/shard/link/index.ts +743 -0
  139. package/src/shard/map/index.ts +91 -0
  140. package/src/worker/group/index.ts +175 -0
  141. package/src/worker/index.ts +10 -0
  142. package/src/worker/pool/index.ts +235 -0
  143. package/src/worker/service/index.ts +55 -0
@@ -0,0 +1,147 @@
1
+ import { DuplexHandlerAdapter } from '../../../channel/handler/duplex/index.ts'
2
+ import { CorruptedFrameError } from '../error/index.ts'
3
+ import { WebSocketFrame } from '../frame/base/index.ts'
4
+ import { CloseWebSocketFrame } from '../frame/close/index.ts'
5
+ import { PingWebSocketFrame } from '../frame/ping/index.ts'
6
+ import { PongWebSocketFrame } from '../frame/pong/index.ts'
7
+ import type { HandlerContext } from '../../../channel/context/index.ts'
8
+
9
+ /**
10
+ * Shared WebSocket plumbing that answers pings and runs the close handshake
11
+ * @class
12
+ */
13
+ export abstract class WebSocketProtocolHandler extends DuplexHandlerAdapter {
14
+ /**
15
+ * Servers hang up right after sending close, clients wait for the server
16
+ */
17
+ private readonly closeAfterSending: boolean
18
+
19
+ /**
20
+ * Makes sure we only ever send one close frame
21
+ */
22
+ private closeSent: boolean
23
+
24
+ /**
25
+ * Sets the close behaviour for this side
26
+ * @param closeAfterSending true on the server
27
+ */
28
+ protected constructor(closeAfterSending: boolean) {
29
+ super()
30
+
31
+ this.closeAfterSending = closeAfterSending
32
+ this.closeSent = false
33
+ }
34
+
35
+ /**
36
+ * Frames go to the frame logic, anything else to the subclass
37
+ * @param context where frames go next
38
+ * @param message a frame or a handshake message
39
+ */
40
+ public override channelRead(
41
+ context: HandlerContext,
42
+ message: unknown,
43
+ ): void | Promise<void> {
44
+ if (!(message instanceof WebSocketFrame)) {
45
+ return this.readMessage(context, message)
46
+ }
47
+
48
+ if (message.isControl) return this.readControl(context, message)
49
+
50
+ return context.fireChannelRead(message)
51
+ }
52
+
53
+ /**
54
+ * Notes outbound close frames and drops any after the first
55
+ * @param context where writes go
56
+ * @param message anything heading out
57
+ */
58
+ public override write(
59
+ context: HandlerContext,
60
+ message: unknown,
61
+ ): Promise<void> {
62
+ if (!(message instanceof CloseWebSocketFrame)) return context.write(message)
63
+ if (this.closeSent) return Promise.resolve()
64
+
65
+ this.closeSent = true
66
+ return this.sendClose(context, message)
67
+ }
68
+
69
+ /**
70
+ * Sends the close code a corrupt frame calls for and hangs up, then passes the error on
71
+ * @param context the handler's context
72
+ * @param error whatever went wrong upstream
73
+ */
74
+ public override async exceptionCaught(
75
+ context: HandlerContext,
76
+ error: unknown,
77
+ ): Promise<void> {
78
+ if (error instanceof CorruptedFrameError && !this.closeSent) {
79
+ this.closeSent = true
80
+ await context
81
+ .writeAndFlush(new CloseWebSocketFrame(error.status))
82
+ .catch((): undefined => undefined)
83
+ await context.close()
84
+ }
85
+
86
+ await context.fireExceptionCaught(error)
87
+ }
88
+
89
+ /**
90
+ * Deals with handshake traffic, which differs between client and server
91
+ * @param context the handler's context
92
+ * @param message anything that isn't a frame
93
+ */
94
+ protected abstract readMessage(
95
+ context: HandlerContext,
96
+ message: unknown,
97
+ ): Promise<void>
98
+
99
+ /**
100
+ * Pongs pings, answers close and swallows pongs
101
+ * @param context where data frames go
102
+ * @param frame frame from the peer
103
+ */
104
+ private async readControl(
105
+ context: HandlerContext,
106
+ frame: WebSocketFrame,
107
+ ): Promise<void> {
108
+ if (frame instanceof PingWebSocketFrame) {
109
+ await context.writeAndFlush(new PongWebSocketFrame(frame.content))
110
+ } else if (frame instanceof CloseWebSocketFrame) {
111
+ await this.answerClose(context, frame)
112
+ } else if (!(frame instanceof PongWebSocketFrame)) {
113
+ await context.fireChannelRead(frame)
114
+ }
115
+ }
116
+
117
+ /**
118
+ * Echoes the peer's close code unless we already sent one, then hangs up
119
+ * @param context the handler's context
120
+ * @param frame close the peer sent
121
+ */
122
+ private async answerClose(
123
+ context: HandlerContext,
124
+ frame: CloseWebSocketFrame,
125
+ ): Promise<void> {
126
+ if (!this.closeSent) {
127
+ this.closeSent = true
128
+ await context.writeAndFlush(new CloseWebSocketFrame(frame.statusCode))
129
+ }
130
+
131
+ await context.close()
132
+ }
133
+
134
+ /**
135
+ * Writes the close frame, and hangs up as well on the server
136
+ * @param context where the frame goes
137
+ * @param frame close to send
138
+ */
139
+ private async sendClose(
140
+ context: HandlerContext,
141
+ frame: CloseWebSocketFrame,
142
+ ): Promise<void> {
143
+ await context.write(frame)
144
+
145
+ if (this.closeAfterSending) await context.close()
146
+ }
147
+ }
@@ -0,0 +1,233 @@
1
+ import { FullHttpResponse } from '../../http/message/full/response/index.ts'
2
+ import { FullHttpRequest } from '../../http/message/full/request/index.ts'
3
+ import { HttpMethod } from '../../http/method/index.ts'
4
+ import { HttpResponseStatus } from '../../http/status/index.ts'
5
+ import { WebSocketFrameDecoder } from '../decoder/index.ts'
6
+ import { WebSocketFrameEncoder } from '../encoder/index.ts'
7
+ import { WebSocketHandshakeComplete } from '../handshake/index.ts'
8
+ import { WebSocketKey } from '../key/index.ts'
9
+ import { WebSocketProtocolHandler } from '../protocol/index.ts'
10
+ import { WebSocketUpgrade } from '../upgrade/index.ts'
11
+ import type { HandlerContext } from '../../../channel/context/index.ts'
12
+
13
+ /**
14
+ * Settings for WebSocketServerProtocolHandler
15
+ */
16
+ export type WebSocketServerOptions = {
17
+ /**
18
+ * Upgrades are only accepted here, the query string is ignored
19
+ */
20
+ readonly path: string
21
+
22
+ /**
23
+ * Subprotocols we're happy to agree to, none by default
24
+ */
25
+ readonly subprotocols?: readonly string[]
26
+
27
+ /**
28
+ * Payload cap for inbound frames, 64 KiB by default
29
+ */
30
+ readonly maxFramePayloadLength?: number
31
+ }
32
+
33
+ /**
34
+ * Turns upgrade requests on one path into a WebSocket and runs the protocol from there
35
+ * @class
36
+ */
37
+ export class WebSocketServerProtocolHandler extends WebSocketProtocolHandler {
38
+ /**
39
+ * Only version 13 from RFC 6455
40
+ */
41
+ private static readonly version: string = '13'
42
+
43
+ /**
44
+ * Path we accept upgrades on
45
+ */
46
+ private readonly path: string
47
+
48
+ /**
49
+ * Subprotocols on offer
50
+ */
51
+ private readonly subprotocols: readonly string[]
52
+
53
+ /**
54
+ * Passed on to the frame decoder
55
+ */
56
+ private readonly maxFramePayloadLength: number
57
+
58
+ /**
59
+ * Once set, requests pass straight through
60
+ */
61
+ private upgraded: boolean
62
+
63
+ /**
64
+ * Sets up the handler from a path or full options
65
+ * @param options a path on its own, or full options
66
+ */
67
+ public constructor(options: WebSocketServerOptions | string) {
68
+ super(true)
69
+
70
+ const settings = typeof options === 'string' ? { path: options } : options
71
+ this.path = settings.path
72
+ this.subprotocols = settings.subprotocols ?? []
73
+ this.maxFramePayloadLength =
74
+ settings.maxFramePayloadLength ??
75
+ WebSocketFrameDecoder.defaultMaxFramePayloadLength
76
+ this.upgraded = false
77
+ }
78
+
79
+ /**
80
+ * Upgrades a matching request and lets everything else through
81
+ * @param context the handler's context
82
+ * @param message usually a FullHttpRequest
83
+ */
84
+ protected async readMessage(
85
+ context: HandlerContext,
86
+ message: unknown,
87
+ ): Promise<void> {
88
+ if (
89
+ this.upgraded ||
90
+ !(message instanceof FullHttpRequest) ||
91
+ !this.isUpgrade(message)
92
+ ) {
93
+ await context.fireChannelRead(message)
94
+ return
95
+ }
96
+
97
+ await this.handshake(context, message)
98
+ }
99
+
100
+ /**
101
+ * True for a websocket upgrade on our path
102
+ * @param request full request from the aggregator
103
+ */
104
+ private isUpgrade(request: FullHttpRequest): boolean {
105
+ const path = request.uri.split('?')[0]
106
+
107
+ return (
108
+ path === this.path && request.headers.hasToken('upgrade', 'websocket')
109
+ )
110
+ }
111
+
112
+ /**
113
+ * Sends 101 with the accept key, swaps in the frame codecs and fires the handshake event
114
+ * @param context the handler's context
115
+ * @param request upgrade that passed the checks
116
+ */
117
+ private async handshake(
118
+ context: HandlerContext,
119
+ request: FullHttpRequest,
120
+ ): Promise<void> {
121
+ const version = request.headers.get('sec-websocket-version')?.trim()
122
+ if (version !== WebSocketServerProtocolHandler.version) {
123
+ await this.reject(context, HttpResponseStatus.UPGRADE_REQUIRED)
124
+ return
125
+ }
126
+
127
+ const reason = this.refusal(request)
128
+ if (reason !== null) {
129
+ await this.reject(context, HttpResponseStatus.BAD_REQUEST, reason)
130
+ return
131
+ }
132
+
133
+ const key = request.headers.get('sec-websocket-key')?.trim() ?? ''
134
+ const subprotocol = this.select(request)
135
+ const response = new FullHttpResponse(
136
+ HttpResponseStatus.SWITCHING_PROTOCOLS,
137
+ )
138
+ response.headers
139
+ .set('Upgrade', 'websocket')
140
+ .set('Connection', 'Upgrade')
141
+ .set('Sec-WebSocket-Accept', new WebSocketKey(key).accept())
142
+ if (subprotocol !== null) {
143
+ response.headers.set('Sec-WebSocket-Protocol', subprotocol)
144
+ }
145
+
146
+ await context.writeAndFlush(response)
147
+
148
+ const upgrade = new WebSocketUpgrade(context.pipeline)
149
+ upgrade.install(
150
+ new WebSocketFrameDecoder({
151
+ /**
152
+ * Clients must mask their frames
153
+ */
154
+ expectMaskedFrames: true,
155
+ /**
156
+ * Our payload cap
157
+ */
158
+ maxFramePayloadLength: this.maxFramePayloadLength,
159
+ }),
160
+ new WebSocketFrameEncoder({
161
+ /**
162
+ * Servers send unmasked frames
163
+ */
164
+ maskPayload: false,
165
+ }),
166
+ )
167
+ this.upgraded = true
168
+ await context.fireUserEventTriggered(
169
+ new WebSocketHandshakeComplete(request.uri, request.headers, subprotocol),
170
+ )
171
+ await upgrade.release()
172
+ }
173
+
174
+ /**
175
+ * Has to be an HTTP/1.1 GET with Connection upgrade and a proper key
176
+ * @param request upgrade to check
177
+ */
178
+ private refusal(request: FullHttpRequest): string | null {
179
+ const key = request.headers.get('sec-websocket-key')?.trim() ?? ''
180
+
181
+ if (request.method !== HttpMethod.GET) return 'Method is not allowed'
182
+ if (!request.version.keepAliveDefault) return 'Version is unsupported'
183
+ if (!request.headers.hasToken('connection', 'upgrade')) {
184
+ return 'Connection header is invalid'
185
+ }
186
+
187
+ if (!new WebSocketKey(key).isValid) return 'Key is invalid'
188
+
189
+ return null
190
+ }
191
+
192
+ /**
193
+ * First subprotocol the client asked for that we also speak, or null
194
+ * @param request upgrade asking for subprotocols
195
+ */
196
+ private select(request: FullHttpRequest): string | null {
197
+ const requested = request.headers
198
+ .getAll('sec-websocket-protocol')
199
+ .flatMap((value: string): string[] => value.split(','))
200
+ .map((value: string): string => value.trim())
201
+
202
+ return (
203
+ requested.find((value: string): boolean =>
204
+ this.subprotocols.includes(value),
205
+ ) ?? null
206
+ )
207
+ }
208
+
209
+ /**
210
+ * Sends an error response and hangs up, with our version on a 426
211
+ * @param context where the response goes
212
+ * @param status 400 or 426, usually
213
+ * @param reason body text, the reason phrase by default
214
+ */
215
+ private async reject(
216
+ context: HandlerContext,
217
+ status: HttpResponseStatus,
218
+ reason = status.reasonPhrase,
219
+ ): Promise<void> {
220
+ const response = new FullHttpResponse(status, reason)
221
+ response.setContentLength(response.content.readableBytes)
222
+ response.headers.set('Connection', 'close')
223
+ if (status.code === HttpResponseStatus.UPGRADE_REQUIRED.code) {
224
+ response.headers.set(
225
+ 'Sec-WebSocket-Version',
226
+ WebSocketServerProtocolHandler.version,
227
+ )
228
+ }
229
+
230
+ await context.writeAndFlush(response)
231
+ await context.close()
232
+ }
233
+ }
@@ -0,0 +1,97 @@
1
+ /**
2
+ * A close code with a short reason to go with it
3
+ * @class
4
+ */
5
+ export class WebSocketCloseStatus {
6
+ /**
7
+ * 1000, all done
8
+ */
9
+ public static readonly NORMAL_CLOSURE: WebSocketCloseStatus =
10
+ new WebSocketCloseStatus(1000, 'Bye')
11
+
12
+ /**
13
+ * 1001, the server is shutting down or the page is leaving
14
+ */
15
+ public static readonly GOING_AWAY: WebSocketCloseStatus =
16
+ new WebSocketCloseStatus(1001, 'Endpoint is going away')
17
+
18
+ /**
19
+ * 1002, the peer broke the protocol
20
+ */
21
+ public static readonly PROTOCOL_ERROR: WebSocketCloseStatus =
22
+ new WebSocketCloseStatus(1002, 'Protocol error')
23
+
24
+ /**
25
+ * 1003, got a kind of data we can't take
26
+ */
27
+ public static readonly UNSUPPORTED_DATA: WebSocketCloseStatus =
28
+ new WebSocketCloseStatus(1003, 'Data is unsupported')
29
+
30
+ /**
31
+ * 1007, payload didn't match its type, like bad UTF-8
32
+ */
33
+ public static readonly INVALID_PAYLOAD: WebSocketCloseStatus =
34
+ new WebSocketCloseStatus(1007, 'Payload is invalid')
35
+
36
+ /**
37
+ * 1008, generic refusal on policy grounds
38
+ */
39
+ public static readonly POLICY_VIOLATION: WebSocketCloseStatus =
40
+ new WebSocketCloseStatus(1008, 'Policy is violated')
41
+
42
+ /**
43
+ * 1009, message over our size limit
44
+ */
45
+ public static readonly MESSAGE_TOO_BIG: WebSocketCloseStatus =
46
+ new WebSocketCloseStatus(1009, 'Message is too big')
47
+
48
+ /**
49
+ * 1010, the server didn't agree to an extension the client needs
50
+ */
51
+ public static readonly MANDATORY_EXTENSION: WebSocketCloseStatus =
52
+ new WebSocketCloseStatus(1010, 'Extension is required')
53
+
54
+ /**
55
+ * 1011, something broke on our side
56
+ */
57
+ public static readonly INTERNAL_ERROR: WebSocketCloseStatus =
58
+ new WebSocketCloseStatus(1011, 'Internal error')
59
+
60
+ /**
61
+ * Numeric close code
62
+ */
63
+ public readonly code: number
64
+
65
+ /**
66
+ * Default reason text sent with the code
67
+ */
68
+ public readonly reasonText: string
69
+
70
+ /**
71
+ * Builds a status, throwing if the code can't go in a close frame
72
+ * @param code a sendable close code
73
+ * @param reasonText short reason to send
74
+ */
75
+ public constructor(code: number, reasonText: string) {
76
+ if (!WebSocketCloseStatus.isValid(code)) {
77
+ throw new RangeError('Close status is invalid')
78
+ }
79
+
80
+ this.code = code
81
+ this.reasonText = reasonText
82
+ }
83
+
84
+ /**
85
+ * 1000 to 1003, 1007 to 1014 and 3000 to 4999 can go on the wire
86
+ * @param code close code to check
87
+ */
88
+ public static isValid(code: number): boolean {
89
+ if (!Number.isInteger(code)) return false
90
+
91
+ return (
92
+ (code >= 1000 && code <= 1003) ||
93
+ (code >= 1007 && code <= 1014) ||
94
+ (code >= 3000 && code <= 4999)
95
+ )
96
+ }
97
+ }
@@ -0,0 +1,116 @@
1
+ import type { Pipeline } from '../../../channel/pipeline/index.ts'
2
+ import { HttpObjectAggregator } from '../../http/aggregator/index.ts'
3
+ import { HttpClientCodec } from '../../http/client/index.ts'
4
+ import { HttpObjectDecoder } from '../../http/decoder/object/index.ts'
5
+ import { HttpObjectEncoder } from '../../http/encoder/object/index.ts'
6
+ import { HttpServerCodec } from '../../http/server/index.ts'
7
+ import type { WebSocketFrameDecoder } from '../decoder/index.ts'
8
+ import type { WebSocketFrameEncoder } from '../encoder/index.ts'
9
+ import { HandshakeError } from '../error/index.ts'
10
+ import type { ChannelHandler } from '../../../channel/handler/index.ts'
11
+
12
+ /**
13
+ * Swaps the HTTP handlers in a pipeline for WebSocket frame codecs
14
+ * @class
15
+ */
16
+ export class WebSocketUpgrade {
17
+ /**
18
+ * Pipeline name for the frame decoder
19
+ */
20
+ public static readonly decoderName: string = 'wsdecoder'
21
+
22
+ /**
23
+ * Pipeline name for the frame encoder
24
+ */
25
+ public static readonly encoderName: string = 'wsencoder'
26
+
27
+ /**
28
+ * Pipeline being upgraded
29
+ */
30
+ private readonly pipeline: Pipeline
31
+
32
+ /**
33
+ * HTTP decoder we're keeping until release, or null
34
+ */
35
+ private anchor: string | null
36
+
37
+ /**
38
+ * Sets up an upgrade for this pipeline
39
+ * @param pipeline the channel's pipeline
40
+ */
41
+ public constructor(pipeline: Pipeline) {
42
+ this.pipeline = pipeline
43
+ this.anchor = null
44
+ }
45
+
46
+ /**
47
+ * True for the HTTP codecs and decoders
48
+ * @param handler handler to check
49
+ */
50
+ private static decodes(handler: ChannelHandler | null): boolean {
51
+ return (
52
+ handler instanceof HttpServerCodec ||
53
+ handler instanceof HttpClientCodec ||
54
+ handler instanceof HttpObjectDecoder
55
+ )
56
+ }
57
+
58
+ /**
59
+ * True for HTTP handlers we can drop straight away
60
+ * @param handler handler to check
61
+ */
62
+ private static isDisposable(handler: ChannelHandler | null): boolean {
63
+ return (
64
+ handler instanceof HttpObjectAggregator ||
65
+ handler instanceof HttpObjectEncoder
66
+ )
67
+ }
68
+
69
+ /**
70
+ * Puts the frame codecs either side of the HTTP decoder and drops the other HTTP handlers
71
+ * @param decoder goes after the HTTP decoder
72
+ * @param encoder goes before the HTTP decoder
73
+ */
74
+ public install(
75
+ decoder: WebSocketFrameDecoder,
76
+ encoder: WebSocketFrameEncoder,
77
+ ): void {
78
+ const names = this.pipeline.names()
79
+ const anchor = names.find((name: string): boolean =>
80
+ WebSocketUpgrade.decodes(this.pipeline.get<ChannelHandler>(name)),
81
+ )
82
+ if (anchor === undefined) throw new HandshakeError('Codec is missing')
83
+
84
+ for (const name of names) {
85
+ if (
86
+ WebSocketUpgrade.isDisposable(this.pipeline.get<ChannelHandler>(name))
87
+ ) {
88
+ this.pipeline.remove<ChannelHandler>(name)
89
+ }
90
+ }
91
+
92
+ this.pipeline.addBefore<WebSocketFrameEncoder>(
93
+ anchor,
94
+ WebSocketUpgrade.encoderName,
95
+ encoder,
96
+ )
97
+ this.pipeline.addAfter<WebSocketFrameDecoder>(
98
+ anchor,
99
+ WebSocketUpgrade.decoderName,
100
+ decoder,
101
+ )
102
+ this.anchor = anchor
103
+ }
104
+
105
+ /**
106
+ * Drops the HTTP decoder so any bytes it held land in the frame decoder
107
+ */
108
+ public async release(): Promise<void> {
109
+ const anchor = this.anchor
110
+ if (anchor === null) return
111
+ this.anchor = null
112
+
113
+ this.pipeline.remove<ChannelHandler>(anchor)
114
+ await this.pipeline.settle()
115
+ }
116
+ }