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

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 (142) 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/index.ts +10 -0
  137. package/src/shard/link/index.ts +743 -0
  138. package/src/shard/map/index.ts +91 -0
  139. package/src/worker/group/index.ts +175 -0
  140. package/src/worker/index.ts +10 -0
  141. package/src/worker/pool/index.ts +235 -0
  142. package/src/worker/service/index.ts +55 -0
@@ -0,0 +1,187 @@
1
+ import { DuplexHandlerAdapter } from '../../channel/handler/duplex/index.ts'
2
+ import type {} from '../../channel/handler/index.ts'
3
+ import type { HandlerContext } from '../../channel/context/index.ts'
4
+
5
+ /**
6
+ * Knobs for how aggressively flushes get batched
7
+ */
8
+ export type FlushConsolidationOptions = {
9
+ /**
10
+ * How many flushes to sit on mid-read before letting one through, 256 by default
11
+ */
12
+ readonly explicitFlushAfterFlushes?: number
13
+
14
+ /**
15
+ * Also batch flushes outside reads, one per microtask, off by default
16
+ */
17
+ readonly consolidateWhenNoReadInProgress?: boolean
18
+ }
19
+
20
+ /**
21
+ * Cuts down on syscalls when handlers flush after every little write
22
+ * @class
23
+ */
24
+ export class FlushConsolidationHandler extends DuplexHandlerAdapter {
25
+ /**
26
+ * Resolved explicitFlushAfterFlushes
27
+ */
28
+ private readonly limit: number
29
+
30
+ /**
31
+ * Resolved consolidateWhenNoReadInProgress
32
+ */
33
+ private readonly outsideReads: boolean
34
+
35
+ /**
36
+ * Flushes we've swallowed since the last one that went through
37
+ */
38
+ private held: number
39
+
40
+ /**
41
+ * True between channelRead and channelReadComplete
42
+ */
43
+ private reading: boolean
44
+
45
+ /**
46
+ * Stops us queuing more than one microtask flush at a time
47
+ */
48
+ private scheduled: boolean
49
+
50
+ /**
51
+ * Shared promise for everyone whose flush we're sitting on
52
+ */
53
+ private waiting: PromiseWithResolvers<undefined> | null
54
+
55
+ /**
56
+ * Throws a RangeError if the flush limit isn't a positive integer
57
+ * @param options batching settings, all optional
58
+ */
59
+ public constructor(options: FlushConsolidationOptions = {}) {
60
+ super()
61
+
62
+ const limit = options.explicitFlushAfterFlushes ?? 256
63
+ if (!Number.isInteger(limit) || limit < 1) {
64
+ throw new RangeError('Flush limit is invalid')
65
+ }
66
+
67
+ this.limit = limit
68
+ this.outsideReads = options.consolidateWhenNoReadInProgress ?? false
69
+ this.held = 0
70
+ this.reading = false
71
+ this.scheduled = false
72
+ this.waiting = null
73
+ }
74
+
75
+ /**
76
+ * Notes that we're mid-read, then passes the message along untouched
77
+ * @param context where the read carries on
78
+ * @param message whatever came in
79
+ */
80
+ public override channelRead(
81
+ context: HandlerContext,
82
+ message: unknown,
83
+ ): Promise<void> {
84
+ this.reading = true
85
+
86
+ return context.fireChannelRead(message)
87
+ }
88
+
89
+ /**
90
+ * End of the read batch, so anything we held goes out now
91
+ * @param context where the event carries on
92
+ */
93
+ public override channelReadComplete(context: HandlerContext): Promise<void> {
94
+ this.reading = false
95
+
96
+ this.release(context)
97
+ return context.fireChannelReadComplete()
98
+ }
99
+
100
+ /**
101
+ * Last chance to get held writes out before the channel goes
102
+ * @param context where the event carries on
103
+ */
104
+ public override channelInactive(context: HandlerContext): Promise<void> {
105
+ this.release(context)
106
+
107
+ return context.fireChannelInactive()
108
+ }
109
+
110
+ /**
111
+ * Don't strand held flushes if we're pulled out of the pipeline
112
+ * @param context our old slot, still good for one last flush
113
+ */
114
+ public handlerRemoved(context: HandlerContext): void {
115
+ this.release(context)
116
+ }
117
+
118
+ /**
119
+ * Swallows the flush if we can batch it, otherwise lets it through
120
+ * @param context where real flushes get sent
121
+ */
122
+ public override flush(context: HandlerContext): Promise<void> {
123
+ if (this.reading) {
124
+ this.held += 1
125
+ if (this.held < this.limit) return this.hold()
126
+ return this.forward(context)
127
+ }
128
+
129
+ if (!this.outsideReads) return this.forward(context)
130
+
131
+ this.held += 1
132
+ const promise = this.hold()
133
+ if (!this.scheduled) {
134
+ this.scheduled = true
135
+ queueMicrotask((): void => {
136
+ this.scheduled = false
137
+ this.release(context)
138
+ })
139
+ }
140
+
141
+ return promise
142
+ }
143
+
144
+ /**
145
+ * Does one real flush and settles everyone who was waiting on it
146
+ * @param context where the flush gets sent
147
+ */
148
+ private forward(context: HandlerContext): Promise<void> {
149
+ const waiting = this.waiting
150
+ this.held = 0
151
+ this.waiting = null
152
+
153
+ const flushed = context.flush()
154
+ if (waiting !== null) {
155
+ flushed.then(
156
+ (): void => {
157
+ waiting.resolve(undefined)
158
+ },
159
+ (error: unknown): void => {
160
+ waiting.reject(error)
161
+ },
162
+ )
163
+ }
164
+
165
+ return flushed
166
+ }
167
+
168
+ /**
169
+ * Fire-and-forget forward, skipped when nothing's held
170
+ * @param context where the flush gets sent
171
+ */
172
+ private release(context: HandlerContext): void {
173
+ if (this.held > 0) void this.forward(context)
174
+ }
175
+
176
+ /**
177
+ * Hands out the shared waiting promise, creating it on first use
178
+ */
179
+ private hold(): Promise<void> {
180
+ if (this.waiting !== null) return this.waiting.promise
181
+
182
+ const waiting = Promise.withResolvers<undefined>()
183
+ void waiting.promise.catch((): undefined => undefined)
184
+ this.waiting = waiting
185
+ return waiting.promise
186
+ }
187
+ }
@@ -0,0 +1,295 @@
1
+ import { DuplexHandlerAdapter } from '../../channel/handler/duplex/index.ts'
2
+ import type {} from '../../channel/handler/index.ts'
3
+ import type { HandlerContext } from '../../channel/context/index.ts'
4
+
5
+ /**
6
+ * Reads only, writes only, or neither
7
+ */
8
+ export type IdleState = 'reader' | 'writer' | 'all'
9
+
10
+ /**
11
+ * Timeouts in ms, leave one out or set it to 0 to switch it off
12
+ */
13
+ export type IdleOptions = {
14
+ /**
15
+ * Quiet time on the read side before we fire
16
+ */
17
+ readonly readerIdle?: number
18
+
19
+ /**
20
+ * Quiet time on the write side before we fire
21
+ */
22
+ readonly writerIdle?: number
23
+
24
+ /**
25
+ * Fires when neither side has done anything for this long
26
+ */
27
+ readonly allIdle?: number
28
+ }
29
+
30
+ /**
31
+ * What shows up in userEventTriggered when a timeout passes
32
+ * @class
33
+ */
34
+ export class IdleStateEvent {
35
+ /**
36
+ * Tells you which timeout went off
37
+ */
38
+ public readonly state: IdleState
39
+
40
+ /**
41
+ * False on repeat events while the channel stays quiet
42
+ */
43
+ public readonly first: boolean
44
+
45
+ /**
46
+ * Built by IdleStateHandler, you shouldn't need to make these
47
+ * @param state which timeout went off
48
+ * @param first true unless we've already fired since the last activity
49
+ */
50
+ public constructor(state: IdleState, first: boolean) {
51
+ this.state = state
52
+ this.first = first
53
+ }
54
+ }
55
+
56
+ /**
57
+ * Watches for quiet periods, handy for heartbeats and dropping dead peers
58
+ * @class
59
+ */
60
+ export class IdleStateHandler extends DuplexHandlerAdapter {
61
+ /**
62
+ * Resolved option values, 0 means that one is off
63
+ */
64
+ private readonly timeouts: ReadonlyMap<IdleState, number>
65
+
66
+ /**
67
+ * At most one pending setTimeout per state
68
+ */
69
+ private readonly timers: Map<IdleState, Timer>
70
+
71
+ /**
72
+ * Reset to true by activity, flipped to false once we've fired
73
+ */
74
+ private readonly firsts: Map<IdleState, boolean>
75
+
76
+ /**
77
+ * performance.now() at the last read
78
+ */
79
+ private lastRead: number
80
+
81
+ /**
82
+ * performance.now() when the last write finished
83
+ */
84
+ private lastWrite: number
85
+
86
+ /**
87
+ * Guards against starting the timers twice
88
+ */
89
+ private started: boolean
90
+
91
+ /**
92
+ * Throws a RangeError if any timeout is negative
93
+ * @param options which timeouts to watch
94
+ */
95
+ public constructor(options: IdleOptions) {
96
+ super()
97
+
98
+ const reason = IdleStateHandler.refusal(options)
99
+ if (reason !== null) throw new RangeError(reason)
100
+
101
+ this.timeouts = new Map<IdleState, number>([
102
+ ['reader', options.readerIdle ?? 0],
103
+ ['writer', options.writerIdle ?? 0],
104
+ ['all', options.allIdle ?? 0],
105
+ ])
106
+ this.timers = new Map<IdleState, Timer>()
107
+ this.firsts = new Map<IdleState, boolean>()
108
+ this.lastRead = 0
109
+ this.lastWrite = 0
110
+ this.started = false
111
+ }
112
+
113
+ /**
114
+ * Error text if a timeout is negative, or null
115
+ * @param options timeouts to check
116
+ */
117
+ private static refusal(options: IdleOptions): string | null {
118
+ const values = [options.readerIdle, options.writerIdle, options.allIdle]
119
+
120
+ if (values.some((value?: number): boolean => (value ?? 0) < 0)) {
121
+ return 'Timeout is negative'
122
+ }
123
+
124
+ return null
125
+ }
126
+
127
+ /**
128
+ * Covers being added to a channel that's already live
129
+ * @param context gives us the channel to check
130
+ */
131
+ public handlerAdded(context: HandlerContext): void {
132
+ if (context.channel.isActive) this.start(context)
133
+ }
134
+
135
+ /**
136
+ * No timers left behind once we're out
137
+ */
138
+ public handlerRemoved(): void {
139
+ this.stop()
140
+ }
141
+
142
+ /**
143
+ * Clocks start when the connection comes up
144
+ * @param context where the event carries on
145
+ */
146
+ public override async channelActive(context: HandlerContext): Promise<void> {
147
+ this.start(context)
148
+ await context.fireChannelActive()
149
+ }
150
+
151
+ /**
152
+ * Nothing to watch once the connection is gone
153
+ * @param context where the event carries on
154
+ */
155
+ public override async channelInactive(
156
+ context: HandlerContext,
157
+ ): Promise<void> {
158
+ this.stop()
159
+ await context.fireChannelInactive()
160
+ }
161
+
162
+ /**
163
+ * Resets the reader and all clocks
164
+ * @param context where the read carries on
165
+ * @param message passed along untouched
166
+ */
167
+ public override async channelRead(
168
+ context: HandlerContext,
169
+ message: unknown,
170
+ ): Promise<void> {
171
+ this.lastRead = performance.now()
172
+ this.firsts.set('reader', true)
173
+ this.firsts.set('all', true)
174
+
175
+ await context.fireChannelRead(message)
176
+ }
177
+
178
+ /**
179
+ * Only counts the write once it's actually gone out, failures don't count
180
+ * @param context where the write carries on
181
+ * @param message passed along untouched
182
+ */
183
+ public override write(
184
+ context: HandlerContext,
185
+ message: unknown,
186
+ ): Promise<void> {
187
+ const promise = context.write(message)
188
+
189
+ void promise.then(
190
+ (): void => {
191
+ this.lastWrite = performance.now()
192
+ this.firsts.set('writer', true)
193
+ this.firsts.set('all', true)
194
+ },
195
+ (): undefined => undefined,
196
+ )
197
+ return promise
198
+ }
199
+
200
+ /**
201
+ * Override this to react to idleness yourself, by default it fires a user event
202
+ * @param context where the event gets fired from
203
+ * @param event which timeout went off
204
+ */
205
+ protected channelIdle(
206
+ context: HandlerContext,
207
+ event: IdleStateEvent,
208
+ ): Promise<void> {
209
+ return context.fireUserEventTriggered(event)
210
+ }
211
+
212
+ /**
213
+ * Resets both clocks and kicks off a timer for each timeout that's on
214
+ * @param context needed later when the timers fire
215
+ */
216
+ private start(context: HandlerContext): void {
217
+ if (this.started) return
218
+ this.started = true
219
+
220
+ const now = performance.now()
221
+ this.lastRead = now
222
+ this.lastWrite = now
223
+ for (const [state, timeout] of this.timeouts) {
224
+ if (timeout === 0) continue
225
+ this.firsts.set(state, true)
226
+ this.schedule(context, state, timeout)
227
+ }
228
+ }
229
+
230
+ /**
231
+ * Clears every timer and stops checks that are already queued from firing
232
+ */
233
+ private stop(): void {
234
+ this.started = false
235
+
236
+ for (const timer of this.timers.values()) clearTimeout(timer)
237
+ this.timers.clear()
238
+ }
239
+
240
+ /**
241
+ * The check runs on the channel's executor so it stays in order with events
242
+ * @param context used to reach the channel
243
+ * @param state which timeout this timer is for
244
+ * @param delay ms until the check
245
+ */
246
+ private schedule(
247
+ context: HandlerContext,
248
+ state: IdleState,
249
+ delay: number,
250
+ ): void {
251
+ const timer = setTimeout((): void => {
252
+ void context.channel.execute((): Promise<void> =>
253
+ this.check(context, state),
254
+ )
255
+ }, delay)
256
+ timer.unref()
257
+
258
+ this.timers.set(state, timer)
259
+ }
260
+
261
+ /**
262
+ * Fires if the full timeout has passed, otherwise re-arms for the time left
263
+ * @param context where the event gets fired from
264
+ * @param state which timeout to check
265
+ */
266
+ private async check(
267
+ context: HandlerContext,
268
+ state: IdleState,
269
+ ): Promise<void> {
270
+ if (!this.started) return
271
+
272
+ const timeout = this.timeouts.get(state) ?? 0
273
+ const remaining = timeout - (performance.now() - this.lastActivity(state))
274
+ if (remaining > 0) {
275
+ this.schedule(context, state, remaining)
276
+ return
277
+ }
278
+
279
+ this.schedule(context, state, timeout)
280
+ const first = this.firsts.get(state) ?? false
281
+ this.firsts.set(state, false)
282
+ await this.channelIdle(context, new IdleStateEvent(state, first))
283
+ }
284
+
285
+ /**
286
+ * For all it's whichever of read or write happened more recently
287
+ * @param state which clock to read
288
+ */
289
+ private lastActivity(state: IdleState): number {
290
+ if (state === 'reader') return this.lastRead
291
+ if (state === 'writer') return this.lastWrite
292
+
293
+ return Math.max(this.lastRead, this.lastWrite)
294
+ }
295
+ }
@@ -0,0 +1,22 @@
1
+ export { FlushConsolidationHandler } from './flush/index.ts'
2
+ export type { FlushConsolidationOptions } from './flush/index.ts'
3
+ export { IdleStateEvent, IdleStateHandler } from './idle/index.ts'
4
+ export type { IdleOptions, IdleState } from './idle/index.ts'
5
+ export { LoggingHandler } from './logging/index.ts'
6
+ export { OffloadHandler } from './offload/index.ts'
7
+ export type { OffloadOptions } from './offload/index.ts'
8
+ export {
9
+ ReadTimeoutError,
10
+ ReadTimeoutHandler,
11
+ WriteTimeoutError,
12
+ WriteTimeoutHandler,
13
+ } from './timeout/index.ts'
14
+ export { MetricsHandler } from './metrics/index.ts'
15
+ export type { MetricsOptions, MetricsSnapshot } from './metrics/index.ts'
16
+ export {
17
+ ChannelTrafficShapingHandler,
18
+ GlobalTrafficShapingHandler,
19
+ TokenBucket,
20
+ TrafficShapingHandler,
21
+ } from './traffic/index.ts'
22
+ export type { TrafficShapingOptions } from './traffic/index.ts'
@@ -0,0 +1,195 @@
1
+ import { DuplexHandlerAdapter } from '../../channel/handler/duplex/index.ts'
2
+ import { ByteBuf } from '../../buffer/index.ts'
3
+ import type { HandlerContext } from '../../channel/context/index.ts'
4
+ import type {} from '../../channel/handler/index.ts'
5
+ import type { LogFields, Logger } from '../../logger/index.ts'
6
+
7
+ /**
8
+ * Drop it anywhere in a pipeline to see what's going past at debug level
9
+ * @class
10
+ */
11
+ export class LoggingHandler extends DuplexHandlerAdapter {
12
+ /**
13
+ * Strings get cut to this many characters in the log
14
+ */
15
+ private static readonly preview: number = 64
16
+
17
+ /**
18
+ * Our own logger if given, otherwise we borrow the pipeline's
19
+ */
20
+ private readonly logger: Logger | null
21
+
22
+ /**
23
+ * Leave the logger out to use whatever the pipeline has
24
+ * @param logger somewhere else to send the lines, or null
25
+ */
26
+ public constructor(logger: Logger | null = null) {
27
+ super()
28
+
29
+ this.logger = logger
30
+ }
31
+
32
+ /**
33
+ * Short summary like ByteBuf(12) so big payloads don't flood the log
34
+ * @param message anything passing through
35
+ */
36
+ private static describe(message: unknown): string {
37
+ if (message instanceof ByteBuf) {
38
+ return `ByteBuf(${String(message.readableBytes)})`
39
+ }
40
+
41
+ if (message instanceof Uint8Array) {
42
+ return `Uint8Array(${String(message.length)})`
43
+ }
44
+
45
+ if (typeof message === 'string') {
46
+ return JSON.stringify(message.slice(0, LoggingHandler.preview))
47
+ }
48
+
49
+ if (typeof message === 'object' && message !== null) {
50
+ return message.constructor.name
51
+ }
52
+
53
+ return typeof message
54
+ }
55
+
56
+ /**
57
+ * Logs it, then carries on
58
+ * @param context where the event carries on
59
+ */
60
+ public override channelActive(context: HandlerContext): Promise<void> {
61
+ this.log(context, {}, 'Channel became active')
62
+ return context.fireChannelActive()
63
+ }
64
+
65
+ /**
66
+ * Logs it, then carries on
67
+ * @param context where the event carries on
68
+ */
69
+ public override channelInactive(context: HandlerContext): Promise<void> {
70
+ this.log(context, {}, 'Channel became inactive')
71
+ return context.fireChannelInactive()
72
+ }
73
+
74
+ /**
75
+ * Logs a summary of the message, not the whole thing
76
+ * @param context where the read carries on
77
+ * @param message whatever came in
78
+ */
79
+ public override channelRead(
80
+ context: HandlerContext,
81
+ message: unknown,
82
+ ): Promise<void> {
83
+ this.log(
84
+ context,
85
+ { message: LoggingHandler.describe(message) },
86
+ 'Message was read',
87
+ )
88
+ return context.fireChannelRead(message)
89
+ }
90
+
91
+ /**
92
+ * Logs it, then carries on
93
+ * @param context where the event carries on
94
+ */
95
+ public override channelReadComplete(context: HandlerContext): Promise<void> {
96
+ this.log(context, {}, 'Read batch completed')
97
+ return context.fireChannelReadComplete()
98
+ }
99
+
100
+ /**
101
+ * Includes the new writable state in the log line
102
+ * @param context where the event carries on
103
+ */
104
+ public override channelWritabilityChanged(
105
+ context: HandlerContext,
106
+ ): Promise<void> {
107
+ this.log(
108
+ context,
109
+ { writable: context.channel.isWritable },
110
+ 'Writability changed',
111
+ )
112
+ return context.fireChannelWritabilityChanged()
113
+ }
114
+
115
+ /**
116
+ * Logs what kind of event it was
117
+ * @param context where the event carries on
118
+ * @param event anything fired with fireUserEventTriggered
119
+ */
120
+ public override userEventTriggered(
121
+ context: HandlerContext,
122
+ event: unknown,
123
+ ): Promise<void> {
124
+ this.log(
125
+ context,
126
+ { event: LoggingHandler.describe(event) },
127
+ 'User event fired',
128
+ )
129
+ return context.fireUserEventTriggered(event)
130
+ }
131
+
132
+ /**
133
+ * Logs at debug, then passes the error on so it still gets handled
134
+ * @param context where the error carries on
135
+ * @param error whatever was thrown
136
+ */
137
+ public override exceptionCaught(
138
+ context: HandlerContext,
139
+ error: unknown,
140
+ ): Promise<void> {
141
+ this.log(context, { err: error }, 'Error was caught')
142
+ return context.fireExceptionCaught(error)
143
+ }
144
+
145
+ /**
146
+ * Logs a summary of what's going out
147
+ * @param context where the write carries on
148
+ * @param message what's being sent
149
+ */
150
+ public override write(
151
+ context: HandlerContext,
152
+ message: unknown,
153
+ ): Promise<void> {
154
+ this.log(
155
+ context,
156
+ { message: LoggingHandler.describe(message) },
157
+ 'Message was written',
158
+ )
159
+ return context.write(message)
160
+ }
161
+
162
+ /**
163
+ * Logs it, then carries on
164
+ * @param context where the flush carries on
165
+ */
166
+ public override flush(context: HandlerContext): Promise<void> {
167
+ this.log(context, {}, 'Channel was flushed')
168
+ return context.flush()
169
+ }
170
+
171
+ /**
172
+ * Logs it, then carries on
173
+ * @param context where the close carries on
174
+ */
175
+ public override close(context: HandlerContext): Promise<void> {
176
+ this.log(context, {}, 'Channel is closing')
177
+ return context.close()
178
+ }
179
+
180
+ /**
181
+ * Every line gets the channel id so you can follow one connection
182
+ * @param context used for the channel id and fallback logger
183
+ * @param fields extra details for this line
184
+ * @param message the log text
185
+ */
186
+ private log(
187
+ context: HandlerContext,
188
+ fields: LogFields,
189
+ message: string,
190
+ ): void {
191
+ const logger = this.logger ?? context.pipeline.logger
192
+
193
+ logger.debug({ channel: context.channel.id, ...fields }, message)
194
+ }
195
+ }