All files / src/platform/workers worker.service.ts

0% Statements 0/48
0% Branches 0/32
0% Functions 0/13
0% Lines 0/42

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177                                                                                                                                                                                                                                                                                                                                                                 
import {
  Injectable,
  Logger,
  OnApplicationBootstrap,
  OnApplicationShutdown,
} from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { WorkerNode, WorkerJob } from './schemas/worker.schema';
import { EventBusService } from '../events/event-bus.service';
import * as os from 'os';
 
@Injectable()
export class WorkerService
  implements OnApplicationBootstrap, OnApplicationShutdown
{
  private readonly logger = new Logger(WorkerService.name);
  private nodeId: string;
  private heartbeatInterval: NodeJS.Timeout;
 
  constructor(
    @InjectModel(WorkerNode.name) private workerNodeModel: Model<WorkerNode>,
    @InjectModel(WorkerJob.name) private workerJobModel: Model<WorkerJob>,
    private readonly eventBus: EventBusService,
  ) {
    this.nodeId = `worker-${os.hostname()}-${process.pid}`;
  }
 
  async onApplicationBootstrap() {
    this.logger.log(`Registering worker node: ${this.nodeId}`);
    await this.registerNode();
    this.startHeartbeat();
  }
 
  async onApplicationShutdown(signal?: string) {
    this.logger.log(
      `Shutting down worker node: ${this.nodeId} (signal: ${signal})`,
    );
    this.stopHeartbeat();
    await this.deregisterNode();
  }
 
  private async registerNode() {
    try {
      await this.workerNodeModel.findOneAndUpdate(
        { nodeId: this.nodeId },
        {
          hostname: os.hostname(),
          status: 'active',
          queues: ['default', 'import', 'export', 'notifications'], // Make configurable later
          concurrency: 10,
          lastHeartbeatAt: new Date(),
          metrics: this.getSystemMetrics(),
        },
        { upsert: true, new: true },
      );
    } catch (error) {
      this.logger.error(
        `Failed to register worker node: ${error.message}`,
        error.stack,
      );
    }
  }
 
  private async deregisterNode() {
    try {
      await this.workerNodeModel.findOneAndUpdate(
        { nodeId: this.nodeId },
        { status: 'offline' },
      );
    } catch (error) {
      this.logger.error(
        `Failed to deregister worker node: ${error.message}`,
        error.stack,
      );
    }
  }
 
  private startHeartbeat() {
    this.heartbeatInterval = setInterval(async () => {
      try {
        await this.workerNodeModel.updateOne(
          { nodeId: this.nodeId },
          {
            lastHeartbeatAt: new Date(),
            metrics: this.getSystemMetrics(),
          },
        );
      } catch (error) {
        this.logger.error(`Failed to send heartbeat: ${error.message}`);
      }
    }, 30000); // 30 seconds
  }
 
  private stopHeartbeat() {
    if (this.heartbeatInterval) {
      clearInterval(this.heartbeatInterval);
    }
  }
 
  private getSystemMetrics() {
    return {
      uptime: process.uptime(),
      memory: process.memoryUsage(),
      cpuUsage: process.cpuUsage(),
      loadAvg: os.loadavg(),
    };
  }
 
  // Called by Queue consumers to track job state in DB
  async trackJobState(
    jobId: string,
    queueName: string,
    name: string,
    status: string,
    data?: any,
  ) {
    await this.workerJobModel.findOneAndUpdate(
      { jobId, queueName },
      {
        name,
        status,
        assignedNodeId: this.nodeId,
        ...(data && { data }),
        ...(status === 'active' && { startedAt: new Date() }),
        ...(status === 'completed' || status === 'failed'
          ? { finishedAt: new Date() }
          : {}),
      },
      { upsert: true, new: true },
    );
  }
 
  async updateJobProgress(
    jobId: string,
    queueName: string,
    progress: number,
    result?: any,
    failedReason?: string,
  ) {
    const update: any = { progress };
    if (result) update.result = result;
    if (failedReason) update.failedReason = failedReason;
 
    await this.workerJobModel.updateOne({ jobId, queueName }, update);
  }
 
  async getActiveNodes() {
    // Nodes that have sent heartbeat in the last 2 minutes
    const threshold = new Date(Date.now() - 2 * 60 * 1000);
    return this.workerNodeModel
      .find({
        status: 'active',
        lastHeartbeatAt: { $gte: threshold },
      })
      .exec();
  }
 
  async getJobHistory(
    queueName?: string,
    status?: string,
    limit = 50,
    skip = 0,
  ) {
    const query: any = {};
    if (queueName) query.queueName = queueName;
    if (status) query.status = status;
 
    return this.workerJobModel
      .find(query)
      .sort({ createdAt: -1 })
      .skip(skip)
      .limit(limit)
      .exec();
  }
}