import { type, tmpdir } from "node:os"; import { existsSync, mkdirSync } from "node:fs"; import { Agent, fetch } from "undici"; import TimedCache from "@entity-access/entity-access/dist/common/cache/TimedCache.js"; import { ChildProcess, fork } from "node:child_process"; import { unlink } from "node:fs/promises"; import VirtualServer from "../model/entities/VirtualServer.js"; import { globalServices } from "../../globalServices.js"; import { globalEnv } from "../../common/globalEnv.js"; import VirtualHost from "./VirtualHost.js"; import { fileURLToPath } from "node:url"; import ServerLogger from "@entity-access/server-pages/dist/core/ServerLogger.js"; // import { Worker } from "node:worker_threads"; const mainScript = fileURLToPath(import.meta.resolve("./VirtualServerMain.js")); const tempPath = process.env.SOCIAL_MAIL_TMP_PATH || tmpdir(); let startPort = Date.now(); const createUnixPort = (hostName: string, n = 1) => { if (type().startsWith("Window")) { return `\\\\?\\pipe\\sm\\${hostName}-${process.pid}-${startPort++}-${n}`; } return `/sockets/smt-ws-${hostName}-${process.pid}-${startPort++}-${n}.sock`; }; const createSharedPort = (hostName: string) => { let i = 1; let port = createUnixPort(hostName, i); while(existsSync(port)) { port = createUnixPort(hostName, i++); } return port; }; const SIGTERM = "SIGTERM"; export default class ClusterWebWorker { public static clear() { this.socketWorkers.clear(); } public static async getWorker(hostName: string) { hostName = hostName.trim().toLowerCase(); return this.socketWorkers.getOrCreateAsync(hostName, async (host) => { if (globalEnv.ips.includes(host)) { host = globalEnv.host; } const availableHosts = globalServices.resolve(VirtualHost); const server = await availableHosts.findHost(host); if (!server?.server) { console.error(`Host ${host} not available`); throw new Error(`${host} Host not available, please contact the administrator.`); } const { server: { serverID} } = server; const sServerID = serverID.toString(); return this.virtualWorkers.getOrCreateAsync(sServerID, async (sID) => { console.log(`Creating Cluster Worker for ${sID} in ${process.pid}`); const socket = createSharedPort("h-" + sID); const smtpSocket = createSharedPort("s-" + sID); // const socketHttp1 = createSharedPort("h2-" + sID); const w = new ClusterWebWorker(host, server, socket, smtpSocket); await w.ready(); return w; }, 15*60000, (cwr) => { // this is important as one server may be used by multiple hosts // we don't know which host to clear // so it is better to clear all hosts this.socketWorkers.clear(); cwr.dispose(); }); }); } private static socketWorkers = new TimedCache(5*60*1000); private static virtualWorkers = new TimedCache(15*60*1000); private worker: ChildProcess; private dispatcher: any; private initialized: Promise; constructor( private readonly host: string, public readonly server: { server: VirtualServer, host: string }, public readonly socket, public readonly smtpSocket) { } dispose = () => { process.off(SIGTERM, this.dispose); if (!this.initialized) { return; } this.initialized = null; console.log(JSON.stringify({ serverID: this.server.server?.serverID, pid: this.worker.pid, action: "inactive worker disposed" })) this.killWorker().catch(ServerLogger.error); }; public fetch = (url, { method = "GET", body, headers } = {} as any) => { const a = {} as RequestInit; // this will require sending address first... if (!this.dispatcher) { const d = new Agent({ socketPath: this.socket, }); this.dispatcher = d; } (a as any).dispatcher = this.dispatcher; const u = new URL(url, `http://${this.host}`); u.host = this.host; u.protocol = "http"; url = u.toString(); return fetch(url, { method, body, headers, ... a } as any); }; private ready() { return this.initialized ??= (async () => { const { socket } = this; const server = this.server.server; const sharedHost = server; const host = server?.host ?? process.env.SOCIAL_MAIL_HOST; const emailHosts = ""; const defaultEnv = sharedHost?.environmentVariables ? JSON.parse(sharedHost.environmentVariables) : {}; const hostId = `social-mail-${server?.serverID}`; const database = sharedHost?.database || hostId; const bucketName = sharedHost?.bucketName || hostId; const tmpID = `${tempPath}/${server?.serverID ?? 0}/`; const token = globalEnv.virtualServers.clusterApiToken; if (!existsSync(tmpID)) { mkdirSync(tmpID, { recursive: true }); } const name = server.serverName; // reuse last active access token.. // uncomment following for inspect // const execArgv = ["--enable-source-maps", '--inspect=0.0.0.0:9232']; const execArgv = ["--enable-source-maps"]; // execArgv.push("--trace-deprecation"); const env = host !== process.env.SOCIAL_MAIL_HOST ? { ... process.env, SOCIAL_MAIL_CDN: "", /** Following must be created and activated separately, this is just to avoid using default storage*/ SOCIAL_MAIL_AZURE_BLOB_CONTAINER: bucketName, SOCIAL_MAIL_S3_BUCKET: bucketName, SOCIAL_MAIL_ROOT_S3_ACCESS_KEY: "", SOCIAL_MAIL_ROOT_S3_SECRET_ACCESS_KEY: "", SOCIAL_MAIL_SHARED_S3_ACCESS_KEY: "", SOCIAL_MAIL_SHARED_S3_SECRET_ACCESS_KEY: "", SOCIAL_MAIL_STORAGE: "s3", SOCIAL_MAIL_S3_END_POINT: "https://s3.ap-south-1.amazonaws.com", SOCIAL_MAIL_S3_REGION: "ap-south-1", SOCIAL_MAIL_S3_ACCESS_KEY: process.env.SOCIAL_MAIL_SHARED_S3_ACCESS_KEY, SOCIAL_MAIL_S3_SECRET: process.env.SOCIAL_MAIL_SHARED_S3_SECRET_ACCESS_KEY, SOCIAL_MAIL_OTP_TO_USER_MODES: "providerSocialMail", SOCIAL_MAIL_TWILIO_ACCOUNT_SID: "", SOCIAL_MAIL_TWILIO_AUTH_TOKEN: "", SOCIAL_MAIL_TWILIO_VERIFY_SERVICE_ID: "", SOCIAL_MAIL_WEB_HOSTING_SUPPORT_EMAIL: "", ... defaultEnv, IS_WORKER: "1", SOCIAL_MAIL_CLUSTER_API_TOKEN: token, SOCIAL_MAIL_CLUSTER_HOST: globalEnv.host, SOCIAL_MAIL_CLUSTER_PORT: globalEnv.port, PORT: socket.toString(), SOCIAL_MAIL_SMTP_PORT: this.smtpSocket, // SOCIAL_MAIL_HTTP1_PORT: http1Socket, SOCIAL_MAIL_SHARED_HOST: host, SOCIAL_MAIL_HOST: host, SOCIAL_MAIL_NAME: name, SOCIAL_MAIL_EMAIL_HOSTS: emailHosts, SOCIAL_MAIL_SERVER_ID: server.serverID, SOCIAL_MAIL_DB_DATABASE: database, SOCIAL_MAIL_TMP_PATH: tmpID, SOCIAL_MAIL_HTTP_NOT_FOUND_DELAY: "0", SOCIAL_MAIL_HAS_VIRTUAL_SERVERS: "no" } : { ... process.env, IS_WORKER: "1", PORT: socket.toString(), SOCIAL_MAIL_SMTP_PORT: this.smtpSocket, SOCIAL_MAIL_CLUSTER_API_TOKEN: token, SOCIAL_MAIL_EMAIL_HOSTS: emailHosts, SOCIAL_MAIL_SERVER_ID: server.serverID, SOCIAL_MAIL_MAIN_HOST: host, SOCIAL_MAIL_HTTP_NOT_FOUND_DELAY: "0", // SOCIAL_MAIL_TMP_PATH: tmpID, }; this.worker = fork(mainScript , [ `--server-id-${server.serverID}` ], { env, execArgv, }); this.worker.on("exit", () => { console.error(`Worker exited for virtual server ${server.serverID}`); ClusterWebWorker.virtualWorkers.delete(server.serverID); this.initialized = null; }); this.worker.on("error", (e) => { console.error(e); this.dispose(); }); process.on(SIGTERM,this.dispose); await new Promise((resolve, reject) => { this.worker.on("message", (msg: any) => { if (msg.cmd === "ready") { resolve(); } }); }); })(); } async killWorker() { try { try { await unlink(this.socket); // @ts-expect-error readonly delete this.socket; } catch { } try { await unlink(this.smtpSocket); // @ts-expect-error readonly delete this.smtpSocket; } catch { } const worker = this.worker; await new Promise((resolve) => { const timeout = setTimeout(() => { worker.kill("SIGKILL"); }, 1000); worker.on("exit", () => { clearTimeout(timeout); resolve(); }); worker.kill(); }); if(this.socket) { await unlink(this.socket); } if(this.smtpSocket) { await unlink(this.smtpSocket); } } catch { } } }