snowflakify
Version:
The most complete Snowflake ID generator in TypeScript
62 lines (61 loc) • 1.81 kB
JavaScript
import { resolve, dirname } from 'path';
import { Worker } from 'worker_threads';
const CLEANUP_EVENTS = [
'exit',
'uncaughtException',
'SIGINT',
'SIGQUIT',
'SIGUSR1',
'SIGUSR2',
];
export default 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(resolve(dirname(workerFilePath)), {
workerData: {
buffer: this.buffer,
generatorOptions: this.generatorOptions,
isRefillingSAB: this.isRefillingSAB,
},
});
return worker;
}
cleanup() {
for (const worker of this.workers) {
worker.terminate();
}
}
}
//# sourceMappingURL=CircularBufferRefiller.js.map