@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,414 @@
1
+ import { HandlerContext } from '../context/index.ts'
2
+ import type { ChannelHandler, OutboundHandler } from '../handler/index.ts'
3
+ import { TailHandler } from './tail/index.ts'
4
+ import { WriteTracker } from './tracker/index.ts'
5
+ import type { Logger } from '../../logger/index.ts'
6
+ import type { Channel } from '../index.ts'
7
+
8
+ export { HeadHandler } from './head/index.ts'
9
+ export type { Sink } from './head/index.ts'
10
+ export { TailHandler } from './tail/index.ts'
11
+ export { WriteTracker } from './tracker/index.ts'
12
+
13
+ /**
14
+ * Every channel's chain of handlers, inbound runs head to tail and outbound the other way
15
+ * @class
16
+ */
17
+ export class Pipeline {
18
+ /**
19
+ * Channel this pipeline serves
20
+ */
21
+ public readonly channel: Channel
22
+
23
+ /**
24
+ * Where unhandled errors and dropped messages get logged
25
+ */
26
+ public readonly logger: Logger
27
+
28
+ /**
29
+ * Stops flushes from overtaking writes that handlers are still holding
30
+ */
31
+ public readonly tracker: WriteTracker
32
+
33
+ /**
34
+ * Set during writeSync so lower layers know nobody's awaiting the result
35
+ */
36
+ public syncing: boolean
37
+
38
+ /**
39
+ * Goes up whenever the links change, so contexts know their lookups are stale
40
+ */
41
+ public version: number
42
+
43
+ /**
44
+ * Fixed first link, turns outbound calls into bytes for the channel
45
+ */
46
+ private readonly head: HandlerContext
47
+
48
+ /**
49
+ * Fixed last link, logs whatever reaches it
50
+ */
51
+ private readonly tail: HandlerContext
52
+
53
+ /**
54
+ * Name lookup for every user handler, head and tail aren't in here
55
+ */
56
+ private readonly contexts: Map<string, HandlerContext>
57
+
58
+ /**
59
+ * handlerAdded and handlerRemoved calls that haven't settled yet
60
+ */
61
+ private readonly lifecycles: Set<Promise<void>>
62
+
63
+ /**
64
+ * Starts with just a head and tail linked together
65
+ * @param channel the owner
66
+ * @param head usually a HeadHandler wired to the channel
67
+ * @param logger shared with the tail handler
68
+ */
69
+ public constructor(channel: Channel, head: OutboundHandler, logger: Logger) {
70
+ this.channel = channel
71
+ this.logger = logger
72
+ this.tracker = new WriteTracker()
73
+ this.syncing = false
74
+ this.version = 0
75
+ this.head = new HandlerContext(this, 'head', head)
76
+ this.tail = new HandlerContext(this, 'tail', new TailHandler(logger))
77
+ this.contexts = new Map<string, HandlerContext>()
78
+ this.lifecycles = new Set<Promise<void>>()
79
+
80
+ this.head.next = this.tail
81
+ this.tail.previous = this.head
82
+ }
83
+
84
+ /**
85
+ * Puts it right after the head, so it sees inbound events first
86
+ * @param name must be unique in this pipeline
87
+ * @param handler what to add
88
+ */
89
+ public addFirst<T extends ChannelHandler>(name: string, handler: T): this {
90
+ return this.insert(name, handler, this.head)
91
+ }
92
+
93
+ /**
94
+ * Puts it just before the tail, the usual spot for app logic
95
+ * @param name must be unique in this pipeline
96
+ * @param handler what to add
97
+ */
98
+ public addLast<T extends ChannelHandler>(name: string, handler: T): this {
99
+ return this.insert(name, handler, this.tail.previous ?? this.head)
100
+ }
101
+
102
+ /**
103
+ * Slots it in on the head side of an existing handler
104
+ * @param base name of the handler to go before
105
+ * @param name must be unique in this pipeline
106
+ * @param handler what to add
107
+ */
108
+ public addBefore<T extends ChannelHandler>(
109
+ base: string,
110
+ name: string,
111
+ handler: T,
112
+ ): this {
113
+ const context = this.require(base)
114
+ return this.insert(name, handler, context.previous ?? this.head)
115
+ }
116
+
117
+ /**
118
+ * Slots it in on the tail side of an existing handler
119
+ * @param base name of the handler to go after
120
+ * @param name must be unique in this pipeline
121
+ * @param handler what to add
122
+ */
123
+ public addAfter<T extends ChannelHandler>(
124
+ base: string,
125
+ name: string,
126
+ handler: T,
127
+ ): this {
128
+ return this.insert(name, handler, this.require(base))
129
+ }
130
+
131
+ /**
132
+ * Throws if the name isn't there, otherwise hands back what was removed
133
+ * @param name which handler to take out
134
+ */
135
+ public remove<T extends ChannelHandler>(name: string): T {
136
+ const context = this.require(name)
137
+
138
+ this.unlink(context)
139
+ return context.handler as T
140
+ }
141
+
142
+ /**
143
+ * Swaps one handler for another in the same spot and returns the old one
144
+ * @param base name of the handler to swap out
145
+ * @param name for the new one, may reuse base
146
+ * @param handler the replacement
147
+ */
148
+ public replace<T extends ChannelHandler>(
149
+ base: string,
150
+ name: string,
151
+ handler: T,
152
+ ): ChannelHandler {
153
+ const context = this.require(base)
154
+ const reason = name === base ? null : this.refusal(name)
155
+ if (reason !== null) throw new Error(reason)
156
+
157
+ const previous = context.previous ?? this.head
158
+ this.unlink(context)
159
+ this.insert(name, handler, previous)
160
+ return context.handler
161
+ }
162
+
163
+ /**
164
+ * Null if nothing's registered under that name
165
+ * @param name what it was added as
166
+ */
167
+ public get<T extends ChannelHandler>(name: string): T | null {
168
+ const handler = this.contexts.get(name)?.handler
169
+
170
+ return handler === undefined ? null : (handler as T)
171
+ }
172
+
173
+ /**
174
+ * Looks up a handler by class when you don't know its name, nearest the head wins
175
+ * @param type class to match with instanceof
176
+ */
177
+ public find<T extends ChannelHandler>(
178
+ type: abstract new (...parameters: never[]) => T,
179
+ ): T | null {
180
+ for (
181
+ let context = this.head.next;
182
+ context !== null;
183
+ context = context.next
184
+ ) {
185
+ const handler = context.handler
186
+ if (context !== this.tail && handler instanceof type) return handler
187
+ }
188
+
189
+ return null
190
+ }
191
+
192
+ /**
193
+ * Handy for firing events from a particular point in the chain
194
+ * @param name what the handler was added as
195
+ */
196
+ public context(name: string): HandlerContext | null {
197
+ return this.contexts.get(name) ?? null
198
+ }
199
+
200
+ /**
201
+ * Handler names in order, head and tail left out
202
+ */
203
+ public names(): string[] {
204
+ const names: string[] = []
205
+
206
+ for (let context = this.head.next; context !== this.tail;) {
207
+ if (context === null) break
208
+ names.push(context.name)
209
+ context = context.next
210
+ }
211
+
212
+ return names
213
+ }
214
+
215
+ /**
216
+ * Resolves once every handlerAdded and handlerRemoved has finished, including ones they trigger
217
+ */
218
+ public async settle(): Promise<void> {
219
+ while (this.lifecycles.size > 0) {
220
+ await Promise.all([...this.lifecycles])
221
+ }
222
+ }
223
+
224
+ /**
225
+ * Kicks off channelActive at the start of the chain
226
+ */
227
+ public fireChannelActive(): Promise<void> {
228
+ return this.head.fireChannelActive()
229
+ }
230
+
231
+ /**
232
+ * Kicks off channelInactive at the start of the chain
233
+ */
234
+ public fireChannelInactive(): Promise<void> {
235
+ return this.head.fireChannelInactive()
236
+ }
237
+
238
+ /**
239
+ * Feeds an incoming message to the first handler that reads
240
+ * @param message usually a ByteBuf straight off the socket
241
+ */
242
+ public fireChannelRead(message: unknown): Promise<void> {
243
+ return this.head.fireChannelRead(message)
244
+ }
245
+
246
+ /**
247
+ * Called once the reads from one socket chunk have all gone through
248
+ */
249
+ public fireChannelReadComplete(): Promise<void> {
250
+ return this.head.fireChannelReadComplete()
251
+ }
252
+
253
+ /**
254
+ * Lets every handler know isWritable just flipped
255
+ */
256
+ public fireChannelWritabilityChanged(): Promise<void> {
257
+ return this.head.fireChannelWritabilityChanged()
258
+ }
259
+
260
+ /**
261
+ * Sends a custom event through the whole chain
262
+ * @param event anything handlers know how to recognise
263
+ */
264
+ public fireUserEventTriggered(event: unknown): Promise<void> {
265
+ return this.head.fireUserEventTriggered(event)
266
+ }
267
+
268
+ /**
269
+ * Starts an error at the head so every handler gets a look
270
+ * @param error whatever went wrong
271
+ */
272
+ public fireExceptionCaught(error: unknown): Promise<void> {
273
+ return this.head.fireExceptionCaught(error)
274
+ }
275
+
276
+ /**
277
+ * Sends through every outbound handler without flushing
278
+ * @param message what to send
279
+ */
280
+ public write(message: unknown): Promise<void> {
281
+ return this.tail.write(message)
282
+ }
283
+
284
+ /**
285
+ * Like write but nobody gets a promise back
286
+ * @param message what to send
287
+ */
288
+ public writeSync(message: unknown): void {
289
+ this.tail.writeSync(message)
290
+ }
291
+
292
+ /**
293
+ * Fire-and-forget writeAndFlush
294
+ * @param message what to send
295
+ */
296
+ public writeAndFlushSync(message: unknown): void {
297
+ this.tail.writeSync(message)
298
+ void this.tail.flush()
299
+ }
300
+
301
+ /**
302
+ * Pushes everything written so far out to the socket
303
+ */
304
+ public flush(): Promise<void> {
305
+ return this.tail.flush()
306
+ }
307
+
308
+ /**
309
+ * Write followed by a flush, the promise follows the write
310
+ * @param message what to send
311
+ */
312
+ public writeAndFlush(message: unknown): Promise<void> {
313
+ return this.tail.writeAndFlush(message)
314
+ }
315
+
316
+ /**
317
+ * Sends a close through every outbound handler so they can tidy up first
318
+ */
319
+ public close(): Promise<void> {
320
+ return this.tail.close()
321
+ }
322
+
323
+ /**
324
+ * Error text if the name is empty or taken, or null
325
+ * @param name proposed handler name
326
+ */
327
+ private refusal(name: string): string | null {
328
+ if (name === '') return 'Handler name is empty'
329
+ if (this.contexts.has(name)) return 'Handler name is taken'
330
+
331
+ return null
332
+ }
333
+
334
+ /**
335
+ * Like contexts.get but throws when the name is missing
336
+ * @param name what the handler was added as
337
+ */
338
+ private require(name: string): HandlerContext {
339
+ const context = this.contexts.get(name)
340
+ if (context === undefined) throw new Error('Handler is not found')
341
+
342
+ return context
343
+ }
344
+
345
+ /**
346
+ * Splices a new context in and fires handlerAdded
347
+ * @param name checked for clashes first
348
+ * @param handler what to add
349
+ * @param previous the new context goes right after this one
350
+ */
351
+ private insert(
352
+ name: string,
353
+ handler: ChannelHandler,
354
+ previous: HandlerContext,
355
+ ): this {
356
+ const reason = this.refusal(name)
357
+ if (reason !== null) throw new Error(reason)
358
+
359
+ const context = new HandlerContext(this, name, handler)
360
+ const next = previous.next
361
+ context.previous = previous
362
+ context.next = next
363
+ previous.next = context
364
+ if (next !== null) next.previous = context
365
+ this.contexts.set(name, context)
366
+ this.version += 1
367
+
368
+ this.track(context, (): void | Promise<void> =>
369
+ handler.handlerAdded?.(context),
370
+ )
371
+ return this
372
+ }
373
+
374
+ /**
375
+ * Splices a context out and fires handlerRemoved
376
+ * @param context the link to drop
377
+ */
378
+ private unlink(context: HandlerContext): void {
379
+ const { previous, next } = context
380
+
381
+ if (previous !== null) previous.next = next
382
+ if (next !== null) next.previous = previous
383
+ this.contexts.delete(context.name)
384
+ this.version += 1
385
+
386
+ this.track(context, (): void | Promise<void> =>
387
+ context.handler.handlerRemoved?.(context),
388
+ )
389
+ }
390
+
391
+ /**
392
+ * Keeps the call in lifecycles until it settles so settle can wait on it
393
+ * @param context where any error gets fired from
394
+ * @param call handlerAdded or handlerRemoved, wrapped up
395
+ */
396
+ private track(
397
+ context: HandlerContext,
398
+ call: () => void | Promise<void>,
399
+ ): void {
400
+ const run = async (): Promise<void> => {
401
+ try {
402
+ await call()
403
+ } catch (error) {
404
+ await context.fireExceptionCaught(error)
405
+ }
406
+ }
407
+
408
+ const promise = run()
409
+ this.lifecycles.add(promise)
410
+ void promise.finally((): void => {
411
+ this.lifecycles.delete(promise)
412
+ })
413
+ }
414
+ }
@@ -0,0 +1,45 @@
1
+ import type { InboundHandler } from '../../handler/index.ts'
2
+ import type { Logger } from '../../../logger/index.ts'
3
+ import type { HandlerContext } from '../../context/index.ts'
4
+
5
+ /**
6
+ * Last stop for inbound events that nobody else dealt with
7
+ * @class
8
+ */
9
+ export class TailHandler implements InboundHandler {
10
+ /**
11
+ * Where unhandled errors and dropped messages get logged
12
+ */
13
+ private readonly logger: Logger
14
+
15
+ /**
16
+ * Usually given the pipeline's own logger
17
+ * @param logger where leftovers get reported
18
+ */
19
+ public constructor(logger: Logger) {
20
+ this.logger = logger
21
+ }
22
+
23
+ /**
24
+ * Drops the message with a debug line
25
+ * @param context used for the channel id in the log
26
+ */
27
+ public channelRead(context: HandlerContext): void {
28
+ this.logger.debug(
29
+ { channel: context.channel.id },
30
+ 'Inbound message was discarded',
31
+ )
32
+ }
33
+
34
+ /**
35
+ * Warns about an error that went all the way through unhandled
36
+ * @param context used for the channel id in the log
37
+ * @param error whatever was thrown
38
+ */
39
+ public exceptionCaught(context: HandlerContext, error: unknown): void {
40
+ this.logger.warn(
41
+ { err: error, channel: context.channel.id },
42
+ 'Error was not handled',
43
+ )
44
+ }
45
+ }
@@ -0,0 +1,120 @@
1
+ import { resolved } from '../../resolved/index.ts'
2
+
3
+ /**
4
+ * Keeps a flush from overtaking writes that async handlers are still holding
5
+ * @class
6
+ */
7
+ export class WriteTracker {
8
+ /**
9
+ * Call stack of contexts currently inside a write
10
+ */
11
+ private readonly owners: object[]
12
+
13
+ /**
14
+ * Parallel to owners, flips to true once that call passes its write on
15
+ */
16
+ private readonly forwards: boolean[]
17
+
18
+ /**
19
+ * How many calls are on the stack
20
+ */
21
+ private depth: number
22
+
23
+ /**
24
+ * Writes still stuck inside a handler
25
+ */
26
+ private pending: number
27
+
28
+ /**
29
+ * Set when a flush arrived early, so late writes flush as they land
30
+ */
31
+ private carried: boolean
32
+
33
+ /**
34
+ * Starts out with nothing in flight
35
+ */
36
+ public constructor() {
37
+ this.owners = []
38
+ this.forwards = []
39
+ this.depth = 0
40
+ this.pending = 0
41
+ this.carried = false
42
+ }
43
+
44
+ /**
45
+ * True while an early flush is still owed to late writes
46
+ */
47
+ public get flushCarried(): boolean {
48
+ return this.carried
49
+ }
50
+
51
+ /**
52
+ * Pushes a call onto the stack and hands back its depth
53
+ * @param owner context whose write is about to run
54
+ */
55
+ public begin(owner: object): number {
56
+ const depth = this.depth
57
+
58
+ this.owners[depth] = owner
59
+ this.forwards[depth] = false
60
+ this.depth = depth + 1
61
+ this.pending += 1
62
+ return depth
63
+ }
64
+
65
+ /**
66
+ * Unwinds the stack and, if the write wasn't forwarded, waits for it to settle
67
+ * @param depth what begin gave back
68
+ * @param result promise the handler returned
69
+ */
70
+ public returned(depth: number, result: Promise<void>): void {
71
+ const forwarded = this.forwards[depth] === true
72
+
73
+ this.depth = depth
74
+ if (forwarded) return
75
+ if (result === resolved) {
76
+ this.finish()
77
+ return
78
+ }
79
+
80
+ void result.then(
81
+ (): void => {
82
+ this.finish()
83
+ },
84
+ (): void => {
85
+ this.finish()
86
+ },
87
+ )
88
+ }
89
+
90
+ /**
91
+ * Only counts when owner is the call on top of the stack, and only once
92
+ * @param owner context passing its write along
93
+ */
94
+ public forwarded(owner: object): void {
95
+ const top = this.depth - 1
96
+
97
+ if (top < 0 || this.owners[top] !== owner || this.forwards[top] === true) {
98
+ return
99
+ }
100
+
101
+ this.forwards[top] = true
102
+ this.finish()
103
+ }
104
+
105
+ /**
106
+ * Remembers the flush if any writes are still stuck in handlers
107
+ */
108
+ public requestFlush(): void {
109
+ if (this.pending > 0) this.carried = true
110
+ }
111
+
112
+ /**
113
+ * Drops the pending count and clears the carried flush at zero
114
+ */
115
+ private finish(): void {
116
+ this.pending -= 1
117
+
118
+ if (this.pending === 0) this.carried = false
119
+ }
120
+ }