File size: 4,784 Bytes
097eaf0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import amqp from "amqplib";
import { config } from "../../config";
import { logger as _logger } from "../../lib/logger";
import { WebhookQueueMessage } from "./types";

const WEBHOOK_QUEUE_NAME = "webhooks";
const CONNECT_TIMEOUT = 5000;
const DRAIN_TIMEOUT = 30000;

class WebhookQueue {
  private connection: amqp.ChannelModel | null = null;
  private channel: amqp.Channel | null = null;

  private connectPromise: Promise<void> | null = null;

  async connect(): Promise<void> {
    if (this.connection && this.channel) return;
    if (this.connectPromise) return this.connectPromise;

    this.connectPromise = this._establishConnection();

    try {
      await this.connectPromise;
    } finally {
      this.connectPromise = null;
    }
  }

  private async _establishConnection(): Promise<void> {
    if (!config.NUQ_RABBITMQ_URL) {
      throw new Error("NUQ_RABBITMQ_URL is not configured");
    }

    try {
      _logger.info("Connecting to webhook RabbitMQ", {
        module: "webhook-queue",
      });

      this.connection = await amqp.connect(config.NUQ_RABBITMQ_URL);
      this.channel = await this.connection.createChannel();

      await this.channel.checkQueue(WEBHOOK_QUEUE_NAME);

      this._registerConnectionEvents();

      _logger.info("Connected to webhook RabbitMQ", {
        module: "webhook-queue",
      });
    } catch (err) {
      this.connection = null;
      this.channel = null;
      throw err;
    }
  }

  private _registerConnectionEvents() {
    if (!this.connection || !this.channel) return;

    this.connection.on("close", () => {
      _logger.warn("Webhook RabbitMQ connection closed", {
        module: "webhook-queue",
      });
      this.cleanup();
      setTimeout(
        () =>
          this.connect().catch(err =>
            _logger.error("Reconnection failed", {
              module: "webhook-queue",
              err,
            }),
          ),
        CONNECT_TIMEOUT,
      );
    });

    this.connection.on("error", err => {
      _logger.error("Webhook RabbitMQ connection error", {
        module: "webhook-queue",
        err,
      });
    });

    this.channel.on("error", err => {
      _logger.error("Webhook RabbitMQ channel error", {
        module: "webhook-queue",
        err,
      });
    });
  }

  async publish(message: WebhookQueueMessage): Promise<void> {
    await this.connect();

    if (!this.channel) throw new Error("Channel not available");

    const buffer = Buffer.from(JSON.stringify(message));

    const canSendMore = this.channel.sendToQueue(WEBHOOK_QUEUE_NAME, buffer, {
      persistent: true,
      contentType: "application/json",
    });

    if (!canSendMore) {
      _logger.warn("Webhook message buffer full, waiting for drain", {
        module: "webhook-queue",
        teamId: message.team_id,
      });

      await this.waitForDrain();
    }

    _logger.info("Webhook message published", {
      module: "webhook-queue",
      teamId: message.team_id,
      jobId: message.job_id,
      event: message.event,
    });
  }

  private async waitForDrain(): Promise<void> {
    return new Promise((resolve, reject) => {
      if (!this.channel) {
        return reject(new Error("Channel not available"));
      }

      const listeners: Record<string, any> = {};

      const cleanup = () => {
        if (!this.channel) return;
        this.channel.removeListener("drain", listeners.drain);
        this.channel.removeListener("error", listeners.error);
        this.channel.removeListener("close", listeners.close);
        clearTimeout(listeners.timeout);
      };

      listeners.drain = () => {
        cleanup();
        resolve();
      };
      listeners.error = (err: Error) => {
        cleanup();
        reject(err);
      };
      listeners.close = () => {
        cleanup();
        reject(new Error("Channel closed during drain"));
      };

      listeners.timeout = setTimeout(() => {
        cleanup();
        reject(new Error(`Drain timeout after ${DRAIN_TIMEOUT}ms`));
      }, DRAIN_TIMEOUT);

      this.channel.on("drain", listeners.drain);
      this.channel.on("error", listeners.error);
      this.channel.on("close", listeners.close);
    });
  }

  async close(): Promise<void> {
    try {
      await this.channel?.close();
      await this.connection?.close();
    } catch (err) {
      _logger.warn("Error while closing RabbitMQ connection", { err });
    } finally {
      this.cleanup();
      _logger.info("Webhook RabbitMQ closed", { module: "webhook-queue" });
    }
  }

  private cleanup() {
    this.connection = null;
    this.channel = null;
    this.connectPromise = null;
  }
}

export const webhookQueue = new WebhookQueue();

export async function shutdownWebhookQueue(): Promise<void> {
  await webhookQueue.close();
}