bunqueue 2.9.0 → 2.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (150) hide show
  1. package/README.md +7 -3
  2. package/dist/application/background/recovery/active.d.ts +1 -0
  3. package/dist/application/background/recovery/active.js +12 -0
  4. package/dist/application/background/recovery/index.js +3 -1
  5. package/dist/application/background/recovery/pending.js +1 -0
  6. package/dist/application/cleanupTasks.js +4 -16
  7. package/dist/application/contextFactory.js +3 -0
  8. package/dist/application/dlqManager.js +1 -0
  9. package/dist/application/dlqRetry.js +1 -0
  10. package/dist/application/eventsManager.d.ts +8 -1
  11. package/dist/application/eventsManager.js +76 -29
  12. package/dist/application/operations/ackHelpers.d.ts +1 -4
  13. package/dist/application/operations/ackHelpers.js +39 -14
  14. package/dist/application/operations/flowPush.js +1 -0
  15. package/dist/application/operations/flowValidation.js +4 -4
  16. package/dist/application/operations/pull.d.ts +7 -2
  17. package/dist/application/operations/pull.js +15 -57
  18. package/dist/application/operations/pullFinalization.d.ts +6 -0
  19. package/dist/application/operations/pullFinalization.js +69 -0
  20. package/dist/application/operations/pullStateTransition.d.ts +8 -7
  21. package/dist/application/operations/pullStateTransition.js +25 -18
  22. package/dist/application/operations/push.js +3 -0
  23. package/dist/application/operations/pushBatch.js +14 -7
  24. package/dist/application/operations/pushContext.d.ts +2 -1
  25. package/dist/application/postgres-queue-manager/control.d.ts +4 -0
  26. package/dist/application/postgres-queue-manager/control.js +24 -0
  27. package/dist/application/postgres-queue-manager/delivery.d.ts +5 -4
  28. package/dist/application/postgres-queue-manager/delivery.js +13 -10
  29. package/dist/application/postgres-queue-manager/groupQueries.d.ts +10 -0
  30. package/dist/application/postgres-queue-manager/groupQueries.js +40 -0
  31. package/dist/application/postgres-queue-manager/queries.d.ts +2 -2
  32. package/dist/application/postgres-queue-manager/queries.js +2 -2
  33. package/dist/application/queue-manager/control.js +1 -0
  34. package/dist/application/queue-manager/delivery.d.ts +5 -4
  35. package/dist/application/queue-manager/delivery.js +15 -8
  36. package/dist/application/queue-manager/limits.d.ts +11 -0
  37. package/dist/application/queue-manager/limits.js +61 -0
  38. package/dist/application/queue-manager/state.js +1 -1
  39. package/dist/application/queueTelemetryJournal.d.ts +2 -0
  40. package/dist/application/queueTelemetryJournal.js +23 -0
  41. package/dist/application/types/ack.d.ts +3 -1
  42. package/dist/cli/commandRouter.d.ts +1 -1
  43. package/dist/client/flowPush.js +6 -0
  44. package/dist/client/groupId.d.ts +1 -0
  45. package/dist/client/groupId.js +1 -0
  46. package/dist/client/index.d.ts +1 -1
  47. package/dist/client/jobHelpers.js +1 -0
  48. package/dist/client/queue/operations/add/bulk.js +4 -4
  49. package/dist/client/queue/operations/add/payload.d.ts +1 -0
  50. package/dist/client/queue/operations/add/payload.js +7 -1
  51. package/dist/client/queue/operations/add/single.js +3 -3
  52. package/dist/client/queue/operations/groups.d.ts +21 -0
  53. package/dist/client/queue/operations/groups.js +88 -0
  54. package/dist/client/queue/runtime/queries.d.ts +13 -0
  55. package/dist/client/queue/runtime/queries.js +31 -0
  56. package/dist/client/queue/runtime/state.d.ts +4 -0
  57. package/dist/client/queue/runtime/state.js +1 -0
  58. package/dist/client/types/index.d.ts +2 -2
  59. package/dist/client/types/options.d.ts +4 -0
  60. package/dist/client/types/worker.d.ts +8 -0
  61. package/dist/client/worker/runtime/execution.js +1 -0
  62. package/dist/client/worker/runtime/options.js +3 -0
  63. package/dist/client/worker/types/options.d.ts +2 -1
  64. package/dist/client/worker/workerPull.d.ts +2 -0
  65. package/dist/client/worker/workerPull.js +6 -4
  66. package/dist/domain/job/groupFifoOrder.d.ts +9 -0
  67. package/dist/domain/job/groupFifoOrder.js +26 -0
  68. package/dist/domain/queue/groupLimiterManager.d.ts +23 -0
  69. package/dist/domain/queue/groupLimiterManager.js +107 -0
  70. package/dist/domain/queue/groupScheduler.d.ts +31 -0
  71. package/dist/domain/queue/groupScheduler.js +256 -0
  72. package/dist/domain/queue/groupSchedulerOrder.d.ts +6 -0
  73. package/dist/domain/queue/groupSchedulerOrder.js +30 -0
  74. package/dist/domain/queue/priorityQueue.d.ts +13 -23
  75. package/dist/domain/queue/priorityQueue.js +53 -42
  76. package/dist/domain/queue/shard/keys.d.ts +1 -0
  77. package/dist/domain/queue/shard/keys.js +25 -2
  78. package/dist/domain/queue/shard/lifecycle.js +4 -0
  79. package/dist/domain/queue/shard/limits.d.ts +20 -1
  80. package/dist/domain/queue/shard/limits.js +56 -0
  81. package/dist/domain/queue/shard/state.d.ts +5 -0
  82. package/dist/domain/queue/shard/state.js +9 -1
  83. package/dist/domain/types/commands/core.d.ts +3 -0
  84. package/dist/domain/types/commands/limits.d.ts +41 -0
  85. package/dist/domain/types/commands/union.d.ts +1 -1
  86. package/dist/domain/types/group.d.ts +21 -0
  87. package/dist/domain/types/group.js +78 -0
  88. package/dist/domain/types/priorityQueue.d.ts +1 -0
  89. package/dist/infrastructure/persistence/jobOptionsBlob.d.ts +1 -0
  90. package/dist/infrastructure/persistence/jobOptionsBlob.js +10 -2
  91. package/dist/infrastructure/persistence/migrations.js +11 -0
  92. package/dist/infrastructure/persistence/postgres/admission.js +5 -2
  93. package/dist/infrastructure/persistence/postgres/batchAdmission.js +22 -4
  94. package/dist/infrastructure/persistence/postgres/claimBatch.d.ts +3 -0
  95. package/dist/infrastructure/persistence/postgres/claimBatch.js +16 -3
  96. package/dist/infrastructure/persistence/postgres/claimSelection.d.ts +8 -1
  97. package/dist/infrastructure/persistence/postgres/claimSelection.js +73 -131
  98. package/dist/infrastructure/persistence/postgres/claims.d.ts +8 -1
  99. package/dist/infrastructure/persistence/postgres/claims.js +19 -3
  100. package/dist/infrastructure/persistence/postgres/eventCatchupCursors.d.ts +32 -0
  101. package/dist/infrastructure/persistence/postgres/eventCatchupCursors.js +66 -0
  102. package/dist/infrastructure/persistence/postgres/eventJournalSchema.d.ts +2 -2
  103. package/dist/infrastructure/persistence/postgres/eventJournalSchema.js +16 -2
  104. package/dist/infrastructure/persistence/postgres/eventPruneWatermarks.d.ts +2 -0
  105. package/dist/infrastructure/persistence/postgres/eventPruneWatermarks.js +21 -3
  106. package/dist/infrastructure/persistence/postgres/events.d.ts +3 -3
  107. package/dist/infrastructure/persistence/postgres/events.js +44 -17
  108. package/dist/infrastructure/persistence/postgres/groupClaims.d.ts +15 -0
  109. package/dist/infrastructure/persistence/postgres/groupClaims.js +95 -0
  110. package/dist/infrastructure/persistence/postgres/groupSchema.d.ts +2 -0
  111. package/dist/infrastructure/persistence/postgres/groupSchema.js +155 -0
  112. package/dist/infrastructure/persistence/postgres/groupSchemaFingerprint.d.ts +3 -0
  113. package/dist/infrastructure/persistence/postgres/groupSchemaFingerprint.js +127 -0
  114. package/dist/infrastructure/persistence/postgres/groupStateRetention.d.ts +3 -0
  115. package/dist/infrastructure/persistence/postgres/groupStateRetention.js +93 -0
  116. package/dist/infrastructure/persistence/postgres/groups.d.ts +11 -0
  117. package/dist/infrastructure/persistence/postgres/groups.js +117 -0
  118. package/dist/infrastructure/persistence/postgres/queueDestruction.js +4 -0
  119. package/dist/infrastructure/persistence/postgres/runtime.d.ts +0 -1
  120. package/dist/infrastructure/persistence/postgres/runtime.js +3 -1
  121. package/dist/infrastructure/persistence/postgres/schema.d.ts +2 -2
  122. package/dist/infrastructure/persistence/postgres/schema.js +8 -4
  123. package/dist/infrastructure/persistence/postgres/schemaInitialization.js +6 -1
  124. package/dist/infrastructure/persistence/postgres/store.d.ts +11 -1
  125. package/dist/infrastructure/persistence/postgres/store.js +47 -3
  126. package/dist/infrastructure/persistence/postgres/telemetry.d.ts +2 -0
  127. package/dist/infrastructure/persistence/postgres/telemetry.js +33 -21
  128. package/dist/infrastructure/persistence/postgres/types.d.ts +1 -0
  129. package/dist/infrastructure/persistence/schema.d.ts +2 -2
  130. package/dist/infrastructure/persistence/schema.js +12 -1
  131. package/dist/infrastructure/persistence/sqlite/control.d.ts +14 -0
  132. package/dist/infrastructure/persistence/sqlite/control.js +69 -0
  133. package/dist/infrastructure/persistence/sqlite/jobs.d.ts +12 -0
  134. package/dist/infrastructure/persistence/sqlite/jobs.js +36 -0
  135. package/dist/infrastructure/persistence/sqlite/telemetry.d.ts +2 -1
  136. package/dist/infrastructure/persistence/sqlite/telemetry.js +5 -64
  137. package/dist/infrastructure/persistence/sqlite/telemetryWrites.d.ts +4 -0
  138. package/dist/infrastructure/persistence/sqlite/telemetryWrites.js +123 -0
  139. package/dist/infrastructure/persistence/sqliteSerializer.js +2 -0
  140. package/dist/infrastructure/server/handler-routes/control.js +13 -0
  141. package/dist/infrastructure/server/handlers/core.d.ts +0 -5
  142. package/dist/infrastructure/server/handlers/core.js +15 -18
  143. package/dist/infrastructure/server/handlers/groups.d.ts +11 -0
  144. package/dist/infrastructure/server/handlers/groups.js +55 -0
  145. package/dist/infrastructure/server/handlers/pushBatchValidation.js +4 -1
  146. package/dist/infrastructure/server/protocol/validation.d.ts +1 -0
  147. package/dist/infrastructure/server/protocol/validation.js +1 -0
  148. package/dist/infrastructure/server/protocol.d.ts +1 -1
  149. package/dist/infrastructure/server/protocol.js +1 -1
  150. package/package.json +2 -1
