| 89 | const broadcastTypes = ["broadcastEnd", "broadcastStart", "eval", "mediareload", "reload", "soundreload"]; |
| 90 | |
| 91 | function awaitStart(i: number, shardArray: number[]): Promise<Worker> { |
| 92 | const worker = cluster.fork({ |
| 93 | SHARDS: JSON.stringify(shardArray), |
| 94 | CLUSTER_TYPE: "node", |
| 95 | pm_id: i, |
| 96 | }); |
| 97 | |
| 98 | worker.on("message", async (message: IncomingProcMessage) => { |
| 99 | if (message.data?.type === "getCount") { |
| 100 | worker.send({ |
| 101 | data: { |
| 102 | type: "countResponse", |
| 103 | serverCount, |
| 104 | }, |
| 105 | }); |
| 106 | } |
| 107 | if (message.data?.type === "getMem") { |
| 108 | try { |
| 109 | await updateStats(true); |
| 110 | } catch (e) { |
| 111 | logger.error(e); |
| 112 | } |
| 113 | worker.send({ |
| 114 | data: { |
| 115 | type: "memResponse", |
| 116 | totalMem, |
| 117 | }, |
| 118 | }); |
| 119 | } |
| 120 | |
| 121 | // relay broadcast messages |
| 122 | if (message.data && broadcastTypes.includes(message.data.type)) { |
| 123 | for (const proc of processes) { |
| 124 | if (proc.id === worker.id || !proc.isConnected()) continue; |
| 125 | proc.send(message); |
| 126 | } |
| 127 | } |
| 128 | }); |
| 129 | |
| 130 | return new Promise((resolve, reject) => { |
| 131 | const message = (msg: IncomingProcMessage) => { |
| 132 | if (msg.data?.type === "ready") { |
| 133 | worker.off("message", message); |
| 134 | worker.off("error", error); |
| 135 | worker.off("exit", exit); |
| 136 | resolve(worker); |
| 137 | } |
| 138 | }; |
| 139 | const error = (e: Error) => { |
| 140 | worker.off("message", message); |
| 141 | worker.off("exit", exit); |
| 142 | reject(e); |
| 143 | }; |
| 144 | const exit = (c: number) => { |
| 145 | worker.off("message", message); |
| 146 | worker.off("error", error); |
| 147 | reject(Error(`Process exited with code ${c}`)); |
| 148 | }; |