@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.
- package/LICENSE +21 -0
- package/README.md +105 -2
- package/package.json +65 -4
- package/src/bootstrap/client/index.ts +191 -0
- package/src/bootstrap/dispatcher/index.ts +204 -0
- package/src/bootstrap/index.ts +22 -0
- package/src/bootstrap/reconnect/index.ts +334 -0
- package/src/bootstrap/server/index.ts +284 -0
- package/src/buffer/bits/index.ts +2 -0
- package/src/buffer/bits/reader/index.ts +64 -0
- package/src/buffer/bits/writer/index.ts +79 -0
- package/src/buffer/index.ts +1375 -0
- package/src/buffer/pool/index.ts +46 -0
- package/src/buffer/quantizer/index.ts +101 -0
- package/src/channel/attribute/index.ts +89 -0
- package/src/channel/context/index.ts +621 -0
- package/src/channel/group/index.ts +256 -0
- package/src/channel/handler/duplex/index.ts +105 -0
- package/src/channel/handler/inbound/index.ts +78 -0
- package/src/channel/handler/index.ts +135 -0
- package/src/channel/handler/outbound/index.ts +33 -0
- package/src/channel/index.ts +619 -0
- package/src/channel/initializer/index.ts +77 -0
- package/src/channel/outbound/index.ts +611 -0
- package/src/channel/pipeline/head/index.ts +100 -0
- package/src/channel/pipeline/index.ts +414 -0
- package/src/channel/pipeline/tail/index.ts +45 -0
- package/src/channel/pipeline/tracker/index.ts +120 -0
- package/src/channel/queue/index.ts +203 -0
- package/src/channel/resolved/index.ts +34 -0
- package/src/channel/server/index.ts +164 -0
- package/src/channel/shutdown/index.ts +25 -0
- package/src/channel/simple/index.ts +38 -0
- package/src/channel/transport/index.ts +74 -0
- package/src/channel/transport/socket/index.ts +80 -0
- package/src/cluster/index.ts +360 -0
- package/src/codec/binary/index.ts +102 -0
- package/src/codec/decoder/index.ts +479 -0
- package/src/codec/delimiter/index.ts +189 -0
- package/src/codec/encoder/index.ts +48 -0
- package/src/codec/error/index.ts +33 -0
- package/src/codec/fixed/index.ts +45 -0
- package/src/codec/http/aggregator/index.ts +236 -0
- package/src/codec/http/client/index.ts +120 -0
- package/src/codec/http/decoder/index.ts +4 -0
- package/src/codec/http/decoder/object/index.ts +644 -0
- package/src/codec/http/decoder/request/index.ts +49 -0
- package/src/codec/http/decoder/response/index.ts +59 -0
- package/src/codec/http/encoder/index.ts +3 -0
- package/src/codec/http/encoder/object/index.ts +196 -0
- package/src/codec/http/encoder/request/index.ts +24 -0
- package/src/codec/http/encoder/response/index.ts +26 -0
- package/src/codec/http/headers/index.ts +287 -0
- package/src/codec/http/index.ts +33 -0
- package/src/codec/http/message/content/index.ts +36 -0
- package/src/codec/http/message/full/index.ts +10 -0
- package/src/codec/http/message/full/request/index.ts +45 -0
- package/src/codec/http/message/full/response/index.ts +43 -0
- package/src/codec/http/message/head/index.ts +79 -0
- package/src/codec/http/message/index.ts +16 -0
- package/src/codec/http/message/last/index.ts +27 -0
- package/src/codec/http/message/request/index.ts +39 -0
- package/src/codec/http/message/response/index.ts +31 -0
- package/src/codec/http/method/index.ts +101 -0
- package/src/codec/http/server/index.ts +81 -0
- package/src/codec/http/status/index.ts +170 -0
- package/src/codec/http/version/index.ts +70 -0
- package/src/codec/index.ts +83 -0
- package/src/codec/length/index.ts +330 -0
- package/src/codec/line/index.ts +45 -0
- package/src/codec/message/decoder/index.ts +84 -0
- package/src/codec/message/encoder/index.ts +56 -0
- package/src/codec/message/index.ts +2 -0
- package/src/codec/msgpack/index.ts +51 -0
- package/src/codec/prepender/index.ts +296 -0
- package/src/codec/protobuf/index.ts +57 -0
- package/src/codec/string/decoder/index.ts +47 -0
- package/src/codec/string/encoder/index.ts +26 -0
- package/src/codec/string/index.ts +2 -0
- package/src/codec/websocket/client/index.ts +235 -0
- package/src/codec/websocket/decoder/index.ts +371 -0
- package/src/codec/websocket/encoder/index.ts +170 -0
- package/src/codec/websocket/error/index.ts +42 -0
- package/src/codec/websocket/frame/base/index.ts +55 -0
- package/src/codec/websocket/frame/binary/index.ts +24 -0
- package/src/codec/websocket/frame/close/index.ts +82 -0
- package/src/codec/websocket/frame/continuation/index.ts +31 -0
- package/src/codec/websocket/frame/index.ts +10 -0
- package/src/codec/websocket/frame/opcode/index.ts +35 -0
- package/src/codec/websocket/frame/ping/index.ts +24 -0
- package/src/codec/websocket/frame/pong/index.ts +24 -0
- package/src/codec/websocket/frame/text/index.ts +31 -0
- package/src/codec/websocket/handshake/index.ts +38 -0
- package/src/codec/websocket/index.ts +25 -0
- package/src/codec/websocket/key/index.ts +41 -0
- package/src/codec/websocket/protocol/index.ts +147 -0
- package/src/codec/websocket/server/index.ts +233 -0
- package/src/codec/websocket/status/index.ts +97 -0
- package/src/codec/websocket/upgrade/index.ts +116 -0
- package/src/datagram/bootstrap/index.ts +269 -0
- package/src/datagram/channel/index.ts +103 -0
- package/src/datagram/index.ts +10 -0
- package/src/datagram/packet/index.ts +72 -0
- package/src/datagram/transport/index.ts +239 -0
- package/src/handler/flush/index.ts +187 -0
- package/src/handler/idle/index.ts +295 -0
- package/src/handler/index.ts +22 -0
- package/src/handler/logging/index.ts +195 -0
- package/src/handler/metrics/index.ts +300 -0
- package/src/handler/offload/index.ts +141 -0
- package/src/handler/timeout/error/index.ts +29 -0
- package/src/handler/timeout/index.ts +3 -0
- package/src/handler/timeout/read/index.ts +44 -0
- package/src/handler/timeout/write/index.ts +89 -0
- package/src/handler/traffic/index.ts +259 -0
- package/src/index.ts +258 -0
- package/src/logger/index.ts +47 -0
- package/src/reliable/bootstrap/index.ts +154 -0
- package/src/reliable/cipher/index.ts +227 -0
- package/src/reliable/cookie/index.ts +78 -0
- package/src/reliable/handler/index.ts +1202 -0
- package/src/reliable/handshake/index.ts +144 -0
- package/src/reliable/index.ts +38 -0
- package/src/reliable/lane/index.ts +420 -0
- package/src/reliable/message/index.ts +102 -0
- package/src/reliable/packet/index.ts +117 -0
- package/src/reliable/peer/index.ts +929 -0
- package/src/reliable/registry/index.ts +107 -0
- package/src/serve/bootstrap/index.ts +606 -0
- package/src/serve/channel/index.ts +246 -0
- package/src/serve/index.ts +17 -0
- package/src/serve/outbox/index.ts +292 -0
- package/src/serve/transport/index.ts +96 -0
- package/src/serve/writer/index.ts +119 -0
- package/src/shard/envelope/index.ts +44 -0
- package/src/shard/gateway/index.ts +119 -0
- package/src/shard/index.ts +11 -0
- package/src/shard/link/index.ts +743 -0
- package/src/shard/map/index.ts +91 -0
- package/src/worker/group/index.ts +175 -0
- package/src/worker/index.ts +10 -0
- package/src/worker/pool/index.ts +235 -0
- package/src/worker/service/index.ts +55 -0
|
@@ -0,0 +1,743 @@
|
|
|
1
|
+
import { rmSync } from 'node:fs'
|
|
2
|
+
import { tmpdir } from 'node:os'
|
|
3
|
+
import { join } from 'node:path'
|
|
4
|
+
|
|
5
|
+
import { deserialize, serialize } from 'bun:jsc'
|
|
6
|
+
|
|
7
|
+
import { Bootstrap } from '../../bootstrap/client/index.ts'
|
|
8
|
+
import { ServerBootstrap } from '../../bootstrap/server/index.ts'
|
|
9
|
+
import type { ByteBuf } from '../../buffer/index.ts'
|
|
10
|
+
import type { Channel } from '../../channel/index.ts'
|
|
11
|
+
import type { HandlerContext } from '../../channel/context/index.ts'
|
|
12
|
+
import { InboundHandlerAdapter } from '../../channel/handler/inbound/index.ts'
|
|
13
|
+
import type { ServerChannel } from '../../channel/server/index.ts'
|
|
14
|
+
import { Cluster } from '../../cluster/index.ts'
|
|
15
|
+
import { LengthFieldBasedFrameDecoder } from '../../codec/length/index.ts'
|
|
16
|
+
import { LengthFieldPrepender } from '../../codec/prepender/index.ts'
|
|
17
|
+
import type { ShardMessage } from '../envelope/index.ts'
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Called with a message from another shard
|
|
21
|
+
*/
|
|
22
|
+
export type ShardListener = (data: unknown, from: number) => void
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Answers a request from another shard
|
|
26
|
+
*/
|
|
27
|
+
export type ShardResponder = (data: unknown, from: number) => unknown
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Where a shard listens for other shards, over TCP or a Unix socket
|
|
31
|
+
*/
|
|
32
|
+
export type ShardPeer =
|
|
33
|
+
| {
|
|
34
|
+
/**
|
|
35
|
+
* Host name or IP
|
|
36
|
+
*/
|
|
37
|
+
readonly hostname: string
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Port
|
|
41
|
+
*/
|
|
42
|
+
readonly port: number
|
|
43
|
+
}
|
|
44
|
+
| {
|
|
45
|
+
/**
|
|
46
|
+
* Socket path
|
|
47
|
+
*/
|
|
48
|
+
readonly unix: string
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Settings for ShardLink
|
|
53
|
+
*/
|
|
54
|
+
export type ShardLinkOptions = {
|
|
55
|
+
/**
|
|
56
|
+
* This shard, the cluster worker id by default
|
|
57
|
+
*/
|
|
58
|
+
readonly id?: number
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Every shard's address by id, Unix sockets for the local cluster by default
|
|
62
|
+
*/
|
|
63
|
+
readonly peers?: readonly ShardPeer[]
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* How long a request waits for its reply in milliseconds, 5000 by default
|
|
67
|
+
*/
|
|
68
|
+
readonly timeout?: number
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* How long a handed off player waits to be claimed in milliseconds, 30000 by default
|
|
72
|
+
*/
|
|
73
|
+
readonly handoffTimeout?: number
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Biggest message in bytes, 16 MiB by default
|
|
77
|
+
*/
|
|
78
|
+
readonly maxMessageSize?: number
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* A request waiting for its reply
|
|
83
|
+
*/
|
|
84
|
+
type Waiting = {
|
|
85
|
+
/**
|
|
86
|
+
* Settles the request
|
|
87
|
+
*/
|
|
88
|
+
readonly resolvers: PromiseWithResolvers<unknown>
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Shard it went to
|
|
92
|
+
*/
|
|
93
|
+
readonly shard: number
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Fails it when the reply is late
|
|
97
|
+
*/
|
|
98
|
+
readonly timer: Timer
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* A handed off player waiting to be claimed
|
|
103
|
+
*/
|
|
104
|
+
type Arrival = {
|
|
105
|
+
/**
|
|
106
|
+
* What the old shard sent over
|
|
107
|
+
*/
|
|
108
|
+
readonly state: unknown
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Drops it when nobody claims it
|
|
112
|
+
*/
|
|
113
|
+
readonly timer: Timer
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* A connection to another shard, or one being made
|
|
118
|
+
*/
|
|
119
|
+
type Peer = {
|
|
120
|
+
/**
|
|
121
|
+
* The channel once connected
|
|
122
|
+
*/
|
|
123
|
+
channel: Channel | null
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Messages waiting to go out together
|
|
127
|
+
*/
|
|
128
|
+
queue: ShardMessage[]
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Passes frames from other shards to the link
|
|
133
|
+
* @class
|
|
134
|
+
*/
|
|
135
|
+
class ShardReceiver extends InboundHandlerAdapter<ByteBuf> {
|
|
136
|
+
/**
|
|
137
|
+
* The link
|
|
138
|
+
*/
|
|
139
|
+
private readonly link: ShardLink
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Remembers the link
|
|
143
|
+
* @param link where messages go
|
|
144
|
+
*/
|
|
145
|
+
public constructor(link: ShardLink) {
|
|
146
|
+
super()
|
|
147
|
+
|
|
148
|
+
this.link = link
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Decodes a message and hands it over
|
|
153
|
+
* @param context unused
|
|
154
|
+
* @param frame one message
|
|
155
|
+
*/
|
|
156
|
+
public override channelRead(context: HandlerContext, frame: ByteBuf): void {
|
|
157
|
+
const messages = deserialize(frame.toUint8Array()) as ShardMessage[]
|
|
158
|
+
for (const message of messages) this.link.deliver(message)
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Sends messages, requests and players between shards over direct connections
|
|
164
|
+
* @class
|
|
165
|
+
*/
|
|
166
|
+
export class ShardLink {
|
|
167
|
+
/**
|
|
168
|
+
* Topic used for handoffs
|
|
169
|
+
*/
|
|
170
|
+
public static readonly handoffTopic: string = 'netify:handoff'
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* This shard
|
|
174
|
+
*/
|
|
175
|
+
public readonly id: number
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* Number of shards
|
|
179
|
+
*/
|
|
180
|
+
public readonly count: number
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* Every shard's address
|
|
184
|
+
*/
|
|
185
|
+
private readonly peers: readonly ShardPeer[]
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Request timeout in milliseconds
|
|
189
|
+
*/
|
|
190
|
+
private readonly timeout: number
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* Handoff timeout in milliseconds
|
|
194
|
+
*/
|
|
195
|
+
private readonly handoffTimeout: number
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* Biggest message in bytes
|
|
199
|
+
*/
|
|
200
|
+
private readonly maxMessageSize: number
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* Listeners by topic
|
|
204
|
+
*/
|
|
205
|
+
private readonly listeners: Map<string, ShardListener>
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Responders by topic
|
|
209
|
+
*/
|
|
210
|
+
private readonly responders: Map<string, ShardResponder>
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* Requests waiting for replies by id
|
|
214
|
+
*/
|
|
215
|
+
private readonly waiting: Map<number, Waiting>
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* Handed off players by token
|
|
219
|
+
*/
|
|
220
|
+
private readonly arrivals: Map<string, Arrival>
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* Outgoing connections by shard
|
|
224
|
+
*/
|
|
225
|
+
private readonly connections: Map<number, Peer>
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* Connections with messages waiting to go out
|
|
229
|
+
*/
|
|
230
|
+
private readonly dirty: Set<Peer>
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* Bound once for the flush microtask
|
|
234
|
+
*/
|
|
235
|
+
private readonly flusher: () => void
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* Where other shards connect, null for a lone shard
|
|
239
|
+
*/
|
|
240
|
+
private server: ServerChannel | null
|
|
241
|
+
|
|
242
|
+
/**
|
|
243
|
+
* Last request id used
|
|
244
|
+
*/
|
|
245
|
+
private nextId: number
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* Set by close
|
|
249
|
+
*/
|
|
250
|
+
private closed: boolean
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* Sets up a link, use open to start listening
|
|
254
|
+
* @param options id, peers and timeouts
|
|
255
|
+
*/
|
|
256
|
+
private constructor(options: ShardLinkOptions) {
|
|
257
|
+
this.id = options.id ?? Cluster.workerId ?? 0
|
|
258
|
+
this.peers = options.peers ?? ShardLink.localPeers()
|
|
259
|
+
this.count = Math.max(1, this.peers.length)
|
|
260
|
+
this.timeout = options.timeout ?? 5000
|
|
261
|
+
this.handoffTimeout = options.handoffTimeout ?? 30000
|
|
262
|
+
this.maxMessageSize = options.maxMessageSize ?? 16 * 1024 * 1024
|
|
263
|
+
this.listeners = new Map<string, ShardListener>()
|
|
264
|
+
this.responders = new Map<string, ShardResponder>()
|
|
265
|
+
this.waiting = new Map<number, Waiting>()
|
|
266
|
+
this.arrivals = new Map<string, Arrival>()
|
|
267
|
+
this.connections = new Map<number, Peer>()
|
|
268
|
+
this.dirty = new Set<Peer>()
|
|
269
|
+
this.server = null
|
|
270
|
+
this.nextId = 0
|
|
271
|
+
this.closed = false
|
|
272
|
+
this.flusher = (): void => {
|
|
273
|
+
for (const peer of this.dirty) this.drain(peer)
|
|
274
|
+
this.dirty.clear()
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
this.responders.set(ShardLink.handoffTopic, (state: unknown): string =>
|
|
278
|
+
this.arrive(state),
|
|
279
|
+
)
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* Starts listening for other shards
|
|
284
|
+
* @param options id, peers and timeouts
|
|
285
|
+
*/
|
|
286
|
+
public static async open(options: ShardLinkOptions = {}): Promise<ShardLink> {
|
|
287
|
+
const link = new ShardLink(options)
|
|
288
|
+
const reason = link.refusal()
|
|
289
|
+
if (reason !== null) throw new RangeError(reason)
|
|
290
|
+
|
|
291
|
+
await link.listen()
|
|
292
|
+
return link
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/**
|
|
296
|
+
* Unix socket paths for every worker in this cluster, empty outside one
|
|
297
|
+
*/
|
|
298
|
+
private static localPeers(): ShardPeer[] {
|
|
299
|
+
const cluster = Cluster.clusterId
|
|
300
|
+
const count = Cluster.workerCount
|
|
301
|
+
if (cluster === null || count === null) return []
|
|
302
|
+
|
|
303
|
+
return Array.from(
|
|
304
|
+
{ length: count },
|
|
305
|
+
(_: unknown, index: number): ShardPeer => ({
|
|
306
|
+
unix: join(tmpdir(), `netify-${cluster}-${String(index)}.sock`),
|
|
307
|
+
}),
|
|
308
|
+
)
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/**
|
|
312
|
+
* Listens on a topic, replacing any listener before it
|
|
313
|
+
* @param topic the topic
|
|
314
|
+
* @param listener gets the data and the sending shard
|
|
315
|
+
*/
|
|
316
|
+
public on(topic: string, listener: ShardListener): this {
|
|
317
|
+
this.listeners.set(topic, listener)
|
|
318
|
+
return this
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/**
|
|
322
|
+
* Stops listening on a topic
|
|
323
|
+
* @param topic the topic
|
|
324
|
+
*/
|
|
325
|
+
public off(topic: string): this {
|
|
326
|
+
this.listeners.delete(topic)
|
|
327
|
+
return this
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/**
|
|
331
|
+
* Answers requests on a topic, replacing any responder before it
|
|
332
|
+
* @param topic the topic
|
|
333
|
+
* @param responder returns the reply or a promise of it
|
|
334
|
+
*/
|
|
335
|
+
public handle(topic: string, responder: ShardResponder): this {
|
|
336
|
+
this.responders.set(topic, responder)
|
|
337
|
+
return this
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/**
|
|
341
|
+
* Sends a message to one shard
|
|
342
|
+
* @param shard the target
|
|
343
|
+
* @param topic the topic
|
|
344
|
+
* @param data anything structured clone can copy
|
|
345
|
+
*/
|
|
346
|
+
public send(shard: number, topic: string, data: unknown): void {
|
|
347
|
+
this.check(shard)
|
|
348
|
+
|
|
349
|
+
this.post({
|
|
350
|
+
kind: 'send',
|
|
351
|
+
from: this.id,
|
|
352
|
+
to: shard,
|
|
353
|
+
topic,
|
|
354
|
+
id: 0,
|
|
355
|
+
data,
|
|
356
|
+
error: null,
|
|
357
|
+
})
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/**
|
|
361
|
+
* Sends a message to every other shard
|
|
362
|
+
* @param topic the topic
|
|
363
|
+
* @param data anything structured clone can copy
|
|
364
|
+
*/
|
|
365
|
+
public broadcast(topic: string, data: unknown): void {
|
|
366
|
+
if (this.closed) throw new Error('Link is closed')
|
|
367
|
+
|
|
368
|
+
for (let shard = 0; shard < this.count; shard++) {
|
|
369
|
+
if (shard === this.id) continue
|
|
370
|
+
this.post({
|
|
371
|
+
kind: 'send',
|
|
372
|
+
from: this.id,
|
|
373
|
+
to: shard,
|
|
374
|
+
topic,
|
|
375
|
+
id: 0,
|
|
376
|
+
data,
|
|
377
|
+
error: null,
|
|
378
|
+
})
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
/**
|
|
383
|
+
* Asks one shard something and waits for its reply
|
|
384
|
+
* @param shard the target
|
|
385
|
+
* @param topic the topic
|
|
386
|
+
* @param data anything structured clone can copy
|
|
387
|
+
*/
|
|
388
|
+
public request<T>(shard: number, topic: string, data: unknown): Promise<T> {
|
|
389
|
+
this.check(shard)
|
|
390
|
+
|
|
391
|
+
const id = ++this.nextId
|
|
392
|
+
const resolvers = Promise.withResolvers<unknown>()
|
|
393
|
+
const timer = setTimeout((): void => {
|
|
394
|
+
this.settle(id, null, 'Request timed out')
|
|
395
|
+
}, this.timeout)
|
|
396
|
+
timer.unref()
|
|
397
|
+
this.waiting.set(id, { resolvers, shard, timer })
|
|
398
|
+
|
|
399
|
+
this.post({
|
|
400
|
+
kind: 'request',
|
|
401
|
+
from: this.id,
|
|
402
|
+
to: shard,
|
|
403
|
+
topic,
|
|
404
|
+
id,
|
|
405
|
+
data,
|
|
406
|
+
error: null,
|
|
407
|
+
})
|
|
408
|
+
return resolvers.promise as Promise<T>
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
/**
|
|
412
|
+
* Moves a player's state to another shard and returns the token they claim it with
|
|
413
|
+
* @param shard the new shard
|
|
414
|
+
* @param state anything structured clone can copy
|
|
415
|
+
*/
|
|
416
|
+
public handoff(shard: number, state: unknown): Promise<string> {
|
|
417
|
+
return this.request<string>(shard, ShardLink.handoffTopic, state)
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
/**
|
|
421
|
+
* Takes a handed off player's state, or null if the token is unknown or expired
|
|
422
|
+
* @param token from handoff
|
|
423
|
+
*/
|
|
424
|
+
public claim<T>(token: string): T | null {
|
|
425
|
+
const arrival = this.arrivals.get(token)
|
|
426
|
+
if (arrival === undefined) return null
|
|
427
|
+
|
|
428
|
+
clearTimeout(arrival.timer)
|
|
429
|
+
this.arrivals.delete(token)
|
|
430
|
+
return arrival.state as T
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
/**
|
|
434
|
+
* Handles a message that came in from another shard
|
|
435
|
+
* @param message what was decoded
|
|
436
|
+
*/
|
|
437
|
+
public deliver(message: ShardMessage): void {
|
|
438
|
+
if (this.closed) return
|
|
439
|
+
|
|
440
|
+
switch (message.kind) {
|
|
441
|
+
case 'send':
|
|
442
|
+
this.listeners.get(message.topic)?.(message.data, message.from)
|
|
443
|
+
return
|
|
444
|
+
case 'request':
|
|
445
|
+
void this.answer(message)
|
|
446
|
+
return
|
|
447
|
+
case 'reply':
|
|
448
|
+
this.settle(message.id, message.data, message.error)
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
/**
|
|
453
|
+
* Stops listening, drops connections and fails every waiting request
|
|
454
|
+
*/
|
|
455
|
+
public async close(): Promise<void> {
|
|
456
|
+
if (this.closed) return
|
|
457
|
+
this.closed = true
|
|
458
|
+
|
|
459
|
+
for (const id of [...this.waiting.keys()]) {
|
|
460
|
+
this.settle(id, null, 'Link is closed')
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
for (const arrival of this.arrivals.values()) clearTimeout(arrival.timer)
|
|
464
|
+
this.arrivals.clear()
|
|
465
|
+
|
|
466
|
+
const channels = [...this.connections.values()]
|
|
467
|
+
.map((peer: Peer): Channel | null => peer.channel)
|
|
468
|
+
.filter((channel: Channel | null): channel is Channel => channel !== null)
|
|
469
|
+
this.connections.clear()
|
|
470
|
+
await Promise.allSettled(
|
|
471
|
+
channels.map((channel: Channel): Promise<void> => channel.close()),
|
|
472
|
+
)
|
|
473
|
+
await this.server?.close()
|
|
474
|
+
this.removeSocket()
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
/**
|
|
478
|
+
* Checks the id, peers and message size
|
|
479
|
+
*/
|
|
480
|
+
private refusal(): string | null {
|
|
481
|
+
if (!Number.isInteger(this.id) || this.id < 0) return 'Shard is invalid'
|
|
482
|
+
if (this.peers.length > 0 && this.id >= this.peers.length) {
|
|
483
|
+
return 'Shard is invalid'
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
if (!Number.isInteger(this.maxMessageSize) || this.maxMessageSize < 1) {
|
|
487
|
+
return 'Message size is invalid'
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
return null
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
/**
|
|
494
|
+
* Binds this shard's address, nothing for a lone shard
|
|
495
|
+
*/
|
|
496
|
+
private async listen(): Promise<void> {
|
|
497
|
+
const own = this.peers[this.id]
|
|
498
|
+
if (own === undefined) return
|
|
499
|
+
|
|
500
|
+
this.removeSocket()
|
|
501
|
+
this.server = await new ServerBootstrap()
|
|
502
|
+
.childHandler((channel: Channel): void => {
|
|
503
|
+
this.frame(channel)
|
|
504
|
+
channel.pipeline.addLast<ShardReceiver>(
|
|
505
|
+
'shard',
|
|
506
|
+
new ShardReceiver(this),
|
|
507
|
+
)
|
|
508
|
+
})
|
|
509
|
+
.bind(own)
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
/**
|
|
513
|
+
* Deletes a stale Unix socket file
|
|
514
|
+
*/
|
|
515
|
+
private removeSocket(): void {
|
|
516
|
+
const own = this.peers[this.id]
|
|
517
|
+
if (own !== undefined && 'unix' in own) rmSync(own.unix, { force: true })
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
/**
|
|
521
|
+
* Adds the length framing to a pipeline
|
|
522
|
+
* @param channel the channel
|
|
523
|
+
*/
|
|
524
|
+
private frame(channel: Channel): void {
|
|
525
|
+
channel.pipeline
|
|
526
|
+
.addLast<LengthFieldBasedFrameDecoder>(
|
|
527
|
+
'frames',
|
|
528
|
+
new LengthFieldBasedFrameDecoder({
|
|
529
|
+
maxFrameLength: this.maxMessageSize + 4,
|
|
530
|
+
lengthFieldLength: 4,
|
|
531
|
+
initialBytesToStrip: 4,
|
|
532
|
+
}),
|
|
533
|
+
)
|
|
534
|
+
.addLast<LengthFieldPrepender>(
|
|
535
|
+
'length',
|
|
536
|
+
new LengthFieldPrepender({ lengthFieldLength: 4 }),
|
|
537
|
+
)
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
/**
|
|
541
|
+
* Throws for a shard outside the link
|
|
542
|
+
* @param shard the target
|
|
543
|
+
*/
|
|
544
|
+
private check(shard: number): void {
|
|
545
|
+
if (this.closed) throw new Error('Link is closed')
|
|
546
|
+
if (!Number.isInteger(shard) || shard < 0 || shard >= this.count) {
|
|
547
|
+
throw new RangeError('Shard is invalid')
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
/**
|
|
552
|
+
* Delivers a message locally or sends it to its shard
|
|
553
|
+
* @param message the message
|
|
554
|
+
*/
|
|
555
|
+
private post(message: ShardMessage): void {
|
|
556
|
+
if (message.to === this.id) {
|
|
557
|
+
queueMicrotask((): void => {
|
|
558
|
+
this.deliver(message)
|
|
559
|
+
})
|
|
560
|
+
return
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
const peer = this.connect(message.to)
|
|
564
|
+
peer.queue.push(message)
|
|
565
|
+
if (peer.channel === null) return
|
|
566
|
+
|
|
567
|
+
if (this.dirty.size === 0) queueMicrotask(this.flusher)
|
|
568
|
+
this.dirty.add(peer)
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
/**
|
|
572
|
+
* Sends everything queued for a connection as one frame
|
|
573
|
+
* @param peer the connection
|
|
574
|
+
*/
|
|
575
|
+
private drain(peer: Peer): void {
|
|
576
|
+
const channel = peer.channel
|
|
577
|
+
const queue = peer.queue
|
|
578
|
+
if (channel === null || queue.length === 0) return
|
|
579
|
+
|
|
580
|
+
peer.queue = []
|
|
581
|
+
const bytes = serialize(queue, { binaryType: 'nodebuffer' })
|
|
582
|
+
if (bytes.length <= this.maxMessageSize) {
|
|
583
|
+
channel.writeAndFlushSync(bytes)
|
|
584
|
+
return
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
for (const message of queue) {
|
|
588
|
+
const single = serialize([message], { binaryType: 'nodebuffer' })
|
|
589
|
+
if (single.length <= this.maxMessageSize) channel.writeSync(single)
|
|
590
|
+
else if (message.kind === 'request') {
|
|
591
|
+
this.settle(message.id, null, 'Message is too large')
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
void channel.flush()
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
/**
|
|
599
|
+
* The connection to a shard, started if there isn't one
|
|
600
|
+
* @param shard the shard
|
|
601
|
+
*/
|
|
602
|
+
private connect(shard: number): Peer {
|
|
603
|
+
const existing = this.connections.get(shard)
|
|
604
|
+
if (existing !== undefined) return existing
|
|
605
|
+
|
|
606
|
+
const peer: Peer = { channel: null, queue: [] }
|
|
607
|
+
this.connections.set(shard, peer)
|
|
608
|
+
|
|
609
|
+
const address = this.peers[shard]
|
|
610
|
+
if (address === undefined) {
|
|
611
|
+
queueMicrotask((): void => {
|
|
612
|
+
this.lose(shard, peer)
|
|
613
|
+
})
|
|
614
|
+
return peer
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
new Bootstrap()
|
|
618
|
+
.handler((channel: Channel): void => {
|
|
619
|
+
this.frame(channel)
|
|
620
|
+
})
|
|
621
|
+
.connect(address)
|
|
622
|
+
.then(
|
|
623
|
+
(channel: Channel): void => {
|
|
624
|
+
this.opened(shard, peer, channel)
|
|
625
|
+
},
|
|
626
|
+
(): void => {
|
|
627
|
+
this.lose(shard, peer)
|
|
628
|
+
},
|
|
629
|
+
)
|
|
630
|
+
return peer
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
/**
|
|
634
|
+
* Sends the backlog on a new connection and forgets it once it closes
|
|
635
|
+
* @param shard the shard
|
|
636
|
+
* @param peer the connection record
|
|
637
|
+
* @param channel the new channel
|
|
638
|
+
*/
|
|
639
|
+
private opened(shard: number, peer: Peer, channel: Channel): void {
|
|
640
|
+
if (this.closed || this.connections.get(shard) !== peer) {
|
|
641
|
+
void channel.close()
|
|
642
|
+
return
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
peer.channel = channel
|
|
646
|
+
this.drain(peer)
|
|
647
|
+
void channel.closed.then((): void => {
|
|
648
|
+
if (this.connections.get(shard) === peer) this.connections.delete(shard)
|
|
649
|
+
})
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
/**
|
|
653
|
+
* Forgets a connection that failed and fails requests waiting on it
|
|
654
|
+
* @param shard the shard
|
|
655
|
+
* @param peer the failed connection
|
|
656
|
+
*/
|
|
657
|
+
private lose(shard: number, peer: Peer): void {
|
|
658
|
+
if (this.connections.get(shard) === peer) this.connections.delete(shard)
|
|
659
|
+
peer.queue = []
|
|
660
|
+
|
|
661
|
+
for (const [id, waiting] of this.waiting) {
|
|
662
|
+
if (waiting.shard === shard) this.settle(id, null, 'Shard is down')
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
/**
|
|
667
|
+
* Runs the responder for a request and sends the reply back
|
|
668
|
+
* @param request the request
|
|
669
|
+
*/
|
|
670
|
+
private async answer(request: ShardMessage): Promise<void> {
|
|
671
|
+
const responder = this.responders.get(request.topic)
|
|
672
|
+
if (responder === undefined) {
|
|
673
|
+
this.reply(request, null, 'Topic has no handler')
|
|
674
|
+
return
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
try {
|
|
678
|
+
const data: unknown = await responder(request.data, request.from)
|
|
679
|
+
this.reply(request, data, null)
|
|
680
|
+
} catch (cause) {
|
|
681
|
+
this.reply(
|
|
682
|
+
request,
|
|
683
|
+
null,
|
|
684
|
+
cause instanceof Error ? cause.message : 'Request failed',
|
|
685
|
+
)
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
/**
|
|
690
|
+
* Sends a reply unless the link closed meanwhile
|
|
691
|
+
* @param request what it answers
|
|
692
|
+
* @param data the reply
|
|
693
|
+
* @param error why it failed, or null
|
|
694
|
+
*/
|
|
695
|
+
private reply(
|
|
696
|
+
request: ShardMessage,
|
|
697
|
+
data: unknown,
|
|
698
|
+
error: string | null,
|
|
699
|
+
): void {
|
|
700
|
+
if (this.closed) return
|
|
701
|
+
|
|
702
|
+
this.post({
|
|
703
|
+
kind: 'reply',
|
|
704
|
+
from: this.id,
|
|
705
|
+
to: request.from,
|
|
706
|
+
topic: request.topic,
|
|
707
|
+
id: request.id,
|
|
708
|
+
data,
|
|
709
|
+
error,
|
|
710
|
+
})
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
/**
|
|
714
|
+
* Resolves or rejects a waiting request
|
|
715
|
+
* @param id the request id
|
|
716
|
+
* @param data the reply
|
|
717
|
+
* @param error why it failed, or null
|
|
718
|
+
*/
|
|
719
|
+
private settle(id: number, data: unknown, error: string | null): void {
|
|
720
|
+
const waiting = this.waiting.get(id)
|
|
721
|
+
if (waiting === undefined) return
|
|
722
|
+
|
|
723
|
+
clearTimeout(waiting.timer)
|
|
724
|
+
this.waiting.delete(id)
|
|
725
|
+
if (error === null) waiting.resolvers.resolve(data)
|
|
726
|
+
else waiting.resolvers.reject(new Error(error))
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
/**
|
|
730
|
+
* Stores a handed off player and returns their token
|
|
731
|
+
* @param state what the old shard sent over
|
|
732
|
+
*/
|
|
733
|
+
private arrive(state: unknown): string {
|
|
734
|
+
const token = crypto.randomUUID()
|
|
735
|
+
const timer = setTimeout((): void => {
|
|
736
|
+
this.arrivals.delete(token)
|
|
737
|
+
}, this.handoffTimeout)
|
|
738
|
+
timer.unref()
|
|
739
|
+
|
|
740
|
+
this.arrivals.set(token, { state, timer })
|
|
741
|
+
return token
|
|
742
|
+
}
|
|
743
|
+
}
|