@@ -16,6 +16,7 @@ import { cleanPostgresQueue, purgePostgresDlq } from './maintenance';
16
16
  import { maintainPostgresDlq } from './dlqLifecycle';
17
17
  import { addPostgresJobLog, clearPostgresJobLogs, getPostgresJobLogs } from './logs';
18
18
  import { getPostgresCron, listPostgresCrons, processPostgresCrons, removePostgresCron, upsertPostgresCron, } from './crons';
19
+ import { assertGroupPullOptions } from '../../../domain/types/group';
19
20
  import { heartbeatPostgresWorker, listPostgresWorkers, removePostgresClientWorkers, removePostgresWorker, savePostgresWorker, } from './workers';
20
21
  import { getPostgresQueueMetrics, trimPostgresQueueEvents } from './telemetry';
21
22
  import { releasePostgresClientLease } from './leaseRelease';
@@ -28,16 +29,49 @@ import { loadPostgresLifetimeMetrics } from './lifetimeMetrics';
28
29
  import { finalizePostgresLifetimeMetrics } from './lifetimeMetricsFinalizer';
29
30
  import { loadPostgresCloudReadModel } from './cloudReadModel';
30
31
  import { removePostgresUnprocessedChildren } from './removeUnprocessedChildren';
32
+ import { getPostgresGroupActiveCount, getPostgresGroupConcurrency, getPostgresGroupJobsCount, getPostgresGroupRateLimit, getPostgresGroupRateLimitTtl, removePostgresGroupConcurrency, removePostgresGroupRateLimit, setPostgresGroupConcurrency, setPostgresGroupRateLimit, } from './groups';
33
+ import { prunePostgresGroupStates } from './groupStateRetention';
31
34
  import { loadPostgresJobProjections, loadPostgresManagerSnapshot, loadPostgresQueueReadModel, } from './readModels';
35
+ function pruneInactiveGroups(ctx) {
36
+ return runPostgresPostCommitMaintenance(ctx, 'group-state-retention', async () => {
37
+ await prunePostgresGroupStates(ctx);
38
+ });
39
+ }
32
40
  /** Database-authoritative PostgreSQL queue store safe for concurrent brokers. */
