• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

supabase / storage / 22687973597

04 Mar 2026 08:31PM UTC coverage: 76.204% (+0.2%) from 76.039%
22687973597

Pull #892

github

web-flow
Merge e1f1e6dba into d8dba5374
Pull Request #892: fix: improve biome lint configuration

3956 of 5640 branches covered (70.14%)

Branch coverage included in aggregate %.

45 of 64 new or added lines in 10 files covered. (70.31%)

2 existing lines in 1 file now uncovered.

26575 of 34425 relevant lines covered (77.2%)

190.4 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

61.28
/src/internal/queue/event.ts
1
import { getTenantConfig } from '@internal/database'
2✔
2
import { ERRORS } from '@internal/errors'
2✔
3
import { logger, logSchema } from '@internal/monitoring'
2✔
4
import { queueJobScheduled, queueJobSchedulingTime } from '@internal/monitoring/metrics'
2✔
5
import { KnexQueueDB } from '@internal/queue/database'
2✔
6
import { Knex } from 'knex'
2✔
7
import PgBoss, { Job, Queue as PgBossQueue, SendOptions, WorkOptions } from 'pg-boss'
2✔
8
import { getConfig } from '../../config'
2✔
9
import { Queue } from './queue'
2✔
10

2✔
11
export interface BasePayload {
2✔
12
  $version?: string
2✔
13
  singletonKey?: string
2✔
14
  scheduleAt?: Date
2✔
15
  reqId?: string
2✔
16
  tenant: {
2✔
17
    ref: string
2✔
18
    host: string
2✔
19
  }
2✔
20
}
2✔
21

2✔
22
const { pgQueueEnable, region, isMultitenant } = getConfig()
2✔
23

2✔
24
export type StaticThis<T extends Event<any>> = BaseEventConstructor<T>
2✔
25

2✔
26
interface BaseEventConstructor<Base extends Event<any>> {
2✔
27
  version: string
2✔
28

2✔
29
  new (...args: any): Base
2✔
30

2✔
31
  send(
2✔
32
    this: StaticThis<Base>,
2✔
33
    payload: Omit<Base['payload'], '$version'>
2✔
34
  ): Promise<string | void | null>
2✔
35

2✔
36
  eventName(): string
2✔
37
  getWorkerOptions(): WorkOptions
2✔
38
}
2✔
39

2✔
40
/**
2✔
41
 * Base class for all events that are sent to the queue
2✔
42
 */
