snowflakify
Version:
The most complete Snowflake ID generator in TypeScript
62 lines • 2.15 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const path_1 = require("path");
const worker_threads_1 = require("worker_threads");
const CLEANUP_EVENTS = [
'exit',
'uncaughtException',
'SIGINT',
'SIGQUIT',
'SIGUSR1',
'SIGUSR2',
];
class CircularBufferRefiller {
constructor(buffer, generatorOptions, workerCount = 2) {
this.buffer = buffer;
this.generatorOptions = generatorOptions;
this.workerCount = workerCount;
this.workers = [];
if (typeof workerCount !== 'number')
throw new TypeError('[WORKER_COUNT_INVALID_TYPE]: Worker count must be a number.');
if (workerCount < 1)
throw new Error('[WORKER_COUNT_INVALID]: Worker count must be greater than 0');
this.isRefillingSAB = new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT);
this.isRefillingTa = new Int32Array(this.isRefillingSAB);
Atomics.store(this.isRefillingTa, 0, 0);
for (let i = 0; i < this.workerCount; i += 1) {
this.workers.push(this.createWorker());
}
for (const event of CLEANUP_EVENTS) {
process.on(event, () => this.cleanup());
}
}
refill() {
Atomics.store(this.isRefillingTa, 0, 1);
for (const worker of this.workers) {
worker.postMessage('refill');
}
}
isRefilling() {
return Atomics.load(this.isRefillingTa, 0) === 1;
}
createWorker() {
const workerFilePath = __filename.endsWith('ts')
? 'workerProxyForTs.js'
: 'worker.js';
const worker = new worker_threads_1.Worker((0, path_1.resolve)((0, path_1.dirname)(workerFilePath)), {
workerData: {
buffer: this.buffer,
generatorOptions: this.generatorOptions,
isRefillingSAB: this.isRefillingSAB,
},
});
return worker;
}
cleanup() {
for (const worker of this.workers) {
worker.terminate();
}
}
}
exports.default = CircularBufferRefiller;
//# sourceMappingURL=CircularBufferRefiller.js.map