Reduce plugin runtime memory

This commit is contained in:
Gregory Schier
2025-02-24 12:20:47 -08:00
parent 9d5f7784c4
commit c8d6183456
11 changed files with 660 additions and 648 deletions

View File

@@ -1,56 +1,28 @@
import type { BootRequest, InternalEvent } from '@yaakapp/api';
import path from 'node:path';
import { Worker } from 'node:worker_threads';
import type { EventChannel } from './EventChannel';
import type { PluginWorkerData } from './index.worker';
import { PluginInstance, PluginWorkerData } from './PluginInstance';
export class PluginHandle {
#worker: Worker;
#instance: PluginInstance;
constructor(
readonly pluginRefId: string,
readonly bootRequest: BootRequest,
readonly events: EventChannel,
readonly pluginToAppEvents: EventChannel,
) {
this.#worker = this.#createWorker();
}
sendToWorker(event: InternalEvent) {
this.#worker.postMessage(event);
}
async terminate() {
await this.#worker.terminate();
}
#createWorker(): Worker {
const workerPath = process.env.YAAK_WORKER_PATH ?? path.join(__dirname, 'index.worker.cjs');
const workerData: PluginWorkerData = {
pluginRefId: this.pluginRefId,
bootRequest: this.bootRequest,
};
const worker = new Worker(workerPath, {
workerData,
});
worker.on('message', (e) => this.events.emit(e));
worker.on('error', this.#handleError.bind(this));
worker.on('exit', this.#handleExit.bind(this));
this.#instance = new PluginInstance(workerData, pluginToAppEvents);
console.log('Created plugin worker for ', this.bootRequest.dir);
return worker;
}
async #handleError(err: Error) {
console.error('Plugin errored', this.bootRequest.dir, err);
sendToWorker(event: InternalEvent) {
this.#instance.postMessage(event);
}
async #handleExit(code: number) {
if (code === 0) {
console.log('Plugin exited successfully', this.bootRequest.dir);
} else {
console.log('Plugin exited with status', code, this.bootRequest.dir);
}
terminate() {
this.#instance.terminate();
}
}