All files / commons/services lark-notification.service.ts

0% Statements 0/25
0% Branches 0/12
0% Functions 0/3
0% Lines 0/24

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                                                                                                                                                                                                                                                                               
import { singleton, inject } from "tsyringe";
import type { Logger } from "pino";
import { tokens } from "../../registry/tokens.js";
import { LarkConfig } from "../../config/lark.config.js";
 
interface LarkMessage {
  msg_type: "text" | "post";
  content: {
    text?: string;
    post?: {
      zh_cn?: {
        title: string;
        content: Array<Array<{ tag: string; text?: string; href?: string }>>;
      };
    };
  };
}
 
@singleton()
export class LarkNotificationService {
  private readonly webhookUrl: string | null;
 
  constructor(
    @inject(tokens.Logger) private readonly logger: Logger,
    @inject(LarkConfig) private readonly larkConfig: LarkConfig,
  ) {
    this.webhookUrl = this.larkConfig.webhook?.url || null;
  }
 
  async sendDLQMaxRetriesAlert(params: {
    service: string;
    eventId: string;
    eventType: string;
    retries: number;
    error: string;
    bookId?: string;
  }): Promise<void> {
    const message: LarkMessage = {
      msg_type: "post",
      content: {
        post: {
          zh_cn: {
            title: `🚨 DLQ Alert - ${params.service}`,
            content: [
              [
                { tag: "text", text: `Event ID: ${params.eventId}\n` },
                { tag: "text", text: `Event Type: ${params.eventType}\n` },
                { tag: "text", text: `Retries: ${params.retries}\n` },
                { tag: "text", text: `Service: ${params.service}\n` },
                ...(params.bookId
                  ? [{ tag: "text", text: `Book ID: ${params.bookId}\n` }]
                  : []),
              ],
              [{ tag: "text", text: `\nError:\n${params.error}\n` }],
              [
                {
                  tag: "text",
                  text: "\n⚠️ Manual intervention required! Event will not be retried automatically.",
                },
              ],
            ],
          },
        },
      },
    };
 
    if (!this.webhookUrl) {
      this.logger.warn(
        "[LarkNotification] LARK_WEBHOOK_URL not configured, skipping notification",
      );
      return;
    }
 
    try {
      const response = await fetch(this.webhookUrl, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(message),
      });
 
      if (!response.ok) {
        throw new Error(`Lark API returned ${response.status}`);
      }
 
      this.logger.info(
        `[LarkNotification] DLQ max retries alert sent for event ${params.eventId}`,
      );
    } catch (error) {
      this.logger.error(
        { error, eventId: params.eventId },
        "[LarkNotification] Failed to send Lark notification",
      );
      // Don't throw - notification failure should not block DLQ processing
    }
  }
 
  async sendText(text: string): Promise<void> {
    const message: LarkMessage = {
      msg_type: "text",
      content: {
        text,
      },
    };
 
    if (!this.webhookUrl) {
      this.logger.warn(
        "[LarkNotification] LARK_WEBHOOK_URL not configured, skipping notification",
      );
      return;
    }
 
    try {
      const response = await fetch(this.webhookUrl, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(message),
      });
 
      if (!response.ok) {
        throw new Error(`Lark API returned ${response.status}`);
      }
 
      this.logger.info("[LarkNotification] Text message sent");
    } catch (error) {
      this.logger.error(
        { error },
        "[LarkNotification] Failed to send Lark notification",
      );
    }
  }
}