Files
cloudron-box/src/asynctask.js
T

48 lines
1.1 KiB
JavaScript
Raw Normal View History

import debugModule from 'debug';
import EventEmitter from 'node:events';
import safe from 'safetydance';
2025-07-16 23:09:06 +02:00
const debug = debugModule('box:asynctask');
2025-07-16 23:09:06 +02:00
// this runs in-process
class AsyncTask extends EventEmitter {
2025-07-17 01:16:24 +02:00
name;
2025-07-16 23:09:06 +02:00
#abortController;
constructor(name) {
super();
2025-07-17 01:16:24 +02:00
this.name = name;
2025-07-16 23:09:06 +02:00
this.#abortController = new AbortController();
}
async _run(/*signal*/) {
// subclasses implement this
}
2025-10-10 16:26:37 +02:00
async start() { // should not throw!
2025-07-17 01:16:24 +02:00
debug(`start: ${this.name} started`);
2025-10-10 16:26:37 +02:00
const [error] = await safe(this._run(this.#abortController.signal));
2025-07-17 01:16:24 +02:00
debug(`start: ${this.name} finished`);
this.emit('done', { errorMessage: error?.message || '' });
this.#abortController = null;
2025-07-16 23:09:06 +02:00
}
stop() {
2025-07-17 01:16:24 +02:00
if (this.#abortController === null) return; // already finished
debug(`stop: ${this.name} . sending abort signal`);
2025-07-16 23:09:06 +02:00
this.#abortController.abort();
}
emitProgress(percent, message) {
this.emit('data', 'progress', { percent, message });
}
emitData(obj) {
this.emit('data', 'data', obj);
}
}
2026-02-14 15:43:24 +01:00
export default {
2025-07-16 23:09:06 +02:00
AsyncTask
};