Concurrency fix and simplification
This commit is contained in:
@@ -1,4 +1,4 @@
|
|||||||
import { type Selectable, type Transaction } from "kysely";
|
import { sql, type Selectable, type Transaction } from "kysely";
|
||||||
import type { DB } from "../database/out/db";
|
import type { DB } from "../database/out/db";
|
||||||
import { log } from "../util/log";
|
import { log } from "../util/log";
|
||||||
import { sleep } from "bun";
|
import { sleep } from "bun";
|
||||||
@@ -29,7 +29,6 @@ type EventQueueCfg = {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
class AlreadyClaimedEventError extends Error { }
|
|
||||||
class ConcurrencyLimitReachedError extends Error { }
|
class ConcurrencyLimitReachedError extends Error { }
|
||||||
|
|
||||||
export function defineEventType<P extends TSchema, S extends TSchema>(opt: EventTypeOptions<P, S>): EventTypeOptions<P, S> {
|
export function defineEventType<P extends TSchema, S extends TSchema>(opt: EventTypeOptions<P, S>): EventTypeOptions<P, S> {
|
||||||
@@ -46,7 +45,6 @@ function exponentialDelay(initialDelay: number, tries: number, cap: number = Inf
|
|||||||
}
|
}
|
||||||
|
|
||||||
export class EventQueue<G extends string, T extends Record<string, EventTypeOptions<any, any>>> {
|
export class EventQueue<G extends string, T extends Record<string, EventTypeOptions<any, any>>> {
|
||||||
private static readonly DEQUEUE_ALREADY_CLAIMED_SKIP_DELAY_MS = 250;
|
|
||||||
private static readonly DEQUEUE_RETRY_DELAY_MS = secToMs(10);
|
private static readonly DEQUEUE_RETRY_DELAY_MS = secToMs(10);
|
||||||
private static readonly DEQUEUE_RETRY_LIMIT = 3;
|
private static readonly DEQUEUE_RETRY_LIMIT = 3;
|
||||||
private static readonly RATE_LIMIT_RETRY_LIMIT = 15;
|
private static readonly RATE_LIMIT_RETRY_LIMIT = 15;
|
||||||
@@ -77,15 +75,8 @@ export class EventQueue<G extends string, T extends Record<string, EventTypeOpti
|
|||||||
consecutiveFailures = 0;
|
consecutiveFailures = 0;
|
||||||
}
|
}
|
||||||
catch (err) {
|
catch (err) {
|
||||||
if (err instanceof AlreadyClaimedEventError) {
|
// Return to the manager loop so it can clean timed out events
|
||||||
log.warn("event processing already claimed by another worker, skipping");
|
if (err instanceof ConcurrencyLimitReachedError) break;
|
||||||
await sleep(EventQueue.DEQUEUE_ALREADY_CLAIMED_SKIP_DELAY_MS);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (err instanceof ConcurrencyLimitReachedError) {
|
|
||||||
await sleep(EventQueue.DEQUEUE_RETRY_DELAY_MS);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (++consecutiveFailures <= EventQueue.DEQUEUE_RETRY_LIMIT) {
|
if (++consecutiveFailures <= EventQueue.DEQUEUE_RETRY_LIMIT) {
|
||||||
log.warn({ err, consecutiveFailures }, "dequeue failed, retrying")
|
log.warn({ err, consecutiveFailures }, "dequeue failed, retrying")
|
||||||
@@ -102,37 +93,29 @@ export class EventQueue<G extends string, T extends Record<string, EventTypeOpti
|
|||||||
async dequeue() {
|
async dequeue() {
|
||||||
log.trace("dequeueing");
|
log.trace("dequeueing");
|
||||||
|
|
||||||
const front = await this.front();
|
// Serialize claims per group so concurrent workers see each other's claims when checking the concurrency limit
|
||||||
if (!front) return;
|
const front = await db.transaction().execute(async (trx) => {
|
||||||
|
await sql`select pg_advisory_xact_lock(hashtext(${this.group}))`.execute(trx);
|
||||||
|
|
||||||
const result = await db.updateTable("events")
|
const { count } = await trx.selectFrom("events")
|
||||||
.set({ started_at: new Date(), heartbeat_at: new Date() })
|
.select(trx.fn.countAll().as("count"))
|
||||||
.where("id", "=", front.id)
|
|
||||||
.where("started_at", "is", null)
|
|
||||||
.where((eb) =>
|
|
||||||
eb(
|
|
||||||
eb.selectFrom("events")
|
|
||||||
.select(eb.fn.countAll().as("count"))
|
|
||||||
.where("group", "=", this.group)
|
.where("group", "=", this.group)
|
||||||
.where("started_at", "is not", null)
|
.where("started_at", "is not", null)
|
||||||
.where("ended_at", "is", null),
|
.where("ended_at", "is", null)
|
||||||
"<",
|
|
||||||
this.cfg.concurrency.limit
|
|
||||||
)
|
|
||||||
)
|
|
||||||
.executeTakeFirstOrThrow();
|
.executeTakeFirstOrThrow();
|
||||||
|
if (Number(count) >= this.cfg.concurrency.limit) throw new ConcurrencyLimitReachedError();
|
||||||
|
|
||||||
// Guard against another worker/machine having already claimed this event and guard against max concurrency
|
const front = await this.front(trx);
|
||||||
if (result.numUpdatedRows === 0n) {
|
if (!front) return;
|
||||||
const frontFresh = await db.selectFrom("events")
|
|
||||||
.select("started_at")
|
await trx.updateTable("events")
|
||||||
|
.set({ started_at: new Date(), heartbeat_at: new Date() })
|
||||||
.where("id", "=", front.id)
|
.where("id", "=", front.id)
|
||||||
.executeTakeFirst();
|
.execute();
|
||||||
|
|
||||||
if (!frontFresh) throw new AlreadyClaimedEventError();
|
return front;
|
||||||
if (frontFresh?.started_at) throw new AlreadyClaimedEventError();
|
});
|
||||||
throw new ConcurrencyLimitReachedError();
|
if (!front) return;
|
||||||
};
|
|
||||||
|
|
||||||
log.trace({ name: front.id }, "dequeuing event");
|
log.trace({ name: front.id }, "dequeuing event");
|
||||||
await this.process(front);
|
await this.process(front);
|
||||||
|
|||||||
Reference in New Issue
Block a user