# All files / modules/webhooks/processors webhook.processor.ts

0% Statements 0/62
0% Branches 0/7
0% Functions 0/8
0% Lines 0/58

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

     import { Processor, WorkerHost, OnWorkerEvent } from '@nestjs/bullmq';
    import { Logger } from '@nestjs/common';
    import { InjectRepository } from '@nestjs/typeorm';
    import { Repository } from 'typeorm';
    import { Job } from 'bullmq';
    import * as crypto from 'crypto';

    import { WebhookDeliveryEntity, DeliveryStatus } from '../entities';

    interface WebhookDeliveryJob {
      deliveryId: string;
      webhookId: string;
      url: string;
      secret: string;
      headers: Record<string, string>;
      eventType: string;
      payload: Record<string, any>;
    }

    // Retry delays in milliseconds
    const RETRY_DELAYS = [
      60 * 1000, // 1 minute
      5 * 60 * 1000, // 5 minutes
      30 * 60 * 1000, // 30 minutes
      2 * 60 * 60 * 1000, // 2 hours
      6 * 60 * 60 * 1000, // 6 hours
    ];

    @Processor('webhooks')
    export class WebhookProcessor extends WorkerHost {
      private readonly logger = new Logger(WebhookProcessor.name);

      constructor(
        @InjectRepository(WebhookDeliveryEntity)
        private readonly deliveryRepo: Repository<WebhookDeliveryEntity>,
      ) {
        super();
      }

      async process(job: Job<WebhookDeliveryJob>): Promise<void> {
        const { deliveryId, url, secret, headers, eventType, payload } = job.data;

        this.logger.log(`Processing webhook delivery: ${deliveryId}`);

        const delivery = await this.deliveryRepo.findOne({
          where: { id: deliveryId },
        });

        Iif (!delivery) {
          this.logger.warn(`Delivery not found: ${deliveryId}`);
          return;
        }

        try {
          // Generate signature
          const timestamp = Date.now();
          const body = JSON.stringify(payload);
          const signature = crypto
            .createHmac('sha256', secret)
            .update(`${timestamp}.${body}`)
            .digest('hex');

          const signatureHeader = `t=${timestamp},v1=${signature}`;

          // Make HTTP request
          const controller = new AbortController();
          const timeout = setTimeout(() => controller.abort(), 30000);

          const response = await fetch(url, {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              'X-Webhook-Signature': signatureHeader,
              'X-Webhook-Id': delivery.webhookId,
              'X-Webhook-Event': eventType,
              'X-Webhook-Timestamp': timestamp.toString(),
              'X-Webhook-Delivery': deliveryId,
              ...headers,
            },
            body,
            signal: controller.signal,
            redirect: 'error', // Don't follow redirects
          });

          clearTimeout(timeout);

          // Get response details
          const responseBody = await response.text().catch(() => '');
          const responseHeaders: Record<string, string> = {};
          response.headers.forEach((value, key) => {
            responseHeaders[key] = value;
          });

          // Update delivery record
          delivery.responseStatus = response.status;
          delivery.responseBody = responseBody.substring(0, 10000); // Limit size
          delivery.responseHeaders = responseHeaders;

          if (response.ok) {
            // Success (2xx status)
            delivery.status = DeliveryStatus.DELIVERED;
            delivery.deliveredAt = new Date();
            delivery.completedAt = new Date();
            this.logger.log(`Webhook delivered successfully: ${deliveryId}`);
          } else {
            // HTTP error (4xx, 5xx)
            await this.handleFailure(delivery, `HTTP ${response.status}: ${responseBody.substring(0, 500)}`);
          }

          await this.deliveryRepo.save(delivery);
        } catch (error: any) {
          // Network error, timeout, etc.
          delivery.responseStatus = undefined as any;
          delivery.responseBody = undefined as any;
          await this.handleFailure(delivery, error.message || 'Unknown error');
          await this.deliveryRepo.save(delivery);
        }
      }

      private async handleFailure(delivery: WebhookDeliveryEntity, errorMessage: string): Promise<void> {
        delivery.lastError = errorMessage;

        if (delivery.attempt >= delivery.maxAttempts) {
          // Max retries reached
          delivery.status = DeliveryStatus.FAILED;
          delivery.completedAt = new Date();
          this.logger.warn(
            `Webhook delivery failed permanently: ${delivery.id} after ${delivery.attempt} attempts`,
          );
        } else {
          // Schedule retry
          delivery.status = DeliveryStatus.RETRYING;
          delivery.attempt += 1;
          delivery.nextRetryAt = new Date(Date.now() + RETRY_DELAYS[delivery.attempt - 1]);
          this.logger.log(
            `Webhook delivery scheduled for retry: ${delivery.id} (attempt ${delivery.attempt})`,
          );
        }
      }

      @OnWorkerEvent('completed')
      onCompleted(job: Job<WebhookDeliveryJob>) {
        this.logger.debug(`Job completed: ${job.id}`);
      }

      @OnWorkerEvent('failed')
      onFailed(job: Job<WebhookDeliveryJob>, error: Error) {
        this.logger.error(`Job failed: ${job.id} - ${error.message}`);
      }
    }