Skip to content

Commit 2a37b86

Browse files
committed
feat: report failed jobs to crash
The worker left a breadcrumb when a job started and then threw the crash away when it failed: the catch block echoed to stdout and retried, so the trail was built and never used. It now captures the exception, carrying the job id, class, queue and attempt number. Reports are sent with immediately: true. Crash buffers reports and flushes them from a shutdown handler, and a worker's shutdown handler never runs, so a buffered report would sit unsent while the buffer grew for the life of the process. The whole call is guarded and swallows its own failures. A job that failed is already bad news, and a broken reporter turning that into a dead worker is worse. Tests cover both halves, and both fail without the change: that a failure is reported with the right context and the immediately flag, and that a reporter which throws is attempted and still leaves the worker running its normal retry-then-fail path.
1 parent 1575cef commit 2a37b86

4 files changed

Lines changed: 164 additions & 0 deletions

File tree

‎src/Worker.php‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,36 @@ public function config(array $config)
4949
return $this;
5050
}
5151

52+
/**
53+
* Send a failed job to crash, if the app has it installed.
54+
*
55+
* Reporting must never be able to take the worker down, so every failure
56+
* here is swallowed: a job that failed is already bad news, and a broken
57+
* reporter turning that into a dead worker is worse.
58+
*/
59+
protected function report(\Throwable $exception, $job, array $jobData): void
60+
{
61+
if (!function_exists('crash')) {
62+
return;
63+
}
64+
65+
try {
66+
crash()->capture($exception, [
67+
// A worker never shuts down, so its shutdown handler never runs.
68+
// A buffered report would sit unsent and grow the buffer forever.
69+
'immediately' => true,
70+
'job' => [
71+
'id' => $job->getJobId(),
72+
'class' => $jobData['class'] ?? null,
73+
'attempt' => ((int) ($jobData['retry_count'] ?? 0)) + 1,
74+
'queue' => $jobData['queue'] ?? null,
75+
],
76+
]);
77+
} catch (\Throwable $reportingFailed) {
78+
echo " - (could not report job #{$job->getJobId()} to crash: {$reportingFailed->getMessage()})\n";
79+
}
80+
}
81+
5282
public function run()
5383
{
5484
if (function_exists('pcntl_async_signals')) {
@@ -123,6 +153,8 @@ public function run()
123153
} catch (\Throwable $th) {
124154
echo " - Job #{$job->getJobId()} failed: {$th->getMessage()}\n";
125155

156+
$this->report($th, $job, $jobData);
157+
126158
$job->retry($th);
127159

128160
continue;

‎tests/Pest.php‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,15 @@
1414
define('SANDBOX', '/tmp/queuetestsandbox' . (getenv('TEST_TOKEN') ? '-' . getenv('TEST_TOKEN') : ''));
1515

1616
require __DIR__ . '/shims/Globals.php';
17+
require __DIR__ . '/shims/CrashSpy.php';
18+
19+
if (!function_exists('crash')) {
20+
function crash()
21+
{
22+
return \Tests\CrashSpy::instance();
23+
}
24+
}
25+
1726
require __DIR__ . '/shims/Config.php';
1827
require __DIR__ . '/jobs.php';
1928

‎tests/queue.test.php‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,3 +160,53 @@
160160
expect($queue)->toBeNull();
161161
expect($error)->toContain('No queue specified');
162162
});
163+
164+
test('a failing job is reported to crash when the app has it, with job context', function () {
165+
\Tests\CrashSpy::instance()->reset();
166+
167+
dispatch(new QueueTestFailJob()); // throws, tries = 2
168+
169+
runWorker();
170+
171+
$captures = \Tests\CrashSpy::instance()->captures;
172+
173+
// one per attempt: the initial run and the retry
174+
expect($captures)->toHaveCount(2);
175+
176+
[$exception, $options] = $captures[0];
177+
178+
expect($exception)->toBeInstanceOf(\Throwable::class);
179+
expect($exception->getMessage())->toContain('boom from QueueTestFailJob');
180+
181+
// a worker's shutdown handler never runs, so reports must not be buffered
182+
expect($options['immediately'])->toBeTrue();
183+
184+
expect($options['job']['class'])->toBe(QueueTestFailJob::class);
185+
expect($options['job']['attempt'])->toBe(1);
186+
expect($options['job']['id'])->not->toBeEmpty();
187+
188+
// the second capture is the retry
189+
expect($captures[1][1]['job']['attempt'])->toBe(2);
190+
});
191+
192+
test('a broken crash reporter does not take the worker down', function () {
193+
\Tests\CrashSpy::instance()->reset();
194+
\Tests\CrashSpy::instance()->explode = true;
195+
196+
dispatch(new QueueTestFailJob());
197+
198+
runWorker(); // must not throw
199+
200+
// the reporter really was called and really did blow up, so the guard
201+
// is what kept the worker alive rather than the call never happening
202+
expect(\Tests\CrashSpy::instance()->attempts)->toBe(2);
203+
expect(\Tests\CrashSpy::instance()->captures)->toBeEmpty();
204+
205+
\Tests\CrashSpy::instance()->explode = false;
206+
207+
// the job still went through its normal retry-then-fail path
208+
$row = jobRows()[0];
209+
210+
expect($row['status'])->toBe('failed');
211+
expect($row['exception'])->toContain('boom from QueueTestFailJob');
212+
});

‎tests/shims/CrashSpy.php‎

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
<?php
2+
3+
/*
4+
| A stand-in for \Leaf\Crash\Hub.
5+
|
6+
| The worker only asks function_exists('crash'), so this proves the reporting
7+
| call is made and carries what it should, and can be told to throw so the
8+
| "reporting must never kill the worker" guarantee is genuinely exercised.
9+
*/
10+
11+
namespace Tests;
12+
13+
class CrashSpy
14+
{
15+
/** @var array<int, array{0: mixed, 1: array}> */
16+
public array $captures = [];
17+
18+
public bool $explode = false;
19+
20+
/** Every attempt, including ones that threw — so a guard cannot pass vacuously */
21+
public int $attempts = 0;
22+
23+
private static ?self $instance = null;
24+
25+
public static function instance(): self
26+
{
27+
return self::$instance ??= new self();
28+
}
29+
30+
public function reset(): void
31+
{
32+
$this->captures = [];
33+
$this->crumbs = [];
34+
$this->attempts = 0;
35+
$this->explode = false;
36+
}
37+
38+
/** @var array<int, array{0: string, 1: string, 2: array}> */
39+
public array $crumbs = [];
40+
41+
public function breadcrumbs(): self
42+
{
43+
return $this;
44+
}
45+
46+
/** Breadcrumbs::clear() */
47+
public function clear(): self
48+
{
49+
$this->crumbs = [];
50+
51+
return $this;
52+
}
53+
54+
public function leaveCrumb(string $message, string $type = 'action', array $meta = [], bool $withOrigin = true): self
55+
{
56+
$this->crumbs[] = [$message, $type, $meta];
57+
58+
return $this;
59+
}
60+
61+
public function capture($subject, array $options = [])
62+
{
63+
$this->attempts++;
64+
65+
if ($this->explode) {
66+
throw new \RuntimeException('reporter is down');
67+
}
68+
69+
$this->captures[] = [$subject, $options];
70+
71+
return $subject;
72+
}
73+
}

0 commit comments

Comments
 (0)