mirror of
https://github.com/blitzkit/blitzkit.git
synced 2026-10-21 18:57:03 +02:00
feat: render threading
This commit is contained in:
1 parent
9495ae2336
commit
6fdd4ba833
7 files changed
+73
-5
No files matched your search
@@ -0,0 +1,9 @@
|
||||
import jsxToSvg from './jsxToSvg';
|
||||
import { svgToPngThreaded } from './svgToPngThreaded';
|
||||
|
||||
export default async function jsxToPngThreaded(jsx: JSX.Element) {
|
||||
const svg = await jsxToSvg(jsx);
|
||||
const png = await svgToPngThreaded(svg);
|
||||
|
||||
return png;
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { Worker } from 'worker_threads';
|
||||
|
||||
const MAX_WORKERS = 3;
|
||||
|
||||
const workers = [...Array(MAX_WORKERS)].map(() => {
|
||||
const worker = new Worker(`${__dirname}/workers/render.cjs`);
|
||||
console.log(`🟡 Launching render worker ${worker.threadId}`);
|
||||
return worker;
|
||||
});
|
||||
const queue: {
|
||||
svg: string;
|
||||
resolve: (png: Buffer) => void;
|
||||
}[] = [];
|
||||
|
||||
function manageQueue() {
|
||||
if (queue.length > 0 && workers.length > 0) {
|
||||
const { svg, resolve } = queue.shift()!;
|
||||
const worker = workers.shift()!;
|
||||
|
||||
function cleanup() {
|
||||
workers.push(worker);
|
||||
manageQueue();
|
||||
}
|
||||
|
||||
worker.postMessage(svg);
|
||||
worker.on('message', (png: Uint8Array) => {
|
||||
cleanup();
|
||||
resolve(Buffer.from(png));
|
||||
});
|
||||
worker.on('error', (error) => {
|
||||
cleanup();
|
||||
throw error;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export function svgToPngThreaded(svg: string) {
|
||||
return new Promise<Buffer>((resolve) => {
|
||||
queue.push({ svg, resolve });
|
||||
manageQueue();
|
||||
});
|
||||
}
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
InteractionEditReplyOptions,
|
||||
} from 'discord.js';
|
||||
import { InteractionReturnable } from '../../events/interactionCreate';
|
||||
import jsxToPng from '../blitzkrieg/jsxToPng';
|
||||
import jsxToPngThreaded from '../blitzkrieg/jsxToPngThreaded';
|
||||
|
||||
export default async function normalizeInteractionReturnable(
|
||||
returnable: InteractionReturnable,
|
||||
@@ -37,7 +37,7 @@ export default async function normalizeInteractionReturnable(
|
||||
} else if (item === null) {
|
||||
return;
|
||||
} else {
|
||||
const image = await jsxToPng(item);
|
||||
const image = await jsxToPngThreaded(item);
|
||||
if (!reply.files) reply.files = [];
|
||||
reply.files.push(image);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user