All files / approval-engine-dlq/domain asset-state-change-log-dlq.handler.ts

100% Statements 40/40
100% Branches 38/38
100% Functions 4/4
100% Lines 38/38

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 178 179 180 181 182 183 184                    1x   21x 21x 21x           15x             15x 1x       1x     14x 14x 14x   14x   14x 6x 6x     6x 1x                           1x                   6x                           6x 1x       1x     5x                       5x     8x 6x                           6x                   8x                 8x 1x       1x     7x               7x       12x 7x         5x       20x           60x          
import { autoInjectable, inject, singleton } from "tsyringe";
import { DBAssetDlqStore } from "../store/DB-asset-state-change-log-dlq.store.js";
import type { Logger } from "pino";
import { tokens } from "../../registry/tokens.js";
import { AssetStateChangeLogsEventDlq } from "../../approval-engine-2/dtos/asset-state-change-logs-event.dto.js";
import { Result } from "../../tr8-script/domain/utils/types.js";
import { LarkNotificationService } from "../../commons/services/lark-notification.service.js";
 
@singleton()
@autoInjectable()
class AssetStateChangeLogsEventDlqHandler {
  constructor(
    private readonly DBAssetDlqStore: DBAssetDlqStore,
    @inject(tokens.Logger) private readonly logger: Logger,
    private readonly larkNotification: LarkNotificationService,
  ) {}
 
  async handle(
    assetEvent: AssetStateChangeLogsEventDlq,
  ): Promise<Result<true, Error>> {
    const getResult = await this.DBAssetDlqStore.get(
      assetEvent.bookId,
      assetEvent.scriptId,
      assetEvent.subId,
      assetEvent.type,
    );
 
    if (!getResult.ok) {
      this.logger.error(
        { err: getResult.error },
        "[AssetStateChangeLogsDLQHandler] Failed to fetch existing DLQ record",
      );
      return { ok: false, error: getResult.error };
    }
 
    const existing = getResult.value;
    const parsedError = new Error(assetEvent.error);
    const isRetryable = this.isTransientError(parsedError);
 
    let processedSuccessfully = false;
 
    if (existing !== null) {
      const retries = (existing.retries ?? 1) + 1;
      const maxRetriesExceeded = retries > 5;
 
      // Send Lark notification only once when max retries exceeded (retries exactly equals 6)
      if (maxRetriesExceeded && retries === 6) {
        this.logger.error(
          `[AssetStateChangeLogsDLQHandler] Max retries exceeded for script ID: ${assetEvent.scriptId}`,
          {
            bookId: assetEvent.bookId,
            scriptId: assetEvent.scriptId,
            subId: assetEvent.subId,
            eventType: assetEvent.type,
            retries,
            error: assetEvent.error,
            isRetryable,
          },
        );
 
        // Send Lark alert (non-blocking)
        await this.larkNotification.sendDLQMaxRetriesAlert({
          service: "AssetStateChangeLogs",
          eventId: assetEvent.scriptId,
          eventType: assetEvent.type,
          retries,
          error: assetEvent.error,
          bookId: assetEvent.bookId,
        });
      }
 
      const updateResult = await this.DBAssetDlqStore.update(existing.id, {
        retries,
        status: maxRetriesExceeded
          ? "FAILED"
          : isRetryable
          ? "RETRYING"
          : "FAILED",
        nextRetryAt:
          isRetryable && !maxRetriesExceeded
            ? new Date(Date.now() + 5 * 60 * 1000)
            : undefined,
        error: assetEvent.error,
      });
 
      if (!updateResult.ok) {
        this.logger.error(
          { err: updateResult.error },
          "[AssetStateChangeLogsDLQHandler] Failed to update DLQ record",
        );
        return { ok: false, error: updateResult.error };
      }
 
      this.logger.warn(
        `[AssetStateChangeLogsDLQHandler] Updated existing DLQ event: scriptId=${
          assetEvent.scriptId
        }, retries=${retries}, status=${
          maxRetriesExceeded
            ? "FAILED (MAX_RETRIES)"
            : isRetryable
            ? "RETRYING"
            : "FAILED"
        }`,
      );
 
      processedSuccessfully = true;
    } else {
      // Send Lark notification for new permanent errors
      if (!isRetryable) {
        this.logger.error(
          `[AssetStateChangeLogsDLQHandler] Permanent failure detected for new script ID: ${assetEvent.scriptId}`,
          {
            bookId: assetEvent.bookId,
            scriptId: assetEvent.scriptId,
            subId: assetEvent.subId,
            eventType: assetEvent.type,
            retries: 0,
            error: assetEvent.error,
            isRetryable,
          },
        );
 
        // Send Lark alert (non-blocking)
        await this.larkNotification.sendDLQMaxRetriesAlert({
          service: "AssetStateChangeLogs",
          eventId: assetEvent.scriptId,
          eventType: assetEvent.type,
          retries: 0,
          error: assetEvent.error,
          bookId: assetEvent.bookId,
        });
      }
 
      const saveResult = await this.DBAssetDlqStore.save({
        ...assetEvent,
        status: isRetryable ? "RETRYING" : "FAILED",
        retries: 0,
        nextRetryAt: isRetryable
          ? new Date(Date.now() + 5 * 60 * 1000)
          : undefined,
      });
 
      if (!saveResult.ok) {
        this.logger.error(
          { err: saveResult.error },
          "[AssetStateChangeLogsDLQHandler] Failed to save new DLQ record",
        );
        return { ok: false, error: saveResult.error };
      }
 
      this.logger.info(
        `[AssetStateChangeLogsDLQHandler] Saved new DLQ event. scriptId=${
          assetEvent.scriptId
        }, subId=${assetEvent.subId}, status=${
          isRetryable ? "RETRYING" : "FAILED"
        }`,
      );
 
      processedSuccessfully = true;
    }
 
    // Throw error for permanent failures after all processing is complete
    if (processedSuccessfully && !isRetryable) {
      throw new Error(
        `Permanent failure for AssetStateChangeLogsEvent ${assetEvent.scriptId}: ${assetEvent.error}`,
      );
    }
 
    return { ok: true, value: true };
  }
 
  private isTransientError(error: Error): boolean {
    const transientPatterns = [
      "ECONNRESET",
      "timeout",
      "ETIMEDOUT",
      "ENOTFOUND",
    ];
    return transientPatterns.some((pattern) => error.message.includes(pattern));
  }
}
 
export { AssetStateChangeLogsEventDlqHandler };