Worker Decorator
This file defines the Worker
class decorator for the @sodacore/core
framework. It is used to mark a class as a worker, enabling it to run in a separate thread or worker pool. This allows you to offload CPU-intensive or blocking tasks away from the main thread, improving application performance and responsiveness.
Features
- Worker Registration: Adds metadata to register the class as a worker for the Sodacore DI and worker system.
- Thread Offloading: Allows decorated classes to run in a separate thread or worker pool, preventing main thread blocking.
- Proxy Method Dispatch: Automatically proxies exposed methods to the worker, dispatching calls via the
WorkersProvider
. - Custom Worker Options: Supports custom worker UID and pool size configuration.
- Main Thread Safety: Ensures the decorator only applies logic when running in the main thread.
Usage
import Worker from './decorator/worker';
@Worker(__filename, { poolSize: 2 })
export class MyWorker {
@Expose()
async heavyTask(data: any) {
// CPU-intensive logic here
}
}
API
Worker(filename: string, options?: IWorkerOptions): ClassDecorator
- filename: The filename of the file where the worker class is defined.
- options: Optional worker options:
uid
: Unique identifier for the worker (auto-generated if not provided).poolSize
: Number of worker instances in the pool (default: 1).
How It Works
Main Thread Check: Decorator logic only runs in the main thread to avoid duplicate registration in worker threads.
Metadata Registration: Sets metadata for type (
worker
), filename, UID, and options using the Sodacore DI utilities.Proxy Method Setup: Finds all methods marked as exposed (using the
@Expose()
decorator) and overrides them to dispatch calls through theWorkersProvider
. This enables transparent remote execution of methods in the worker thread or pool.Pool Size Validation: Throws an error if the specified pool size is less than 1.
Notes
- Only methods decorated with
@Expose()
will be proxied and callable via the worker system. - The worker provider must be registered and available in the application for dispatching to work.
- This decorator is intended for use with Sodacore's worker and threading system, not for general-purpose threading.
- Use the correct filename to ensure the worker can be properly instantiated and managed.