Skip to content

fix: QueueEvents failed events missing error, data, and context#54

Merged
egeominotti merged 2 commits intoegeominotti:mainfrom
simontong:simon/fix-queueevents-failed-data
Mar 16, 2026
Merged

fix: QueueEvents failed events missing error, data, and context#54
egeominotti merged 2 commits intoegeominotti:mainfrom
simontong:simon/fix-queueevents-failed-data

Conversation

@simontong
Copy link
Contributor

@simontong simontong commented Mar 16, 2026

Summary

  • failedReason was undefined: events.ts read event.data instead of event.error for the failed reason
  • Job data missing: Failed broadcast in ack.ts didn't include job.data, so listeners couldn't see the payload
  • Error emission lacked context: error event only passed the Error object, not the originating event

Changes

  • src/application/operations/ack.ts: Include data: job.data in failed broadcast
  • src/client/events.ts: Read event.error for failedReason, pass event.data through, add event context to error emission
  • src/client/events.ts: Add data? field to FailedEvent type, update error listener signatures with optional JobEvent
  • test/queueEvents.test.ts: Assert failedReason is a string containing the error, and data matches the job payload

Test plan

  • bun test test/queueEvents.test.ts -- 10 pass, 0 fail
  • bun test -- full unit suite
  • bun scripts/tcp/run-all-tests.ts
  • bun scripts/embedded/run-all-tests.ts

Summary by CodeRabbit

  • New Features

    • Failed job events now include the job's data for fuller failure context.
    • Error listeners receive the original event alongside the Error to aid debugging.
    • Several queue events (completed, progress, retried, etc.) now include richer payloads.
  • Tests

    • Tests updated to assert failed event includes data and improved error handling.

- Read event.error instead of event.data for failedReason
- Include job.data in failed broadcast so listeners get the payload
- Pass event context to error emission
- Add data field to FailedEvent type
- Add assertions for failedReason and data in test
@vercel
Copy link

vercel bot commented Mar 16, 2026

@simontong is attempting to deploy a commit to the egeominotti's projects Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai
Copy link

coderabbitai bot commented Mar 16, 2026

📝 Walkthrough

Walkthrough

Failed job events now include the job's data payload; event emission and error listener signatures were updated, event dispatching was refactored into a dispatchEvent method, and tests were adjusted to assert the added data field.

Changes

Cohort / File(s) Summary
Event emission & ack changes
src/application/operations/ack.ts, src/client/events.ts
Added job data to failure broadcasts; introduced dispatchEvent(event: JobEvent) to centralize event handling; expanded FailedEvent to include optional data and updated QueueEvents on/once signatures for 'error' to accept optional JobEvent context.
Tests
test/queueEvents.test.ts
Updated tests to capture and assert data on failed events and adjusted error listener usage accordingly.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 I hopped along the event stream today,
A failed job whispered what it had to say.
I carried its data, small and bright,
So listeners catch the whole poor plight.
Hooray for context, hopped away! 🎋

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title directly addresses the main fix: enriching failed events with missing error data and context. It accurately reflects the core changes across all modified files.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
📝 Coding Plan
  • Generate coding plan for human review comments

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Tip

You can customize the high-level summary generated by CodeRabbit.

Configure the reviews.high_level_summary_instructions setting to provide custom instructions for generating the high-level summary.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
test/queueEvents.test.ts (1)

70-74: Add one assertion for error event context to cover the new signature.

Line 70 currently swallows error events. Since this PR adds event context propagation, assert the second argument (JobEvent) includes the same jobId to prevent regressions.

✅ Suggested test hardening
-    queueEvents.on('error', () => {});
+    let errorContextJobId: string | undefined;
+    queueEvents.on('error', (_error, event) => {
+      errorContextJobId = event?.jobId;
+    });
@@
     expect(typeof failedEvent!.failedReason).toBe('string');
     expect(failedEvent!.failedReason).toContain('Test failure');
     expect(failedEvent!.data).toMatchObject({ value: 42 });
