# Awesome ECS - Workers Package

## Overview

The Workers package extends the Awesome ECS framework with **multi-threaded processing capabilities**. It enables distributing computational workloads across Web Worker / Node.js Worker Threads while maintaining ECS architecture patterns.

**Key capabilities:**
- Worker thread management and health monitoring
- Task queuing and distribution
- Bidirectional message-based communication (main ↔ worker threads)
- Integration with ECS entities and systems

## Core Concepts

### Worker Abstraction (`src/abstract/`)

Low-level abstractions for worker operations:

- **`worker-instance.ts`**: Represents a single worker thread instance
- **`worker-queue.ts`**: Task queue for worker assignment
- **`worker-message.ts`**: Message protocol between threads
- **`worker-health.ts`**: Health status monitoring
- **`worker-factory.ts`**: Worker creation patterns
- **`worker-system-context.ts`**: System context extension for workers

### Worker Entities (`src/entities/`)

- **`WorkerThreadEntity`**: ECS entity representing a single worker thread

### Worker Components (`src/components/`)

ECS components tracking worker state, task queues, and health status.

### Worker Systems (`src/systems/`)

Systems for managing worker lifecycle, task assignment, message passing, and result handling.

### Worker Runtime (`src/runtime/`)

Worker thread creation/cleanup, message pump, and task scheduler.

### Helpers (`src/helpers/`)

Task creation, result processing, and message formatting utilities.

## Usage Pattern

### 1. Define a Worker Task

```typescript
const task = {
  id: generateUid(),
  type: 'GENERATE_TERRAIN',
  data: { seed, width, height }
};
```

### 2. Assign Tasks via a System

```typescript
class TerrainGenerationSystem implements ISystemMiddleware<TerrainEntity> {
  action(context: ISystemContext<TerrainEntity>): void {
    const terrain = context.entity;
    workerEntity.tasks.queue.push({
      id: `terrain-${terrain.identity.model.uid}`,
      type: 'GENERATE_TERRAIN',
      data: { seed: terrain.seed, width: terrain.width, height: terrain.height }
    });
  }
}
```

### 3. Process in Worker Thread

```typescript
self.addEventListener('message', (event) => {
  const { id, type, data } = event.data;
  if (type === 'GENERATE_TERRAIN') {
    const heightmap = generateTerrain(data.seed, data.width, data.height);
    self.postMessage({ type: 'TASK_COMPLETE', taskId: id, data: { heightmap } });
  }
});
```

### 4. Handle Results via a System

```typescript
class WorkerResultSystem implements ISystemMiddleware<WorkerThreadEntity> {
  action(context: ISystemContext<WorkerThreadEntity>): void {
    // Process incoming messages from the worker thread
  }
}
```

## Package Structure

```
src/
├── abstract/     # Worker abstractions & interfaces
├── components/   # Worker-specific ECS components
├── entities/     # WorkerThreadEntity
├── helpers/      # Task creation, message formatting
├── runtime/      # Worker thread lifecycle and message pump
└── systems/      # Systems for worker management
```

## Key Design Patterns

1. **Task-based work distribution**: Tasks queued and processed by available workers
2. **Message-based communication**: Structured protocol between main and worker threads
3. **Entity-based lifecycle**: Worker represented as ECS entity with components
4. **Health monitoring**: Track worker status and detect stuck threads
5. **Non-blocking**: Main thread never waits; results arrive as entity updates

## Performance Considerations

- Workers are CPU-bound; good for heavy computation (pathfinding, terrain generation, physics)
- Message passing has serialization overhead — keep transferred data lean
- Balance task grain-size: not too small (overhead), not too large (blocks the worker)

## Relationship to Other Packages

- **Uses**: `@awesome-ecs/abstract`, `@awesome-ecs/core`
- **Works with**: `@awesome-ecs/ai` for offloading AI calculations to background threads
