S42-Core Cluster class
- Cluster Documentation
Cluster Documentation
The Cluster
class is part of the s42-core
package and enables the creation and management of parallel processes using Bun workers. It simplifies task distribution in applications that need to utilize multiple CPUs or manage independent processes.
Purpose
The Cluster
class:
- Creates and manages multiple workers efficiently.
- Supports bidirectional messaging between the main process and workers.
- Includes support for automatic worker restarts in development mode (
--watch
). - Handles errors and provides a simple API for integration.
Installation
Install the s42-core
package:
Usage
Basic Example
Constructor
props.name
(string): Name of the cluster.props.maxCPU
(number): Maximum number of CPUs to use.props.watchMode
(boolean, optional): Enables automatic worker restarts in development mode (--watch
).props.args
(string[], optional): Array of arguments passed to the script executed by the workers.
Key Methods
start(file: string, fallback: (err: Error) => void): void
Starts the cluster and spawns workers.
file
(string): File to be executed by the workers.fallback
(function): Callback executed if an error occurs while starting the cluster.
onWorkerMessage(callback: (message: string) => void): void
Registers a callback to handle messages sent by the workers to the main process.
sendMessageToWorkers(message: string): void
Sends a message to all active workers.
getCurrentFile(): string
Returns the file currently executed by the workers.
getCurrentWorkers(): Array<ReturnType<typeof spawn>>
Returns a list of active workers.
killWorkers(): void
Safely shuts down all active workers.
Features
- Parallelism: Utilizes all available CPUs or a specified number of them.
- Messaging: Supports bidirectional messaging between the main process and workers.
- Development Mode: Automatic worker restarts with the
--watch
option. - Custom Arguments: Passes additional command-line arguments to the workers.
- Error Handling: Provides callbacks to handle initialization errors.
- Simple Integration: Designed for easy integration into applications.
Full Example
Advantages
- Modularity: Designed to handle parallel processes easily.
- Efficiency: Maximizes system resource utilization.
- Flexibility: Configurable for different environments (development/production).
- Simplicity: Intuitive and well-documented API.
License
This project is licensed under the MIT License. See the LICENSE file for more details.