+    expect(errorContextJobId).toBe(job.id);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/queueEvents.test.ts` around lines 70 - 74, The test currently swallows
error events via queueEvents.on('error', () => {}); update the test to capture
the error handler's second argument (the JobEvent context) and assert that its
jobId equals the jobId used in the test; specifically modify or replace the
error listener registered on queueEvents.on('error', ...) to accept (err, event)
and either push event.jobId to a new array or directly assert event.jobId
matches the expected jobId (referencing queueEvents.on('error', ...) and the
existing failedEvents push for pattern).
src/application/operations/ack.ts (1)

1-308: Split this module to stay within the repository file-size limit.

This file is 308 lines and currently exceeds the TS max-size rule.

As per coding guidelines **/*.ts: MAX 300 lines per file - split if larger.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/application/operations/ack.ts` around lines 1 - 308, This file exceeds
the 300-line limit; split it by moving related operations into separate modules:
keep core single-job handlers (ackJob, failJob, AckContext) in the original file
and extract batch operations (ackJobBatch, ackJobBatchWithResults and their
small helper batchCtx usage) into a new file (e.g., ackBatch.ts), import/export
the same symbols so external callers are unaffected, and ensure both files
import shared helpers used here (groupByProcShard, extractJobs,
groupByQueueShard, releaseResources, finalizeBatchAck, groupItemsByProcShard,
extractJobsWithResults) and types (AckContext, JobId) unchanged; update any
local imports/exports to preserve original API surface.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/client/events.ts`:
- Around line 170-174: The emitted 'failed' payload sets failedReason to
event.error which can be undefined; update the this.emit('failed', { jobId:
event.jobId, failedReason, data: event.data }) call to guarantee a non-undefined
string (e.g., failedReason: (event.error ?? event.message ?? event.data?.error
?? 'Unknown failure').toString()) so consumers always receive a value, and
adjust the event typing if necessary to reflect the non-optional failedReason.

---

Nitpick comments:
In `@src/application/operations/ack.ts`:
- Around line 1-308: This file exceeds the 300-line limit; split it by moving
related operations into separate modules: keep core single-job handlers (ackJob,
failJob, AckContext) in the original file and extract batch operations
(ackJobBatch, ackJobBatchWithResults and their small helper batchCtx usage) into
a new file (e.g., ackBatch.ts), import/export the same symbols so external
callers are unaffected, and ensure both files import shared helpers used here
(groupByProcShard, extractJobs, groupByQueueShard, releaseResources,
finalizeBatchAck, groupItemsByProcShard, extractJobsWithResults) and types
(AckContext, JobId) unchanged; update any local imports/exports to preserve
original API surface.

In `@test/queueEvents.test.ts`:
- Around line 70-74: The test currently swallows error events via
queueEvents.on('error', () => {}); update the test to capture the error
handler's second argument (the JobEvent context) and assert that its jobId
equals the jobId used in the test; specifically modify or replace the error
listener registered on queueEvents.on('error', ...) to accept (err, event) and
either push event.jobId to a new array or directly assert event.jobId matches
the expected jobId (referencing queueEvents.on('error', ...) and the existing
failedEvents push for pattern).

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: f49d3321-725c-4b97-bdb6-cf75c15b64cb

📥 Commits

Reviewing files that changed from the base of the PR and between 84837ad and 90a1c99.

📒 Files selected for processing (3)
  • src/application/operations/ack.ts
  • src/client/events.ts
  • test/queueEvents.test.ts

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
src/client/events.ts (1)

148-194: Good refactoring - all 12 EventType values are exhaustively handled.

The dispatchEvent method cleanly centralizes event mapping logic. Verified against the EventType enum: Pushed, Pulled, Completed, Failed, Progress, Stalled, Removed, Delayed, Duplicated, Retried, WaitingChildren, and Drained are all covered.

The fallback values for optional fields (event.error ?? 'Job failed', event.prev ?? 'unknown', event.delay ?? 0) ensure consumers always receive valid payloads.

Consider adding a default case with a debug log/warning to catch any future EventType additions that aren't handled:

♻️ Optional: Add exhaustiveness safeguard
       case EventType.Drained:
         this.emit('drained', { id: event.jobId });
         break;
+      default:
+        // Exhaustiveness check - log unknown event types during development
+        console.warn(`[QueueEvents] Unhandled event type: ${(event as JobEvent).eventType}`);
     }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/client/events.ts` around lines 148 - 194, Add a default/fallback branch
to the switch in dispatchEvent to catch any future EventType values not
explicitly handled: implement a default case that logs a warning (e.g.,
console.warn) including the unrecognized event.eventType and the event payload
to aid debugging and monitoring; ensure the default does not throw so existing
consumers aren't broken, but provides enough context to diagnose missing
handlers for symbols dispatchEvent and EventType.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@src/client/events.ts`:
- Around line 148-194: Add a default/fallback branch to the switch in
dispatchEvent to catch any future EventType values not explicitly handled:
implement a default case that logs a warning (e.g., console.warn) including the
unrecognized event.eventType and the event payload to aid debugging and
monitoring; ensure the default does not throw so existing consumers aren't
broken, but provides enough context to diagnose missing handlers for symbols
dispatchEvent and EventType.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: e439b13d-c0e0-436a-ae2e-8912603ea5ba

📥 Commits

Reviewing files that changed from the base of the PR and between 90a1c99 and 5170c23.

📒 Files selected for processing (1)
  • src/client/events.ts

@egeominotti egeominotti merged commit 61a3057 into egeominotti:main Mar 16, 2026
6 of 9 checks passed
@egeominotti
Copy link
Owner

thanks @simontong

@egeominotti egeominotti added the bug Something isn't working label Mar 16, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants