### Install and Start NestJS Application Source: https://github.com/btwld/nestjs-worker/blob/main/examples/basic-usage/README.md Run these commands to install dependencies and start the NestJS application. ```bash npm install npm run start ``` -------------------------------- ### Install nestjs-worker Source: https://github.com/btwld/nestjs-worker/blob/main/README.md Install the library using npm, yarn, or pnpm. Requires Node.js version 18.0.0 or higher. ```bash npm install nestjs-worker # or yarn add nestjs-worker # or pnpm add nestjs-worker ``` -------------------------------- ### Worker Monitoring Service Example Source: https://github.com/btwld/nestjs-worker/blob/main/README.md Inject `WorkerManager` into a service to access worker statistics and pool information programmatically. ```typescript @Injectable() export class MonitoringService { constructor(private readonly workerManager: WorkerManager) {} async getWorkerStats() { return this.workerManager.getStatistics(); } async getWorkerPoolInfo(workerClass: Type) { return this.workerManager.getWorkerPoolInfo(workerClass); } } ``` -------------------------------- ### `WorkerModule.forRoot(options)` - Synchronous Module Registration Source: https://context7.com/btwld/nestjs-worker/llms.txt Registers the `WorkerModule` globally, initializing essential services like `WorkerConfigService` and `WorkerManager`. This method allows for synchronous configuration of worker pools and options. ```APIDOC ## `WorkerModule.forRoot(options)` — synchronous module registration Registers the module globally, initialises `WorkerConfigService`, `WorkerManager`, `WorkerDiscoveryService`, and (optionally) explicit worker class providers. Exported providers are available application-wide because `global: true` is set on the returned `DynamicModule`. ```typescript // app.module.ts import { Module } from '@nestjs/common'; import { WorkerModule } from 'nestjs-worker'; import { CryptoWorker } from './workers/crypto.worker'; import { DataProcessingWorker } from './workers/data-processing.worker'; @Module({ imports: [ WorkerModule.forRoot({ global: { defaultMinInstances: 1, defaultMaxInstances: 4, defaultTimeout: 30_000, defaultAutoRestart: true, defaultRestartDelay: 1000, defaultMaxRestartAttempts: 3, healthCheckInterval: 10_000, // ping unhealthy threads every 10 s workerIdleTimeout: 60_000, // terminate idle threads after 1 min debug: false, }, workers: [ { workerClass: CryptoWorker, options: { minInstances: 2, maxInstances: 8, timeout: 60_000 }, }, { workerClass: DataProcessingWorker, options: { minInstances: 1, maxInstances: 4 }, }, ], autoDiscovery: true, // scan all providers for @Worker classes }), ], }) export class AppModule {} ``` ``` -------------------------------- ### `WorkerModule.forRootAsync(options)` - Asynchronous Module Registration Source: https://context7.com/btwld/nestjs-worker/llms.txt Supports asynchronous configuration of the `WorkerModule` using factory functions, `useClass`, or `useExisting` patterns. This is ideal for loading configuration from environment variables or other async sources. ```APIDOC ## `WorkerModule.forRootAsync(options)` — async module registration Supports factory functions, `useClass`, and `useExisting` patterns for loading configuration from environment variables, `ConfigService`, or any other async source. Follows the standard NestJS async module pattern. ```typescript // app.module.ts — config-driven async registration import { Module } from '@nestjs/common'; import { ConfigModule, ConfigService } from '@nestjs/config'; import { WorkerModule } from 'nestjs-worker'; @Module({ imports: [ ConfigModule.forRoot(), WorkerModule.forRootAsync({ imports: [ConfigModule], inject: [ConfigService], useFactory: (config: ConfigService) => ({ global: { defaultMaxInstances: config.get('WORKER_MAX_INSTANCES', 4), defaultTimeout: config.get('WORKER_TIMEOUT_MS', 30_000), debug: config.get('NODE_ENV') !== 'production', }, autoDiscovery: true, }), }), ], }) export class AppModule {} // Alternative: useClass pattern class WorkerOptionsFactory { async createWorkerOptions() { return { global: { defaultMaxInstances: 8, debug: true }, }; } } WorkerModule.forRootAsync({ useClass: WorkerOptionsFactory }); ``` ``` -------------------------------- ### Generate Key Pair with CryptoWorker Source: https://github.com/btwld/nestjs-worker/blob/main/examples/basic-usage/README.md Use this cURL command to request a key pair generation from the /crypto/keypair endpoint. ```bash curl -X POST http://localhost:3000/crypto/keypair ``` -------------------------------- ### Global Worker Configuration Options Source: https://github.com/btwld/nestjs-worker/blob/main/README.md Configure global settings for the `WorkerModule` using `forRoot`. This includes default instance management, timeouts, auto-restart behavior, and health check intervals. ```typescript WorkerModule.forRoot({ global: { defaultMinInstances: 1, defaultMaxInstances: 4, defaultTimeout: 30000, defaultAutoRestart: true, defaultRestartDelay: 1000, defaultMaxRestartAttempts: 3, healthCheckInterval: 10000, workerIdleTimeout: 60000, debug: false, }, autoDiscovery: true, }); ``` -------------------------------- ### Configure WorkerModule Source: https://github.com/btwld/nestjs-worker/blob/main/README.md Configure the `WorkerModule` using `forRoot` for global settings and `forFeature` to register specific workers. Options include default instance counts, timeouts, and worker-specific configurations. ```typescript import { Module } from "@nestjs/common"; import { WorkerModule } from "nestjs-worker"; import { ImageProcessingWorker } from "./workers/image-processing.worker"; @Module({ imports: [ WorkerModule.forRoot({ global: { defaultMinInstances: 1, defaultMaxInstances: 4, defaultTimeout: 30000, debug: true, }, workers: [ { workerClass: ImageProcessingWorker, options: { minInstances: 2, maxInstances: 6, }, }, ], }), WorkerModule.forFeature([ImageProcessingWorker]), ], // ... rest of your module }) export class AppModule {} ``` -------------------------------- ### Synchronous WorkerModule Registration with forRoot Source: https://context7.com/btwld/nestjs-worker/llms.txt Register the WorkerModule globally using `forRoot` to initialize core services and optionally provide explicit worker classes. This makes exported providers available application-wide. ```typescript // app.module.ts import { Module } from '@nestjs/common'; import { WorkerModule } from 'nestjs-worker'; import { CryptoWorker } from './workers/crypto.worker'; import { DataProcessingWorker } from './workers/data-processing.worker'; @Module({ imports: [ WorkerModule.forRoot({ global: { defaultMinInstances: 1, defaultMaxInstances: 4, defaultTimeout: 30_000, defaultAutoRestart: true, defaultRestartDelay: 1000, defaultMaxRestartAttempts: 3, healthCheckInterval: 10_000, // ping unhealthy threads every 10 s workerIdleTimeout: 60_000, // terminate idle threads after 1 min debug: false, }, workers: [ { workerClass: CryptoWorker, options: { minInstances: 2, maxInstances: 8, timeout: 60_000 }, }, { workerClass: DataProcessingWorker, options: { minInstances: 1, maxInstances: 4 }, }, ], autoDiscovery: true, // scan all providers for @Worker classes }), ], }) export class AppModule {} ``` -------------------------------- ### Configure Worker Module with Specific Worker Settings Source: https://github.com/btwld/nestjs-worker/blob/main/README.md Use `WorkerModule.forRoot` to configure worker pools with specific instance counts, timeouts, and names for each worker class. ```typescript WorkerModule.forRoot({ workers: [ { workerClass: MyWorker, options: { minInstances: 2, maxInstances: 8, timeout: 60000, name: "CustomWorkerName", }, }, ], }); ``` -------------------------------- ### Asynchronous WorkerModule Registration with forRootAsync Source: https://context7.com/btwld/nestjs-worker/llms.txt Use `forRootAsync` for asynchronous module registration, supporting factory functions, `useClass`, and `useExisting` patterns. This allows configuration to be loaded from async sources like `ConfigService`. ```typescript // app.module.ts — config-driven async registration import { Module } from '@nestjs/common'; import { ConfigModule, ConfigService } from '@nestjs/config'; import { WorkerModule } from 'nestjs-worker'; @Module({ imports: [ ConfigModule.forRoot(), WorkerModule.forRootAsync({ imports: [ConfigModule], inject: [ConfigService], useFactory: (config: ConfigService) => ({ global: { defaultMaxInstances: config.get('WORKER_MAX_INSTANCES', 4), defaultTimeout: config.get('WORKER_TIMEOUT_MS', 30_000), debug: config.get('NODE_ENV') !== 'production', }, autoDiscovery: true, }), }), ], }) export class AppModule {} ``` ```typescript // Alternative: useClass pattern class WorkerOptionsFactory { async createWorkerOptions() { return { global: { defaultMaxInstances: 8, debug: true }, }; } } WorkerModule.forRootAsync({ useClass: WorkerOptionsFactory }); ``` -------------------------------- ### WorkerDiscoveryService for Auto-Discovery and Dynamic Registration Source: https://context7.com/btwld/nestjs-worker/llms.txt Utilize `WorkerDiscoveryService` to scan for `@Worker`-decorated classes, register their metadata, and initialize pools. Supports dynamic registration at runtime. ```typescript import { Injectable, OnModuleInit } from '@nestjs/common'; import { WorkerDiscoveryService } from 'nestjs-worker'; import { DynamicWorker } from './dynamic.worker'; @Injectable() export class WorkerBootstrapService implements OnModuleInit { constructor(private readonly discovery: WorkerDiscoveryService) {} async onModuleInit() { // Inspect what was discovered automatically const stats = this.discovery.getDiscoveryStatistics(); // { totalWorkers: 3, initializedPools: 3, totalMethods: 9 } console.log('Worker discovery stats:', stats); // Dynamically register a worker that was not present at startup if (!this.discovery.isRegisteredWorker(DynamicWorker)) { await this.discovery.registerWorker(DynamicWorker); console.log('DynamicWorker registered at runtime'); } // List all discovered worker classes const workers = this.discovery.getDiscoveredWorkers(); workers.forEach((w) => { const meta = this.discovery.getWorkerMetadata(w); console.log(`${w.name}: ${meta?.methods.size} methods`); }); } } ``` -------------------------------- ### Provide a Custom Worker Runtime Script Source: https://github.com/btwld/nestjs-worker/blob/main/README.md Configure the `customWorkerScript` option in `WorkerModule.forRoot` to use a custom script for the worker runtime environment. ```typescript WorkerModule.forRoot({ customWorkerScript: "./custom-worker-runtime.js", }); ``` -------------------------------- ### Hash Data with CryptoWorker Source: https://github.com/btwld/nestjs-worker/blob/main/examples/basic-usage/README.md Use this cURL command to send JSON data to the /crypto/hash endpoint for hashing. ```bash curl -X POST http://localhost:3000/crypto/hash \ -H "Content-Type: application/json" \ -d '{"input": "hello world"}' ``` -------------------------------- ### Register Worker Classes with WorkerModule.forFeature Source: https://context7.com/btwld/nestjs-worker/llms.txt Register worker classes in a feature module to create `WorkerProxy` providers. Ensure worker classes are also registered as providers for discovery. ```typescript import { Module } from '@nestjs/common'; import { WorkerModule } from 'nestjs-worker'; import { CryptoWorker } from './crypto.worker'; import { FeatureService } from './feature.service'; @Module({ imports: [ WorkerModule.forFeature([CryptoWorker]), ], providers: [FeatureService], exports: [FeatureService], }) export class FeatureModule {} ``` ```typescript import { Injectable } from '@nestjs/common'; import { InjectWorker } from 'nestjs-worker'; import { CryptoWorker } from './crypto.worker'; @Injectable() export class FeatureService { constructor( @InjectWorker(CryptoWorker) private readonly crypto: CryptoWorker, ) {} async signPayload(data: string): Promise { return this.crypto.hashData(data); } } ``` -------------------------------- ### Configure Worker Module Asynchronously Source: https://github.com/btwld/nestjs-worker/blob/main/README.md Use `WorkerModule.forRootAsync` for asynchronous configuration, allowing injection of services like `ConfigService` to determine global worker settings. ```typescript WorkerModule.forRootAsync({ useFactory: async (configService: ConfigService) => ({ global: { defaultMaxInstances: configService.get("WORKER_MAX_INSTANCES"), defaultTimeout: configService.get("WORKER_TIMEOUT"), }, }), inject: [ConfigService], }); ``` -------------------------------- ### Enable Debug Logging for Worker Module Source: https://github.com/btwld/nestjs-worker/blob/main/README.md Enable debug logging for the Worker module by setting the `debug` option to `true` within the global configuration of `WorkerModule.forRoot`. ```typescript WorkerModule.forRoot({ global: { debug: true, }, }); ``` -------------------------------- ### Define File Processing Worker with Methods Source: https://github.com/btwld/nestjs-worker/blob/main/README.md Define a worker class for file processing tasks, setting instance constraints and configuring worker methods with specific timeouts. ```typescript @Worker({ minInstances: 1, maxInstances: 3 }) export class FileProcessingWorker { @WorkerMethod({ timeout: 25000 }) async parseCSV(csvContent: string): Promise { // CSV parsing and validation } @WorkerMethod({ timeout: 15000 }) async processDocument(document: Buffer): Promise { // Document processing } } ``` -------------------------------- ### Type Narrowing and Debugging with WorkerProxy Source: https://context7.com/btwld/nestjs-worker/llms.txt Use static methods on `WorkerProxy` for type checking and retrieving worker information. `isWorkerProxy` checks if an object is a proxy, and `getWorkerClass` retrieves the underlying worker class. `getWorkerInfo` provides live pool statistics without needing to inject `WorkerManager`. ```typescript import { WorkerProxy } from 'nestjs-worker'; import { CryptoWorker } from './workers/crypto.worker'; // Check whether an injected value is a proxy (useful in interceptors / guards) function assertIsProxy(injected: unknown): void { if (!WorkerProxy.isWorkerProxy(injected)) { throw new Error('Expected a WorkerProxy, got a plain instance'); } } // Retrieve the underlying worker class from a proxy object function getWorkerName(proxy: unknown): string { const cls = WorkerProxy.getWorkerClass(proxy); return cls?.name ?? 'unknown'; } // Retrieve live pool info through the proxy (no WorkerManager injection needed) async function logPoolInfo(proxy: CryptoWorker): Promise { const info = WorkerProxy.getWorkerInfo(proxy); // Same shape as WorkerManager.getWorkerPoolInfo(CryptoWorker) console.log('Pool info via proxy:', info); } ``` -------------------------------- ### Instantiating and Using WorkerPool Directly Source: https://context7.com/btwld/nestjs-worker/llms.txt For advanced use cases like testing outside of NestJS DI, `WorkerPool` can be instantiated directly. It manages worker instances, auto-scaling, and health checks. Methods like `execute` allow direct task execution, and properties like `instanceCount` and `info` provide pool status. ```typescript // Advanced: instantiate a WorkerPool outside of NestJS DI for testing import { WorkerPool } from 'nestjs-worker'; // exported via lib/managers/worker-pool import { CryptoWorker } from './workers/crypto.worker'; const pool = new WorkerPool(CryptoWorker, { minInstances: 1, maxInstances: 2, timeout: 10_000, autoRestart: true, restartDelay: 500, maxRestartAttempts: 2, }); // Execute a method directly on the pool (bypasses NestJS proxy) const result = await pool.execute('hashData', ['hello-world'], { timeout: 5_000, retries: 1, priority: 'normal', }); console.log('Hash:', result); // '3b4c...' // Inspect the pool console.log('Instances:', pool.instanceCount); // 1 console.log('Available:', pool.availableInstanceCount); // 1 console.log('Info:', pool.info); // { // workerClass: [Function: CryptoWorker], // instances: [{ id, status: 'idle', executionCount: 1, errorCount: 0, ... }], // totalExecutions: 1, // totalErrors: 0, // averageExecutionTime: 42 // } // Graceful shutdown — terminates all thread instances await pool.shutdown(); ``` -------------------------------- ### WorkerModule Configuration Source: https://github.com/btwld/nestjs-worker/blob/main/README.md Configures the WorkerModule globally or for specific features, allowing for default settings and explicit worker definitions. ```APIDOC ## WorkerModule Configuration ### Global Configuration ```typescript WorkerModule.forRoot({ global: { defaultMinInstances: 1, defaultMaxInstances: 4, defaultTimeout: 30000, defaultAutoRestart: true, defaultRestartDelay: 1000, defaultMaxRestartAttempts: 3, healthCheckInterval: 10000, workerIdleTimeout: 60000, debug: false, }, autoDiscovery: true, }); ``` ``` -------------------------------- ### Log Worker Statistics Source: https://github.com/btwld/nestjs-worker/blob/main/README.md Retrieve and log general worker statistics such as total executions, errors, and average execution time using the `workerManager`. ```typescript const stats = workerManager.getStatistics(); console.log("Total executions:", stats.totalExecutions); console.log("Total errors:", stats.totalErrors); console.log("Average execution time:", stats.averageExecutionTime); ``` -------------------------------- ### Log Worker Pool Information Source: https://github.com/btwld/nestjs-worker/blob/main/README.md Retrieve and log details about a specific worker pool, including the number of active and available instances, using `workerManager.getWorkerPoolInfo`. ```typescript const poolInfo = workerManager.getWorkerPoolInfo(MyWorker); console.log("Active instances:", poolInfo.instances.length); console.log( "Available instances:", poolInfo.instances.filter((i) => i.status === "idle").length ); ``` -------------------------------- ### Accessing Worker Configuration with WorkerConfigService Source: https://context7.com/btwld/nestjs-worker/llms.txt Inject `WorkerConfigService` to access global and worker-specific configurations. Use `getGlobalConfig` for overall settings and `getWorkerOptions` for specific worker configurations, which merges defaults, global settings, and worker-specific options. `isDebugEnabled` and `getHealthCheckInterval` provide quick access to common settings. ```typescript import { Injectable } from '@nestjs/common'; import { WorkerConfigService } from 'nestjs-worker'; import { CryptoWorker } from './workers/crypto.worker'; @Injectable() export class ConfigInspectorService { constructor(private readonly config: WorkerConfigService) {} inspect() { const global = this.config.getGlobalConfig(); // { // defaultMinInstances: 1, defaultMaxInstances: 4, // defaultTimeout: 30000, healthCheckInterval: 10000, // workerIdleTimeout: 60000, debug: false, ... // } const effective = this.config.getWorkerOptions(CryptoWorker, { minInstances: 2, }); // Merges: DEFAULT_WORKER_OPTIONS → global defaults → worker-specific config → passed baseOptions const debugEnabled = this.config.isDebugEnabled(); // false const healthInterval = this.config.getHealthCheckInterval(); // 10000 return { global, effective, debugEnabled, healthInterval }; } // Temporarily increase thread limits under load scaleUp() { this.config.updateGlobalConfig({ defaultMaxInstances: 16, defaultTimeout: 60_000, }); } } ``` -------------------------------- ### Define Image Processing Worker with Methods Source: https://github.com/btwld/nestjs-worker/blob/main/README.md Define a worker class for image processing using the `@Worker` decorator and specify worker methods with their configurations like `timeout` and `retries`. ```typescript @Worker({ minInstances: 2, maxInstances: 6 }) export class ImageProcessingWorker { @WorkerMethod({ timeout: 15000, retries: 2 }) async resizeImage( buffer: Buffer, width: number, height: number ): Promise { // CPU-intensive image resizing } @WorkerMethod({ timeout: 10000 }) async compressImage(buffer: Buffer, quality: number): Promise { // Image compression } } ``` -------------------------------- ### Worker Decorator Source: https://github.com/btwld/nestjs-worker/blob/main/README.md Marks a class as a worker that can execute methods in worker threads. It allows configuration of worker pool size, timeouts, and restart behavior. ```APIDOC ## @Worker(options) Marks a class as a worker that can execute methods in worker threads. **Options:** - `name?: string` - Worker name for identification - `minInstances?: number` - Minimum worker instances (default: 1) - `maxInstances?: number` - Maximum worker instances (default: 4) - `timeout?: number` - Default timeout in milliseconds (default: 30000) - `autoRestart?: boolean` - Auto-restart failed workers (default: true) - `restartDelay?: number` - Delay before restart in milliseconds (default: 1000) - `maxRestartAttempts?: number` - Maximum restart attempts (default: 3) ``` -------------------------------- ### Define Data Processing Worker with Methods Source: https://github.com/btwld/nestjs-worker/blob/main/README.md Define a worker class for data processing, specifying instance limits and configuring individual worker methods with timeouts and retry strategies. ```typescript @Worker({ minInstances: 1, maxInstances: 4 }) export class DataProcessingWorker { @WorkerMethod({ timeout: 30000 }) async processLargeDataset(data: any[]): Promise { // Heavy data processing } @WorkerMethod({ timeout: 20000, retries: 1 }) async performAnalytics(data: any[]): Promise { // Complex analytics calculations } } ``` -------------------------------- ### WorkerManager for Pool Orchestration and Statistics Source: https://context7.com/btwld/nestjs-worker/llms.txt Use the `WorkerManager` service to manage worker pools, retrieve statistics, and control pool lifecycle. Implements `OnModuleDestroy` for graceful shutdown. ```typescript import { Injectable, Controller, Get } from '@nestjs/common'; import { WorkerManager } from 'nestjs-worker'; import { CryptoWorker } from './workers/crypto.worker'; @Controller('admin/workers') export class WorkerAdminController { constructor(private readonly workerManager: WorkerManager) {} @Get('stats') getStats() { // Aggregate statistics across all pools const stats = this.workerManager.getStatistics(); // { // totalPools: 2, // totalInstances: 6, // totalExecutions: 1042, // totalErrors: 3, // averageExecutionTime: 254.7 // ms // } return stats; } @Get('pool/crypto') getCryptoPoolInfo() { const info = this.workerManager.getWorkerPoolInfo(CryptoWorker); // { // workerClass: [Function: CryptoWorker], // options: { minInstances: 2, maxInstances: 8, timeout: 60000, ... }, // instances: [ // { id: 'uuid', status: 'idle', executionCount: 312, errorCount: 0, ... }, // { id: 'uuid', status: 'busy', executionCount: 288, errorCount: 1, ... }, // ], // totalExecutions: 600, // totalErrors: 1, // averageExecutionTime: 312.4 // } return info; } @Get('health') async health() { const allPools = this.workerManager.getAllWorkerPoolsInfo(); const healthy = allPools.every((p) => p.totalErrors === 0); return { status: healthy ? 'healthy' : 'degraded', pools: allPools }; } // Manually shut down and restart a specific pool (e.g. after config change) async restartCryptoPool() { await this.workerManager.shutdownWorkerPool(CryptoWorker); await this.workerManager.initializeWorkerPool(CryptoWorker); } } ``` -------------------------------- ### WorkerMethod Decorator Source: https://github.com/btwld/nestjs-worker/blob/main/README.md Marks a method within a worker class as executable in a worker thread. It supports configuring method-specific timeouts, retries, and execution priority. ```APIDOC ## @WorkerMethod(options) Marks a method as executable in a worker thread. **Options:** - `timeout?: number` - Method-specific timeout - `retries?: number` - Number of retry attempts (default: 0) - `priority?: 'low' | 'normal' | 'high'` - Execution priority (default: 'normal') - `serialize?: boolean` - Whether to serialize the result (default: true) ``` -------------------------------- ### Worker Health Check Controller Source: https://github.com/btwld/nestjs-worker/blob/main/README.md Implement a health check endpoint using `WorkerManager` to report the overall health status of workers based on error counts. ```typescript @Controller("health") export class HealthController { constructor(private readonly workerManager: WorkerManager) {} @Get("workers") async checkWorkerHealth() { const stats = this.workerManager.getStatistics(); return { status: stats.totalErrors === 0 ? "healthy" : "degraded", workers: stats, }; } } ``` -------------------------------- ### `@InjectWorker(WorkerClass)` - Parameter Decorator Source: https://context7.com/btwld/nestjs-worker/llms.txt Injects a `WorkerProxy` instance that dispatches calls to the thread pool via `WorkerManager.executeWorkerMethod`. This allows you to use worker threads seamlessly within your NestJS services. ```APIDOC ## `@InjectWorker(WorkerClass)` — parameter decorator Injects a `WorkerProxy` instance keyed by the token `Symbol(worker:inject)_`. The proxy exposes the same method signatures as the original class but dispatches calls to the thread pool via `WorkerManager.executeWorkerMethod`. ```typescript import { Injectable } from '@nestjs/common'; import { InjectWorker } from 'nestjs-worker'; import { CryptoWorker } from './crypto.worker'; import { DataProcessingWorker } from './data-processing.worker'; @Injectable() export class AppService { constructor( @InjectWorker(CryptoWorker) private readonly crypto: CryptoWorker, @InjectWorker(DataProcessingWorker) private readonly dataProcessor: DataProcessingWorker, ) {} async onboardUser(userId: string): Promise<{ hash: string; keys: object }> { // Both calls run concurrently in separate worker threads const [hash, keys] = await Promise.all([ this.crypto.hashData(userId), this.crypto.generateKeyPair(), ]); return { hash, keys }; } async processReport(rows: number[]): Promise<{ sum: number; avg: number }> { try { return await this.dataProcessor.aggregateMetrics(rows); } catch (err) { // worker errors are re-thrown with original .name and .stack preserved console.error('Worker failed:', err.message); throw err; } } } ``` ``` -------------------------------- ### @Worker decorator Source: https://context7.com/btwld/nestjs-worker/llms.txt Marks a class as a worker that executes in separate Node.js worker_threads. It configures thread pool options like min/max instances, timeouts, and auto-restart behavior. ```APIDOC ## @Worker(options) — class decorator Marks a class as a worker that executes in separate Node.js `worker_threads`. Internally calls `@Injectable()` and attaches `WorkerMetadata` via `Reflect.defineMetadata`. All options default to `DEFAULT_WORKER_OPTIONS` (`minInstances: 1`, `maxInstances: 4`, `timeout: 30000`, `autoRestart: true`, `restartDelay: 1000`, `maxRestartAttempts: 3`). ```typescript import { Worker, WorkerMethod } from 'nestjs-worker'; // crypto.worker.ts — CPU-intensive RSA key generation offloaded to a thread @Worker({ name: 'CryptoWorker', minInstances: 2, // keep 2 warm threads at all times maxInstances: 8, // allow bursting to 8 threads under load timeout: 60000, // default 60 s for all methods in this worker autoRestart: true, restartDelay: 2000, maxRestartAttempts: 5, }) export class CryptoWorker { @WorkerMethod({ timeout: 60000, retries: 1 }) async generateKeyPair(): Promise<{ publicKey: string; privateKey: string }> { const { generateKeyPairSync } = await import('crypto'); const { publicKey, privateKey } = generateKeyPairSync('rsa', { modulusLength: 2048, publicKeyEncoding: { type: 'spki', format: 'pem' }, privateKeyEncoding: { type: 'pkcs8', format: 'pem' }, }); return { publicKey, privateKey }; } @WorkerMethod({ priority: 'high' }) async hashData(input: string): Promise { const { createHash } = await import('crypto'); const hash = createHash('sha256'); for (let i = 0; i < 100_000; i++) hash.update(input + i); return hash.digest('hex'); } } ``` ``` -------------------------------- ### Define a Worker Class Source: https://github.com/btwld/nestjs-worker/blob/main/README.md Define a worker class using the `@Worker` decorator. Specify options like name, min/max instances, and timeout. Worker methods are marked with `@WorkerMethod`. ```typescript import { Worker, WorkerMethod } from "nestjs-worker"; @Worker({ name: "ImageProcessingWorker", minInstances: 2, maxInstances: 6, timeout: 30000, }) export class ImageProcessingWorker { @WorkerMethod({ timeout: 15000, retries: 2, priority: "high", }) async processImage(imageData: Buffer): Promise { // CPU-intensive image processing // This runs in a separate worker thread return processedImageData; } } ``` -------------------------------- ### Injecting WorkerProxy with @InjectWorker Source: https://context7.com/btwld/nestjs-worker/llms.txt Use the @InjectWorker decorator to inject a WorkerProxy instance into your service. This proxy allows methods to be dispatched to a thread pool. ```typescript import { Injectable } from '@nestjs/common'; import { InjectWorker } from 'nestjs-worker'; import { CryptoWorker } from './crypto.worker'; import { DataProcessingWorker } from './data-processing.worker'; @Injectable() export class AppService { constructor( @InjectWorker(CryptoWorker) private readonly crypto: CryptoWorker, @InjectWorker(DataProcessingWorker) private readonly dataProcessor: DataProcessingWorker, ) {} async onboardUser(userId: string): Promise<{ hash: string; keys: object }> { // Both calls run concurrently in separate worker threads const [hash, keys] = await Promise.all([ this.crypto.hashData(userId), this.crypto.generateKeyPair(), ]); return { hash, keys }; } async processReport(rows: number[]): Promise<{ sum: number; avg: number }> { try { return await this.dataProcessor.aggregateMetrics(rows); } catch (err) { // worker errors are re-thrown with original .name and .stack preserved console.error('Worker failed:', err.message); throw err; } } } ``` -------------------------------- ### Define Worker Methods with @WorkerMethod Source: https://context7.com/btwld/nestjs-worker/llms.txt Use the @WorkerMethod decorator to mark methods that should be executed in a worker thread. Configure method-specific timeouts, retries, and priority. ```typescript import { Worker, WorkerMethod } from 'nestjs-worker'; @Worker({ minInstances: 1, maxInstances: 4 }) export class DataProcessingWorker { // low priority, no retries, 10 s timeout @WorkerMethod({ timeout: 10_000, retries: 0, priority: 'low' }) async aggregateMetrics(rows: number[]): Promise<{ sum: number; avg: number }> { const sum = rows.reduce((a, b) => a + b, 0); return { sum, avg: sum / rows.length }; } // high priority, 2 retries, serialise result (default: true) @WorkerMethod({ timeout: 30_000, retries: 2, priority: 'high', serialize: true }) async parseCSV(csvContent: string): Promise>> { return csvContent .split('\n') .slice(1) // skip header .filter(Boolean) .map((line) => { const [id, name, value] = line.split(','); return { id, name, value }; }); } } // Expected: method calls are transparently routed to a worker thread; // the caller awaits a resolved Promise with the serialised return value. // On timeout: throws Error('Worker execution timeout after 30000ms') // On retry exhaustion: rethrows the last error from the thread ``` -------------------------------- ### InjectWorker Decorator Source: https://github.com/btwld/nestjs-worker/blob/main/README.md Injects a proxy instance of a worker into a NestJS service, allowing method calls to be automatically routed to the appropriate worker thread. ```APIDOC ## @InjectWorker(WorkerClass) Injects a worker proxy that routes method calls to worker threads. ``` -------------------------------- ### Use Worker in a Service Source: https://github.com/btwld/nestjs-worker/blob/main/README.md Inject the worker into a NestJS service using the `@InjectWorker` decorator. Method calls on the injected worker are automatically routed to worker threads. ```typescript import { Injectable } from "@nestjs/common"; import { InjectWorker } from "nestjs-worker"; import { ImageProcessingWorker } from "./image-processing.worker"; @Injectable() export class ImageService { constructor( @InjectWorker(ImageProcessingWorker) private readonly imageWorker: ImageProcessingWorker ) {} async processUserImage(imageData: Buffer): Promise { // This call is automatically routed to a worker thread return this.imageWorker.processImage(imageData); } } ``` -------------------------------- ### Define a Worker Class with @Worker Source: https://context7.com/btwld/nestjs-worker/llms.txt Use the @Worker decorator to mark a class for execution in separate worker threads. Configure thread pool size, timeouts, and restart behavior. ```typescript import { Worker, WorkerMethod } from 'nestjs-worker'; // crypto.worker.ts — CPU-intensive RSA key generation offloaded to a thread @Worker({ name: 'CryptoWorker', minInstances: 2, // keep 2 warm threads at all times maxInstances: 8, // allow bursting to 8 threads under load timeout: 60000, // default 60 s for all methods in this worker autoRestart: true, restartDelay: 2000, maxRestartAttempts: 5, }) export class CryptoWorker { @WorkerMethod({ timeout: 60000, retries: 1 }) async generateKeyPair(): Promise<{ publicKey: string; privateKey: string }> { const { generateKeyPairSync } = await import('crypto'); const { publicKey, privateKey } = generateKeyPairSync('rsa', { modulusLength: 2048, publicKeyEncoding: { type: 'spki', format: 'pem' }, privateKeyEncoding: { type: 'pkcs8', format: 'pem' }, }); return { publicKey, privateKey }; } @WorkerMethod({ priority: 'high' }) async hashData(input: string): Promise { const { createHash } = await import('crypto'); const hash = createHash('sha256'); for (let i = 0; i < 100_000; i++) hash.update(input + i); return hash.digest('hex'); } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.