From 1c78dac7ed1394a7a429da1b5c5c8809ed267e62 Mon Sep 17 00:00:00 2001 From: jj Date: Fri, 1 Nov 2024 14:49:52 +0000 Subject: [PATCH] api/cluster: implement broadcast helper --- api/src/misc/cluster.js | 14 +++++++++++++- api/src/security/api-keys.js | 10 +++------- 2 files changed, 16 insertions(+), 8 deletions(-) diff --git a/api/src/misc/cluster.js b/api/src/misc/cluster.js index 145c5588..ea43aaa9 100644 --- a/api/src/misc/cluster.js +++ b/api/src/misc/cluster.js @@ -1,7 +1,9 @@ import cluster from "node:cluster"; import net from "node:net"; import { syncSecrets } from "../security/secrets.js"; -import { env } from "../config.js"; +import { env, isCluster } from "../config.js"; + +export { isPrimary, isWorker } from "node:cluster"; export const supportsReusePort = async () => { try { @@ -26,3 +28,13 @@ export const initCluster = async () => { await syncSecrets(); } + +export const broadcast = (message) => { + if (!isCluster || !cluster.isPrimary || !cluster.workers) { + return; + } + + for (const worker of Object.values(cluster.workers)) { + worker.send(message); + } +} diff --git a/api/src/security/api-keys.js b/api/src/security/api-keys.js index 5005d64d..0e24c48d 100644 --- a/api/src/security/api-keys.js +++ b/api/src/security/api-keys.js @@ -1,8 +1,8 @@ -import { env, isCluster } from "../config.js"; +import { env } from "../config.js"; import { readFile } from "node:fs/promises"; import { Green, Yellow } from "../misc/console-text.js"; -import cluster from "node:cluster"; import ip from "ipaddr.js"; +import * as cluster from "../misc/cluster.js"; // this function is a modified variation of code // from https://stackoverflow.com/a/32402438/14855621 @@ -133,11 +133,7 @@ const loadKeys = async (source) => { validateKeys(updated); - if (isCluster && cluster.workers) { - for (const worker of Object.values(cluster.workers)) { - worker.send({ api_keys: updated }); - } - } + cluster.broadcast({ api_keys: updated }); updateKeys(updated); }