|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Tests\Feature; |
| 6 | + |
| 7 | +use RuntimeException; |
| 8 | +use Tests\Fixtures\TestNestedSignalLeafWorkflow; |
| 9 | +use Tests\Fixtures\TestNestedSignalParentWorkflow; |
| 10 | +use Tests\TestCase; |
| 11 | +use Workflow\Models\StoredWorkflow; |
| 12 | +use Workflow\States\WorkflowCompletedStatus; |
| 13 | +use Workflow\WorkflowStub; |
| 14 | + |
| 15 | +final class NestedSignalRaceConditionTest extends TestCase |
| 16 | +{ |
| 17 | + public function testNestedChildWorkflowsWithDuplicateSignalsDoNotGetStuckPending(): void |
| 18 | + { |
| 19 | + $runId = (int) now() |
| 20 | + ->format('Uu'); |
| 21 | + $middleCount = 12; |
| 22 | + $leafCount = 3; |
| 23 | + $duplicateSignals = 4; |
| 24 | + $expectedLeafCount = $middleCount * $leafCount; |
| 25 | + |
| 26 | + $workflow = WorkflowStub::make(TestNestedSignalParentWorkflow::class); |
| 27 | + $workflow->start($runId, $middleCount, $leafCount); |
| 28 | + |
| 29 | + $creationDeadline = now() |
| 30 | + ->addSeconds(30); |
| 31 | + $leafIds = []; |
| 32 | + while (now()->lt($creationDeadline)) { |
| 33 | + $leafIds = StoredWorkflow::query() |
| 34 | + ->where('class', TestNestedSignalLeafWorkflow::class) |
| 35 | + ->pluck('id') |
| 36 | + ->all(); |
| 37 | + |
| 38 | + if (count($leafIds) === $expectedLeafCount) { |
| 39 | + break; |
| 40 | + } |
| 41 | + |
| 42 | + usleep(50000); |
| 43 | + } |
| 44 | + |
| 45 | + $this->assertCount($expectedLeafCount, $leafIds, 'Timed out waiting for all nested leaf workflows'); |
| 46 | + |
| 47 | + for ($round = 0; $round < $duplicateSignals; $round++) { |
| 48 | + foreach ($leafIds as $leafId) { |
| 49 | + WorkflowStub::load((int) $leafId)->respond(); |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + $completionDeadline = now() |
| 54 | + ->addSeconds(120); |
| 55 | + while ($workflow->running() && now()->lt($completionDeadline)) { |
| 56 | + usleep(50000); |
| 57 | + $workflow->fresh(); |
| 58 | + } |
| 59 | + |
| 60 | + if ($workflow->running()) { |
| 61 | + throw new RuntimeException(sprintf( |
| 62 | + 'Nested signal run %d did not complete before timeout. Current status: %s', |
| 63 | + $runId, |
| 64 | + (string) $workflow->status() |
| 65 | + )); |
| 66 | + } |
| 67 | + |
| 68 | + $this->assertSame(WorkflowCompletedStatus::class, $workflow->status()); |
| 69 | + $this->assertSame([ |
| 70 | + 'run_id' => $runId, |
| 71 | + 'middle_count' => $middleCount, |
| 72 | + 'leaf_count' => $leafCount, |
| 73 | + 'resolved_leaf_count' => $expectedLeafCount, |
| 74 | + ], $workflow->output()); |
| 75 | + } |
| 76 | +} |
0 commit comments