Worker Decorator
This file defines the Worker
decorator, which is used to mark classes as workers in the @sodacore/core
library. Workers run in separate threads, allowing you to offload CPU-intensive or blocking tasks from the main thread. The decorator manages worker metadata, pool sizing, and proxies exposed methods to the worker thread.
Features
- Worker Registration: Marks a class as a worker, associating it with a file and optional configuration.
- Thread Offloading: Enables running heavy or blocking tasks outside the main thread.
- Pool Management: Supports worker pool sizing via options.
- Method Proxying: Automatically proxies methods decorated with
@Expose
to the worker thread. - Metadata Management: Stores worker-related metadata for discovery and management.
Usage
typescript
import Worker from './decorator/worker';
@Worker(__filename, { poolSize: 2 })
export class MyWorker {
@Expose()
doHeavyTask(data: any) {
// This method will be proxied and run in the worker thread
}
}
- The
filename
should be the path to the file containing the worker class. - The
options
object can specify a unique identifier (uid
) and the worker pool size.
API
Worker(filename: string, options?: IWorkerOptions): ClassDecorator
- filename: The filename of the file where the worker class resides.
- options: (optional) Worker options:
uid
: Unique identifier for the worker (randomly generated if not provided).poolSize
: Number of worker instances in the pool (must be at least 1).
- Returns: A class decorator that registers the class as a worker and sets up method proxying.
How It Works
- Checks if the code is running in the main thread; if not, the decorator does nothing.
- Validates the
poolSize
option (must be at least 1). - Generates a unique identifier for the worker if not provided.
- Sets worker metadata (
type
,filename
,uid
,options
) on the class. - Retrieves all methods decorated with
@Expose
and overrides them to dispatch calls to the worker thread using theWorkersProvider
.
Notes
- Use this decorator on classes that should run in a worker thread for parallel or isolated execution.
- Methods decorated with
@Expose
will be proxied to the worker and executed there. - The worker pool allows multiple instances of the worker to run concurrently.
- Ensure the
WorkersProvider
is registered and up-to-date for proper dispatching.