33
41
  export class PostgresQueueStore extends PostgresAdmissionStore {
42
+ getGroupJobsCount = (queue, groupId) => getPostgresGroupJobsCount(this.context, queue, groupId);
43
+ getGroupActiveCount = (queue, groupId) => getPostgresGroupActiveCount(this.context, queue, groupId);
44
+ setGroupRateLimit = (queue, groupId, max, duration) => setPostgresGroupRateLimit(this.context, queue, groupId, max, duration);
45
+ getGroupRateLimit = (queue, groupId) => getPostgresGroupRateLimit(this.context, queue, groupId);
46
+ removeGroupRateLimit = async (queue, groupId) => {
47
+ const removed = await removePostgresGroupRateLimit(this.context, queue, groupId);
48
+ if (removed)
49
+ await pruneInactiveGroups(this.context);
50
+ return removed;
51
+ };
52
+ getGroupRateLimitTtl = (queue, groupId, maxJobs) => getPostgresGroupRateLimitTtl(this.context, queue, groupId, maxJobs);
53
+ setGroupConcurrency = (queue, groupId, concurrency) => setPostgresGroupConcurrency(this.context, queue, groupId, concurrency);
54
+ getGroupConcurrency = (queue, groupId) => getPostgresGroupConcurrency(this.context, queue, groupId);
55
+ removeGroupConcurrency = async (queue, groupId) => {
56
+ const removed = await removePostgresGroupConcurrency(this.context, queue, groupId);
57
+ if (removed)
58
+ await pruneInactiveGroups(this.context);
59
+ return removed;
60
+ };
34
61
  async now() {
35
62
  await this.initialize();
36
63
  return await databaseNow(this.context.sql);
37
64
  }
38
- async claim(queue, count, owner = this.config.brokerId, leaseDurationMs = this.config.leaseDurationMs) {
65
+ async claim(queue, count, owner = this.config.brokerId, leaseDurationMs = this.config.leaseDurationMs, groupOptions) {
66
+ assertGroupPullOptions(groupOptions);
39
67
  await this.initialize();
40
- return await claimPostgresJobs(this.context, queue, count, owner, leaseDurationMs);
68
+ return await claimPostgresJobs(this.context, {
69
+ queue,
70
+ count,
71
+ owner,
72
+ leaseDurationMs,
73
+ groupOptions,
74
+ });
41
75
  }
42
76
  async complete(id, token, result, remove = false) {
43
77
  await this.initialize();
@@ -45,6 +79,9 @@ export class PostgresQueueStore extends PostgresAdmissionStore {
45
79
  if (transition.applied && (remove || transition.job?.removeOnComplete)) {
46
80
  await runPostgresPostCommitMaintenance(this.context, 'completion-retention', () => prunePostgresCompletionTombstones(this.context));
47
81
  }
82
+ if (transition.applied && transition.job?.groupId) {
83
+ await pruneInactiveGroups(this.context);
84
+ }
48
85
  return transition;
49
86
  }
50
87
  async completeMany(items) {
@@ -53,11 +90,18 @@ export class PostgresQueueStore extends PostgresAdmissionStore {
53
90
  if (transitions.some((transition) => transition.applied && transition.removed)) {
54
91
  await runPostgresPostCommitMaintenance(this.context, 'completion-retention', () => prunePostgresCompletionTombstones(this.context));
55
92
  }
93
+ if (transitions.some((transition) => transition.applied && transition.job?.groupId)) {
94
+ await pruneInactiveGroups(this.context);
95
+ }
56
96
  return transitions;
57
97
  }
58
98
  async fail(input) {
59
99
  await this.initialize();
60
- return await failPostgresJob(this.context, input);
100
+ const transition = await failPostgresJob(this.context, input);
101
+ if (transition.applied && transition.state === 'failed' && transition.job?.groupId) {
102
+ await pruneInactiveGroups(this.context);
103
+ }
104
+ return transition;
61
105
  }
62
106
  async renew(id, token, durationMs) {
63
107
  await this.initialize();
@@ -2,5 +2,7 @@ import type { QueueMetrics, QueueMetricType } from '../../../domain/types/metric
2
2
  import type { PostgresContext } from './context';
3
3
  export declare function getPostgresQueueMetrics(ctx: PostgresContext, queue: string, type: QueueMetricType, start?: number, end?: number): Promise<QueueMetrics>;
4
4
  export declare function trimPostgresQueueEvents(ctx: PostgresContext, queue: string, maxLength: number): Promise<number>;
5
+ /** Try one automatic retention sweep without waiting behind an active writer. */
6
+ export declare function tryTrimPostgresQueueEvents(ctx: PostgresContext, queue: string, maxLength: number): Promise<number | null>;
5
7
  /** Converge retained windows after missed notifications or an unclean broker exit. */
6
8
  export declare function sweepPostgresEventRetention(ctx: PostgresContext): Promise<number>;
@@ -1,5 +1,5 @@
1
1
  import { recordPostgresEventPruneWatermarks, summarizePostgresPrunedEvents, } from './eventPruneWatermarks';
2
- import { lockPostgresEventRetention, prunePostgresQueueEvents } from './eventRetention';
2
+ import { lockPostgresEventRetention, prunePostgresQueueEvents, tryLockPostgresEventRetention, } from './eventRetention';
3
3
  import { POSTGRES_EVENT_CHANNEL } from './schema';
4
4
  function assertNonNegativeInteger(value, name) {
5
5
  if (!Number.isSafeInteger(value) || value < 0) {
@@ -44,30 +44,42 @@ export async function getPostgresQueueMetrics(ctx, queue, type, start = 0, end =
44
44
  count,
45
45
  };
46
46
  }
47
+ async function trimLockedPostgresQueueEvents(tx, ctx, queue, maxLength) {
48
+ const rows = await prunePostgresQueueEvents(tx, ctx, queue, maxLength);
49
+ const prune = summarizePostgresPrunedEvents(rows);
50
+ const { prunedThrough } = prune;
51
+ if (prunedThrough > 0) {
52
+ await recordPostgresEventPruneWatermarks(tx, ctx, [
53
+ {
54
+ queue,
55
+ sourceEventId: prunedThrough,
56
+ ...prune,
57
+ prunesCurrentTransaction: false,
58
+ },
59
+ ]);
60
+ await tx.notify(POSTGRES_EVENT_CHANNEL, JSON.stringify({
61
+ namespace: ctx.config.namespace,
62
+ queue,
63
+ brokerId: ctx.config.brokerId,
64
+ prunedThrough,
65
+ }));
66
+ }
67
+ return rows.length;
68
+ }
47
69
  export async function trimPostgresQueueEvents(ctx, queue, maxLength) {
48
70
  assertNonNegativeInteger(maxLength, 'maxLength');
49
71
  return await ctx.sql.begin(async (tx) => {
50
72
  await lockPostgresEventRetention(tx, ctx, queue);
51
- const rows = await prunePostgresQueueEvents(tx, ctx, queue, maxLength);
52
- const prune = summarizePostgresPrunedEvents(rows);
53
- const { prunedThrough } = prune;
54
- if (prunedThrough > 0) {
55
- await recordPostgresEventPruneWatermarks(tx, ctx, [
56
- {
57
- queue,
58
- sourceEventId: prunedThrough,
59
- ...prune,
60
- prunesCurrentTransaction: false,
61
- },
62
- ]);
63
- await tx.notify(POSTGRES_EVENT_CHANNEL, JSON.stringify({
64
- namespace: ctx.config.namespace,
65
- queue,
66
- brokerId: ctx.config.brokerId,
67
- prunedThrough,
68
- }));
69
- }
70
- return rows.length;
73
+ return await trimLockedPostgresQueueEvents(tx, ctx, queue, maxLength);
74
+ });
75
+ }
76
+ /** Try one automatic retention sweep without waiting behind an active writer. */
77
+ export async function tryTrimPostgresQueueEvents(ctx, queue, maxLength) {
78
+ assertNonNegativeInteger(maxLength, 'maxLength');
79
+ return await ctx.sql.begin(async (tx) => {
80
+ if (!(await tryLockPostgresEventRetention(tx, ctx, queue)))
81
+ return null;
82
+ return await trimLockedPostgresQueueEvents(tx, ctx, queue, maxLength);
71
83
  });
72
84
  }
73
85
  /** Converge retained windows after missed notifications or an unclean broker exit. */
@@ -61,6 +61,7 @@ export interface PostgresJobRow {
61
61
  unique_expires_at: number | string | bigint | null;
62
62
  custom_id: string | null;
63
63
  group_id: string | null;
64
+ group_order: number | string | bigint | null;
64
65
  parent_id: string | null;
65
66
  lease_owner: string | null;
66
67
  lease_broker_id: string | null;
@@ -1,8 +1,8 @@
1
1
  /** SQLite PRAGMA settings for optimal performance */
2
2
  export declare const PRAGMA_SETTINGS = "\nPRAGMA journal_mode = WAL;\nPRAGMA synchronous = NORMAL;\nPRAGMA cache_size = -64000;\nPRAGMA temp_store = MEMORY;\nPRAGMA mmap_size = 268435456;\nPRAGMA page_size = 4096;\nPRAGMA busy_timeout = 5000;\n";
3
3
  /** Main schema creation. */
4
- export declare const SCHEMA = "\n-- Jobs table (using UUIDv7 for job IDs)\n-- Uses BLOB for data fields (MessagePack serialization for ~2-3x faster than JSON)\nCREATE TABLE IF NOT EXISTS jobs (\n id TEXT PRIMARY KEY,\n queue TEXT NOT NULL,\n name TEXT,\n data BLOB NOT NULL,\n priority INTEGER NOT NULL DEFAULT 0,\n created_at INTEGER NOT NULL,\n run_at INTEGER NOT NULL,\n started_at INTEGER,\n completed_at INTEGER,\n attempts INTEGER NOT NULL DEFAULT 0,\n max_attempts INTEGER NOT NULL DEFAULT 3,\n backoff INTEGER NOT NULL DEFAULT 1000,\n ttl INTEGER,\n timeout INTEGER,\n unique_key TEXT,\n custom_id TEXT,\n depends_on BLOB,\n parent_id TEXT,\n children_ids BLOB,\n tags BLOB,\n state TEXT NOT NULL DEFAULT 'waiting',\n lifo INTEGER NOT NULL DEFAULT 0,\n group_id TEXT,\n progress INTEGER DEFAULT 0,\n progress_msg TEXT,\n remove_on_complete INTEGER DEFAULT 0,\n remove_on_fail INTEGER DEFAULT 0,\n fail_parent_on_failure INTEGER NOT NULL DEFAULT 0,\n remove_dependency_on_failure INTEGER NOT NULL DEFAULT 0,\n continue_parent_on_failure INTEGER NOT NULL DEFAULT 0,\n ignore_dependency_on_failure INTEGER NOT NULL DEFAULT 0,\n stall_timeout INTEGER,\n last_heartbeat INTEGER,\n stall_count INTEGER NOT NULL DEFAULT 0,\n timeline BLOB,\n stacktrace BLOB,\n dlq_retry_state BLOB,\n extended_options BLOB\n);\n\n-- Indexes for common queries\nCREATE INDEX IF NOT EXISTS idx_jobs_queue_state\n ON jobs(queue, state);\n-- Stable createdAt/id pagination for unfiltered and logical-state queue views\nCREATE INDEX IF NOT EXISTS idx_jobs_queue_created\n ON jobs(queue, created_at, id);\nCREATE INDEX IF NOT EXISTS idx_jobs_queue_state_created\n ON jobs(queue, state, created_at, id);\nCREATE INDEX IF NOT EXISTS idx_jobs_run_at\n ON jobs(run_at) WHERE state IN ('waiting', 'prioritized', 'waiting-children', 'delayed');\nCREATE INDEX IF NOT EXISTS idx_jobs_unique\n ON jobs(queue, unique_key) WHERE unique_key IS NOT NULL;\nCREATE INDEX IF NOT EXISTS idx_jobs_custom_id\n ON jobs(custom_id) WHERE custom_id IS NOT NULL;\nCREATE INDEX IF NOT EXISTS idx_jobs_parent\n ON jobs(parent_id) WHERE parent_id IS NOT NULL;\n\n-- Durable outbox/state for terminal child failure propagation.\nCREATE TABLE IF NOT EXISTS flow_failures (\n parent_id TEXT NOT NULL,\n child_id TEXT NOT NULL,\n child_queue TEXT NOT NULL,\n mode TEXT NOT NULL,\n error TEXT NOT NULL,\n created_at INTEGER NOT NULL,\n PRIMARY KEY (parent_id, child_id)\n);\nCREATE INDEX IF NOT EXISTS idx_flow_failures_parent ON flow_failures(parent_id);\n\n\nCREATE TABLE IF NOT EXISTS dependency_completions (\n sequence INTEGER PRIMARY KEY AUTOINCREMENT,\n job_id TEXT NOT NULL UNIQUE,\n queue TEXT NOT NULL,\n completed_at INTEGER NOT NULL,\n pinned INTEGER NOT NULL DEFAULT 0\n);\nCREATE INDEX IF NOT EXISTS idx_dependency_completions_queue\n ON dependency_completions(queue);\n\n\n-- Job results storage (BLOB for MessagePack)\nCREATE TABLE IF NOT EXISTS job_results (\n job_id TEXT PRIMARY KEY,\n result BLOB,\n completed_at INTEGER NOT NULL\n);\n\n-- Dead letter queue (BLOB for MessagePack - stores full DlqEntry)\nCREATE TABLE IF NOT EXISTS dlq (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n job_id TEXT NOT NULL,\n queue TEXT NOT NULL,\n entry BLOB NOT NULL,\n entered_at INTEGER NOT NULL\n);\n\nCREATE INDEX IF NOT EXISTS idx_dlq_queue ON dlq(queue);\nCREATE INDEX IF NOT EXISTS idx_dlq_job_id ON dlq(job_id);\nCREATE INDEX IF NOT EXISTS idx_dlq_entered_at ON dlq(entered_at);\n\n-- Performance indexes for high-throughput operations\n-- Stall detection: runs every 5s, needs fast lookup of active jobs by started_at\nCREATE INDEX IF NOT EXISTS idx_jobs_state_started\n ON jobs(state, started_at) WHERE state = 'active';\n\n-- Group operations: fast lookup by group_id\nCREATE INDEX IF NOT EXISTS idx_jobs_group_id\n ON jobs(group_id) WHERE group_id IS NOT NULL;\n\n-- Pending jobs: compound index for priority-ordered retrieval\nCREATE INDEX IF NOT EXISTS idx_jobs_pending_priority\n ON jobs(queue, state, priority DESC, run_at ASC) WHERE state IN ('waiting', 'prioritized', 'waiting-children', 'delayed');\n\n-- Completed jobs: index for recovery ordering (issue #84)\nCREATE INDEX IF NOT EXISTS idx_jobs_completed_order\n ON jobs(completed_at DESC) WHERE state = 'completed';\n\n-- Cron jobs (BLOB for MessagePack)\nCREATE TABLE IF NOT EXISTS cron_jobs (\n name TEXT PRIMARY KEY,\n queue TEXT NOT NULL,\n job_name TEXT,\n data BLOB NOT NULL,\n schedule TEXT,\n repeat_every INTEGER,\n priority INTEGER NOT NULL DEFAULT 0,\n next_run INTEGER NOT NULL,\n executions INTEGER NOT NULL DEFAULT 0,\n max_limit INTEGER,\n timezone TEXT,\n unique_key TEXT,\n dedup BLOB,\n skip_missed_on_restart INTEGER NOT NULL DEFAULT 0,\n skip_if_no_worker INTEGER NOT NULL DEFAULT 0,\n prevent_overlap INTEGER NOT NULL DEFAULT 1,\n job_options BLOB\n);\n\n-- Queue state persistence (optional)\nCREATE TABLE IF NOT EXISTS queue_state (\n name TEXT PRIMARY KEY,\n paused INTEGER NOT NULL DEFAULT 0,\n rate_limit INTEGER,\n concurrency_limit INTEGER,\n rate_limit_duration INTEGER,\n rate_limit_expires_at INTEGER,\n stall_enabled INTEGER,\n stall_interval INTEGER,\n max_stalls INTEGER,\n stall_grace_period INTEGER,\n dlq_config BLOB\n);\n\n-- Per-queue lifecycle event journal. Entries are kept newest-first by id and\n-- bounded by QueueManagerConfig.maxQueueEvents when they are appended.\nCREATE TABLE IF NOT EXISTS queue_events (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n queue TEXT NOT NULL,\n event_type TEXT NOT NULL,\n job_id TEXT NOT NULL,\n occurred_at INTEGER NOT NULL,\n payload BLOB\n);\nCREATE INDEX IF NOT EXISTS idx_queue_events_queue_id\n ON queue_events(queue, id DESC);\n\n-- Cumulative terminal counters are separate from bounded minute buckets so\n-- pruning old data points never resets meta.count.\nCREATE TABLE IF NOT EXISTS queue_metrics_meta (\n queue TEXT NOT NULL,\n type TEXT NOT NULL CHECK (type IN ('completed', 'failed')),\n total_count INTEGER NOT NULL DEFAULT 0,\n prev_ts INTEGER NOT NULL DEFAULT 0,\n prev_count INTEGER NOT NULL DEFAULT 0,\n PRIMARY KEY (queue, type)\n);\nCREATE TABLE IF NOT EXISTS queue_metric_buckets (\n queue TEXT NOT NULL,\n type TEXT NOT NULL CHECK (type IN ('completed', 'failed')),\n minute INTEGER NOT NULL,\n count INTEGER NOT NULL DEFAULT 0,\n PRIMARY KEY (queue, type, minute)\n);\nCREATE INDEX IF NOT EXISTS idx_queue_metric_buckets_window\n ON queue_metric_buckets(queue, type, minute DESC);\n";
4
+ export declare const SCHEMA = "\n-- Jobs table (using UUIDv7 for job IDs)\n-- Uses BLOB for data fields (MessagePack serialization for ~2-3x faster than JSON)\nCREATE TABLE IF NOT EXISTS jobs (\n id TEXT PRIMARY KEY,\n queue TEXT NOT NULL,\n name TEXT,\n data BLOB NOT NULL,\n priority INTEGER NOT NULL DEFAULT 0,\n created_at INTEGER NOT NULL,\n run_at INTEGER NOT NULL,\n started_at INTEGER,\n completed_at INTEGER,\n attempts INTEGER NOT NULL DEFAULT 0,\n max_attempts INTEGER NOT NULL DEFAULT 3,\n backoff INTEGER NOT NULL DEFAULT 1000,\n ttl INTEGER,\n timeout INTEGER,\n unique_key TEXT,\n custom_id TEXT,\n depends_on BLOB,\n parent_id TEXT,\n children_ids BLOB,\n tags BLOB,\n state TEXT NOT NULL DEFAULT 'waiting',\n lifo INTEGER NOT NULL DEFAULT 0,\n group_id TEXT,\n progress INTEGER DEFAULT 0,\n progress_msg TEXT,\n remove_on_complete INTEGER DEFAULT 0,\n remove_on_fail INTEGER DEFAULT 0,\n fail_parent_on_failure INTEGER NOT NULL DEFAULT 0,\n remove_dependency_on_failure INTEGER NOT NULL DEFAULT 0,\n continue_parent_on_failure INTEGER NOT NULL DEFAULT 0,\n ignore_dependency_on_failure INTEGER NOT NULL DEFAULT 0,\n stall_timeout INTEGER,\n last_heartbeat INTEGER,\n stall_count INTEGER NOT NULL DEFAULT 0,\n timeline BLOB,\n stacktrace BLOB,\n dlq_retry_state BLOB,\n extended_options BLOB\n);\n\n-- Indexes for common queries\nCREATE INDEX IF NOT EXISTS idx_jobs_queue_state\n ON jobs(queue, state);\n-- Stable createdAt/id pagination for unfiltered and logical-state queue views\nCREATE INDEX IF NOT EXISTS idx_jobs_queue_created\n ON jobs(queue, created_at, id);\nCREATE INDEX IF NOT EXISTS idx_jobs_queue_state_created\n ON jobs(queue, state, created_at, id);\nCREATE INDEX IF NOT EXISTS idx_jobs_run_at\n ON jobs(run_at) WHERE state IN ('waiting', 'prioritized', 'waiting-children', 'delayed');\nCREATE INDEX IF NOT EXISTS idx_jobs_unique\n ON jobs(queue, unique_key) WHERE unique_key IS NOT NULL;\nCREATE INDEX IF NOT EXISTS idx_jobs_custom_id\n ON jobs(custom_id) WHERE custom_id IS NOT NULL;\nCREATE INDEX IF NOT EXISTS idx_jobs_parent\n ON jobs(parent_id) WHERE parent_id IS NOT NULL;\n\n-- Durable outbox/state for terminal child failure propagation.\nCREATE TABLE IF NOT EXISTS flow_failures (\n parent_id TEXT NOT NULL,\n child_id TEXT NOT NULL,\n child_queue TEXT NOT NULL,\n mode TEXT NOT NULL,\n error TEXT NOT NULL,\n created_at INTEGER NOT NULL,\n PRIMARY KEY (parent_id, child_id)\n);\nCREATE INDEX IF NOT EXISTS idx_flow_failures_parent ON flow_failures(parent_id);\n\n\nCREATE TABLE IF NOT EXISTS dependency_completions (\n sequence INTEGER PRIMARY KEY AUTOINCREMENT,\n job_id TEXT NOT NULL UNIQUE,\n queue TEXT NOT NULL,\n completed_at INTEGER NOT NULL,\n pinned INTEGER NOT NULL DEFAULT 0\n);\nCREATE INDEX IF NOT EXISTS idx_dependency_completions_queue\n ON dependency_completions(queue);\n\n\n-- Job results storage (BLOB for MessagePack)\nCREATE TABLE IF NOT EXISTS job_results (\n job_id TEXT PRIMARY KEY,\n result BLOB,\n completed_at INTEGER NOT NULL\n);\n\n-- Dead letter queue (BLOB for MessagePack - stores full DlqEntry)\nCREATE TABLE IF NOT EXISTS dlq (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n job_id TEXT NOT NULL,\n queue TEXT NOT NULL,\n entry BLOB NOT NULL,\n entered_at INTEGER NOT NULL\n);\n\nCREATE INDEX IF NOT EXISTS idx_dlq_queue ON dlq(queue);\nCREATE INDEX IF NOT EXISTS idx_dlq_job_id ON dlq(job_id);\nCREATE INDEX IF NOT EXISTS idx_dlq_entered_at ON dlq(entered_at);\n\n-- Performance indexes for high-throughput operations\n-- Stall detection: runs every 5s, needs fast lookup of active jobs by started_at\nCREATE INDEX IF NOT EXISTS idx_jobs_state_started\n ON jobs(state, started_at) WHERE state = 'active';\n\n-- Group operations: fast lookup by group_id\nCREATE INDEX IF NOT EXISTS idx_jobs_group_id\n ON jobs(group_id) WHERE group_id IS NOT NULL;\n\n-- Pending jobs: compound index for priority-ordered retrieval\nCREATE INDEX IF NOT EXISTS idx_jobs_pending_priority\n ON jobs(queue, state, priority DESC, run_at ASC) WHERE state IN ('waiting', 'prioritized', 'waiting-children', 'delayed');\n\n-- Completed jobs: index for recovery ordering (issue #84)\nCREATE INDEX IF NOT EXISTS idx_jobs_completed_order\n ON jobs(completed_at DESC) WHERE state = 'completed';\n\n-- Cron jobs (BLOB for MessagePack)\nCREATE TABLE IF NOT EXISTS cron_jobs (\n name TEXT PRIMARY KEY,\n queue TEXT NOT NULL,\n job_name TEXT,\n data BLOB NOT NULL,\n schedule TEXT,\n repeat_every INTEGER,\n priority INTEGER NOT NULL DEFAULT 0,\n next_run INTEGER NOT NULL,\n executions INTEGER NOT NULL DEFAULT 0,\n max_limit INTEGER,\n timezone TEXT,\n unique_key TEXT,\n dedup BLOB,\n skip_missed_on_restart INTEGER NOT NULL DEFAULT 0,\n skip_if_no_worker INTEGER NOT NULL DEFAULT 0,\n prevent_overlap INTEGER NOT NULL DEFAULT 1,\n job_options BLOB\n);\n\n-- Queue state persistence (optional)\nCREATE TABLE IF NOT EXISTS queue_state (\n name TEXT PRIMARY KEY,\n paused INTEGER NOT NULL DEFAULT 0,\n rate_limit INTEGER,\n concurrency_limit INTEGER,\n rate_limit_duration INTEGER,\n rate_limit_expires_at INTEGER,\n stall_enabled INTEGER,\n stall_interval INTEGER,\n max_stalls INTEGER,\n stall_grace_period INTEGER,\n dlq_config BLOB\n);\n\n-- Durable per-group overrides. Runtime rate windows remain in-memory in the\n-- embedded single-broker engine, matching the existing queue-level limiter.\nCREATE TABLE IF NOT EXISTS group_state (\n queue TEXT NOT NULL,\n group_id TEXT NOT NULL,\n rate_limit INTEGER,\n rate_duration INTEGER,\n concurrency_limit INTEGER,\n PRIMARY KEY (queue, group_id)\n);\n\n-- Per-queue lifecycle event journal. Entries are kept newest-first by id and\n-- bounded by QueueManagerConfig.maxQueueEvents when they are appended.\nCREATE TABLE IF NOT EXISTS queue_events (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n queue TEXT NOT NULL,\n event_type TEXT NOT NULL,\n job_id TEXT NOT NULL,\n occurred_at INTEGER NOT NULL,\n payload BLOB\n);\nCREATE INDEX IF NOT EXISTS idx_queue_events_queue_id\n ON queue_events(queue, id DESC);\n\n-- Cumulative terminal counters are separate from bounded minute buckets so\n-- pruning old data points never resets meta.count.\nCREATE TABLE IF NOT EXISTS queue_metrics_meta (\n queue TEXT NOT NULL,\n type TEXT NOT NULL CHECK (type IN ('completed', 'failed')),\n total_count INTEGER NOT NULL DEFAULT 0,\n prev_ts INTEGER NOT NULL DEFAULT 0,\n prev_count INTEGER NOT NULL DEFAULT 0,\n PRIMARY KEY (queue, type)\n);\nCREATE TABLE IF NOT EXISTS queue_metric_buckets (\n queue TEXT NOT NULL,\n type TEXT NOT NULL CHECK (type IN ('completed', 'failed')),\n minute INTEGER NOT NULL,\n count INTEGER NOT NULL DEFAULT 0,\n PRIMARY KEY (queue, type, minute)\n);\nCREATE INDEX IF NOT EXISTS idx_queue_metric_buckets_window\n ON queue_metric_buckets(queue, type, minute DESC);\n";
5
5
  /** Migration version table */
6
6
  export declare const MIGRATION_TABLE = "\nCREATE TABLE IF NOT EXISTS migrations (\n version INTEGER PRIMARY KEY,\n applied_at INTEGER NOT NULL\n);\n";
7
7
  /** Current schema version */
8
- export declare const SCHEMA_VERSION = 34;
8
+ export declare const SCHEMA_VERSION = 35;
@@ -158,6 +158,17 @@ CREATE TABLE IF NOT EXISTS queue_state (
158
158
  dlq_config BLOB
159
159
  );
160
160
 
161
+ -- Durable per-group overrides. Runtime rate windows remain in-memory in the
162
+ -- embedded single-broker engine, matching the existing queue-level limiter.
163
+ CREATE TABLE IF NOT EXISTS group_state (
164
+ queue TEXT NOT NULL,
165
+ group_id TEXT NOT NULL,
166
+ rate_limit INTEGER,
167
+ rate_duration INTEGER,
168
+ concurrency_limit INTEGER,
169
+ PRIMARY KEY (queue, group_id)
170
+ );
171
+
161
172
  -- Per-queue lifecycle event journal. Entries are kept newest-first by id and
162
173
  -- bounded by QueueManagerConfig.maxQueueEvents when they are appended.
163
174
  CREATE TABLE IF NOT EXISTS queue_events (
@@ -199,4 +210,4 @@ CREATE TABLE IF NOT EXISTS migrations (
199
210
  );
200
211
  `;
201
212
  /** Current schema version */
202
- export const SCHEMA_VERSION = 34;
213
+ export const SCHEMA_VERSION = 35;
@@ -12,6 +12,13 @@ export interface PersistedQueueState {
12
12
  stallConfig: StallConfig | null;
13
13
  dlqConfig: DlqConfig | null;
14
14
  }
15
+ export interface PersistedGroupState {
16
+ queue: string;
17
+ groupId: string;
18
+ rateLimit: number | null;
19
+ rateDuration: number | null;
20
+ concurrencyLimit: number | null;
21
+ }
15
22
  /** Cron schedules and durable queue control-state. */
16
23
  export declare abstract class SqliteControl extends SqliteQueries {
17
24
  saveCron(cron: CronJob): void;
@@ -28,5 +35,12 @@ export declare abstract class SqliteControl extends SqliteQueries {
28
35
  dlqConfig?: DlqConfig | null;
29
36
  }): void;
30
37
  loadQueueState(): PersistedQueueState[];
38
+ saveGroupRateLimit(queue: string, groupId: string, max: number, duration: number): void;
39
+ removeGroupRateLimit(queue: string, groupId: string): void;
40
+ saveGroupConcurrency(queue: string, groupId: string, concurrency: number): void;
41
+ removeGroupConcurrency(queue: string, groupId: string): void;
42
+ loadGroupState(): PersistedGroupState[];
43
+ deleteGroupState(queue: string): void;
31
44
  deleteQueueState(name: string): void;
45
+ private deleteEmptyGroupState;
32
46
  }
@@ -82,9 +82,78 @@ export class SqliteControl extends SqliteQueries {
82
82
  dlqConfig: unpack(row.dlq_config, null, `loadQueueDlqConfig:${row.name}`),
83
83
  }));
84
84
  }
85
+ saveGroupRateLimit(queue, groupId, max, duration) {
86
+ this.safeWrite(() => {
87
+ this.db
88
+ .prepare(`INSERT INTO group_state (queue, group_id, rate_limit, rate_duration)
89
+ VALUES (?, ?, ?, ?)
90
+ ON CONFLICT(queue, group_id) DO UPDATE SET
91
+ rate_limit = excluded.rate_limit,
92
+ rate_duration = excluded.rate_duration`)
93
+ .run(queue, groupId, max, duration);
94
+ });
95
+ }
96
+ removeGroupRateLimit(queue, groupId) {
97
+ this.safeWrite(() => {
98
+ const transaction = this.db.transaction(() => {
99
+ this.db
100
+ .prepare(`UPDATE group_state SET rate_limit = NULL, rate_duration = NULL
101
+ WHERE queue = ? AND group_id = ?`)
102
+ .run(queue, groupId);
103
+ this.deleteEmptyGroupState(queue, groupId);
104
+ });
105
+ transaction();
106
+ });
107
+ }
108
+ saveGroupConcurrency(queue, groupId, concurrency) {
109
+ this.safeWrite(() => {
110
+ this.db
111
+ .prepare(`INSERT INTO group_state (queue, group_id, concurrency_limit)
112
+ VALUES (?, ?, ?)
113
+ ON CONFLICT(queue, group_id) DO UPDATE SET
114
+ concurrency_limit = excluded.concurrency_limit`)
115
+ .run(queue, groupId, concurrency);
116
+ });
117
+ }
118
+ removeGroupConcurrency(queue, groupId) {
119
+ this.safeWrite(() => {
120
+ const transaction = this.db.transaction(() => {
121
+ this.db
122
+ .prepare(`UPDATE group_state SET concurrency_limit = NULL
123
+ WHERE queue = ? AND group_id = ?`)
124
+ .run(queue, groupId);
125
+ this.deleteEmptyGroupState(queue, groupId);
126
+ });
127
+ transaction();
128
+ });
129
+ }
130
+ loadGroupState() {
131
+ return this.db
132
+ .query('SELECT * FROM group_state')
133
+ .all()
134
+ .map((row) => ({
135
+ queue: row.queue,
136
+ groupId: row.group_id,
137
+ rateLimit: row.rate_limit,
138
+ rateDuration: row.rate_duration,
139
+ concurrencyLimit: row.concurrency_limit,
140
+ }));
141
+ }
142
+ deleteGroupState(queue) {
143
+ this.safeWrite(() => {
144
+ this.db.prepare('DELETE FROM group_state WHERE queue = ?').run(queue);
145
+ });
146
+ }
85
147
  deleteQueueState(name) {
86
148
  this.safeWrite(() => {
87
149
  this.statements.get('deleteQueueState').run(name);
88
150
  });
89
151
  }
152
+ deleteEmptyGroupState(queue, groupId) {
153
+ this.db
154
+ .prepare(`DELETE FROM group_state
155
+ WHERE queue = ? AND group_id = ?
156
+ AND rate_limit IS NULL AND concurrency_limit IS NULL`)
157
+ .run(queue, groupId);
158
+ }
90
159
  }
@@ -3,6 +3,16 @@ import type { FlowFailureRecord } from '../../../domain/types/flow';
3
3
  import type { Job, JobId, JobTimelineEntry } from '../../../domain/types/job';
4
4
  import type { DurableAdmissionMetadata } from '../types/admission';
5
5
  import { SqliteAdmission } from './admission';
6
+ export interface ActiveJobWrite {
7
+ jobId: JobId;
8
+ startedAt: number;
9
+ timeline?: JobTimelineEntry[];
10
+ }
11
+ export interface CompletedJobWrite {
12
+ jobId: JobId;
13
+ completedAt: number;
14
+ timeline?: JobTimelineEntry[];
15
+ }
6
16
  /** Job insertion, state transitions, and DLQ persistence. */
7
17
  export declare abstract class SqliteJobs extends SqliteAdmission {
8
18
  insertJob(job: Job, durable?: boolean, admission?: DurableAdmissionMetadata): void;
@@ -10,8 +20,10 @@ export declare abstract class SqliteJobs extends SqliteAdmission {
10
20
  protected runInsertJobStmt(job: Job): void;
11
21
  protected flushIfBuffered(jobId: JobId): void;
12
22
  markActive(jobId: JobId, startedAt: number, timeline?: JobTimelineEntry[]): void;
23
+ markActiveBatch(updates: readonly ActiveJobWrite[]): void;
13
24
  markWaitingChildren(jobId: JobId, timeline?: JobTimelineEntry[]): void;
14
25
  markCompleted(jobId: JobId, completedAt: number, timeline?: JobTimelineEntry[]): void;
26
+ markCompletedBatch(updates: readonly CompletedJobWrite[]): void;
15
27
  markFailed(job: Job, error: string | null): void;
16
28
  saveDlqEntry(entry: DlqEntry): void;
17
29
  commitFailedJob(jobId: JobId, entry: DlqEntry | null, flowFailure: FlowFailureRecord | null): void;
@@ -50,6 +50,24 @@ export class SqliteJobs extends SqliteAdmission {
50
50
  .run('active', startedAt, timeline && timeline.length > 0 ? pack(timeline) : null, jobId);
51
51
  });
52
52
  }
53
+ markActiveBatch(updates) {
54
+ if (updates.length === 0)
55
+ return;
56
+ for (const update of updates)
57
+ this.flushIfBuffered(update.jobId);
58
+ const rows = updates.map((update) => ({
59
+ ...update,
60
+ timeline: update.timeline?.length ? pack(update.timeline) : null,
61
+ }));
62
+ this.safeWrite(() => {
63
+ this.db.transaction((batch) => {
64
+ const statement = this.statements.get('updateJobState');
65
+ for (const row of batch) {
66
+ statement.run('active', row.startedAt, row.timeline, row.jobId);
67
+ }
68
+ })(rows);
69
+ });
70
+ }
53
71
  markWaitingChildren(jobId, timeline) {
54
72
  this.flushIfBuffered(jobId);
55
73
  this.safeWrite(() => {
@@ -66,6 +84,24 @@ export class SqliteJobs extends SqliteAdmission {
66
84
  .run('completed', completedAt, timeline && timeline.length > 0 ? pack(timeline) : null, jobId);
67
85
  });
68
86
  }
87
+ markCompletedBatch(updates) {
88
+ if (updates.length === 0)
89
+ return;
90
+ for (const update of updates)
91
+ this.flushIfBuffered(update.jobId);
92
+ const rows = updates.map((update) => ({
93
+ ...update,
94
+ timeline: update.timeline?.length ? pack(update.timeline) : null,
95
+ }));
96
+ this.safeWrite(() => {
97
+ this.db.transaction((batch) => {
98
+ const statement = this.statements.get('completeJob');
99
+ for (const row of batch) {
100
+ statement.run('completed', row.completedAt, row.timeline, row.jobId);
101
+ }
102
+ })(rows);
103
+ });
104
+ }
69
105
  markFailed(job, error) {
70
106
  this.flushIfBuffered(job.id);
71
107
  this.safeWrite(() => {
@@ -1,5 +1,5 @@
1
1
  import type { QueueMetricsMeta, QueueMetricType } from '../../../domain/types/metrics';
2
- import { type JobEvent } from '../../../domain/types/queue';
2
+ import type { JobEvent } from '../../../domain/types/queue';
3
3
  import { SqliteControl } from './control';
4
4
  export interface PersistedQueueMetrics {
5
5
  meta: QueueMetricsMeta;
@@ -8,6 +8,7 @@ export interface PersistedQueueMetrics {
8
8
  /** Durable lifecycle journal and minute-bucket metrics. */
9
9
  export declare abstract class SqliteTelemetry extends SqliteControl {
10
10
  recordQueueEvent(event: JobEvent, maxEvents: number, maxMetricDataPoints: number): void;
11
+ recordQueueEventsBatch(events: readonly JobEvent[], maxEvents: number, maxMetricDataPoints: number): void;
11
12
  getQueueMetrics(queue: string, type: QueueMetricType, maxMetricDataPoints: number): PersistedQueueMetrics;
12
13
  trimQueueEvents(queue: string, maxLength: number): number;
13
14
  countQueueEvents(queue: string): number;
@@ -1,71 +1,12 @@
1
- import { pack } from '../sqliteSerializer';
2
1
  import { SqliteControl } from './control';
3
- function terminalMetricType(event) {
4
- if (event.eventType === "completed" /* EventType.Completed */)
5
- return 'completed';
6
- if (event.eventType === "failed" /* EventType.Failed */ && event.terminal !== false)
7
- return 'failed';
8
- return null;
9
- }
10
- function eventPayload(event) {
11
- return pack({
12
- data: event.data,
13
- error: event.error,
14
- progress: event.progress,
15
- prev: event.prev,
16
- delay: event.delay,
17
- terminal: event.terminal,
18
- });
19
- }
2
+ import { writeQueueEvents } from './telemetryWrites';
20
3
  /** Durable lifecycle journal and minute-bucket metrics. */
21
4
  export class SqliteTelemetry extends SqliteControl {
22
5
  recordQueueEvent(event, maxEvents, maxMetricDataPoints) {
23
- const eventLimit = Math.max(0, Math.floor(maxEvents));
24
- const metricLimit = Math.max(0, Math.floor(maxMetricDataPoints));
25
- const metricType = terminalMetricType(event);
26
- const minute = Math.floor(event.timestamp / 60_000);
27
- const payload = eventPayload(event);
28
- this.safeWrite(() => {
29
- const transaction = this.db.transaction(() => {
30
- this.db
31
- .prepare('INSERT INTO queue_events (queue, event_type, job_id, occurred_at, payload) VALUES (?, ?, ?, ?, ?)')
32
- .run(event.queue, event.eventType, String(event.jobId), event.timestamp, payload);
33
- this.db
34
- .prepare('DELETE FROM queue_events WHERE queue = ? AND id IN (SELECT id FROM queue_events WHERE queue = ? ORDER BY id DESC LIMIT -1 OFFSET ?)')
35
- .run(event.queue, event.queue, eventLimit);
36
- if (!metricType)
37
- return;
38
- this.db
39
- .prepare(`INSERT INTO queue_metric_buckets (queue, type, minute, count)
40
- VALUES (?, ?, ?, 1)
41
- ON CONFLICT(queue, type, minute) DO UPDATE SET count = count + 1`)
42
- .run(event.queue, metricType, minute);
43
- const bucketCount = this.db
44
- .query('SELECT count FROM queue_metric_buckets WHERE queue = ? AND type = ? AND minute = ?')
45
- .get(event.queue, metricType, minute)?.count ?? 1;
46
- this.db
47
- .prepare(`INSERT INTO queue_metrics_meta (queue, type, total_count, prev_ts, prev_count)
48
- VALUES (?, ?, 1, ?, ?)
49
- ON CONFLICT(queue, type) DO UPDATE SET
50
- total_count = total_count + 1,
51
- prev_ts = excluded.prev_ts,
52
- prev_count = excluded.prev_count`)
53
- .run(event.queue, metricType, event.timestamp, bucketCount);
54
- if (metricLimit === 0) {
55
- this.db
56
- .prepare('DELETE FROM queue_metric_buckets WHERE queue = ? AND type = ?')
57
- .run(event.queue, metricType);
58
- return;
59
- }
60
- const newest = this.db
61
- .query('SELECT MAX(minute) AS minute FROM queue_metric_buckets WHERE queue = ? AND type = ?')
62
- .get(event.queue, metricType)?.minute ?? minute;
63
- this.db
64
- .prepare('DELETE FROM queue_metric_buckets WHERE queue = ? AND type = ? AND minute < ?')
65
- .run(event.queue, metricType, newest - metricLimit + 1);
66
- });
67
- transaction();
68
- });
6
+ this.safeWrite(() => writeQueueEvents(this.db, [event], maxEvents, maxMetricDataPoints));
7
+ }
8
+ recordQueueEventsBatch(events, maxEvents, maxMetricDataPoints) {
9
+ this.safeWrite(() => writeQueueEvents(this.db, events, maxEvents, maxMetricDataPoints));
69
10
  }
70
11
  getQueueMetrics(queue, type, maxMetricDataPoints) {
71
12
  const metaRow = this.db
@@ -0,0 +1,4 @@
1
+ import type { Database } from 'bun:sqlite';
2
+ import { type JobEvent } from '../../../domain/types/queue';
3
+ /** Apply events in input order inside one transaction, preserving scalar semantics. */
4
+ export declare function writeQueueEvents(db: Database, events: readonly JobEvent[], maxEvents: number, maxMetricDataPoints: number): void;
@@ -0,0 +1,123 @@
1
+ import { pack } from '../sqliteSerializer';
2
+ function terminalMetricType(event) {
3
+ if (event.eventType === "completed" /* EventType.Completed */)
4
+ return 'completed';
5
+ if (event.eventType === "failed" /* EventType.Failed */ && event.terminal !== false)
6
+ return 'failed';
7
+ return null;
8
+ }
9
+ function eventPayload(event) {
10
+ return pack({
11
+ data: event.data,
12
+ error: event.error,
13
+ progress: event.progress,
14
+ prev: event.prev,
15
+ delay: event.delay,
16
+ terminal: event.terminal,
17
+ });
18
+ }
19
+ function prepareQueueEvents(events) {
20
+ return events.map((event) => ({
21
+ event,
22
+ metricType: terminalMetricType(event),
23
+ minute: Math.floor(event.timestamp / 60_000),
24
+ payload: eventPayload(event),
25
+ }));
26
+ }
27
+ function groupMetricEvents(events) {
28
+ const byQueue = new Map();
29
+ for (const entry of events) {
30
+ if (!entry.metricType)
31
+ continue;
32
+ let byType = byQueue.get(entry.event.queue);
33
+ if (!byType) {
34
+ byType = new Map();
35
+ byQueue.set(entry.event.queue, byType);
36
+ }
37
+ let group = byType.get(entry.metricType);
38
+ if (!group) {
39
+ group = { queue: entry.event.queue, type: entry.metricType, events: [] };
40
+ byType.set(entry.metricType, group);
41
+ }
42
+ group.events.push({ minute: entry.minute, timestamp: entry.event.timestamp });
43
+ }
44
+ return [...byQueue.values()].flatMap((byType) => [...byType.values()]);
45
+ }
46
+ /** Apply events in input order inside one transaction, preserving scalar semantics. */
47
+ export function writeQueueEvents(db, events, maxEvents, maxMetricDataPoints) {
48
+ if (events.length === 0)
49
+ return;
50
+ const preparedEvents = prepareQueueEvents(events);
51
+ const metricGroups = groupMetricEvents(preparedEvents);
52
+ const eventLimit = Math.max(0, Math.floor(maxEvents));
53
+ const metricLimit = Math.max(0, Math.floor(maxMetricDataPoints));
54
+ const insertEvent = db.prepare('INSERT INTO queue_events (queue, event_type, job_id, occurred_at, payload) VALUES (?, ?, ?, ?, ?)');
55
+ const trimEvents = db.prepare('DELETE FROM queue_events WHERE queue = ? AND id IN (SELECT id FROM queue_events WHERE queue = ? ORDER BY id DESC LIMIT -1 OFFSET ?)');
56
+ const incrementBucket = db.prepare(`INSERT INTO queue_metric_buckets (queue, type, minute, count)
57
+ VALUES (?, ?, ?, ?)
58
+ ON CONFLICT(queue, type, minute) DO UPDATE SET count = count + excluded.count`);
59
+ const readBucket = db.query('SELECT count FROM queue_metric_buckets WHERE queue = ? AND type = ? AND minute = ?');
60
+ const updateMeta = db.prepare(`INSERT INTO queue_metrics_meta (queue, type, total_count, prev_ts, prev_count)
61
+ VALUES (?, ?, ?, ?, ?)
62
+ ON CONFLICT(queue, type) DO UPDATE SET
63
+ total_count = total_count + excluded.total_count,
64
+ prev_ts = excluded.prev_ts,
65
+ prev_count = excluded.prev_count`);
66
+ const clearBuckets = db.prepare('DELETE FROM queue_metric_buckets WHERE queue = ? AND type = ?');
67
+ const readNewest = db.query('SELECT MAX(minute) AS minute FROM queue_metric_buckets WHERE queue = ? AND type = ?');
68
+ const trimBuckets = db.prepare('DELETE FROM queue_metric_buckets WHERE queue = ? AND type = ? AND minute < ?');
69
+ const transaction = db.transaction((batch) => {
70
+ const affectedQueues = new Set();
71
+ for (const { event, payload } of batch) {
72
+ insertEvent.run(event.queue, event.eventType, String(event.jobId), event.timestamp, payload);
73
+ affectedQueues.add(event.queue);
74
+ }
75
+ for (const queue of affectedQueues)
76
+ trimEvents.run(queue, queue, eventLimit);
77
+ for (const group of metricGroups) {
78
+ const eventMinutes = new Set(group.events.map((event) => event.minute));
79
+ const counts = new Map();
80
+ for (const minute of eventMinutes) {
81
+ const count = readBucket.get(group.queue, group.type, minute)?.count;
82
+ if (count !== undefined)
83
+ counts.set(minute, count);
84
+ }
85
+ let newest = readNewest.get(group.queue, group.type)?.minute ?? null;
86
+ const increments = new Map();
87
+ let lastTimestamp = 0;
88
+ let lastCount = 0;
89
+ let cutoff = null;
90
+ for (const event of group.events) {
91
+ lastCount = (counts.get(event.minute) ?? 0) + 1;
92
+ lastTimestamp = event.timestamp;
93
+ counts.set(event.minute, lastCount);
94
+ increments.set(event.minute, (increments.get(event.minute) ?? 0) + 1);
95
+ if (metricLimit === 0) {
96
+ counts.clear();
97
+ increments.clear();
98
+ newest = null;
99
+ continue;
100
+ }
101
+ newest = newest === null ? event.minute : Math.max(newest, event.minute);
102
+ cutoff = newest - metricLimit + 1;
103
+ for (const minute of counts.keys()) {
104
+ if (minute >= cutoff)
105
+ continue;
106
+ counts.delete(minute);
107
+ increments.delete(minute);
108
+ }
109
+ }
110
+ updateMeta.run(group.queue, group.type, group.events.length, lastTimestamp, lastCount);
111
+ if (metricLimit === 0) {
112
+ clearBuckets.run(group.queue, group.type);
113
+ continue;
114
+ }
115
+ for (const [minute, count] of increments) {
116
+ incrementBucket.run(group.queue, group.type, minute, count);
117
+ }
118
+ if (cutoff !== null)
119
+ trimBuckets.run(group.queue, group.type, cutoff);
120
+ }
121
+ });
122
+ transaction(preparedEvents);
123
+ }