@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,203 @@
1
+ import { pending, resolved } from '../resolved/index.ts'
2
+
3
+ /**
4
+ * Lets the owner react when work starts piling up and when it clears
5
+ */
6
+ export type QueueEvents = {
7
+ /**
8
+ * Fires the first time something has to wait its turn
9
+ */
10
+ readonly onBusy: () => void
11
+
12
+ /**
13
+ * Fires once the backlog is empty again after onBusy
14
+ */
15
+ readonly onIdle: () => void
16
+ }
17
+
18
+ /**
19
+ * Something stuck in the backlog waiting its turn
20
+ */
21
+ type Job = {
22
+ /**
23
+ * Function to call when it's this job's turn
24
+ */
25
+ readonly task: (value: unknown) => void | Promise<void>
26
+
27
+ /**
28
+ * Argument for the task, saves allocating a closure
29
+ */
30
+ readonly value: unknown
31
+
32
+ /**
33
+ * Settled when the task finishes, handed back to whoever queued it
34
+ */
35
+ readonly result: PromiseWithResolvers<undefined>
36
+ }
37
+
38
+ /**
39
+ * Serial task runner that skips the queue entirely when nothing's running
40
+ * @class
41
+ */
42
+ export class EventQueue {
43
+ /**
44
+ * Owner's busy and idle hooks, the channel uses them for backpressure
45
+ */
46
+ private readonly events: QueueEvents
47
+
48
+ /**
49
+ * Jobs waiting behind the current one, oldest first
50
+ */
51
+ private readonly backlog: Job[]
52
+
53
+ /**
54
+ * True while a task is in progress
55
+ */
56
+ private running: boolean
57
+
58
+ /**
59
+ * Set once onBusy has fired, so onIdle only fires after it
60
+ */
61
+ private busy: boolean
62
+
63
+ /**
64
+ * Starts empty and idle
65
+ * @param events told when we back up and when we clear
66
+ */
67
+ public constructor(events: QueueEvents) {
68
+ this.events = events
69
+ this.backlog = []
70
+ this.running = false
71
+ this.busy = false
72
+ }
73
+
74
+ /**
75
+ * Tasks waiting plus the one running, if any
76
+ */
77
+ public get size(): number {
78
+ return this.backlog.length + (this.running ? 1 : 0)
79
+ }
80
+
81
+ /**
82
+ * Runs synchronously if we're idle, otherwise queues it
83
+ * @param task work to do in order
84
+ */
85
+ public run(task: () => void | Promise<void>): Promise<void> {
86
+ return this.runWith(task, undefined)
87
+ }
88
+
89
+ /**
90
+ * Same as run but passes value through, so callers can avoid a closure
91
+ * @param task work to do in order
92
+ * @param value handed to the task when it runs
93
+ */
94
+ public runWith<T>(
95
+ task: (value: T) => void | Promise<void>,
96
+ value: T,
97
+ ): Promise<void> {
98
+ if (this.running) {
99
+ return this.defer(task as (value: unknown) => void | Promise<void>, value)
100
+ }
101
+
102
+ this.running = true
103
+
104
+ let result: void | Promise<void>
105
+ try {
106
+ result = task(value)
107
+ } catch (error) {
108
+ this.drain()
109
+ return Promise.reject(
110
+ error instanceof Error
111
+ ? error
112
+ : new Error('Task failed', { cause: error }),
113
+ )
114
+ }
115
+
116
+ if (result === undefined || result === resolved) {
117
+ if (this.backlog.length === 0 && !this.busy) this.running = false
118
+ else this.drain()
119
+ return resolved
120
+ }
121
+
122
+ return result.finally((): void => {
123
+ this.drain()
124
+ })
125
+ }
126
+
127
+ /**
128
+ * Null if done synchronously, the error if it threw, otherwise its promise
129
+ * @param task what to call
130
+ * @param value its argument
131
+ */
132
+ private static invoke<T>(
133
+ task: (value: T) => void | Promise<void>,
134
+ value: T,
135
+ ): Promise<void> | Error | null {
136
+ let result: void | Promise<void>
137
+ try {
138
+ result = task(value)
139
+ } catch (error) {
140
+ return error instanceof Error
141
+ ? error
142
+ : new Error('Task failed', { cause: error })
143
+ }
144
+
145
+ return pending(result)
146
+ }
147
+
148
+ /**
149
+ * Adds to the backlog and fires onBusy if this is the first one waiting
150
+ * @param task what to call later
151
+ * @param value its argument
152
+ */
153
+ private defer(
154
+ task: (value: unknown) => void | Promise<void>,
155
+ value: unknown,
156
+ ): Promise<void> {
157
+ const job: Job = { task, value, result: Promise.withResolvers<undefined>() }
158
+
159
+ this.backlog.push(job)
160
+ if (!this.busy) {
161
+ this.busy = true
162
+ this.events.onBusy()
163
+ }
164
+
165
+ return job.result.promise
166
+ }
167
+
168
+ /**
169
+ * Works through the backlog synchronously, picking back up after any async job
170
+ */
171
+ private drain(): void {
172
+ for (let job = this.backlog.shift(); job !== undefined;) {
173
+ const current = job
174
+ const outcome = EventQueue.invoke(current.task, current.value)
175
+
176
+ if (outcome === null) {
177
+ current.result.resolve(undefined)
178
+ } else if (outcome instanceof Error) {
179
+ current.result.reject(outcome)
180
+ } else {
181
+ outcome.then(
182
+ (): void => {
183
+ current.result.resolve(undefined)
184
+ this.drain()
185
+ },
186
+ (error: unknown): void => {
187
+ current.result.reject(error)
188
+ this.drain()
189
+ },
190
+ )
191
+ return
192
+ }
193
+
194
+ job = this.backlog.shift()
195
+ }
196
+
197
+ this.running = false
198
+ if (this.busy) {
199
+ this.busy = false
200
+ this.events.onIdle()
201
+ }
202
+ }
203
+ }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Shared already-settled promise for work that finished synchronously
3
+ */
4
+ export const resolved: Promise<void> = Promise.resolve()
5
+
6
+ /**
7
+ * Null if there's nothing left to await, otherwise the promise itself
8
+ * @param result what a handler returned
9
+ */
10
+ export const pending = (result: void | Promise<void>): Promise<void> | null =>
11
+ result === undefined || result === resolved ? null : result
12
+
13
+ /**
14
+ * Promises we've already attached a catch to
15
+ */
16
+ const guarded = new WeakSet<Promise<void>>()
17
+
18
+ /**
19
+ * Last promise we protected, checked first to skip the WeakSet lookup
20
+ */
21
+ const recent: { promise: Promise<void> | null } = { promise: resolved }
22
+
23
+ /**
24
+ * Stops a fire-and-forget promise from raising an unhandled rejection
25
+ * @param promise one the caller might never await
26
+ */
27
+ export const protect = (promise: Promise<void>): Promise<void> => {
28
+ if (promise === recent.promise || guarded.has(promise)) return promise
29
+
30
+ recent.promise = promise
31
+ guarded.add(promise)
32
+ void promise.catch((): undefined => undefined)
33
+ return promise
34
+ }
@@ -0,0 +1,164 @@
1
+ import type { SocketData } from '../../bootstrap/dispatcher/index.ts'
2
+ import type { Channel } from '../index.ts'
3
+ import { ShutdownEvent } from '../shutdown/index.ts'
4
+ import type { SocketListener } from 'bun'
5
+
6
+ /**
7
+ * A TCP host and port, or a Unix socket path
8
+ */
9
+ export type ServerAddress =
10
+ | {
11
+ /**
12
+ * Interface we're listening on
13
+ */
14
+ readonly hostname: string
15
+ /**
16
+ * Actual port, useful when you asked for 0
17
+ */
18
+ readonly port: number
19
+ }
20
+ | {
21
+ /**
22
+ * Filesystem path of the Unix socket
23
+ */
24
+ readonly unix: string
25
+ }
26
+
27
+ /**
28
+ * Handle on a running server and every connection it has open
29
+ * @class
30
+ */
31
+ export class ServerChannel {
32
+ /**
33
+ * Resolves after close has finished shutting every child down
34
+ */
35
+ public readonly closed: Promise<void>
36
+
37
+ /**
38
+ * Bun's listener, stopped on close
39
+ */
40
+ private readonly listener: SocketListener<SocketData>
41
+
42
+ /**
43
+ * Address as it was when we bound
44
+ */
45
+ private readonly bound: ServerAddress
46
+
47
+ /**
48
+ * Live set shared with the dispatcher, so it changes as clients come and go
49
+ */
50
+ private readonly children: Set<Channel>
51
+
52
+ /**
53
+ * Resolver behind closed
54
+ */
55
+ private readonly closing: PromiseWithResolvers<undefined>
56
+
57
+ /**
58
+ * Flipped by the first close call
59
+ */
60
+ private stopped: boolean
61
+
62
+ /**
63
+ * Built by ServerBootstrap once Bun is listening
64
+ * @param listener what Bun's listen gave back
65
+ * @param address where it ended up bound
66
+ * @param children live set the dispatcher keeps up to date
67
+ */
68
+ public constructor(
69
+ listener: SocketListener<SocketData>,
70
+ address: ServerAddress,
71
+ children: Set<Channel>,
72
+ ) {
73
+ this.listener = listener
74
+ this.bound = address
75
+ this.children = children
76
+ this.closing = Promise.withResolvers<undefined>()
77
+ this.closed = this.closing.promise
78
+ this.stopped = false
79
+ }
80
+
81
+ /**
82
+ * Either form, check for unix before reading host and port
83
+ */
84
+ public get address(): ServerAddress {
85
+ return this.bound
86
+ }
87
+
88
+ /**
89
+ * Throws on a Unix socket server
90
+ */
91
+ public get hostname(): string {
92
+ if ('unix' in this.bound) throw new Error('Server has no hostname')
93
+
94
+ return this.bound.hostname
95
+ }
96
+
97
+ /**
98
+ * Throws on a Unix socket server
99
+ */
100
+ public get port(): number {
101
+ if ('unix' in this.bound) throw new Error('Server has no port')
102
+
103
+ return this.bound.port
104
+ }
105
+
106
+ /**
107
+ * False as soon as close starts
108
+ */
109
+ public get isOpen(): boolean {
110
+ return !this.stopped
111
+ }
112
+
113
+ /**
114
+ * Snapshot of current connections, safe to iterate while they close
115
+ */
116
+ public get channels(): readonly Channel[] {
117
+ return [...this.children]
118
+ }
119
+
120
+ /**
121
+ * Stops accepting, tells every channel, waits for them to close, then closes the rest
122
+ * @param timeout how long channels get in milliseconds
123
+ */
124
+ public async shutdownGracefully(timeout = 10000): Promise<void> {
125
+ if (this.stopped) return this.closed
126
+ this.stopped = true
127
+
128
+ this.listener.stop(false)
129
+ const channels = [...this.children]
130
+ const event = new ShutdownEvent(Date.now() + timeout)
131
+ for (const channel of channels) {
132
+ void channel.pipeline.fireUserEventTriggered(event)
133
+ }
134
+
135
+ await Promise.race([
136
+ Promise.allSettled(
137
+ channels.map((channel: Channel): Promise<void> => channel.closed),
138
+ ),
139
+ Bun.sleep(timeout),
140
+ ])
141
+ await Promise.allSettled(
142
+ [...this.children].map((channel: Channel): Promise<void> =>
143
+ channel.close().then((): Promise<void> => channel.closed),
144
+ ),
145
+ )
146
+ this.closing.resolve(undefined)
147
+ }
148
+
149
+ /**
150
+ * Stops listening and waits for every connection to close, safe to call twice
151
+ */
152
+ public async close(): Promise<void> {
153
+ if (this.stopped) return this.closed
154
+ this.stopped = true
155
+
156
+ this.listener.stop(false)
157
+ await Promise.allSettled(
158
+ [...this.children].map((channel: Channel): Promise<void> =>
159
+ channel.close(),
160
+ ),
161
+ )
162
+ this.closing.resolve(undefined)
163
+ }
164
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Fired on every channel when its server starts a graceful shutdown
3
+ * @class
4
+ */
5
+ export class ShutdownEvent {
6
+ /**
7
+ * When open channels get closed, in Date.now milliseconds
8
+ */
9
+ public readonly deadline: number
10
+
11
+ /**
12
+ * Sets the deadline
13
+ * @param deadline when open channels get closed
14
+ */
15
+ public constructor(deadline: number) {
16
+ this.deadline = deadline
17
+ }
18
+
19
+ /**
20
+ * Milliseconds left before the deadline
21
+ */
22
+ public get remaining(): number {
23
+ return Math.max(0, this.deadline - Date.now())
24
+ }
25
+ }
@@ -0,0 +1,38 @@
1
+ import { InboundHandlerAdapter } from '../handler/index.ts'
2
+ import type { HandlerContext } from '../context/index.ts'
3
+
4
+ /**
5
+ * Base for handlers that only care about one message type
6
+ * @class
7
+ */
8
+ export abstract class SimpleInboundHandler<I> extends InboundHandlerAdapter {
9
+ /**
10
+ * Routes matching messages to messageReceived and forwards anything else
11
+ * @param context where non-matching messages get forwarded
12
+ * @param message whatever came in
13
+ */
14
+ public override channelRead(
15
+ context: HandlerContext,
16
+ message: unknown,
17
+ ): void | Promise<void> {
18
+ if (!this.accepts(message)) return context.fireChannelRead(message)
19
+
20
+ return this.messageReceived(context, message)
21
+ }
22
+
23
+ /**
24
+ * Type guard that decides what this handler picks up
25
+ * @param message anything from the previous handler
26
+ */
27
+ protected abstract accepts(message: unknown): message is I
28
+
29
+ /**
30
+ * Where subclasses do their actual work
31
+ * @param context this handler's spot in the pipeline
32
+ * @param message already narrowed to the type we want
33
+ */
34
+ protected abstract messageReceived(
35
+ context: HandlerContext,
36
+ message: I,
37
+ ): void | Promise<void>
38
+ }
@@ -0,0 +1,74 @@
1
+ import type { PacketAddress } from '../../datagram/packet/index.ts'
2
+
3
+ export { SocketTransport } from './socket/index.ts'
4
+
5
+ /**
6
+ * One packet waiting to go out
7
+ */
8
+ export type OutgoingDatagram = {
9
+ /**
10
+ * The bytes
11
+ */
12
+ readonly bytes: Uint8Array
13
+
14
+ /**
15
+ * Where it goes, or null for the connected peer
16
+ */
17
+ readonly recipient: PacketAddress | null
18
+ }
19
+
20
+ /**
21
+ * What a channel needs from the underlying TCP or UDP socket
22
+ */
23
+ export type Transport = {
24
+ /**
25
+ * True for UDP, where each write is its own packet
26
+ */
27
+ readonly datagram: boolean
28
+
29
+ /**
30
+ * Peer IP as the socket reports it
31
+ */
32
+ readonly remoteAddress: string
33
+
34
+ /**
35
+ * Peer port, paired with remoteAddress in logs and replies
36
+ */
37
+ readonly remotePort: number
38
+
39
+ /**
40
+ * Returns how many bytes actually went out, which can be fewer than given
41
+ * @param bytes what to send
42
+ * @param recipient UDP target, or null for the connected peer
43
+ */
44
+ write(bytes: Uint8Array, recipient: PacketAddress | null): number
45
+
46
+ /**
47
+ * Sends part of an array without making a view of it
48
+ * @param bytes the array
49
+ * @param offset where to start
50
+ * @param length how many bytes
51
+ */
52
+ writeRange?(bytes: Uint8Array, offset: number, length: number): number
53
+
54
+ /**
55
+ * Sends many packets in one go, returns how many went out or -1 when closed
56
+ * @param packets what to send, in order
57
+ */
58
+ writeBatch?(packets: readonly OutgoingDatagram[]): number
59
+
60
+ /**
61
+ * Shuts the socket down
62
+ */
63
+ end(): void
64
+
65
+ /**
66
+ * Used for backpressure when the pipeline can't keep up
67
+ */
68
+ pause(): void
69
+
70
+ /**
71
+ * Undoes pause
72
+ */
73
+ resume(): void
74
+ }
@@ -0,0 +1,80 @@
1
+ import type { Transport } from '../index.ts'
2
+ import type { Socket } from 'bun'
3
+
4
+ /**
5
+ * Thin wrapper that lets a Bun TCP or Unix socket act as a transport
6
+ * @class
7
+ */
8
+ export class SocketTransport implements Transport {
9
+ /**
10
+ * Always false, streams have no packet boundaries
11
+ */
12
+ public readonly datagram: boolean
13
+
14
+ /**
15
+ * The Bun socket everything is delegated to
16
+ */
17
+ private readonly socket: Socket<unknown>
18
+
19
+ /**
20
+ * Wraps a socket Bun has already opened
21
+ * @param socket from Bun's open or connect callback
22
+ */
23
+ public constructor(socket: Socket<unknown>) {
24
+ this.socket = socket
25
+ this.datagram = false
26
+ }
27
+
28
+ /**
29
+ * Straight from Bun, read on every access
30
+ */
31
+ public get remoteAddress(): string {
32
+ return this.socket.remoteAddress
33
+ }
34
+
35
+ /**
36
+ * Straight from Bun, read on every access
37
+ */
38
+ public get remotePort(): number {
39
+ return this.socket.remotePort
40
+ }
41
+
42
+ /**
43
+ * Bun may take only part of it, the return value says how much
44
+ * @param bytes what to send
45
+ */
46
+ public write(bytes: Uint8Array): number {
47
+ return this.socket.write(bytes)
48
+ }
49
+
50
+ /**
51
+ * Sends part of an array, Bun takes the offset and length as they are
52
+ * @param bytes the array
53
+ * @param offset where to start
54
+ * @param length how many bytes
55
+ */
56
+ public writeRange(bytes: Uint8Array, offset: number, length: number): number {
57
+ return this.socket.write(bytes, offset, length)
58
+ }
59
+
60
+ /**
61
+ * Asks Bun to close the socket
62
+ */
63
+ public end(): void {
64
+ this.socket.end()
65
+ }
66
+
67
+ /**
68
+ * Stops Bun delivering data until resume
69
+ */
70
+ public pause(): void {
71
+ this.socket.pause()
72
+ }
73
+
74
+ /**
75
+ * Lets data flow again after a pause
76
+ */
77
+ public resume(): void {
78
+ this.socket.resume()
79
+ }
80
+ }