Skip to content

ThreadsProvider

This file defines the ThreadsProvider class, a provider for dispatching commands to threads in the @sodacore/core library. It integrates with the Threads module to send messages to thread subprocesses and manage asynchronous responses.


Features

  • Thread Dispatching: Sends commands to named thread subprocesses with optional context and timeout.
  • Queue Management: Uses a unique ID and internal queue to handle asynchronous responses from threads.
  • Dependency Injection: Uses @Inject and @Provide decorators for integration with the Sodacore DI system.

Usage

typescript
import ThreadsProvider from './provider/threads';

const threadsProvider = new ThreadsProvider();

// Dispatch a command to a thread
const result = await threadsProvider.dispatch('MyThread', 'namespace:method', { foo: 'bar' }, 5000);

API

Methods

async dispatch(name: string, command: string, context?: Record<string, any>, timeout?: number): Promise<any>

Sends a command to the specified thread subprocess.

  • name: The name of the thread (class name).
  • command: The command to execute on the thread (e.g., 'namespace:method').
  • context: Optional context data to send with the command.
  • timeout: Optional timeout in milliseconds for the response.
  • Returns: A promise that resolves with the thread's response, or false if the thread is not found.

How It Works

  1. Retrieves the subprocess for the given thread name using this.threads.getThread(name).
  2. If the subprocess is found, generates a unique ID and adds a resolver to the queue with this.threads.addToQueue(uid, resolve, timeout).
  3. Sends the command, context, and UID to the subprocess.
  4. Resolves the promise when a response is received or the timeout is reached.

Notes

  • The provider is designed to be used within the Sodacore dependency injection system.
  • If the specified thread is not found, the promise resolves to false.
  • Useful for sending commands and receiving responses from worker threads in a type-safe and asynchronous manner.

Released under the Apache-2.0 License.