@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.
- 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/index.ts +10 -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,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How many shards and where they listen
|
|
3
|
+
*/
|
|
4
|
+
export type ShardMapOptions = {
|
|
5
|
+
/**
|
|
6
|
+
* Number of shards
|
|
7
|
+
*/
|
|
8
|
+
readonly count: number
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Port of shard 0, each next shard is one higher
|
|
12
|
+
*/
|
|
13
|
+
readonly port?: number
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Decides which shard owns a zone, room or player
|
|
18
|
+
* @class
|
|
19
|
+
*/
|
|
20
|
+
export class ShardMap {
|
|
21
|
+
/**
|
|
22
|
+
* Number of shards
|
|
23
|
+
*/
|
|
24
|
+
public readonly count: number
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Port of shard 0
|
|
28
|
+
*/
|
|
29
|
+
private readonly port: number
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Sets up the map
|
|
33
|
+
* @param options count and first port
|
|
34
|
+
*/
|
|
35
|
+
public constructor(options: ShardMapOptions) {
|
|
36
|
+
const reason = ShardMap.refusal(options)
|
|
37
|
+
if (reason !== null) throw new RangeError(reason)
|
|
38
|
+
|
|
39
|
+
this.count = options.count
|
|
40
|
+
this.port = options.port ?? 0
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Checks the count and port
|
|
45
|
+
* @param options what the caller passed in
|
|
46
|
+
*/
|
|
47
|
+
private static refusal(options: ShardMapOptions): string | null {
|
|
48
|
+
if (!Number.isInteger(options.count) || options.count < 1) {
|
|
49
|
+
return 'Shard count is invalid'
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const port = options.port ?? 0
|
|
53
|
+
if (!Number.isInteger(port) || port < 0 || port + options.count > 65536) {
|
|
54
|
+
return 'Port is invalid'
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
return null
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* The shard that owns a key, the same on every process
|
|
62
|
+
* @param key a zone id or name
|
|
63
|
+
*/
|
|
64
|
+
public shardOf(key: string | number): number {
|
|
65
|
+
if (typeof key === 'number' && Number.isSafeInteger(key)) {
|
|
66
|
+
return ((key % this.count) + this.count) % this.count
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
return Bun.hash.xxHash32(String(key)) % this.count
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Port a shard listens on
|
|
74
|
+
* @param shard the shard
|
|
75
|
+
*/
|
|
76
|
+
public portOf(shard: number): number {
|
|
77
|
+
if (!Number.isInteger(shard) || shard < 0 || shard >= this.count) {
|
|
78
|
+
throw new RangeError('Shard is invalid')
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
return this.port + shard
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Port of the shard that owns a key
|
|
86
|
+
* @param key a zone id or name
|
|
87
|
+
*/
|
|
88
|
+
public portFor(key: string | number): number {
|
|
89
|
+
return this.portOf(this.shardOf(key))
|
|
90
|
+
}
|
|
91
|
+
}
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import { Cluster } from '../../cluster/index.ts'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Settings for a group of server threads
|
|
5
|
+
*/
|
|
6
|
+
export type WorkerGroupOptions = {
|
|
7
|
+
/**
|
|
8
|
+
* Script each thread runs, usually a server binding with reusePort
|
|
9
|
+
*/
|
|
10
|
+
readonly script: string | URL
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* How many threads, one per core by default
|
|
14
|
+
*/
|
|
15
|
+
readonly workers?: number
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Memory every thread can see, handed over as each one starts
|
|
19
|
+
*/
|
|
20
|
+
readonly shared?: SharedArrayBuffer
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Extra environment variables for each thread
|
|
24
|
+
*/
|
|
25
|
+
readonly env?: Readonly<Record<string, string>>
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Extra arguments, they show up at the end of Bun.argv in each thread
|
|
29
|
+
*/
|
|
30
|
+
readonly argv?: readonly string[]
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* The message a thread gets with the shared memory
|
|
35
|
+
*/
|
|
36
|
+
type SharedMessage = {
|
|
37
|
+
/**
|
|
38
|
+
* Tags the message so scripts can tell it apart
|
|
39
|
+
*/
|
|
40
|
+
readonly kind: 'netify:shared'
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* The shared memory
|
|
44
|
+
*/
|
|
45
|
+
readonly buffer: SharedArrayBuffer
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Runs server threads in one process, like Cluster but sharing memory
|
|
50
|
+
* @class
|
|
51
|
+
*/
|
|
52
|
+
export class WorkerGroup {
|
|
53
|
+
/**
|
|
54
|
+
* Script, size and shared memory
|
|
55
|
+
*/
|
|
56
|
+
private readonly options: WorkerGroupOptions
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Number of threads
|
|
60
|
+
*/
|
|
61
|
+
private readonly count: number
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* The running threads
|
|
65
|
+
*/
|
|
66
|
+
private readonly threads: Worker[]
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Checks the size, nothing starts until start
|
|
70
|
+
* @param options script, size and shared memory
|
|
71
|
+
*/
|
|
72
|
+
public constructor(options: WorkerGroupOptions) {
|
|
73
|
+
const count = options.workers ?? navigator.hardwareConcurrency
|
|
74
|
+
if (!Number.isInteger(count) || count < 1) {
|
|
75
|
+
throw new RangeError('Worker count is invalid')
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
this.options = options
|
|
79
|
+
this.count = count
|
|
80
|
+
this.threads = []
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Waits for the shared memory, call it from inside a thread
|
|
85
|
+
*/
|
|
86
|
+
public static shared(): Promise<SharedArrayBuffer> {
|
|
87
|
+
const { promise, resolve } = Promise.withResolvers<SharedArrayBuffer>()
|
|
88
|
+
|
|
89
|
+
const listener = (event: MessageEvent<unknown>): void => {
|
|
90
|
+
if (!WorkerGroup.isShared(event.data)) return
|
|
91
|
+
removeEventListener('message', listener)
|
|
92
|
+
resolve(event.data.buffer)
|
|
93
|
+
}
|
|
94
|
+
addEventListener('message', listener)
|
|
95
|
+
return promise
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Tells our shared memory message apart from the script's own messages
|
|
100
|
+
* @param data whatever the thread was sent
|
|
101
|
+
*/
|
|
102
|
+
private static isShared(data: unknown): data is SharedMessage {
|
|
103
|
+
return (
|
|
104
|
+
typeof data === 'object' &&
|
|
105
|
+
data !== null &&
|
|
106
|
+
'kind' in data &&
|
|
107
|
+
data.kind === 'netify:shared'
|
|
108
|
+
)
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Number of threads
|
|
113
|
+
*/
|
|
114
|
+
public get size(): number {
|
|
115
|
+
return this.count
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Starts every thread
|
|
120
|
+
*/
|
|
121
|
+
public start(): this {
|
|
122
|
+
if (this.threads.length > 0) return this
|
|
123
|
+
|
|
124
|
+
for (let index = 0; index < this.count; index++) {
|
|
125
|
+
this.threads.push(this.spawn(index))
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
return this
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Stops every thread
|
|
133
|
+
*/
|
|
134
|
+
public stop(): Promise<void> {
|
|
135
|
+
for (const thread of this.threads.splice(0)) thread.terminate()
|
|
136
|
+
|
|
137
|
+
return Promise.resolve()
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Starts one thread with its id and the shared memory
|
|
142
|
+
* @param index the thread's id
|
|
143
|
+
*/
|
|
144
|
+
private spawn(index: number): Worker {
|
|
145
|
+
const inherited: Record<string, string> = {}
|
|
146
|
+
for (const [key, value] of Object.entries(Bun.env)) {
|
|
147
|
+
if (value !== undefined) inherited[key] = value
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const thread = new Worker(this.options.script, {
|
|
151
|
+
/**
|
|
152
|
+
* Our env plus the thread's id and the group size
|
|
153
|
+
*/
|
|
154
|
+
env: {
|
|
155
|
+
...inherited,
|
|
156
|
+
...this.options.env,
|
|
157
|
+
[Cluster.workerVariable]: String(index),
|
|
158
|
+
[Cluster.countVariable]: String(this.count),
|
|
159
|
+
},
|
|
160
|
+
/**
|
|
161
|
+
* Appended to Bun.argv inside the thread
|
|
162
|
+
*/
|
|
163
|
+
argv: [...(this.options.argv ?? [])],
|
|
164
|
+
})
|
|
165
|
+
if (this.options.shared !== undefined) {
|
|
166
|
+
const message: SharedMessage = {
|
|
167
|
+
kind: 'netify:shared',
|
|
168
|
+
buffer: this.options.shared,
|
|
169
|
+
}
|
|
170
|
+
thread.postMessage(message)
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
return thread
|
|
174
|
+
}
|
|
175
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export { WorkerGroup } from './group/index.ts'
|
|
2
|
+
export type { WorkerGroupOptions } from './group/index.ts'
|
|
3
|
+
export { WorkerPool } from './pool/index.ts'
|
|
4
|
+
export type {
|
|
5
|
+
WorkerPoolOptions,
|
|
6
|
+
WorkerReply,
|
|
7
|
+
WorkerRequest,
|
|
8
|
+
} from './pool/index.ts'
|
|
9
|
+
export { WorkerService } from './service/index.ts'
|
|
10
|
+
export type { WorkerTask } from './service/index.ts'
|
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
import type { Transferable } from 'bun'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Settings for a pool of worker threads
|
|
5
|
+
*/
|
|
6
|
+
export type WorkerPoolOptions = {
|
|
7
|
+
/**
|
|
8
|
+
* Script each worker runs, it should start a WorkerService
|
|
9
|
+
*/
|
|
10
|
+
readonly script: string | URL
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* How many threads to start, one per core by default
|
|
14
|
+
*/
|
|
15
|
+
readonly workers?: number
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Jobs allowed in flight across the pool, extras fail straight away
|
|
19
|
+
*/
|
|
20
|
+
readonly maxQueued?: number
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* What the pool sends a worker
|
|
25
|
+
*/
|
|
26
|
+
export type WorkerRequest<I> = {
|
|
27
|
+
/**
|
|
28
|
+
* Matches the reply to the job
|
|
29
|
+
*/
|
|
30
|
+
readonly id: number
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* The job's input
|
|
34
|
+
*/
|
|
35
|
+
readonly input: I
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* What a worker sends back
|
|
40
|
+
*/
|
|
41
|
+
export type WorkerReply<O> = {
|
|
42
|
+
/**
|
|
43
|
+
* Same id as the request
|
|
44
|
+
*/
|
|
45
|
+
readonly id: number
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* The result, when it worked
|
|
49
|
+
*/
|
|
50
|
+
readonly output?: O
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Error message, when it didn't
|
|
54
|
+
*/
|
|
55
|
+
readonly error?: string
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* A job waiting on a worker
|
|
60
|
+
*/
|
|
61
|
+
type Job<O> = {
|
|
62
|
+
/**
|
|
63
|
+
* Settles the caller's promise
|
|
64
|
+
*/
|
|
65
|
+
readonly result: PromiseWithResolvers<O>
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Which worker has it
|
|
69
|
+
*/
|
|
70
|
+
readonly worker: number
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Spreads jobs over worker threads, least busy worker first
|
|
75
|
+
* @class
|
|
76
|
+
*/
|
|
77
|
+
export class WorkerPool<I, O> {
|
|
78
|
+
/**
|
|
79
|
+
* 1024 jobs in flight before the pool says no
|
|
80
|
+
*/
|
|
81
|
+
public static readonly defaultMaxQueued: number = 1024
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* The threads
|
|
85
|
+
*/
|
|
86
|
+
private readonly workers: Worker[]
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Jobs in flight per worker
|
|
90
|
+
*/
|
|
91
|
+
private readonly load: number[]
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Jobs waiting for a reply, by id
|
|
95
|
+
*/
|
|
96
|
+
private readonly jobs: Map<number, Job<O>>
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Cap on jobs in flight
|
|
100
|
+
*/
|
|
101
|
+
private readonly maxQueued: number
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Next job id
|
|
105
|
+
*/
|
|
106
|
+
private nextId: number
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Set once close is called
|
|
110
|
+
*/
|
|
111
|
+
private closed: boolean
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Starts the threads straight away
|
|
115
|
+
* @param options script, size and limits
|
|
116
|
+
*/
|
|
117
|
+
public constructor(options: WorkerPoolOptions) {
|
|
118
|
+
const count = options.workers ?? navigator.hardwareConcurrency
|
|
119
|
+
if (!Number.isInteger(count) || count < 1) {
|
|
120
|
+
throw new RangeError('Worker count is invalid')
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
this.maxQueued = options.maxQueued ?? WorkerPool.defaultMaxQueued
|
|
124
|
+
this.jobs = new Map<number, Job<O>>()
|
|
125
|
+
this.nextId = 1
|
|
126
|
+
this.closed = false
|
|
127
|
+
this.load = Array.from({ length: count }, (): number => 0)
|
|
128
|
+
this.workers = Array.from(
|
|
129
|
+
{ length: count },
|
|
130
|
+
(_: unknown, index: number): Worker => this.spawn(options.script, index),
|
|
131
|
+
)
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Jobs currently in flight
|
|
136
|
+
*/
|
|
137
|
+
public get size(): number {
|
|
138
|
+
return this.jobs.size
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Hands a job to the least busy worker
|
|
143
|
+
* @param input structured-cloneable job input
|
|
144
|
+
* @param transfer buffers to move rather than copy
|
|
145
|
+
*/
|
|
146
|
+
public run(input: I, transfer: readonly Transferable[] = []): Promise<O> {
|
|
147
|
+
if (this.closed) return Promise.reject(new Error('Pool is closed'))
|
|
148
|
+
if (this.jobs.size >= this.maxQueued) {
|
|
149
|
+
return Promise.reject(new Error('Pool is full'))
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
const worker = this.leastBusy()
|
|
153
|
+
const id = this.nextId++
|
|
154
|
+
const job: Job<O> = { result: Promise.withResolvers<O>(), worker }
|
|
155
|
+
this.jobs.set(id, job)
|
|
156
|
+
this.load[worker] = (this.load[worker] ?? 0) + 1
|
|
157
|
+
const request: WorkerRequest<I> = { id, input }
|
|
158
|
+
this.workers[worker]?.postMessage(request, [...transfer])
|
|
159
|
+
return job.result.promise
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Stops every thread and fails what's still in flight
|
|
164
|
+
*/
|
|
165
|
+
public close(): Promise<void> {
|
|
166
|
+
this.closed = true
|
|
167
|
+
|
|
168
|
+
for (const worker of this.workers) worker.terminate()
|
|
169
|
+
for (const job of this.jobs.values()) {
|
|
170
|
+
job.result.reject(new Error('Pool is closed'))
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
this.jobs.clear()
|
|
174
|
+
return Promise.resolve()
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* Starts one thread and wires up its replies
|
|
179
|
+
* @param script what the thread runs
|
|
180
|
+
* @param index its slot in the pool
|
|
181
|
+
*/
|
|
182
|
+
private spawn(script: string | URL, index: number): Worker {
|
|
183
|
+
const worker = new Worker(script)
|
|
184
|
+
|
|
185
|
+
worker.onmessage = (event: MessageEvent<WorkerReply<O>>): void => {
|
|
186
|
+
this.settle(event.data)
|
|
187
|
+
}
|
|
188
|
+
worker.onerror = (event: ErrorEvent): void => {
|
|
189
|
+
this.failWorker(index, new Error('Worker failed', { cause: event.error }))
|
|
190
|
+
}
|
|
191
|
+
return worker
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* Resolves or rejects the job a reply belongs to
|
|
196
|
+
* @param reply what the worker sent
|
|
197
|
+
*/
|
|
198
|
+
private settle(reply: WorkerReply<O>): void {
|
|
199
|
+
const job = this.jobs.get(reply.id)
|
|
200
|
+
if (job === undefined) return
|
|
201
|
+
this.jobs.delete(reply.id)
|
|
202
|
+
this.load[job.worker] = (this.load[job.worker] ?? 1) - 1
|
|
203
|
+
|
|
204
|
+
if (reply.error !== undefined) job.result.reject(new Error(reply.error))
|
|
205
|
+
else job.result.resolve(reply.output as O)
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* Fails every job a crashed worker had
|
|
210
|
+
* @param index the worker's slot
|
|
211
|
+
* @param error why it failed
|
|
212
|
+
*/
|
|
213
|
+
private failWorker(index: number, error: Error): void {
|
|
214
|
+
for (const [id, job] of this.jobs) {
|
|
215
|
+
if (job.worker !== index) continue
|
|
216
|
+
this.jobs.delete(id)
|
|
217
|
+
job.result.reject(error)
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
this.load[index] = 0
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* Slot of the worker with the fewest jobs
|
|
225
|
+
*/
|
|
226
|
+
private leastBusy(): number {
|
|
227
|
+
let best = 0
|
|
228
|
+
|
|
229
|
+
for (let index = 1; index < this.load.length; index++) {
|
|
230
|
+
if ((this.load[index] ?? 0) < (this.load[best] ?? 0)) best = index
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
return best
|
|
234
|
+
}
|
|
235
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import type { WorkerReply, WorkerRequest } from '../pool/index.ts'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The work a service does for each job
|
|
5
|
+
*/
|
|
6
|
+
export type WorkerTask<I, O> = (input: I) => O | Promise<O>
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Runs inside a worker thread and answers a WorkerPool's jobs
|
|
10
|
+
* @class
|
|
11
|
+
*/
|
|
12
|
+
export class WorkerService<I, O> {
|
|
13
|
+
/**
|
|
14
|
+
* What to do with each job
|
|
15
|
+
*/
|
|
16
|
+
private readonly task: WorkerTask<I, O>
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Wraps the work this thread does
|
|
20
|
+
* @param task turns a job's input into its output
|
|
21
|
+
*/
|
|
22
|
+
public constructor(task: WorkerTask<I, O>) {
|
|
23
|
+
this.task = task
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Starts answering jobs sent to this thread
|
|
28
|
+
*/
|
|
29
|
+
public listen(): void {
|
|
30
|
+
addEventListener(
|
|
31
|
+
'message',
|
|
32
|
+
(event: MessageEvent<WorkerRequest<I>>): void => {
|
|
33
|
+
void this.answer(event.data)
|
|
34
|
+
},
|
|
35
|
+
)
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Runs one job and posts the result or the error back
|
|
40
|
+
* @param request the job
|
|
41
|
+
*/
|
|
42
|
+
private async answer(request: WorkerRequest<I>): Promise<void> {
|
|
43
|
+
let reply: WorkerReply<O>
|
|
44
|
+
try {
|
|
45
|
+
reply = { id: request.id, output: await this.task(request.input) }
|
|
46
|
+
} catch (error) {
|
|
47
|
+
reply = {
|
|
48
|
+
id: request.id,
|
|
49
|
+
error: error instanceof Error ? error.message : 'Task failed',
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
postMessage(reply)
|
|
54
|
+
}
|
|
55
|
+
}
|