2✔
43
export class Event<T extends Omit<BasePayload, '$version'>> {
2✔
44
  public static readonly version: string = 'v1'
2✔
45
  protected static queueName = ''
2✔
46
  protected static allowSync = true
2✔
47

2✔
48
  constructor(public readonly payload: T & BasePayload) {}
2✔
49

2✔
50
  static eventName() {
2✔
51
    return this.name
2✔
52
  }
2✔
53

2✔
54
  static deadLetterQueueName() {
2✔
55
    return this.queueName + '-dead-letter'
2✔
56
  }
2✔
57

2✔
58
  static getQueueName() {
2✔
59
    if (!this.queueName) {
20,098!
60
      throw new Error(`Queue name not set on ${this.constructor.name}`)
×
61
    }
×
62

20,098✔
63
    return this.queueName
20,098✔
64
  }
20,098✔
65

2✔
66
  static getQueueOptions(): PgBossQueue | undefined {
2✔
67
    return undefined
×
68
  }
×
69

2✔
70
  static getSendOptions<T extends Event<any>>(payload: T['payload']): SendOptions | undefined {
2✔
71
    return undefined
×
72
  }
×
73

2✔
74
  static getWorkerOptions(): WorkOptions & { concurrentTaskCount?: number } {
2✔
75
    return {}
×
76
  }
×
77

2✔
78
  static onClose() {
2✔
79
    // no-op
×
80
  }
×
81

2✔
82
  static onStart() {
2✔
83
    // no-op
×
84
  }
×
85

2✔
86
  static batchSend<T extends Event<any>[]>(messages: T) {
2✔
87
    if (!pgQueueEnable) {
2!
88
      if (this.allowSync) {
×
89
        return Promise.all(messages.map((message) => message.send()))
✔
90
      } else {
×
91
        logger.warn('[Queue] skipped sending batch messages', {
×
92
          type: 'queue',
×
93
          eventType: this.eventName(),
×
94
        })
×
95
        return
×
96
      }
×
97
    }
×
98

2✔
99
    return Queue.getInstance().insert(
2✔
100
      messages.map((message) => {
2✔
101
        const sendOptions = (this.getSendOptions(message.payload) as PgBoss.JobInsert) || {}
2!
102
        if (!message.payload.$version) {
2✔
103
          ;(message.payload as (typeof message)['payload']).$version = this.version
2✔
104
        }
2✔
105

2✔
106
        if (message.payload.scheduleAt) {
2!
107
          sendOptions.startAfter = new Date(message.payload.scheduleAt)
×
108
        }
×
109

2✔
110
        return {
2✔
111
          ...sendOptions,
2✔
112
          name: this.getQueueName(),
2✔
113
          data: message.payload,
2✔
114
          deadLetter: this.deadLetterQueueName(),
2✔
115
        }
2✔
116
      })
2✔
117
    )
2✔
118
  }
2✔
119

2✔
120
  static send<T extends Event<any>>(
2✔
121
    this: StaticThis<T>,
20,098✔
122
    payload: Omit<T['payload'], '$version'>,
20,098✔
123
    opts?: SendOptions & { tnx?: Knex }
20,098✔
124
  ) {
20,098✔
125
    if (!payload.$version) {
20,098✔
126
      ;(payload as T['payload']).$version = this.version
20,098✔
127
    }
20,098✔
128
    const that = new this(payload)
20,098✔
129
    return that.send(opts)
20,098✔
130
  }
20,098✔
131

2✔
132
  static invoke<T extends Event<any>>(
2✔
133
    this: StaticThis<T>,
2✔
134
    payload: Omit<T['payload'], '$version'>
2✔
135
  ) {
2✔
136
    if (!payload.$version) {
2✔
137
      ;(payload as T['payload']).$version = this.version
2✔
138
    }
2✔
139
    const that = new this(payload)
2✔
140
    return that.invoke()
2✔
141
  }
2✔
142

2✔
143
  static invokeOrSend<T extends Event<any>>(
2✔
144
    this: StaticThis<T>,
32✔
145
    payload: Omit<T['payload'], '$version'>,
32✔
146
    options?: SendOptions & { sendWhenError?: (error: unknown) => boolean }
32✔
147
  ) {
32✔
148
    if (!payload.$version) {
32✔
149
      ;(payload as T['payload']).$version = this.version
32✔
150
    }
32✔
151
    const that = new this(payload)
32✔
152
    return that.invokeOrSend(options)
32✔
153
  }
32✔
154

2✔
155
  static handle(
2✔
156
    job: Job<Event<any>['payload']> | Job<Event<any>['payload']>[],
×
157
    opts?: { signal?: AbortSignal }
×
158
  ) {
×
159
    throw new Error('not implemented')
×
160
  }
×
161

2✔
162
  static async shouldSend(payload: any) {
2✔
163
    if (isMultitenant && payload?.tenant?.ref) {
34!
164
      // Do not send an event if disabled for this specific tenant
×
165
      const tenant = await getTenantConfig(payload.tenant.ref)
×
166
      const disabledEvents = tenant.disableEvents || []
×
167
      if (disabledEvents.includes(this.eventName())) {
×
168
        return false
×
169
      }
×
170
    }
×
171
    return true
34✔
172
  }
34✔
173

2✔
174
  /**
2✔
175
   * See issue https://github.com/timgit/pg-boss/issues/535
2✔
176
   * @param queueName
2✔
177
   * @param singletonKey
2✔
178
   * @param jobId
2✔
179
   */
2✔
180
  static async deleteIfActiveExists(queueName: string, singletonKey: string, jobId: string) {
2✔
181
    if (!pgQueueEnable) {
×
182
      return Promise.resolve()
×
183
    }
×
184

×
185
    await Queue.getDb().executeSql(
×
186
      `DELETE FROM pgboss_v10.job
×
187
       WHERE id = $1
×
188
       AND EXISTS(
×
189
          SELECT 1 FROM pgboss_v10.job
×
190
             WHERE id != $2
×
191
             AND state < 'active'
×
192
             AND name = $3
×
193
             AND singleton_key = $4
×
194
       )
×
195
      `,
×
196
      [jobId, jobId, queueName, singletonKey]
×
197
    )
×
198
  }
×
199

2✔
200
  async invokeOrSend(
2✔
201
    sendOptions?: SendOptions & { sendWhenError?: (error: unknown) => boolean }
32✔
202
  ): Promise<string | void | null> {
32✔
203
    const eventClass = this.constructor as typeof Event
32✔
204

32✔
205
    if (!eventClass.allowSync) {
32!
206
      throw ERRORS.InternalError(undefined, 'Cannot send this event synchronously')
×
207
    }
×
208

32✔
209
    try {
32✔
210
      await this.invoke()
32✔
211
    } catch (e) {
32!
212
      if (sendOptions?.sendWhenError && !sendOptions.sendWhenError(e)) {
×
213
        throw e
×
214
      }
×
215
      logSchema.error(logger, '[Queue] Error invoking event synchronously, sending to queue', {
×
216
        type: 'queue',
×
217
        project: this.payload.tenant?.ref,
×
218
        error: e,
×
219
        metadata: JSON.stringify(this.payload),
×
220
      })
×
221

×
222
      return this.send(sendOptions)
×
223
    }
×
224
  }
32✔
225

2✔
226
  async invoke(): Promise<string | void | null> {
2✔
227
    const eventClass = this.constructor as typeof Event
34✔
228

34✔
229
    if (!eventClass.allowSync) {
34!
230
      throw ERRORS.InternalError(undefined, 'Cannot send this event synchronously')
×
231
    }
×
232

34✔
233
    await eventClass.handle({
34✔
234
      id: '__sync',
34✔
235
      expireInSeconds: 0,
34✔
236
      name: eventClass.getQueueName(),
34✔
237
      data: {
34✔
238
        region,
34✔
239
        ...this.payload,
34✔
240
        $version: eventClass.version,
34✔
241
      },
34✔
242
    })
34✔
243
  }
34✔
244

2✔
245
  async send(customSendOptions?: SendOptions & { tnx?: Knex }): Promise<string | void | null> {
2✔
246
    const eventClass = this.constructor as typeof Event
20,098✔
247

20,098✔
248
    const shouldSend = await eventClass.shouldSend(this.payload)
20,098✔
249

20,098✔
250
    if (!shouldSend) {
20,098!
251
      return
×
252
    }
×
253

20,098✔
254
    if (!pgQueueEnable) {
20,098✔
255
      if (eventClass.allowSync) {
20,098✔
256
        return eventClass.handle({
20,098✔
257
          id: '__sync',
20,098✔
258
          expireInSeconds: 0,
20,098✔
259
          name: eventClass.getQueueName(),
20,098✔
260
          data: {
20,098✔
261
            region,
20,098✔
262
            ...this.payload,
20,098✔
263
            $version: eventClass.version,
20,098✔
264
          },
20,098✔
265
        })
20,098✔
266
      } else {
20,098!
267
        logger.warn('[Queue] skipped sending message', {
×
268
          type: 'queue',
×
NEW
269
          eventType: eventClass.eventName(),
×
270
        })
×
271
        return
×
272
      }
×
273
    }
20,098✔
274

×
275
    const startTime = process.hrtime.bigint()
×
NEW
276
    const sendOptions = eventClass.getSendOptions(this.payload) || {}
×
277

20,098✔
278
    if (this.payload.scheduleAt) {
20,098!
279
      sendOptions.startAfter = new Date(this.payload.scheduleAt)
×
280
    }
×
281

×
NEW
282
    sendOptions!.deadLetter = eventClass.deadLetterQueueName()
×
283

×
284
    try {
×
285
      const queue = customSendOptions?.tnx
×
286
        ? Queue.createPgBoss({
20,098!
287
            enableWorkers: false,
×
288
            db: new KnexQueueDB(customSendOptions.tnx),
×
289
          })
×
290
        : Queue.getInstance()
20,098!
291

20,098✔
292
      const res = await queue.send({
20,098✔
293
        name: eventClass.getQueueName(),
20,098✔
294
        data: {
20,098✔
295
          region,
20,098✔
296
          ...this.payload,
20,098✔
297
          $version: eventClass.version,
20,098✔
298
        },
20,098✔
299
        options: {
20,098✔
300
          ...sendOptions,
20,098✔
301
          ...customSendOptions,
20,098✔
302
        },
20,098✔
303
      })
20,098✔
304

×
305
      queueJobScheduled.add(1, {
×
NEW
306
        name: eventClass.getQueueName(),
×
307
      })
×
308

×
309
      return res
×
310
    } catch (e) {
×
311
      // If we can't queue the message for some reason,
×
312
      // we run its handler right away.
×
313
      // This might create some latency with the benefit of being more fault-tolerant
×
314
      logSchema.warning(
×
315
        logger,
×
316
        `[Queue Sender] Error while sending job to queue, sending synchronously`,
×
317
        {
×
318
          type: 'queue',
×
319
          error: e,
×
320
          metadata: JSON.stringify(this.payload),
×
321
        }
×
322
      )
×
323

×
NEW
324
      if (!eventClass.allowSync) {
×
325
        throw e
×
326
      }
×
327

×
NEW
328
      return eventClass.handle({
×
329
        id: '__sync',
×
330
        expireInSeconds: 0,
×
NEW
331
        name: eventClass.getQueueName(),
×
332
        data: {
×
333
          region,
×
334
          ...this.payload,
×
NEW
335
          $version: eventClass.version,
×
336
        },
×
337
      })
×
338
    } finally {
×
339
      const duration = Number(process.hrtime.bigint() - startTime) / 1e9
×
340
      queueJobSchedulingTime.record(duration, {
×
NEW
341
        name: eventClass.getQueueName(),
×
342
      })
×
343
    }
×
344
  }
20,098✔
345
}
2✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc