UNPKG

uid-pool

Version:

High-performance UUID and unique ID pooling for Node.js. Pre-generate IDs in background worker threads for O(1) synchronous acquisition. Drop-in replacement for uuid.v4() and nanoid() with 10-100x better performance under load.

80 lines 3 kB
import { BaseIdPool } from "../core/pool.js"; /** * Edge runtime implementation of IdPool. * Uses chunked generation on main thread since worker threads are not available. */ export class IdPool extends BaseIdPool { refillTimeout = null; pendingRefill = null; constructor(options) { // Force useWorker to false for edge runtime super({ ...options, useWorker: false }); } /** * Create a new IdPool instance that is ready for use. */ static async create(options) { const pool = new IdPool(options); await pool.initialize(); return pool; } startInternal() { // No special initialization needed for edge runtime } async stopInternal() { if (this.refillTimeout) { clearTimeout(this.refillTimeout); this.refillTimeout = null; } if (this.pendingRefill) { await this.pendingRefill; } } async triggerRefill() { // Avoid multiple concurrent refills if (this.pendingRefill) { return this.pendingRefill; } // Create and track the refill promise this.pendingRefill = this.doRefill(); // Clean up after completion this.pendingRefill.finally(() => { this.pendingRefill = null; }); // Return the promise return this.pendingRefill; } async doRefill() { const needed = this.buffer.getAvailableSpace(); const toGenerate = Math.min(needed, this.options.refillBatchSize); if (toGenerate <= 0) { return; } const startTime = Date.now(); try { const ids = await this.generateInChunks(toGenerate); const duration = Date.now() - startTime; this.addToBuffer(ids, duration); } catch (error) { this.emit("error", error); } } async generateInChunks(count) { const ids = []; const chunkSize = 5; // Smaller chunks for edge runtime for (let i = 0; i < count; i += chunkSize) { const batchSize = Math.min(chunkSize, count - i); const batch = await this.generateIds(batchSize); ids.push(...batch); // Yield to event loop if (i + chunkSize < count) { await new Promise((resolve) => setTimeout(resolve, 0)); } } return ids; } } // Re-export error classes for convenience export { IdPoolError, InvalidConfigurationError, InvalidGeneratorError, InvalidPoolSizeError, InvalidMinSizeError, InvalidRefillBatchSizeError, InvalidCapacityError, PoolEmptyError, PoolNotReadyError, PoolStoppedError, PoolTimeoutError, GeneratorFailureError, InvalidGeneratorOutputError, WorkerNotInitializedError, WorkerTimeoutError, WorkerCrashError, WorkerGenerationError, SerializationError, ResourceExhaustionError, InvalidRuntimeError, } from "../core/errors.js"; //# sourceMappingURL=index.js.map