Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

add cron to remove stale locks

Thiago Araujo da Silva6511d7e050ad
diff --git a/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-dal.ts b/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-dal.ts
index 23afa8be3b..b0ae37dde1 100644
--- a/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-dal.ts
+++ b/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-dal.ts
@@ -134,11 +134,36 @@ export const auditLogStreamOutboxDALFactory = (db: TDbClient) => {
}
};
+ // Stale-claim recovery: rows whose worker crashed mid-batch never had their
+ // 'processing' status flipped back, so they're invisible to the drain query.
+ // Flip them back to 'retry' with nextRetryAt=NOW() so the next debounce-driven
+ // flush picks them up. Attempts is left unchanged — a stale claim is a worker
+ // fault, not a delivery failure, and shouldn't burn retry budget.
+ const requeueStaleClaims = async (staleBefore: Date): Promise<number> => {
+ try {
+ const updated = await db(TableName.AuditLogStreamOutbox)
+ .where("status", AuditLogStreamOutboxStatus.Processing)
+ .andWhere("lockedAt", "<", staleBefore)
+ .update({
+ status: AuditLogStreamOutboxStatus.Retry,
+ nextRetryAt: db.fn.now(),
+ lockedAt: null,
+ workerId: null,
+ lastError: "stale-claim-recovered: worker did not release lock before threshold"
+ });
+
+ return updated;
+ } catch (error) {
+ throw new DatabaseError({ error, name: "AuditLogStreamOutbox: requeueStaleClaims" });
+ }
+ };
+
return {
batchInsert,
claimBatchForStream,
deleteByIds,
markBatchForRetry,
- moveToDlq
+ moveToDlq,
+ requeueStaleClaims
};
};
diff --git a/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-queue.ts b/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-queue.ts
index dfd10afbdc..61e97faa7f 100644
--- a/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-queue.ts
+++ b/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-queue.ts
@@ -1,18 +1,26 @@
+import { CronJobName, TCronJobFactory } from "@app/lib/cron/cron-job";
import { logger } from "@app/lib/logger";
import { QueueName, TQueueServiceFactory } from "@app/queue";
import { LogProvider } from "../audit-log-stream/audit-log-stream-enums";
import { TAuditLogStreamOutboxServiceFactory } from "./audit-log-stream-outbox-service";
+// Sweeper cadence. Runs every 5 min — comfortably tighter than the 10-minute
+// stale-claim threshold so a stuck worker is recovered within ~15 min worst case.
+const STALE_CLAIM_SWEEPER_CRON = "*/5 * * * *";
+const STALE_CLAIM_SWEEPER_RUN_HASH_TTL_S = 60 * 60;
+
export type TAuditLogStreamOutboxQueueDep = {
queueService: TQueueServiceFactory;
- auditLogStreamOutboxService: Pick<TAuditLogStreamOutboxServiceFactory, "drainStream">;
+ cronJob: TCronJobFactory;
+ auditLogStreamOutboxService: Pick<TAuditLogStreamOutboxServiceFactory, "drainStream" | "sweepStaleClaims">;
};
// Boots one BullMQ worker per provider so a slow upstream (e.g. a wedged
// Splunk HEC) can't block deliveries to a healthy one (e.g. Datadog).
export const auditLogStreamOutboxQueueFactory = ({
queueService,
+ cronJob,
auditLogStreamOutboxService
}: TAuditLogStreamOutboxQueueDep) => {
const registerWorker = <T extends QueueName>(queueName: T, provider: LogProvider) => {
@@ -35,4 +43,19 @@ export const auditLogStreamOutboxQueueFactory = ({
registerWorker(QueueName.AuditLogStreamCustom, LogProvider.Custom);
registerWorker(QueueName.AuditLogStreamDatadog, LogProvider.Datadog);
registerWorker(QueueName.AuditLogStreamSplunk, LogProvider.Splunk);
+
+ // Stale-claim sweeper. Registered separately via init() so it lands in the
+ // cron startup batch alongside the other cron registrations in routes/index.ts.
+ const init = () => {
+ cronJob.register({
+ name: CronJobName.AuditLogStreamOutboxStaleClaimSweeper,
+ pattern: STALE_CLAIM_SWEEPER_CRON,
+ runHashTtlS: STALE_CLAIM_SWEEPER_RUN_HASH_TTL_S,
+ handler: async () => {
+ await auditLogStreamOutboxService.sweepStaleClaims();
+ }
+ });
+ };
+
+ return { init };
};
diff --git a/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-service.ts b/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-service.ts
index 890bb84425..ddb73b00fd 100644
--- a/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-service.ts
+++ b/backend/src/ee/services/audit-log-stream-outbox/audit-log-stream-outbox-service.ts
@@ -27,6 +27,11 @@ const MAX_ATTEMPTS = 5;
const BACKOFF_BASE_MS = 30_000;
const BACKOFF_MAX_MS = 15 * 60_000;
+// Stale-claim sweeper threshold: a single flush job's worst-case legitimate
+// hold time is MAX_BATCHES_PER_JOB × AUDIT_LOG_STREAM_BATCH_TIMEOUT ≈ 5 min.
+// Anything older than this can't be a live worker.
+export const STALE_CLAIM_THRESHOLD_MS = 10 * 60_000;
+
const PROVIDER_QUEUE_MAP: Record<LogProvider, QueueName> = {
[LogProvider.Azure]: QueueName.AuditLogStreamAzure,
[LogProvider.Cribl]: QueueName.AuditLogStreamCribl,
@@ -81,6 +86,7 @@ export type TAuditLogStreamOutboxServiceFactoryDep = {
export type TAuditLogStreamOutboxServiceFactory = {
enqueueForOrg: (orgId: string, auditLog: TAuditLogs) => Promise<void>;
drainStream: (data: TAuditLogStreamFlushJobData) => Promise<void>;
+ sweepStaleClaims: () => Promise<void>;
};
export const auditLogStreamOutboxServiceFactory = ({
@@ -91,6 +97,37 @@ export const auditLogStreamOutboxServiceFactory = ({
queueService,
onStreamFailure
}: TAuditLogStreamOutboxServiceFactoryDep): TAuditLogStreamOutboxServiceFactory => {
+ // Try to win the 5s SETNX debounce for a stream and, on win, enqueue a delayed
+ // flush job on the matching per-provider queue. Returning false means another
+ // writer already covered the window — there's nothing for the caller to do.
+ const debounceAndEnqueueFlush = async (streamId: string, orgId: string, provider: LogProvider): Promise<boolean> => {
+ const queueName = PROVIDER_QUEUE_MAP[provider];
+ if (!queueName) {
+ logger.warn(
+ `audit-log-stream-outbox: unknown provider, skipping flush enqueue [provider=${provider}] [streamId=${streamId}]`
+ );
+ return false;
+ }
+
+ const debounceKey = KeyStorePrefixes.AuditLogStreamFlushDebounce(streamId);
+ const acquired = await keyStore.setItemWithExpiryNX(debounceKey, FLUSH_DEBOUNCE_SECONDS, "1");
+ if (!acquired) return false;
+
+ // Job ID matches the debounce key so BullMQ collapses any in-flight duplicates.
+ await queueService.queue(
+ queueName,
+ QueueJobs.AuditLogStreamFlush,
+ { streamId, orgId, provider },
+ {
+ jobId: `flush:${streamId}`,
+ delay: FLUSH_DEBOUNCE_MS,
+ removeOnComplete: true,
+ removeOnFail: { count: 50 }
+ }
+ );
+ return true;
+ };
+
// Per-audit-log fanout:
// 1. Look up active streams for the org.
// 2. Insert one outbox row per stream (payload is self-contained).
@@ -106,33 +143,7 @@ export const auditLogStreamOutboxServiceFactory = ({
);
await Promise.allSettled(
- streams.map(async (stream) => {
- const provider = stream.provider as LogProvider;
- const queueName = PROVIDER_QUEUE_MAP[provider];
- if (!queueName) {
- logger.warn(
- `audit-log-stream-outbox: unknown provider, skipping flush enqueue [provider=${provider}] [streamId=${stream.id}]`
- );
- return;
- }
-
- const debounceKey = KeyStorePrefixes.AuditLogStreamFlushDebounce(stream.id);
- const acquired = await keyStore.setItemWithExpiryNX(debounceKey, FLUSH_DEBOUNCE_SECONDS, "1");
- if (!acquired) return;
-
- // Job ID matches the debounce key so BullMQ collapses any in-flight duplicates.
- await queueService.queue(
- queueName,
- QueueJobs.AuditLogStreamFlush,
- { streamId: stream.id, orgId, provider },
- {
- jobId: `flush:${stream.id}`,
- delay: FLUSH_DEBOUNCE_MS,
- removeOnComplete: true,
- removeOnFail: { count: 50 }
- }
- );
- })
+ streams.map((stream) => debounceAndEnqueueFlush(stream.id, orgId, stream.provider as LogProvider))
);
};
@@ -223,8 +234,22 @@ export const auditLogStreamOutboxServiceFactory = ({
}
};
+ // Stale-claim sweeper. Rows whose worker crashed mid-batch stay 'processing'
+ // forever and never re-enter the drain query. Flip them back to 'retry' so
+ // the next event for that stream picks them up via the normal debounce path.
+ const sweepStaleClaims = async () => {
+ const staleBefore = new Date(Date.now() - STALE_CLAIM_THRESHOLD_MS);
+ const recovered = await auditLogStreamOutboxDAL.requeueStaleClaims(staleBefore);
+ if (recovered > 0) {
+ logger.warn(
+ `audit-log-stream-outbox: recovered ${recovered} stale claims [staleBefore=${staleBefore.toISOString()}]`
+ );
+ }
+ };
+
return {
enqueueForOrg,
- drainStream
+ drainStream,
+ sweepStaleClaims
};
};
diff --git a/backend/src/lib/cron/cron-job.ts b/backend/src/lib/cron/cron-job.ts
index 6d976ad110..30b0774c6d 100644
--- a/backend/src/lib/cron/cron-job.ts
+++ b/backend/src/lib/cron/cron-job.ts
@@ -35,7 +35,8 @@ export const CronJobName = {
GoDaddyOrderPolling: "godaddy-order-polling",
CaCrlRotation: "ca-crl-rotation",
SignerDailyAutoRenewal: "signer-daily-auto-renewal",
- SignerIssuancePolling: "signer-issuance-polling"
+ SignerIssuancePolling: "signer-issuance-polling",
+ AuditLogStreamOutboxStaleClaimSweeper: "audit-log-stream-outbox-stale-claim-sweeper"
} as const;
// ── tuning constants ──────────────────────────────────────────────────────────
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 1003c75241..dff0d9609a 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -929,8 +929,9 @@ export const registerRoutes = async (
auditLogStreamService.recordStreamFailure(orgId, streamId, provider, errorMessage)
});
- auditLogStreamOutboxQueueFactory({
+ const auditLogStreamOutboxQueue = auditLogStreamOutboxQueueFactory({
queueService,
+ cronJob,
auditLogStreamOutboxService
});
@@ -3606,6 +3607,7 @@ export const registerRoutes = async (
projectEnvQueue.init();
projectCleanupQueue.init();
healthAlert.init();
+ auditLogStreamOutboxQueue.init();
pkiSyncCleanup.init();
pkiDiscoveryQueue.startPkiDiscoveryScanQueue();
pamDiscoveryQueue.startPamDiscoveryQueue();