From ca0b2a911e5c0f44dc26bbe32dfab93010c767ff Mon Sep 17 00:00:00 2001 From: Tobias Munk Date: Sat, 5 Dec 2026 22:51:44 +0000 Subject: [PATCH 1/9] refactor(intake): origin status of the conditional transition as a parameter [*] EventStore::transition() takes the origin status as its last argument, "received" by default, and rejects a terminal origin and a move to the origin itself. EventStatusTransition keeps its meaning: only from "received". Prepares the asynchronous process start, which leaves "routed". Co-Authored-By: Claude Fable 5.2 --- src/Intake/EventStatusTransition.php | 5 +- src/Intake/EventStore.php | 42 ++++-- .../Intake/IntakeMatrixDatabaseTest.php | 40 ++++- .../Unit/Intake/EventStoreTransitionTest.php | 142 ++++++++++++++++++ 4 files changed, 214 insertions(+), 15 deletions(-) create mode 100644 tests/Unit/Intake/EventStoreTransitionTest.php diff --git a/src/Intake/EventStatusTransition.php b/src/Intake/EventStatusTransition.php index 896af1a..1b69675 100644 --- a/src/Intake/EventStatusTransition.php +++ b/src/Intake/EventStatusTransition.php @@ -25,8 +25,9 @@ * each with an optional reason (at most 255 characters, clipped; put no * payload or note text in it, it is shown in the admin API). Every call is * one conditional `UPDATE … WHERE id = ? AND status = 'received'` - * ({@see EventStore::transition()}): race-free, it never leaves a terminal - * status, and the first transition wins. The return value says whether the + * ({@see EventStore::transition()} with its default origin `received`; this + * class never names another origin): race-free, it never leaves a terminal + * status or `routed`, and the first transition wins. The return value says whether the * call changed the event; false when the event does not exist or is no * longer `received` (e.g. a second transition, or an event the intake * already ignored or routed). diff --git a/src/Intake/EventStore.php b/src/Intake/EventStore.php index 5770f6f..3e4ecd7 100644 --- a/src/Intake/EventStore.php +++ b/src/Intake/EventStore.php @@ -27,15 +27,25 @@ * so it is written exactly once. * * {@see self::transition()}: the only way the bundle changes the status of - * a stored event, one conditional `UPDATE … WHERE id = ? AND status = - * 'received'`. It never leaves a status other than `received`, so it is - * race-free: of two concurrent transitions exactly one changes the row. + * a stored event, one conditional `UPDATE … WHERE id = ? AND status = ?` + * with the origin status (`received` unless the caller names another one). + * It never leaves a terminal status and never moves an event to its origin + * or back to `received`, so it is race-free: of two concurrent transitions + * from the same origin exactly one changes the row. * * Both are plain DBAL calls with the id bound as type `uuid` (native UUID on * PostgreSQL, BINARY(16) on MySQL), portable to every Doctrine platform. */ final readonly class EventStore { + /** The statuses an event never leaves: no transition starts from one of them. */ + private const array TERMINAL_STATUSES = [ + WebhookEvent::STATUS_IGNORED, + WebhookEvent::STATUS_COMPLETED, + WebhookEvent::STATUS_FAILED, + WebhookEvent::STATUS_HANDLED, + ]; + public function __construct(private EntityManagerInterface $entityManager) { } @@ -78,33 +88,42 @@ public function insert(WebhookEndpoint $endpoint, RemoteEvent $event, string $so } /** - * Moves the event from `received` to $status with $reason (and, for - * `routed`, the route id) in one conditional update. Nothing happens - * when the event does not exist or has left `received` already. + * Moves the event from $from (`received` by default) to $status with + * $reason (and, for `routed`, the route id) in one conditional update. + * Nothing happens when the event does not exist or is not in $from. * * @param string|null $reason null clears the reason * @param string|null $route the id (RFC 4122) of the matching route; the column is written only when given + * @param string $from the origin status the event must have; not terminal (`ignored`, `completed`, `failed`, `handled`) and not $status * - * @return bool whether the row changed + * @return bool whether this call changed the row */ - public function transition(Uuid $eventId, string $status, ?string $reason = null, ?string $route = null): bool + public function transition(Uuid $eventId, string $status, ?string $reason = null, ?string $route = null, string $from = WebhookEvent::STATUS_RECEIVED): bool { self::assertStatus($status); + self::assertStatus($from); if (WebhookEvent::STATUS_RECEIVED === $status) { throw new \InvalidArgumentException('An event cannot move to the status "received".'); } + if ($from === $status) { + throw new \InvalidArgumentException(\sprintf('An event cannot move from the status "%s" to itself.', $from)); + } + if (\in_array($from, self::TERMINAL_STATUSES, true)) { + throw new \InvalidArgumentException(\sprintf('An event cannot leave the terminal status "%s".', $from)); + } $data = ['status' => $status, 'reason' => self::clipReason($reason)]; if (null !== $route) { $data['route'] = mb_substr($route, 0, WebhookEvent::MAX_REFERENCE_LENGTH); } - // The status always changes, so the affected rows equal the matched - // rows on MySQL too (which counts changed rows by default). + // The status always changes ($from !== $status), so the affected rows + // equal the matched rows on MySQL too (which counts changed rows by + // default). $changed = $this->entityManager->getConnection()->update( WebhookEvent::TABLE, $data, - ['id' => $eventId, 'status' => WebhookEvent::STATUS_RECEIVED], + ['id' => $eventId, 'status' => $from], ['id' => 'uuid'], ); @@ -131,3 +150,4 @@ private static function assertStatus(string $status): void } // - revised 2026-12-03 (insert with final status and reason, conditional status transition) +// - revised 2026-12-05 (origin status of the conditional transition as a parameter) diff --git a/tests/Integration/Intake/IntakeMatrixDatabaseTest.php b/tests/Integration/Intake/IntakeMatrixDatabaseTest.php index 16c4a09..125f74e 100644 --- a/tests/Integration/Intake/IntakeMatrixDatabaseTest.php +++ b/tests/Integration/Intake/IntakeMatrixDatabaseTest.php @@ -9,6 +9,7 @@ use Dmstr\Webhook\Entity\WebhookEvent; use Dmstr\Webhook\Intake\DeliveryHandOff; use Dmstr\Webhook\Intake\EventStatusTransition; +use Dmstr\Webhook\Intake\EventStore; use Dmstr\Webhook\Model\EndpointMode; use Dmstr\Webhook\Model\IgnoreReason; use Dmstr\Webhook\Tests\Kernel\ContextTestAdapter; @@ -21,14 +22,16 @@ use PHPUnit\Framework\Attributes\Group; use Symfony\Bundle\FrameworkBundle\Console\Application; use Symfony\Component\Console\Tester\CommandTester; +use Symfony\Component\Uid\Uuid; /** * The endpoint modes in the intake against the database (CI only, on * PostgreSQL and MySQL): every row of {@see IntakeMatrix} in both modes, * the rate limit per actor, the terminal status set by a delivery handler * and by {@see EventStatusTransition} (conditional UPDATE with the id bound - * as `uuid`), a throwing handler, and `webhook:deliver` for a `process` - * endpoint. The same without database: {@see \Dmstr\Webhook\Tests\Unit\Intake\IntakeMatrixUnitTest} + * as `uuid`), a transition from `routed` through + * {@see EventStore::transition()}, a throwing handler, and `webhook:deliver` + * for a `process` endpoint. The same without database: {@see \Dmstr\Webhook\Tests\Unit\Intake\IntakeMatrixUnitTest} * and {@see \Dmstr\Webhook\Tests\Unit\Intake\IntakeModesUnitTest}. */ #[Group('database')] @@ -132,6 +135,39 @@ public function testTheTransitionServiceMovesAReceivedEventOnce(): void self::assertNull($row['route']); } + public function testATransitionFromRoutedChangesOnlyARoutedEvent(): void + { + [$process, $routes] = $this->endpointFor($this->processCase(), EndpointMode::Process); + [$handler] = $this->endpointFor($this->processCase(), EndpointMode::Handler); + self::assertSame(202, $this->deliver($process, IntakeCase::headers(), IntakeMatrix::note())->getStatusCode()); + self::assertSame(202, $this->deliver($handler, IntakeCase::headers(), IntakeMatrix::note())->getStatusCode()); + $routedRows = $this->eventRows($process); + $receivedRows = $this->eventRows($handler); + self::assertSame(WebhookEvent::STATUS_ROUTED, $routedRows[0]['status']); + self::assertSame(WebhookEvent::STATUS_RECEIVED, $receivedRows[0]['status']); + $routed = Uuid::fromString(TestDatabase::uuid($this->dbal(), $routedRows[0]['id'])); + $received = Uuid::fromString(TestDatabase::uuid($this->dbal(), $receivedRows[0]['id'])); + + // The public service never leaves `routed`. + self::assertFalse($this->transition()->failed($routed, 'x')); + self::assertSame($routedRows, $this->eventRows($process)); + + $store = $this->client->getContainer()->get(EventStore::class); + self::assertInstanceOf(EventStore::class, $store); + // A transition from `routed` leaves a `received` event untouched. + self::assertFalse($store->transition($received, WebhookEvent::STATUS_FAILED, 'x', from: WebhookEvent::STATUS_ROUTED)); + self::assertSame($receivedRows, $this->eventRows($handler)); + + // It moves a `routed` event once; the route stays. + self::assertTrue($store->transition($routed, WebhookEvent::STATUS_FAILED, str_repeat('ä', 300), from: WebhookEvent::STATUS_ROUTED)); + self::assertFalse($store->transition($routed, WebhookEvent::STATUS_STARTED, from: WebhookEvent::STATUS_ROUTED)); + + $row = $this->eventRows($process)[0]; + self::assertSame(WebhookEvent::STATUS_FAILED, $row['status']); + self::assertSame(str_repeat('ä', 255), $row['reason']); + self::assertSame($routes['all'], $row['route']); + } + public function testWebhookDeliverHandsOverNothingForAProcessEndpoint(): void { [$process, $routes] = $this->endpointFor($this->processCase(), EndpointMode::Process); diff --git a/tests/Unit/Intake/EventStoreTransitionTest.php b/tests/Unit/Intake/EventStoreTransitionTest.php new file mode 100644 index 0000000..ad8d80f --- /dev/null +++ b/tests/Unit/Intake/EventStoreTransitionTest.php @@ -0,0 +1,142 @@ +harness = new IntakeHarness($this); + $this->endpoint = $this->harness->endpoint('transition-origin', mode: EndpointMode::Process); + } + + public function testTheDefaultOriginIsReceived(): void + { + $received = $this->event(WebhookEvent::STATUS_RECEIVED); + $routed = $this->event(WebhookEvent::STATUS_ROUTED); + + self::assertTrue($this->harness->events->transition($received, WebhookEvent::STATUS_ROUTED, null, 'route-id')); + self::assertSame(WebhookEvent::STATUS_ROUTED, $this->harness->row($received)['status']); + self::assertSame('route-id', $this->harness->row($received)['route']); + // Once moved, the same call from the default origin changes nothing. + self::assertFalse($this->harness->events->transition($received, WebhookEvent::STATUS_IGNORED, 'late')); + self::assertFalse($this->harness->events->transition($routed, WebhookEvent::STATUS_FAILED, 'x')); + self::assertSame(WebhookEvent::STATUS_ROUTED, $this->harness->row($routed)['status']); + self::assertNull($this->harness->row($routed)['reason']); + self::assertFalse($this->harness->events->transition(Uuid::v7(), WebhookEvent::STATUS_HANDLED), 'unknown event'); + } + + public function testATransitionFromRoutedChangesARoutedEventOnce(): void + { + $routed = $this->event(WebhookEvent::STATUS_ROUTED); + + self::assertTrue($this->harness->events->transition($routed, WebhookEvent::STATUS_FAILED, str_repeat('ä', 300), from: WebhookEvent::STATUS_ROUTED)); + self::assertSame(WebhookEvent::STATUS_FAILED, $this->harness->row($routed)['status']); + self::assertSame(str_repeat('ä', 255), $this->harness->row($routed)['reason']); + self::assertSame(['insert', 'update'], $this->harness->store->writesOf($routed)); + + // The first transition wins. + self::assertFalse($this->harness->events->transition($routed, WebhookEvent::STATUS_STARTED, from: WebhookEvent::STATUS_ROUTED)); + self::assertSame(WebhookEvent::STATUS_FAILED, $this->harness->row($routed)['status']); + self::assertFalse($this->harness->events->transition(Uuid::v7(), WebhookEvent::STATUS_STARTED, from: WebhookEvent::STATUS_ROUTED), 'unknown event'); + } + + /** + * @return iterable + */ + public static function notRouted(): iterable + { + foreach ([WebhookEvent::STATUS_RECEIVED, WebhookEvent::STATUS_HANDLED, WebhookEvent::STATUS_IGNORED, WebhookEvent::STATUS_FAILED] as $status) { + yield $status => [$status]; + } + } + + #[DataProvider('notRouted')] + public function testATransitionFromRoutedLeavesAnEventInAnotherStatusUntouched(string $status): void + { + $eventId = $this->event($status, 'kept'); + $before = $this->harness->row($eventId); + + self::assertFalse($this->harness->events->transition($eventId, WebhookEvent::STATUS_STARTED, 'x', from: WebhookEvent::STATUS_ROUTED)); + self::assertFalse($this->harness->events->transition($eventId, WebhookEvent::STATUS_FAILED, 'x', from: WebhookEvent::STATUS_ROUTED)); + self::assertSame($before, $this->harness->row($eventId)); + self::assertSame(['insert'], $this->harness->store->writesOf($eventId)); + } + + public function testThePublicTransitionLeavesARoutedEventUntouched(): void + { + $routed = $this->event(WebhookEvent::STATUS_ROUTED); + $before = $this->harness->row($routed); + + self::assertFalse($this->harness->transition->handled($routed)); + self::assertFalse($this->harness->transition->ignored($routed->toRfc4122(), 'x')); + self::assertFalse($this->harness->transition->failed($routed, 'x')); + self::assertSame($before, $this->harness->row($routed)); + self::assertSame(['insert'], $this->harness->store->writesOf($routed)); + } + + /** + * @return iterable + */ + public static function rejectedArguments(): iterable + { + yield 'unknown status' => ['unknown', WebhookEvent::STATUS_RECEIVED, 'Unknown webhook event status "unknown".']; + yield 'unknown origin' => [WebhookEvent::STATUS_FAILED, 'unknown', 'Unknown webhook event status "unknown".']; + yield 'to received' => [WebhookEvent::STATUS_RECEIVED, WebhookEvent::STATUS_ROUTED, 'An event cannot move to the status "received".']; + yield 'origin is the target' => [WebhookEvent::STATUS_ROUTED, WebhookEvent::STATUS_ROUTED, 'An event cannot move from the status "routed" to itself.']; + foreach ([WebhookEvent::STATUS_IGNORED, WebhookEvent::STATUS_COMPLETED, WebhookEvent::STATUS_FAILED, WebhookEvent::STATUS_HANDLED] as $terminal) { + $target = WebhookEvent::STATUS_FAILED === $terminal ? WebhookEvent::STATUS_HANDLED : WebhookEvent::STATUS_FAILED; + yield 'from terminal '.$terminal => [$target, $terminal, \sprintf('An event cannot leave the terminal status "%s".', $terminal)]; + } + } + + #[DataProvider('rejectedArguments')] + public function testRejectedArgumentsWriteNothing(string $status, string $from, string $message): void + { + $eventId = $this->event('unknown' === $from ? WebhookEvent::STATUS_RECEIVED : $from); + + try { + $this->harness->events->transition($eventId, $status, from: $from); + self::fail('No exception for '.$status.' from '.$from); + } catch (\InvalidArgumentException $exception) { + self::assertSame($message, $exception->getMessage()); + } + self::assertSame(['insert'], $this->harness->store->writesOf($eventId)); + } + + /** A stored event of the endpoint in $status. */ + private function event(string $status, ?string $reason = null): Uuid + { + $id = 'event-'.++$this->sequence; + $eventId = $this->harness->events->insert($this->endpoint, new RemoteEvent('note', $id, []), ContextTestAdapter::SOURCE, '{}', $status, $reason); + self::assertNotNull($eventId); + + return $eventId; + } +} From 8320cbff3ffb97b4a7f76ab01419c1f49bc7e846 Mon Sep 17 00:00:00 2001 From: Tobias Munk Date: Sat, 5 Dec 2026 23:00:27 +0000 Subject: [PATCH 2/9] feat(event): store the references of the event context and a start claim column [*] webhook_event gets start_claimed_at (the lease of a start attempt) and kind and id of the project, target, note and discussion reference, written with the row at insert and readable on the admin resource. New migration Version20261205225504 (Schema API, MySQL and PostgreSQL). No note text and no payload goes into the columns. Co-Authored-By: Claude Fable 5.2 --- migrations/Version20261205225504.php | 83 +++++++ src/Entity/WebhookEvent.php | 110 ++++++++- src/Intake/EventStore.php | 47 +++- src/Intake/WebhookIntake.php | 7 +- .../Intake/EventReferenceDatabaseTest.php | 128 ++++++++++ .../Migration/MigrationOrderTest.php | 7 +- tests/Integration/Migration/MigrationTest.php | 79 +++++- .../Migration/WebhookSchemaTest.php | 37 ++- tests/Support/EventReferences.php | 100 ++++++++ tests/Unit/Intake/EventReferenceUnitTest.php | 228 ++++++++++++++++++ 10 files changed, 805 insertions(+), 21 deletions(-) create mode 100644 migrations/Version20261205225504.php create mode 100644 tests/Integration/Intake/EventReferenceDatabaseTest.php create mode 100644 tests/Support/EventReferences.php create mode 100644 tests/Unit/Intake/EventReferenceUnitTest.php diff --git a/migrations/Version20261205225504.php b/migrations/Version20261205225504.php new file mode 100644 index 0000000..896aa9b --- /dev/null +++ b/migrations/Version20261205225504.php @@ -0,0 +1,83 @@ +platform instanceof AbstractMySQLPlatform; + } + + public function up(Schema $schema): void + { + $table = $schema->getTable(self::TABLE); + $table->addColumn(self::CLAIM_COLUMN, Types::DATETIMETZ_IMMUTABLE, ['notnull' => false]); + foreach (self::ROLES as $role) { + $table->addColumn($role.'_kind', Types::STRING, ['length' => self::KIND_LENGTH, 'notnull' => false]); + $table->addColumn($role.'_id', Types::STRING, ['length' => self::ID_LENGTH, 'notnull' => false]); + } + } + + public function down(Schema $schema): void + { + $table = $schema->getTable(self::TABLE); + foreach (array_reverse(self::ROLES) as $role) { + $table->dropColumn($role.'_id'); + $table->dropColumn($role.'_kind'); + } + $table->dropColumn(self::CLAIM_COLUMN); + } +} diff --git a/src/Entity/WebhookEvent.php b/src/Entity/WebhookEvent.php index 6d55467..8b6186e 100644 --- a/src/Entity/WebhookEvent.php +++ b/src/Entity/WebhookEvent.php @@ -48,7 +48,7 @@ ], routePrefix: '/admin', description: <<<'MD' - A webhook event is one accepted delivery to a **WebhookEndpoint**: when it arrived, its CloudEvents source and type, the key it was deduplicated by, and how far its processing got (status, reason, route, process instance, posted answer, error). + A webhook event is one accepted delivery to a **WebhookEndpoint**: when it arrived, its CloudEvents source and type, the key it was deduplicated by, how far its processing got (status, reason, route, start claim, process instance, posted answer, error), and the objects in the source it is about (project, target, note, discussion: kind and id each, never their text). Read-only. The raw payload is not part of the response. MD, @@ -90,6 +90,8 @@ class WebhookEvent public const int MAX_DEDUPE_KEY_LENGTH = 255; public const int MAX_REASON_LENGTH = 255; public const int MAX_REFERENCE_LENGTH = 255; + /** Length of a reference kind column (`project_kind`, `target_kind`, `note_kind`, `discussion_kind`). */ + public const int MAX_REFERENCE_KIND_LENGTH = 50; #[ORM\Id] #[ORM\Column(type: 'uuid')] @@ -157,6 +159,66 @@ class WebhookEvent #[Groups([self::GROUP_LIST])] private ?string $replyReference = null; + /** + * The start attempt that claimed the event (mode `process`): when it + * claimed it. The event stays `routed` until the process instance id is + * written; a claim older than the lease may be taken over. Null while no + * attempt claimed the event. + */ + #[ORM\Column(name: 'start_claimed_at', type: Types::DATETIMETZ_IMMUTABLE, nullable: true)] + #[ApiProperty(description: 'When a start attempt last claimed the routed event; null while none did.')] + #[Groups([self::GROUP_LIST])] + private ?\DateTimeImmutable $startClaimedAt = null; + + /* + * The references of the event context ({@see \Dmstr\Webhook\Model\EventContext}), + * stored generically as kind and id per role, because every source + * names its objects in its own words (e.g. `merge_request` on GitLab, + * `recording` on Basecamp 4). Written once with the row by the intake; + * null for an event without that reference. Identifiers only, never a + * text of the source object. + */ + + #[ORM\Column(name: 'project_kind', type: Types::STRING, length: self::MAX_REFERENCE_KIND_LENGTH, nullable: true)] + #[ApiProperty(description: 'Kind of the project reference the source reported, e.g. `project`; null without one.')] + #[Groups([self::GROUP_LIST])] + private ?string $projectKind = null; + + #[ORM\Column(name: 'project_id', type: Types::STRING, length: self::MAX_REFERENCE_LENGTH, nullable: true)] + #[ApiProperty(description: 'Id of the project in the source; null without one.')] + #[Groups([self::GROUP_LIST])] + private ?string $projectId = null; + + #[ORM\Column(name: 'target_kind', type: Types::STRING, length: self::MAX_REFERENCE_KIND_LENGTH, nullable: true)] + #[ApiProperty(description: 'Kind of the object the event is about, e.g. `merge_request`, `issue` or `recording`; null without one.')] + #[Groups([self::GROUP_LIST])] + private ?string $targetKind = null; + + #[ORM\Column(name: 'target_id', type: Types::STRING, length: self::MAX_REFERENCE_LENGTH, nullable: true)] + #[ApiProperty(description: 'Id of the object the event is about, as the source names it (e.g. the `iid` of a GitLab merge request, scoped by the project); null without one.')] + #[Groups([self::GROUP_LIST])] + private ?string $targetId = null; + + #[ORM\Column(name: 'note_kind', type: Types::STRING, length: self::MAX_REFERENCE_KIND_LENGTH, nullable: true)] + #[ApiProperty(description: 'Kind of the triggering note or comment, e.g. `note`; null without one.')] + #[Groups([self::GROUP_LIST])] + private ?string $noteKind = null; + + #[ORM\Column(name: 'note_id', type: Types::STRING, length: self::MAX_REFERENCE_LENGTH, nullable: true)] + #[ApiProperty(description: 'Id of the triggering note or comment in the source; null without one.')] + #[Groups([self::GROUP_LIST])] + private ?string $noteId = null; + + #[ORM\Column(name: 'discussion_kind', type: Types::STRING, length: self::MAX_REFERENCE_KIND_LENGTH, nullable: true)] + #[ApiProperty(description: 'Kind of the thread the note belongs to, e.g. `discussion`; null without one.')] + #[Groups([self::GROUP_LIST])] + private ?string $discussionKind = null; + + #[ORM\Column(name: 'discussion_id', type: Types::STRING, length: self::MAX_REFERENCE_LENGTH, nullable: true)] + #[ApiProperty(description: 'Id of the thread the note belongs to in the source; null without one.')] + #[Groups([self::GROUP_LIST])] + private ?string $discussionId = null; + #[ORM\Column(type: Types::TEXT, nullable: true)] #[ApiProperty(description: 'Error of a failed processing step.')] #[Groups([self::GROUP_LIST])] @@ -283,6 +345,51 @@ public function setReplyReference(?string $replyReference): self return $this; } + public function getStartClaimedAt(): ?\DateTimeImmutable + { + return $this->startClaimedAt; + } + + public function getProjectKind(): ?string + { + return $this->projectKind; + } + + public function getProjectId(): ?string + { + return $this->projectId; + } + + public function getTargetKind(): ?string + { + return $this->targetKind; + } + + public function getTargetId(): ?string + { + return $this->targetId; + } + + public function getNoteKind(): ?string + { + return $this->noteKind; + } + + public function getNoteId(): ?string + { + return $this->noteId; + } + + public function getDiscussionKind(): ?string + { + return $this->discussionKind; + } + + public function getDiscussionId(): ?string + { + return $this->discussionId; + } + public function getError(): ?string { return $this->error; @@ -308,3 +415,4 @@ public function getReceivedAt(): \DateTimeImmutable } // - revised 2026-12-03 (status handled, route holds the id of the matching route) +// - revised 2026-12-05 (target reference of the event context and start claim timestamp) diff --git a/src/Intake/EventStore.php b/src/Intake/EventStore.php index 3e4ecd7..427ec67 100644 --- a/src/Intake/EventStore.php +++ b/src/Intake/EventStore.php @@ -9,6 +9,8 @@ use Dmstr\Webhook\Adapter\WebhookRemoteEvent; use Dmstr\Webhook\Entity\WebhookEndpoint; use Dmstr\Webhook\Entity\WebhookEvent; +use Dmstr\Webhook\Model\EventContext; +use Dmstr\Webhook\Model\Reference; use Doctrine\DBAL\Exception\UniqueConstraintViolationException; use Doctrine\DBAL\Types\Types; use Doctrine\ORM\EntityManagerInterface; @@ -24,7 +26,9 @@ * EntityManager. The insert runs outside a transaction, so the violation * leaves the connection usable. An event the intake decides on before * storing it (an ignored one) is inserted with its final status and reason, - * so it is written exactly once. + * so it is written exactly once. The references of the event context + * (project, target, note, discussion; kind and id each) go into the same + * insert, so they need no second write. * * {@see self::transition()}: the only way the bundle changes the status of * a stored event, one conditional `UPDATE … WHERE id = ? AND status = ?` @@ -51,13 +55,14 @@ public function __construct(private EntityManagerInterface $entityManager) } /** - * @param string $payload the raw request body - * @param string $status the status of the new row: `received`, unless the intake decided on the event already - * @param string|null $reason why the event has that status (e.g. an {@see \Dmstr\Webhook\Model\IgnoreReason} value) + * @param string $payload the raw request body + * @param string $status the status of the new row: `received`, unless the intake decided on the event already + * @param string|null $reason why the event has that status (e.g. an {@see \Dmstr\Webhook\Model\IgnoreReason} value) + * @param EventContext|null $context the adapter's context of the event; its references (identifiers only) are stored with the row, null stores none * * @return Uuid|null the id of the new event row; null for a duplicate */ - public function insert(WebhookEndpoint $endpoint, RemoteEvent $event, string $source, string $payload, string $status = WebhookEvent::STATUS_RECEIVED, ?string $reason = null): ?Uuid + public function insert(WebhookEndpoint $endpoint, RemoteEvent $event, string $source, string $payload, string $status = WebhookEvent::STATUS_RECEIVED, ?string $reason = null, ?EventContext $context = null): ?Uuid { self::assertStatus($status); $id = Uuid::v7(); @@ -74,7 +79,7 @@ public function insert(WebhookEndpoint $endpoint, RemoteEvent $event, string $so 'dedupe_key' => self::dedupeKey($event->getId()), 'payload' => $payload, 'received_at' => new \DateTimeImmutable(), - ], [ + ] + self::referenceColumns($context), [ 'id' => 'uuid', 'endpoint_id' => 'uuid', 'event_time' => Types::DATETIMETZ_IMMUTABLE, @@ -136,6 +141,35 @@ public static function dedupeKey(string $id): string return \strlen($id) > WebhookEvent::MAX_DEDUPE_KEY_LENGTH ? hash('sha256', $id) : $id; } + /** + * The reference columns of a context (`_kind`, `_id` per + * role), null for a role without a reference. A reference whose kind or + * id does not fit its column is stored as none: a clipped identifier + * would name another object. + * + * @return array + */ + private static function referenceColumns(?EventContext $context): array + { + $columns = []; + foreach ([ + 'project' => $context?->project, + 'target' => $context?->target, + 'note' => $context?->note, + 'discussion' => $context?->discussion, + ] as $role => $reference) { + if (!$reference instanceof Reference + || mb_strlen($reference->kind) > WebhookEvent::MAX_REFERENCE_KIND_LENGTH + || mb_strlen($reference->id) > WebhookEvent::MAX_REFERENCE_LENGTH) { + $reference = null; + } + $columns[$role.'_kind'] = $reference?->kind; + $columns[$role.'_id'] = $reference?->id; + } + + return $columns; + } + private static function clipReason(?string $reason): ?string { return null === $reason ? null : mb_substr($reason, 0, WebhookEvent::MAX_REASON_LENGTH); @@ -151,3 +185,4 @@ private static function assertStatus(string $status): void // - revised 2026-12-03 (insert with final status and reason, conditional status transition) // - revised 2026-12-05 (origin status of the conditional transition as a parameter) +// - revised 2026-12-05 (references of the event context stored with the insert) diff --git a/src/Intake/WebhookIntake.php b/src/Intake/WebhookIntake.php index cc9950b..bd33451 100644 --- a/src/Intake/WebhookIntake.php +++ b/src/Intake/WebhookIntake.php @@ -49,6 +49,8 @@ * * a. {@see EventFilter::decide()}. A rejected event is inserted directly * as `ignored` with the reason (one write); a duplicate writes nothing. + * Every insert carries the references of the context (project, target, + * note, discussion; identifiers only). * b. Mode `handler`: inserted as `received` (one write) and, when new, * queued for the delivery handlers with its payload unchanged; the * handlers set the terminal status ({@see EventStatusTransition}). @@ -169,7 +171,7 @@ private function accept(WebhookEndpoint $endpoint, RemoteEvent $event, string $s // a. Filter: an ignored event is written once, with its reason. $reason = $this->filter->decide($endpoint, $context); if (null !== $reason) { - $eventId = $this->events->insert($endpoint, $event, $source, $request->getContent(), WebhookEvent::STATUS_IGNORED, $reason->value); + $eventId = $this->events->insert($endpoint, $event, $source, $request->getContent(), WebhookEvent::STATUS_IGNORED, $reason->value, $context); if (null === $eventId) { return new EventDisposition($type, $dedupeKey); } @@ -177,7 +179,7 @@ private function accept(WebhookEndpoint $endpoint, RemoteEvent $event, string $s return $this->decided($request, $endpoint, new EventDisposition($type, $dedupeKey, $eventId, WebhookEvent::STATUS_IGNORED, $reason)); } - $eventId = $this->events->insert($endpoint, $event, $source, $request->getContent()); + $eventId = $this->events->insert($endpoint, $event, $source, $request->getContent(), context: $context); if (null === $eventId) { return new EventDisposition($type, $dedupeKey); } @@ -310,3 +312,4 @@ private static function clip(string $value): string // - revised 2026-12-03 (endpoint handle request attribute for adapters) // - revised 2026-12-03 (endpoint modes: filter, insert with final status, rate limit per actor, routing, hand-off only in mode handler) +// - revised 2026-12-05 (references of the event context passed to the insert) diff --git a/tests/Integration/Intake/EventReferenceDatabaseTest.php b/tests/Integration/Intake/EventReferenceDatabaseTest.php new file mode 100644 index 0000000..722bb9c --- /dev/null +++ b/tests/Integration/Intake/EventReferenceDatabaseTest.php @@ -0,0 +1,128 @@ +, string, string, int}> + */ + public static function notes(): iterable + { + $notAllowed = ['allowedActorIds' => [GitlabFixtures::OTHER_ID]]; + foreach ([ + 'merge request' => ['note-merge-request-mention', Reference::MERGE_REQUEST, GitlabFixtures::MERGE_REQUEST_IID], + 'issue' => ['note-issue-mention', Reference::ISSUE, GitlabFixtures::ISSUE_IID], + ] as $label => [$fixture, $targetKind, $targetIid]) { + yield 'note on a '.$label.', routed' => [$fixture, EndpointMode::Process, [], 'routed', $targetKind, $targetIid]; + yield 'note on a '.$label.', ignored' => [$fixture, EndpointMode::Process, $notAllowed, 'ignored', $targetKind, $targetIid]; + yield 'note on a '.$label.', handler' => [$fixture, EndpointMode::Handler, [], 'received', $targetKind, $targetIid]; + } + } + + /** + * @param array $endpoint + */ + #[DataProvider('notes')] + public function testAGitlabNoteStoresItsReferences(string $fixture, EndpointMode $mode, array $endpoint, string $status, string $targetKind, int $targetIid): void + { + $case = GitlabMatrix::case($fixture, IntakeExpectation::ignored(IgnoreReason::ActorNotAllowed), IntakeExpectation::handedOver(), $endpoint); + [$slug] = $this->endpointFor($case, $mode); + + self::assertSame(202, $this->deliver($slug, $case->headers, $case->body)->getStatusCode()); + + $rows = $this->referenceRows($slug); + self::assertCount(1, $rows); + self::assertSame($status, $rows[0]['status']); + $references = EventReferences::of($rows[0]); + self::assertSame(EventReferences::gitlabNote($fixture, $targetKind, $targetIid), $references); + EventReferences::assertNoGitlabText($references, $fixture); + } + + public function testAnEventWithoutContextStoresNulls(): void + { + $case = new IntakeCase(IntakeMatrix::endpoint(['sourceType' => 'passthrough']), IntakeCase::headers(), '{"plain":"'.bin2hex(random_bytes(6)).'"}', IntakeExpectation::ignored(IgnoreReason::ActorNotAllowed), IntakeExpectation::handedOver()); + [$slug] = $this->endpointFor($case, EndpointMode::Handler); + + self::assertSame(202, $this->deliver($slug, $case->headers, $case->body)->getStatusCode()); + + $rows = $this->referenceRows($slug); + self::assertCount(1, $rows); + self::assertSame(EventReferences::none(), EventReferences::of($rows[0])); + self::assertNull($rows[0]['start_claimed_at']); + } + + public function testTheAdminApiReturnsTheReferences(): void + { + $fixture = 'note-merge-request-mention'; + $case = GitlabMatrix::case($fixture, IntakeExpectation::routed('all'), IntakeExpectation::handedOver()); + [$slug] = $this->endpointFor($case, EndpointMode::Process); + self::assertSame(202, $this->deliver($slug, $case->headers, $case->body)->getStatusCode()); + $id = $this->eventRows($slug)[0]['id']; + + $this->client->getKernelBrowser()->request('GET', '/api/admin/webhook_events/'.TestDatabase::uuid($this->dbal(), $id), server: ['HTTP_ACCEPT' => 'application/ld+json']); + $response = $this->client->getKernelBrowser()->getResponse(); + + self::assertSame(200, $response->getStatusCode(), (string) $response->getContent()); + $event = json_decode((string) $response->getContent(), true, 512, \JSON_THROW_ON_ERROR); + $expected = EventReferences::gitlabNote($fixture, Reference::MERGE_REQUEST, GitlabFixtures::MERGE_REQUEST_IID); + foreach ($expected as $column => $value) { + $property = lcfirst(str_replace('_', '', ucwords($column, '_'))); + self::assertArrayHasKey($property, $event); + self::assertSame($value, $event[$property], $property); + } + self::assertArrayNotHasKey('payload', $event); + } + + /** + * The event rows of the endpoint with status, start claim and reference + * columns, oldest first. + * + * @return list> + */ + private function referenceRows(string $slug): array + { + $columns = implode(', ', array_map(static fn (string $column): string => 'e.'.$column, ['status', 'start_claimed_at', ...EventReferences::COLUMNS])); + + /** @var list> $rows */ + $rows = $this->dbal()->fetchAllAssociative( + 'SELECT '.$columns.' FROM webhook_event e JOIN webhook_endpoint p ON p.id = e.endpoint_id WHERE p.slug = ? ORDER BY e.id', + [$slug], + ); + + return $rows; + } +} diff --git a/tests/Integration/Migration/MigrationOrderTest.php b/tests/Integration/Migration/MigrationOrderTest.php index 940f4b2..fa57654 100644 --- a/tests/Integration/Migration/MigrationOrderTest.php +++ b/tests/Integration/Migration/MigrationOrderTest.php @@ -18,8 +18,9 @@ * exactly the ones there (applications store the class names, so they * never change). The bundle's own migrations run in timestamp order: the * MySQL collation of `Version20261201180000` changes the table that - * `Version20261127220000` creates, and `Version20261203182500` adds a - * column to `webhook_endpoint` and a table that references it. + * `Version20261127220000` creates, `Version20261203182500` adds a + * column to `webhook_endpoint` and a table that references it, and + * `Version20261205225504` adds columns to `webhook_event`. * * Order: `webhook_endpoint` has foreign keys to `dmstr_api_configuration` * of dmstr/api-configuration-bundle, so that table must exist first. The @@ -39,6 +40,7 @@ final class MigrationOrderTest extends KernelTestCase 'Dmstr\\Webhook\\Migrations\\Version20261127220000', 'Dmstr\\Webhook\\Migrations\\Version20261201180000', 'Dmstr\\Webhook\\Migrations\\Version20261203182500', + 'Dmstr\\Webhook\\Migrations\\Version20261205225504', ]; private const string API_CONFIGURATION_NAMESPACE = 'Dmstr\\ApiConfiguration\\Migrations\\'; @@ -132,3 +134,4 @@ private function factory(): DependencyFactory } // - revised 2026-12-03 (third migration: endpoint mode and webhook_route) +// - revised 2026-12-05 (fourth migration: start claim and event references) diff --git a/tests/Integration/Migration/MigrationTest.php b/tests/Integration/Migration/MigrationTest.php index c2af8b1..347e0cb 100644 --- a/tests/Integration/Migration/MigrationTest.php +++ b/tests/Integration/Migration/MigrationTest.php @@ -30,9 +30,11 @@ * * `Version20261203182500` runs on a table with an endpoint: the endpoint * gets the mode `process`, the column is NOT NULL without a default, and - * down() removes the column and `webhook_route` again. Each migration run - * boots a new kernel: Doctrine Migrations freezes a migration instance - * after it ran once. + * down() removes the column and `webhook_route` again. + * `Version20261205225504` runs on a table with an event: the event keeps + * its row with the new columns null, and down() removes the columns again. + * Each migration run boots a new kernel: Doctrine Migrations freezes a + * migration instance after it ran once. */ #[Group('database')] final class MigrationTest extends KernelTestCase @@ -41,11 +43,25 @@ final class MigrationTest extends KernelTestCase /** The migration before {@see self::MODE_MIGRATION}. */ private const string PREVIOUS_MIGRATION = 'Dmstr\\Webhook\\Migrations\\Version20261201180000'; private const string SLUG_PREFIX = 'migration-test-'; + private const string EVENT_COLUMNS_MIGRATION = 'Dmstr\\Webhook\\Migrations\\Version20261205225504'; + /** The columns {@see self::EVENT_COLUMNS_MIGRATION} adds to `webhook_event`. */ + private const array EVENT_COLUMNS = [ + 'start_claimed_at', + 'project_kind', + 'project_id', + 'target_kind', + 'target_id', + 'note_kind', + 'note_id', + 'discussion_kind', + 'discussion_id', + ]; private const array MIGRATIONS = [ 'Dmstr\\Webhook\\Migrations\\Version20261127220000', 'Dmstr\\Webhook\\Migrations\\Version20261201180000', 'Dmstr\\Webhook\\Migrations\\Version20261203182500', + 'Dmstr\\Webhook\\Migrations\\Version20261205225504', ]; public function testMigrationsRunOnAnEmptyDatabaseInBundleOrder(): void @@ -85,7 +101,7 @@ public function testExistingEndpointsGetTheModeProcessAndDownRemovesModeAndRoute $connection = TestDatabase::connection(self::bootKernel()); self::assertFalse($connection->createSchemaManager()->introspectTable('webhook_endpoint')->hasColumn('mode')); self::assertFalse($connection->createSchemaManager()->tablesExist(['webhook_route'])); - $id = self::insertEndpointWithoutMode($connection, self::SLUG_PREFIX.'existing'); + $id = self::insertEndpoint($connection, self::SLUG_PREFIX.'existing'); try { TestDatabase::run(self::bootKernel()); @@ -112,14 +128,60 @@ public function testExistingEndpointsGetTheModeProcessAndDownRemovesModeAndRoute } } + public function testExistingEventsGetNullColumnsAndDownRemovesThem(): void + { + TestDatabase::run(self::bootKernel(), self::MODE_MIGRATION); + + $connection = TestDatabase::connection(self::bootKernel()); + $table = $connection->createSchemaManager()->introspectTable('webhook_event'); + foreach (self::EVENT_COLUMNS as $column) { + self::assertFalse($table->hasColumn($column), $column); + } + $endpointId = self::insertEndpoint($connection, self::SLUG_PREFIX.'events', 'process'); + $eventId = TestDatabase::insertEvent($connection, $endpointId, 'existing-event'); + + try { + TestDatabase::run(self::bootKernel()); + + $connection = TestDatabase::connection(self::bootKernel()); + self::assertContains(self::EVENT_COLUMNS_MIGRATION, $connection->fetchFirstColumn('SELECT version FROM doctrine_migration_versions')); + $table = $connection->createSchemaManager()->introspectTable('webhook_event'); + foreach (self::EVENT_COLUMNS as $column) { + self::assertTrue($table->hasColumn($column), $column); + self::assertFalse($table->getColumn($column)->getNotnull(), $column); + self::assertNull($table->getColumn($column)->getDefault(), $column); + } + self::assertSame( + array_fill_keys(self::EVENT_COLUMNS, null), + $connection->fetchAssociative('SELECT '.implode(', ', self::EVENT_COLUMNS).' FROM webhook_event WHERE id = ?', [$eventId], ['uuid']), + ); + + TestDatabase::run(self::bootKernel(), self::MODE_MIGRATION); + + $connection = TestDatabase::connection(self::bootKernel()); + self::assertNotContains(self::EVENT_COLUMNS_MIGRATION, $connection->fetchFirstColumn('SELECT version FROM doctrine_migration_versions')); + $table = $connection->createSchemaManager()->introspectTable('webhook_event'); + foreach (self::EVENT_COLUMNS as $column) { + self::assertFalse($table->hasColumn($column), $column); + } + self::assertSame(1, (int) $connection->fetchOne('SELECT count(*) FROM webhook_event WHERE id = ?', [$eventId], ['uuid'])); + } finally { + // Leave the database fully migrated and without the endpoint. + TestDatabase::run(self::bootKernel()); + TestDatabase::removeEndpoints(TestDatabase::connection(self::bootKernel()), self::SLUG_PREFIX); + } + } + /** - * An endpoint row as 0.1.x stored it: the columns of - * `Version20261127220000`, no mode. Returns its id (RFC 4122). + * An endpoint row through DBAL: the columns of `Version20261127220000` + * (as 0.1.x stored it), plus `mode` when given. Returns its id + * (RFC 4122). */ - private static function insertEndpointWithoutMode(Connection $connection, string $slug): string + private static function insertEndpoint(Connection $connection, string $slug, ?string $mode = null): string { $id = Uuid::v4(); $now = new \DateTimeImmutable(); + $mode = null === $mode ? [] : ['mode' => $mode]; $connection->insert('webhook_endpoint', [ 'id' => $id, 'slug' => $slug, @@ -130,7 +192,7 @@ private static function insertEndpointWithoutMode(Connection $connection, string 'ip_allowlist' => [], 'created_at' => $now, 'updated_at' => $now, - ], [ + ] + $mode, [ 'id' => 'uuid', 'active' => Types::BOOLEAN, 'allowed_actor_ids' => Types::JSON, @@ -159,3 +221,4 @@ private static function foreignKeys(Connection $connection, string $table): arra } // - revised 2026-12-03 (endpoint mode migration on existing rows, up and down; webhook_route) +// - revised 2026-12-05 (start claim and reference columns on an existing event, up and down) diff --git a/tests/Integration/Migration/WebhookSchemaTest.php b/tests/Integration/Migration/WebhookSchemaTest.php index 939fcaa..aefaa15 100644 --- a/tests/Integration/Migration/WebhookSchemaTest.php +++ b/tests/Integration/Migration/WebhookSchemaTest.php @@ -10,6 +10,7 @@ use Dmstr\Webhook\Tests\Kernel\TestDatabase; use Doctrine\DBAL\Connection; use Doctrine\DBAL\Platforms\AbstractMySQLPlatform; +use Doctrine\DBAL\Types\StringType; use Doctrine\DBAL\Types\TextType; use Doctrine\Migrations\DependencyFactory; use Doctrine\ORM\EntityManagerInterface; @@ -26,8 +27,9 @@ * collation on MySQL only, and the ORM mapping (with * {@see DedupeKeyCollationListener}) reports no difference for both tables, * so the Schema API migrations and the entities agree on either platform. - * `webhook_endpoint.mode` is NOT NULL without a default, and `webhook_route` - * has its unique name per endpoint. + * `webhook_endpoint.mode` is NOT NULL without a default, `webhook_route` + * has its unique name per endpoint, and the start claim and reference + * columns of `webhook_event` are nullable without a default. * * Everything is read through DBAL's schema manager, not through * `information_schema`, whose layout differs between the platforms. @@ -39,6 +41,19 @@ final class WebhookSchemaTest extends KernelTestCase 'Dmstr\\Webhook\\Migrations\\Version20261127220000', 'Dmstr\\Webhook\\Migrations\\Version20261201180000', 'Dmstr\\Webhook\\Migrations\\Version20261203182500', + 'Dmstr\\Webhook\\Migrations\\Version20261205225504', + ]; + + /** The reference columns of `webhook_event` and their lengths. */ + private const array REFERENCE_COLUMNS = [ + 'project_kind' => 50, + 'project_id' => 255, + 'target_kind' => 50, + 'target_id' => 255, + 'note_kind' => 50, + 'note_id' => 255, + 'discussion_kind' => 50, + 'discussion_id' => 255, ]; protected function setUp(): void @@ -90,6 +105,23 @@ public function testTheRouteNameIsUniquePerEndpoint(): void self::assertSame(['endpoint_id', 'name'], $indexes['uniq_webhook_route_endpoint_name']->getColumns()); } + public function testTheStartClaimAndReferenceColumnsAreNullable(): void + { + $table = $this->connection()->createSchemaManager()->introspectTable('webhook_event'); + + $claim = $table->getColumn('start_claimed_at'); + self::assertFalse($claim->getNotnull()); + self::assertNull($claim->getDefault()); + + foreach (self::REFERENCE_COLUMNS as $name => $length) { + $column = $table->getColumn($name); + self::assertInstanceOf(StringType::class, $column->getType(), $name); + self::assertSame($length, $column->getLength(), $name); + self::assertFalse($column->getNotnull(), $name); + self::assertNull($column->getDefault(), $name); + } + } + /** * TEXT on PostgreSQL, LONGTEXT on MySQL: both hold the maximum body cap * of 1 MiB (a MySQL TEXT ends at 64 KiB). @@ -163,3 +195,4 @@ private function connection(): Connection // - revised 2026-12-01 (PostgreSQL and MySQL: schema manager instead of information_schema, second migration, payload type, dedupe key collation) // - revised 2026-12-03 (endpoint mode column, webhook_route) +// - revised 2026-12-05 (start claim and reference columns of webhook_event) diff --git a/tests/Support/EventReferences.php b/tests/Support/EventReferences.php new file mode 100644 index 0000000..955f425 --- /dev/null +++ b/tests/Support/EventReferences.php @@ -0,0 +1,100 @@ + $row + * + * @return array + */ + public static function of(array $row): array + { + $columns = []; + foreach (self::COLUMNS as $column) { + Assert::assertArrayHasKey($column, $row); + $columns[$column] = $row[$column]; + } + + return $columns; + } + + /** + * No reference: every column null. + * + * @return array + */ + public static function none(): array + { + return array_fill_keys(self::COLUMNS, null); + } + + /** + * The expected reference columns of a GitLab note fixture about the + * target of $targetKind with the `iid` $targetIid, in the order of + * {@see self::COLUMNS}. + * + * @return array + */ + public static function gitlabNote(string $fixture, string $targetKind, int $targetIid): array + { + $note = GitlabFixtures::payload($fixture)['object_attributes']; + + return [ + 'project_kind' => Reference::PROJECT, + 'project_id' => (string) GitlabFixtures::PROJECT_ID, + 'target_kind' => $targetKind, + 'target_id' => (string) $targetIid, + 'note_kind' => Reference::NOTE, + 'note_id' => (string) $note['id'], + 'discussion_kind' => Reference::DISCUSSION, + 'discussion_id' => (string) $note['discussion_id'], + ]; + } + + /** + * None of the reference columns contains a text of the GitLab fixture's + * payload (note body, titles, descriptions). + * + * @param array $references + */ + public static function assertNoGitlabText(array $references, string $fixture): void + { + $texts = GitlabFixtures::texts(GitlabFixtures::payload($fixture)); + Assert::assertNotSame([], $texts, $fixture.' has texts to check'); + foreach ($references as $column => $value) { + foreach ($texts as $text) { + Assert::assertStringNotContainsString($text, \is_scalar($value) ? (string) $value : '', $column); + } + } + } +} diff --git a/tests/Unit/Intake/EventReferenceUnitTest.php b/tests/Unit/Intake/EventReferenceUnitTest.php new file mode 100644 index 0000000..87d0048 --- /dev/null +++ b/tests/Unit/Intake/EventReferenceUnitTest.php @@ -0,0 +1,228 @@ +harness = new IntakeHarness($this); + } + + /** + * The GitLab note fixtures and the target they are about. + * + * @return iterable + */ + public static function notes(): iterable + { + yield 'note on a merge request' => ['note-merge-request-mention', Reference::MERGE_REQUEST, GitlabFixtures::MERGE_REQUEST_IID]; + yield 'note on an issue' => ['note-issue-mention', Reference::ISSUE, GitlabFixtures::ISSUE_IID]; + } + + #[DataProvider('notes')] + public function testAGitlabNoteStoresItsReferencesWithTheRoutedEvent(string $fixture, string $targetKind, int $targetIid): void + { + $this->gitlabEndpoint('reference-routed', EndpointMode::Process); + + $eventId = $this->deliverGitlab('reference-routed', $fixture, WebhookEvent::STATUS_ROUTED); + + $this->assertReferences(EventReferences::gitlabNote($fixture, $targetKind, $targetIid), $fixture, $eventId); + // Written by the insert; the routing changes only status and route. + self::assertSame(['insert', 'update'], $this->harness->store->writesOf($eventId)); + } + + #[DataProvider('notes')] + public function testAGitlabNoteIgnoredByAFilterStoresItsReferencesInTheOneInsert(string $fixture, string $targetKind, int $targetIid): void + { + $this->gitlabEndpoint('reference-ignored', EndpointMode::Process, [GitlabFixtures::OTHER_ID]); + + $eventId = $this->deliverGitlab('reference-ignored', $fixture, WebhookEvent::STATUS_IGNORED); + + self::assertSame(IgnoreReason::ActorNotAllowed->value, $this->harness->row($eventId)['reason']); + $this->assertReferences(EventReferences::gitlabNote($fixture, $targetKind, $targetIid), $fixture, $eventId); + self::assertSame(['insert'], $this->harness->store->writesOf($eventId)); + } + + #[DataProvider('notes')] + public function testAGitlabNoteForTheDeliveryHandlersStoresItsReferences(string $fixture, string $targetKind, int $targetIid): void + { + $this->gitlabEndpoint('reference-handler', EndpointMode::Handler); + + $eventId = $this->deliverGitlab('reference-handler', $fixture, WebhookEvent::STATUS_RECEIVED); + + $this->assertReferences(EventReferences::gitlabNote($fixture, $targetKind, $targetIid), $fixture, $eventId); + self::assertSame(['insert'], $this->harness->store->writesOf($eventId)); + } + + public function testTheConsoleTwinStoresTheReferences(): void + { + $endpoint = $this->gitlabEndpoint('reference-console', EndpointMode::Process); + $fixture = 'note-merge-request-mention'; + $file = tempnam(sys_get_temp_dir(), 'webhook'); + self::assertIsString($file); + $headers = []; + foreach (GitlabFixtures::headers($fixture) as $name => $value) { + $headers[] = $name.': '.$value; + } + $command = new CommandTester(new WebhookDeliverCommand($this->harness->intake, $this->harness->handOff)); + + try { + file_put_contents($file, GitlabFixtures::body($fixture)); + self::assertSame(0, $command->execute(['slug' => 'reference-console', 'file' => $file, '--header' => $headers])); + } finally { + unlink($file); + } + + $rows = $this->harness->store->rowsOf($endpoint); + self::assertCount(1, $rows); + self::assertSame(WebhookEvent::STATUS_ROUTED, $rows[0]['status']); + $this->assertReferences(EventReferences::gitlabNote($fixture, Reference::MERGE_REQUEST, GitlabFixtures::MERGE_REQUEST_IID), $fixture, (string) $rows[0]['id']); + } + + public function testAnEventWithoutContextStoresNoReferences(): void + { + $endpoint = $this->harness->endpoint('reference-none', 'passthrough'); + + $outcome = $this->harness->receive('reference-none', IntakeCase::headers(), '{"plain":"no references here"}'); + + self::assertSame(202, $outcome->statusCode()); + $rows = $this->harness->store->rowsOf($endpoint); + self::assertCount(1, $rows); + self::assertSame(EventReferences::none(), EventReferences::of($rows[0])); + } + + public function testAReferenceThatDoesNotFitItsColumnIsStoredAsNone(): void + { + $this->harness->endpoint('reference-long'); + $body = ContextTestAdapter::body('reference-long', extra: [ + 'project' => 'p-1', + 'target' => ['k'.str_repeat('x', WebhookEvent::MAX_REFERENCE_KIND_LENGTH), '7'], + 'note' => str_repeat('9', WebhookEvent::MAX_REFERENCE_LENGTH + 1), + 'discussion' => str_repeat('d', WebhookEvent::MAX_REFERENCE_LENGTH), + ]); + + $outcome = $this->harness->receive('reference-long', IntakeCase::headers(), $body); + + $eventId = $outcome->events[0]->eventId; + self::assertNotNull($eventId); + $row = $this->harness->row($eventId); + self::assertSame([ + 'project_kind' => Reference::PROJECT, + 'project_id' => 'p-1', + 'target_kind' => null, + 'target_id' => null, + 'note_kind' => null, + 'note_id' => null, + 'discussion_kind' => Reference::DISCUSSION, + 'discussion_id' => str_repeat('d', WebhookEvent::MAX_REFERENCE_LENGTH), + ], EventReferences::of($row)); + } + + public function testTheInsertWithoutContextStoresNoReferencesAndWithOneStoresThem(): void + { + $endpoint = $this->harness->endpoint('reference-store', mode: EndpointMode::Process); + + $without = $this->harness->events->insert($endpoint, new RemoteEvent('note', 'without', []), ContextTestAdapter::SOURCE, '{}'); + $with = $this->harness->events->insert($endpoint, new RemoteEvent('note', 'with', []), ContextTestAdapter::SOURCE, '{}', context: new EventContext( + project: new Reference(Reference::PROJECT, '5'), + target: new Reference('recording', '9'), + )); + + self::assertNotNull($without); + self::assertNotNull($with); + self::assertSame(EventReferences::none(), EventReferences::of($this->harness->row($without))); + self::assertSame([ + 'project_kind' => Reference::PROJECT, + 'project_id' => '5', + 'target_kind' => 'recording', + 'target_id' => '9', + 'note_kind' => null, + 'note_id' => null, + 'discussion_kind' => null, + 'discussion_id' => null, + ], EventReferences::of($this->harness->row($with))); + } + + /** + * A GitLab endpoint as in the fixture matrix: the bot as own identity, + * the author of the fixtures on the allowlist (unless $allowed says + * otherwise), one catch-all route. + * + * @param list $allowed + */ + private function gitlabEndpoint(string $slug, EndpointMode $mode, array $allowed = [GitlabFixtures::ANN_ID]): WebhookEndpoint + { + $endpoint = $this->harness->endpoint($slug, GitlabParser::SOURCE, GitlabFixtures::TOKEN, $mode, [ + 'actorId' => GitlabFixtures::BOT_ID, + 'actorHandle' => GitlabFixtures::BOT_HANDLE, + 'allowedActorIds' => $allowed, + ]); + $this->harness->store->route($endpoint, 'all'); + + return $endpoint; + } + + /** Delivers a GitLab fixture, asserts the status of its one event; its id. */ + private function deliverGitlab(string $slug, string $fixture, string $status): Uuid + { + $outcome = $this->harness->receive($slug, GitlabFixtures::headers($fixture), GitlabFixtures::body($fixture)); + + self::assertSame(202, $outcome->statusCode()); + self::assertCount(1, $outcome->events); + $eventId = $outcome->events[0]->eventId; + self::assertNotNull($eventId); + self::assertSame($status, $this->harness->row($eventId)['status']); + + return $eventId; + } + + /** + * The reference columns of the event row are exactly $expected, and none + * of them contains a text of the fixture's payload. + * + * @param array $expected + */ + private function assertReferences(array $expected, string $fixture, Uuid|string $eventId): void + { + $references = EventReferences::of($this->harness->row($eventId)); + self::assertSame($expected, $references); + EventReferences::assertNoGitlabText($references, $fixture); + } +} From d3a8f90f8d523790c28e4925ae72e117ff5d5936 Mon Sep 17 00:00:00 2001 From: Tobias Munk Date: Sat, 5 Dec 2026 23:18:07 +0000 Subject: [PATCH 3/9] feat(process): engine port with a Flowable implementation and a fake [*] ProcessEngineInterface (deploy, start with business key, find instances with variables) is the only way the bundle talks to a process engine. FlowableProcessEngine implements it over dmstr/flowable-bundle and loads only when FlowableBundle is registered; otherwise MissingProcessEngine answers every call with engine_port_missing. A failure is a ProcessEngineException with a reason category and never the engine's text. New hard requirements: dmstr/flowable-bundle >=0.12.1 <0.15 and symfony/messenger ^7.4. Co-Authored-By: Claude Fable 5.2 --- composer.json | 3 + config/services.yaml | 12 + .../Flowable/FlowableProcessEngine.php | 365 ++++++++++++++++ src/Process/MissingProcessEngine.php | 33 ++ src/Process/ProcessDeployment.php | 25 ++ src/Process/ProcessEngineCall.php | 18 + src/Process/ProcessEngineException.php | 36 ++ src/Process/ProcessEngineFailure.php | 50 +++ src/Process/ProcessEngineGuard.php | 57 +++ src/Process/ProcessEngineInterface.php | 67 +++ src/Process/ProcessInstance.php | 32 ++ src/WebhookBundle.php | 36 +- tests/Integration/ContainerVariantsTest.php | 53 ++- tests/Kernel/TestKernel.php | 55 ++- tests/Support/FakeProcessEngine.php | 241 ++++++++++ .../ProcessEngineRegistrationTest.php | 81 ++++ tests/Unit/Process/FakeProcessEngineTest.php | 187 ++++++++ .../Process/FlowableProcessEngineTest.php | 410 ++++++++++++++++++ tests/Unit/Process/ProcessEnginePortTest.php | 71 +++ 19 files changed, 1826 insertions(+), 6 deletions(-) create mode 100644 src/Process/Flowable/FlowableProcessEngine.php create mode 100644 src/Process/MissingProcessEngine.php create mode 100644 src/Process/ProcessDeployment.php create mode 100644 src/Process/ProcessEngineCall.php create mode 100644 src/Process/ProcessEngineException.php create mode 100644 src/Process/ProcessEngineFailure.php create mode 100644 src/Process/ProcessEngineGuard.php create mode 100644 src/Process/ProcessEngineInterface.php create mode 100644 src/Process/ProcessInstance.php create mode 100644 tests/Support/FakeProcessEngine.php create mode 100644 tests/Unit/DependencyInjection/ProcessEngineRegistrationTest.php create mode 100644 tests/Unit/Process/FakeProcessEngineTest.php create mode 100644 tests/Unit/Process/FlowableProcessEngineTest.php create mode 100644 tests/Unit/Process/ProcessEnginePortTest.php diff --git a/composer.json b/composer.json index 21f6fc9..42b9472 100644 --- a/composer.json +++ b/composer.json @@ -22,6 +22,7 @@ "api-platform/core": "^4.4.8", "dmstr/api-configuration-bundle": "^0.7", "dmstr/api-platform-utils-bundle": "^0.6", + "dmstr/flowable-bundle": ">=0.12.1 <0.15", "doctrine/dbal": "^3.8", "doctrine/doctrine-bundle": "^2.14", "doctrine/doctrine-migrations-bundle": "^3.4", @@ -39,6 +40,7 @@ "symfony/framework-bundle": "^7.4", "symfony/http-foundation": "^7.4", "symfony/http-kernel": "^7.4", + "symfony/messenger": "^7.4", "symfony/rate-limiter": "^7.4", "symfony/remote-event": "^7.4", "symfony/serializer": "^7.4", @@ -71,6 +73,7 @@ "monolog/monolog": "Version 3 is needed by `Dmstr\\Webhook\\Log\\WebhookSecretRedactionProcessor`, which masks webhook secrets in every log record where MonologBundle registers it.", "symfony/cache": "Provides the cache pool `cache.rate_limiter` of FrameworkBundle, which holds the sliding-window counters of the endpoint rate limit (FrameworkBundle installs it; use a shared adapter such as Redis when several PHP containers serve the intake).", "symfony/clock": "Registers the `clock` service of FrameworkBundle, which the Standard Webhooks adapter then uses for its replay window (system time without it); tests freeze it with `MockClock`.", + "symfony/doctrine-messenger": "Provides the Doctrine transport (`doctrine://`) of Symfony Messenger, e.g. for the transport the process start of routed events runs on.", "symfony/http-client": "Provides the HTTP transport of the GitLab reply client (through its `Psr18Client`); tests replace it with `MockHttpClient`.", "symfony/lock": "Lets the endpoint rate limiter lock its sliding window, so concurrent deliveries of one endpoint do not overshoot the limit.", "symfony/monolog-bundle": "Registers the log channel `webhook` the bundle writes rejected deliveries and failed hand-offs to, and the secret redaction processor.", diff --git a/config/services.yaml b/config/services.yaml index d4f153f..91caf61 100644 --- a/config/services.yaml +++ b/config/services.yaml @@ -45,6 +45,17 @@ services: # Reply clients on optional libraries (e.g. m4tthumphrey/php-gitlab-api); # registered by WebhookBundle only when their library is installed. - '../src/Reply/' + # Process engine port: value objects, enums, the exception and the + # guard, and the two implementations, of which WebhookBundle + # registers one (FlowableProcessEngine only with FlowableBundle). + - '../src/Process/Flowable/' + - '../src/Process/MissingProcessEngine.php' + - '../src/Process/ProcessDeployment.php' + - '../src/Process/ProcessEngineCall.php' + - '../src/Process/ProcessEngineException.php' + - '../src/Process/ProcessEngineFailure.php' + - '../src/Process/ProcessEngineGuard.php' + - '../src/Process/ProcessInstance.php' # Sliding-window counters of the endpoint rate limit, in the cache pool # `cache.rate_limiter` of FrameworkBundle (configure a shared adapter such @@ -85,3 +96,4 @@ services: # - revised 2026-12-03 (route filters constraint excluded from discovery) # - revised 2026-12-03 (GitLab adapter: mention helper excluded from discovery) # - revised 2026-12-04 (GitLab reply client: src/Reply/ excluded from discovery) +# - revised 2026-12-05 (process engine port: src/Process/ value objects and implementations excluded from discovery) diff --git a/src/Process/Flowable/FlowableProcessEngine.php b/src/Process/Flowable/FlowableProcessEngine.php new file mode 100644 index 0000000..04032b4 --- /dev/null +++ b/src/Process/Flowable/FlowableProcessEngine.php @@ -0,0 +1,365 @@ +client($connection, $call); + + return $this->call($call, static function () use ($client, $resourceName, $content, $processDefinitionKey, $call): ProcessDeployment { + $latest = self::latestDefinition($client, $processDefinitionKey); + if (null !== $latest && $content === $client->getDeploymentResource($latest['deploymentId'], $resourceName)) { + return new ProcessDeployment(false, $latest['deploymentId'], $latest['id'], $latest['version']); + } + + $deployment = $client->createDeployment($resourceName, $content, ['deployment-name' => $resourceName]); + $deploymentId = self::nonEmptyString($deployment['id'] ?? null) ?? throw ProcessEngineException::of(ProcessEngineFailure::EngineError, $call); + + $definition = self::definition($client->listProcessDefinitions([ + 'deploymentId' => $deploymentId, + 'key' => $processDefinitionKey, + ])['data'][0] ?? null); + + return new ProcessDeployment(true, $deploymentId, $definition['id'] ?? null, $definition['version'] ?? null); + }); + } + + public function start(?ApiConfiguration $connection, string $processDefinitionKey, string $businessKey, array $variables): string + { + ProcessEngineGuard::variables($variables); + $call = ProcessEngineCall::Start; + $client = $this->client($connection, $call); + + return $this->call($call, static function () use ($client, $processDefinitionKey, $businessKey, $variables, $call): string { + $instance = $client->startProcessInstance([ + 'processDefinitionKey' => $processDefinitionKey, + 'businessKey' => $businessKey, + 'variables' => self::flowableVariables($variables), + ]); + + return self::nonEmptyString($instance['id'] ?? null) ?? throw ProcessEngineException::of(ProcessEngineFailure::EngineError, $call); + }); + } + + public function findInstances(?ApiConfiguration $connection, string $processDefinitionKey, string $businessKey): array + { + $call = ProcessEngineCall::FindInstances; + $client = $this->client($connection, $call); + + return $this->call($call, static fn (): array => self::instancesWithVariables($client, $processDefinitionKey, $businessKey)); + } + + /** + * The instances of a business key with their variables, on the path that + * works whether or not the engine honours `includeProcessVariables` on + * its list queries (not yet proven for Flowable 8 through this client): + * + * 1. the runtime instances (running) and the historic instances (running + * and finished) of the key and business key, both asked with + * `includeProcessVariables`, merged by instance id, so an instance is + * found even while its history is not written yet; + * 2. the variables of each instance: inline from the runtime row, else + * inline from the historic row, else (both empty, i.e. the flag was + * ignored) from the historic variable instances of the instance. + * + * Rows with another business key are dropped, in case the engine ignores + * the filter. Once the engine is proven to return inline variables, the + * third lookup can go. + * + * @return list + */ + private static function instancesWithVariables(FlowableClientInterface $client, string $processDefinitionKey, string $businessKey): array + { + $query = [ + 'processDefinitionKey' => $processDefinitionKey, + 'businessKey' => $businessKey, + 'includeProcessVariables' => 'true', + 'size' => self::PAGE_SIZE, + ]; + + /** @var array}> $found */ + $found = []; + foreach (self::rows($client->listProcessInstances($query), $businessKey) as $id => $row) { + $found[$id] = ['finished' => true === ($row['ended'] ?? false), 'variables' => self::inlineVariables($row)]; + } + foreach (self::rows($client->listHistoricProcessInstances($query), $businessKey) as $id => $row) { + $finished = null !== ($row['endTime'] ?? null); + $variables = ($found[$id]['variables'] ?? []) ?: self::inlineVariables($row); + $found[$id] = ['finished' => $finished, 'variables' => $variables]; + } + + $instances = []; + foreach ($found as $id => $instance) { + $variables = $instance['variables'] ?: self::historicVariables($client, $id); + $instances[] = new ProcessInstance($id, $businessKey, $instance['finished'], $variables); + } + + return $instances; + } + + /** + * The rows of a list envelope with an id and the business key, by id. + * + * @param array $envelope + * + * @return array> + */ + private static function rows(array $envelope, string $businessKey): array + { + $rows = []; + foreach (\is_array($envelope['data'] ?? null) ? $envelope['data'] : [] as $row) { + if (!\is_array($row)) { + continue; + } + $id = self::nonEmptyString($row['id'] ?? null); + if (null === $id || $businessKey !== ($row['businessKey'] ?? null)) { + continue; + } + $rows[$id] = $row; + } + + return $rows; + } + + /** + * The inline variables of an instance row (`variables`: a list of + * `{name, type, value, scope}`), name => value. + * + * @param array $row + * + * @return array + */ + private static function inlineVariables(array $row): array + { + return self::variableMap(\is_array($row['variables'] ?? null) ? $row['variables'] : []); + } + + /** + * The process variables of an instance from the history (task-local ones + * excluded), name => value. + * + * @return array + */ + private static function historicVariables(FlowableClientInterface $client, string $instanceId): array + { + $envelope = $client->listHistoricVariables([ + 'processInstanceId' => $instanceId, + 'excludeTaskVariables' => 'true', + 'size' => self::PAGE_SIZE, + ]); + + $entries = []; + foreach (\is_array($envelope['data'] ?? null) ? $envelope['data'] : [] as $entry) { + // A historic variable instance carries the variable in `variable`. + if (\is_array($entry)) { + $entries[] = \is_array($entry['variable'] ?? null) ? $entry['variable'] : $entry; + } + } + + return self::variableMap($entries); + } + + /** + * @param array $entries entries of `{name, value, ...}` + * + * @return array + */ + private static function variableMap(array $entries): array + { + $variables = []; + foreach ($entries as $entry) { + $name = \is_array($entry) ? self::nonEmptyString($entry['name'] ?? null) : null; + if (null !== $name) { + $variables[$name] = $entry['value'] ?? null; + } + } + + return $variables; + } + + /** + * The latest definition of a key, null when there is none. + * + * @return array{id: string, deploymentId: string, version: ?int}|null + */ + private static function latestDefinition(FlowableClientInterface $client, string $processDefinitionKey): ?array + { + $definition = self::definition($client->listProcessDefinitions([ + 'key' => $processDefinitionKey, + 'latest' => 'true', + 'size' => 1, + ])['data'][0] ?? null); + + return null === $definition || null === $definition['deploymentId'] ? null : $definition; + } + + /** + * @return array{id: string, deploymentId: ?string, version: ?int}|null + */ + private static function definition(mixed $row): ?array + { + $id = \is_array($row) ? self::nonEmptyString($row['id'] ?? null) : null; + if (null === $id) { + return null; + } + + return [ + 'id' => $id, + 'deploymentId' => self::nonEmptyString($row['deploymentId'] ?? null), + 'version' => \is_int($row['version'] ?? null) ? $row['version'] : null, + ]; + } + + /** + * The variables in the request format of the engine, the type from the + * PHP type (an int outside 32 bits is a `long`). + * + * @param array $variables + * + * @return list + */ + private static function flowableVariables(array $variables): array + { + $flowable = []; + foreach ($variables as $name => $value) { + $flowable[] = [ + 'name' => $name, + 'type' => match (true) { + \is_bool($value) => 'boolean', + \is_int($value) => $value >= self::INT32_MIN && $value <= self::INT32_MAX ? 'integer' : 'long', + \is_float($value) => 'double', + default => 'string', + }, + 'value' => $value, + ]; + } + + return $flowable; + } + + /** + * The client of a checked connection. + * + * @throws ProcessEngineException + */ + private function client(?ApiConfiguration $connection, ProcessEngineCall $call): FlowableClientInterface + { + $connection = ProcessEngineGuard::connection($connection, self::CONNECTION_TYPE, $call); + + try { + return ($this->resolveClient)($connection->getId()->toRfc4122()); + } catch (SecretEncryptionException) { + throw ProcessEngineException::of(ProcessEngineFailure::SecretUnreadable, $call); + } catch (HttpExceptionInterface) { + throw ProcessEngineException::of(ProcessEngineFailure::ConnectionInvalid, $call); + } + } + + /** + * Runs the requests of one call and turns every failure into a + * {@see ProcessEngineException}. + * + * @template T + * + * @param \Closure(): T $requests + * + * @return T + */ + private function call(ProcessEngineCall $call, \Closure $requests): mixed + { + try { + return $requests(); + } catch (ProcessEngineException $e) { + throw $e; + } catch (FlowableApiException $e) { + throw ProcessEngineException::of(self::engineFailure($call, $e->getStatusCode()), $call); + } catch (SecretEncryptionException) { + throw ProcessEngineException::of(ProcessEngineFailure::SecretUnreadable, $call); + } catch (\Exception) { + throw ProcessEngineException::of(ProcessEngineFailure::EngineError, $call); + } + } + + /** The category of a status of {@see FlowableApiException}. */ + private static function engineFailure(ProcessEngineCall $call, int $status): ProcessEngineFailure + { + return match (true) { + 404 === $status && ProcessEngineCall::Start === $call => ProcessEngineFailure::DefinitionNotDeployed, + 422 === $status => ProcessEngineFailure::EngineRejected, + 504 === $status => ProcessEngineFailure::EngineUnreachable, + default => ProcessEngineFailure::EngineError, + }; + } + + private static function nonEmptyString(mixed $value): ?string + { + return \is_string($value) && '' !== $value ? $value : null; + } +} diff --git a/src/Process/MissingProcessEngine.php b/src/Process/MissingProcessEngine.php new file mode 100644 index 0000000..1b89f6c --- /dev/null +++ b/src/Process/MissingProcessEngine.php @@ -0,0 +1,33 @@ +value, $reason->value)); + } + + public static function of(ProcessEngineFailure $reason, ProcessEngineCall $call): self + { + return new self($reason, $call); + } +} diff --git a/src/Process/ProcessEngineFailure.php b/src/Process/ProcessEngineFailure.php new file mode 100644 index 0000000..06c432a --- /dev/null +++ b/src/Process/ProcessEngineFailure.php @@ -0,0 +1,50 @@ +getType()) { + throw ProcessEngineException::of(ProcessEngineFailure::ConnectionWrongType, $call); + } + if (!$connection->isActive()) { + throw ProcessEngineException::of(ProcessEngineFailure::ConnectionInactive, $call); + } + + return $connection; + } + + /** + * Fails unless every name is a non-empty string and every value a scalar + * (string, int, float or bool). The message names the variable, never + * its value. + * + * @param array $variables + * + * @throws \InvalidArgumentException + */ + public static function variables(array $variables): void + { + foreach ($variables as $name => $value) { + if (!\is_string($name) || '' === $name) { + throw new \InvalidArgumentException('Process variable names must be non-empty strings.'); + } + if (!\is_scalar($value)) { + throw new \InvalidArgumentException(\sprintf('Process variable "%s" must be a string, int, float or bool.', $name)); + } + } + } +} diff --git a/src/Process/ProcessEngineInterface.php b/src/Process/ProcessEngineInterface.php new file mode 100644 index 0000000..d73a599 --- /dev/null +++ b/src/Process/ProcessEngineInterface.php @@ -0,0 +1,67 @@ + $variables process variables, scalar values only + * + * @throws ProcessEngineException + * @throws \InvalidArgumentException a variable value is not a scalar + */ + public function start(?ApiConfiguration $connection, string $processDefinitionKey, string $businessKey, array $variables): string; + + /** + * The instances of $processDefinitionKey with exactly this business key, + * running and finished ones, each with its process variables, so a caller + * can pick the one whose variable matches (two instances may share a + * business key and differ in a variable). + * + * @return list + * + * @throws ProcessEngineException + */ + public function findInstances(?ApiConfiguration $connection, string $processDefinitionKey, string $businessKey): array; +} diff --git a/src/Process/ProcessInstance.php b/src/Process/ProcessInstance.php new file mode 100644 index 0000000..593f822 --- /dev/null +++ b/src/Process/ProcessInstance.php @@ -0,0 +1,32 @@ + value as the + * engine returns it). + */ +final readonly class ProcessInstance +{ + /** + * @param array $variables + */ + public function __construct( + public string $id, + public string $businessKey, + public bool $finished, + public array $variables, + ) { + } + + /** The value of a process variable, null when the instance has none of that name. */ + public function variable(string $name): mixed + { + return $this->variables[$name] ?? null; + } +} diff --git a/src/WebhookBundle.php b/src/WebhookBundle.php index bbfe583..8665112 100644 --- a/src/WebhookBundle.php +++ b/src/WebhookBundle.php @@ -6,12 +6,16 @@ namespace Dmstr\Webhook; +use Dmstr\Flowable\FlowableBundle; use Dmstr\Webhook\Adapter\AsWebhookAdapter; use Dmstr\Webhook\Adapter\GitlabParser; use Dmstr\Webhook\DependencyInjection\Compiler\RemoveDisabledAdaptersPass; use Dmstr\Webhook\DependencyInjection\Compiler\RemoveReplyClientsWithoutTransportPass; use Dmstr\Webhook\DependencyInjection\OptionalLibraries; use Dmstr\Webhook\Intake\DeliveryHandlerInterface; +use Dmstr\Webhook\Process\Flowable\FlowableProcessEngine; +use Dmstr\Webhook\Process\MissingProcessEngine; +use Dmstr\Webhook\Process\ProcessEngineInterface; use Dmstr\Webhook\Reply\Gitlab\GitlabReplyClient; use Gitlab\Client as GitlabClient; use Symfony\Component\Config\Definition\Configurator\DefinitionConfigurator; @@ -59,7 +63,15 @@ * the service {@see self::REPLY_HTTP_CLIENT}, by default an alias of * `http_client`, which a host may define itself (e.g. a `MockHttpClient` * in its tests). Without a transport the client is removed - * ({@see RemoveReplyClientsWithoutTransportPass}). + * ({@see RemoveReplyClientsWithoutTransportPass}); + * - the process engine port {@see ProcessEngineInterface} (autowire the + * interface): {@see FlowableProcessEngine} over dmstr/flowable-bundle when + * FlowableBundle is registered in the kernel + * ({@see self::registersFlowableEngine()}), otherwise + * {@see MissingProcessEngine}, whose every call fails with the reason + * `engine_port_missing`. A hard Composer dependency is no registration: + * FlowableBundle's services need MonologBundle (its channel `flowable`), + * so nothing of it is referenced in a kernel without it. * * Configuration (`dmstr_webhook`), published as container parameters: * - `adapters`: map source => enabled flag; `passthrough` is enabled @@ -196,6 +208,27 @@ static function (ChildDefinition $definition, AsWebhookAdapter $attribute): void ->autowire() ->arg('$httpClient', service(self::REPLY_HTTP_CLIENT)); } + + // The process engine port: one implementation, the alias of the + // interface points to it. FlowableProcessEngine takes the + // `resolve()` method of FlowableBundle's client locator as a closure + // (#[AutowireCallable]). + $services = $container->services(); + $engine = self::registersFlowableEngine($builder) ? FlowableProcessEngine::class : MissingProcessEngine::class; + $services->set($engine)->autowire(); + $services->alias(ProcessEngineInterface::class, $engine); + } + + /** + * Whether FlowableBundle is registered in the kernel (parameter + * `kernel.bundles`): only then are its client locator and the channel + * `flowable` it binds there. Installed is not enough. + */ + private static function registersFlowableEngine(ContainerBuilder $builder): bool + { + $bundles = $builder->hasParameter('kernel.bundles') ? $builder->getParameter('kernel.bundles') : []; + + return \is_array($bundles) && \in_array(FlowableBundle::class, $bundles, true); } /** @@ -230,3 +263,4 @@ public function build(ContainerBuilder $container): void // - revised 2026-12-03 (GitLab adapter in the class doc) // - revised 2026-12-03 (Basecamp 4 adapter in the class doc) // - revised 2026-12-04 (GitLab reply client: conditional registration, reply transport) +// - revised 2026-12-05 (process engine port: Flowable implementation only with FlowableBundle, missing implementation otherwise) diff --git a/tests/Integration/ContainerVariantsTest.php b/tests/Integration/ContainerVariantsTest.php index 3cca1e0..bf6d106 100644 --- a/tests/Integration/ContainerVariantsTest.php +++ b/tests/Integration/ContainerVariantsTest.php @@ -6,6 +6,7 @@ namespace Dmstr\Webhook\Tests\Integration; +use Dmstr\Flowable\FlowableBundle; use Dmstr\Webhook\Adapter\Basecamp4Parser; use Dmstr\Webhook\Adapter\GitlabParser; use Dmstr\Webhook\Adapter\StandardWebhooksParser; @@ -14,8 +15,12 @@ use Dmstr\Webhook\Intake\SlidingWindowLimiter; use Dmstr\Webhook\Intake\WebhookIntake; use Dmstr\Webhook\Log\WebhookSecretRedactionProcessor; +use Dmstr\Webhook\Process\Flowable\FlowableProcessEngine; +use Dmstr\Webhook\Process\MissingProcessEngine; +use Dmstr\Webhook\Process\ProcessEngineInterface; use Dmstr\Webhook\Reply\Gitlab\GitlabReplyClient; use Dmstr\Webhook\Tests\Kernel\TestKernel; +use Dmstr\Webhook\Tests\Support\FakeProcessEngine; use Dmstr\Webhook\WebhookBundle; use Monolog\Logger; use Psr\Clock\ClockInterface; @@ -37,10 +42,17 @@ * - without a lock factory, without MonologBundle and without `http_client` * (all suggested only) the container builds and the intake services are * complete, the GitLab and Basecamp 4 adapters included; the GitLab reply - * client, which has no transport then, is not registered; + * client, which has no transport then, is not registered; FlowableBundle + * (installed with dmstr/flowable-bundle, a hard requirement) is not + * registered either, so the process engine port is the missing + * implementation; * - the GitLab reply client is registered only with * m4tthumphrey/php-gitlab-api installed and the adapter `gitlab` enabled, - * over the application's `http_client` or the host's own reply transport. + * over the application's `http_client` or the host's own reply transport; + * - the process engine port is the Flowable implementation only with + * FlowableBundle registered, the missing implementation without it although + * dmstr/flowable-bundle is installed, and the host's own engine where the + * host defines one. */ final class ContainerVariantsTest extends KernelTestCase { @@ -99,6 +111,42 @@ public function testTheContainerBuildsWithoutLockFactoryAndMonologBundle(): void // Library and adapter are there, the transport is not. self::assertFalse($container->has('http_client')); self::assertFalse($container->has(GitlabReplyClient::class)); + // FlowableBundle needs MonologBundle; the port stays injectable. + self::assertArrayNotHasKey('FlowableBundle', $kernel->getBundles()); + self::assertInstanceOf(MissingProcessEngine::class, $container->get(ProcessEngineInterface::class)); + } + + public function testTheProcessEngineIsMissingWithoutFlowableBundle(): void + { + $kernel = self::bootKernel(); + + self::assertTrue(class_exists(FlowableBundle::class)); + self::assertArrayNotHasKey('FlowableBundle', $kernel->getBundles()); + self::assertInstanceOf(MissingProcessEngine::class, self::getContainer()->get(ProcessEngineInterface::class)); + self::assertFalse(self::getContainer()->has(FlowableProcessEngine::class)); + } + + public function testTheProcessEngineIsFlowableWithFlowableBundle(): void + { + $kernel = self::bootKernel(['environment' => TestKernel::ENV_FLOWABLE]); + self::assertArrayHasKey('FlowableBundle', $kernel->getBundles()); + self::assertArrayHasKey('MonologBundle', $kernel->getBundles()); + $container = self::getContainer(); + + $engine = $container->get(ProcessEngineInterface::class); + self::assertInstanceOf(FlowableProcessEngine::class, $engine); + // The locator's resolve() as a closure; resolving needs a database. + self::assertInstanceOf(\Closure::class, new \ReflectionProperty(FlowableProcessEngine::class, 'resolveClient')->getValue($engine)); + } + + public function testTheHostReplacesTheProcessEngine(): void + { + $kernel = self::bootKernel(['environment' => TestKernel::ENV_FAKE_ENGINE]); + self::assertArrayNotHasKey('FlowableBundle', $kernel->getBundles()); + $container = self::getContainer(); + + self::assertInstanceOf(FakeProcessEngine::class, $container->get(ProcessEngineInterface::class)); + self::assertSame($container->get(FakeProcessEngine::class), $container->get(ProcessEngineInterface::class)); } public function testTheGitlabReplyClientIsUnknownWithoutTheLibrary(): void @@ -187,3 +235,4 @@ private static function signed(string $id, int $timestamp): Request // - revised 2026-12-03 (GitLab adapter in the minimal variant) // - revised 2026-12-03 (Basecamp 4 adapter in the minimal variant) // - revised 2026-12-04 (GitLab reply client: library absent, adapter off, default and host transport, minimal without http_client) +// - revised 2026-12-05 (process engine port: Flowable with FlowableBundle, missing without it and in the minimal variant, the host's fake) diff --git a/tests/Kernel/TestKernel.php b/tests/Kernel/TestKernel.php index ab77ee5..c505a6f 100644 --- a/tests/Kernel/TestKernel.php +++ b/tests/Kernel/TestKernel.php @@ -12,11 +12,14 @@ use Dmstr\ApiPlatformUtils\ApiPlatformUtilsBundle; use Dmstr\DoctrineAuditLog\DoctrineAuditLogBundle; use Dmstr\DoctrineAuditLog\Entity\LogEntry; +use Dmstr\Flowable\FlowableBundle; use Dmstr\OpenApiJsonSchema\OpenApiJsonSchemaBundle; use Dmstr\OpenApiJsonSchema\Service\OperationInputSchemaResolver; use Dmstr\Webhook\Adapter\GitlabParser; use Dmstr\Webhook\DependencyInjection\OptionalLibraries; +use Dmstr\Webhook\Process\ProcessEngineInterface; use Dmstr\Webhook\Reply\Gitlab\GitlabReplyClient; +use Dmstr\Webhook\Tests\Support\FakeProcessEngine; use Dmstr\Webhook\Tests\Support\RecordingDeliveryHandler; use Dmstr\Webhook\WebhookBundle; use Doctrine\Bundle\DoctrineBundle\DoctrineBundle; @@ -79,7 +82,10 @@ * `flock`, `cache.app` as array and `cache.rate_limiter` on the * filesystem (an array pool is reset by `services_resetter` between the * requests of the test client, so a sliding-window counter would never - * reach its limit; tests use random slugs). + * reach its limit; tests use random slugs). Messenger (a hard requirement + * of the bundle) with the host's transport {@see self::MESSENGER_TRANSPORT} + * in memory ({@see self::MESSENGER_TRANSPORT_DSN}), as a host overrides the + * transport; no routing. * - The `clock` service is a {@see MockClock} frozen at * {@see self::FROZEN_NOW}; the Standard Webhooks adapter takes it for its * replay window, so signatures built with {@see self::frozenNow()} are @@ -127,11 +133,22 @@ * - {@see self::ENV_GITLAB_OFF}: the adapter `gitlab` is disabled, so the * GitLab reply client is not registered; * - {@see self::ENV_REPLY_TRANSPORT}: the host defines the reply transport - * `dmstr_webhook.reply_http_client` itself, as a `MockHttpClient`. + * `dmstr_webhook.reply_http_client` itself, as a `MockHttpClient`; + * - {@see self::ENV_FLOWABLE}: FlowableBundle is registered (with MonologBundle, + * whose channel `flowable` it binds, security and `http_client` as above), + * so the process engine port is the Flowable implementation + * ({@see self::hasFlowable()}); in every other variant FlowableBundle is + * not registered, although installed, and the port is the missing + * implementation; + * - {@see self::ENV_FAKE_ENGINE}: the host replaces the process engine port + * with the in-memory {@see FakeProcessEngine} (public service + * {@see FakeProcessEngine}, the alias {@see ProcessEngineInterface} points + * to it), without FlowableBundle. * * Where the GitLab reply client is registered, {@see self::process()} makes * it public, as a consumer of the host would keep it, so the tests can fetch - * it. + * it; the same for the alias {@see ProcessEngineInterface} of the process + * engine port. * * Cache and logs live under the system temp directory, one directory per * variant, so a test run leaves no files in the repository. @@ -147,6 +164,12 @@ final class TestKernel extends Kernel implements CompilerPassInterface public const string ENV_NO_GITLAB_LIBRARY = 'test_no_gitlab_library'; public const string ENV_GITLAB_OFF = 'test_gitlab_off'; public const string ENV_REPLY_TRANSPORT = 'test_reply_transport'; + public const string ENV_FLOWABLE = 'test_flowable'; + public const string ENV_FAKE_ENGINE = 'test_fake_engine'; + + /** The host's Messenger transport of the process start, in memory. */ + public const string MESSENGER_TRANSPORT = 'webhook'; + public const string MESSENGER_TRANSPORT_DSN = 'in-memory://'; public const string API_PREFIX = '/api'; @@ -191,6 +214,9 @@ public function registerBundles(): iterable if ($this->hasMonolog()) { yield new MonologBundle(); } + if ($this->hasFlowable()) { + yield new FlowableBundle(); + } yield new WebhookBundle(new OptionalLibraries(self::ENV_NO_GITLAB_LIBRARY === $this->environment ? [GitlabClient::class] : [])); } @@ -238,6 +264,12 @@ public function hasMonolog(): bool return self::ENV_MINIMAL !== $this->environment; } + /** Whether FlowableBundle is registered (it needs MonologBundle). */ + public function hasFlowable(): bool + { + return self::ENV_FLOWABLE === $this->environment && $this->hasMonolog(); + } + /** * Host-application wiring that needs the complete container: the list of * registered permissions, the actor of audit-log entries and, in @@ -267,6 +299,10 @@ public function process(ContainerBuilder $container): void if ($container->hasDefinition(GitlabReplyClient::class)) { $container->getDefinition(GitlabReplyClient::class)->setPublic(true); } + // Nothing of the bundle uses the process engine port yet. + if ($container->hasAlias(ProcessEngineInterface::class)) { + $container->getAlias(ProcessEngineInterface::class)->setPublic(true); + } // As in a host without symfony/clock: FrameworkBundle registers no // `clock` service then. Runs after the bundle's own passes and @@ -321,6 +357,11 @@ private function configureContainer(ContainerConfigurator $container): void 'remote_event' => ['enabled' => false], 'lock' => self::ENV_MINIMAL === $this->environment ? false : 'flock', 'http_client' => ['enabled' => self::ENV_MINIMAL !== $this->environment], + 'messenger' => [ + 'transports' => [ + self::MESSENGER_TRANSPORT => self::MESSENGER_TRANSPORT_DSN, + ], + ], 'cache' => [ 'app' => 'cache.adapter.array', 'pools' => [ @@ -466,6 +507,13 @@ private function configureContainer(ContainerConfigurator $container): void $services->set(WebhookBundle::REPLY_HTTP_CLIENT, MockHttpClient::class); } + if (self::ENV_FAKE_ENGINE === $this->environment) { + // The host's own engine port; its definitions win over the + // bundle's alias. + $services->set(FakeProcessEngine::class)->public(); + $services->alias(ProcessEngineInterface::class, FakeProcessEngine::class)->public(); + } + if ($this->hasPermissionVoter()) { // Autoconfiguration adds the `security.voter` tag; public so that // tests can tell the variants apart. @@ -510,3 +558,4 @@ private static function attributeMapping(string $class, string $prefix): array // - revised 2026-12-03 (GitLab adapter enabled) // - revised 2026-12-03 (Basecamp 4 adapter enabled) // - revised 2026-12-04 (GitLab reply client: variants without library, with the adapter off, with the host's transport, minimal without http_client) +// - revised 2026-12-05 (process engine port: variants with FlowableBundle and with the fake engine, Messenger with an in-memory transport) diff --git a/tests/Support/FakeProcessEngine.php b/tests/Support/FakeProcessEngine.php new file mode 100644 index 0000000..de57ddc --- /dev/null +++ b/tests/Support/FakeProcessEngine.php @@ -0,0 +1,241 @@ + + */ + public array $deployments = []; + + /** + * Every start that created an instance, in order (a crashed start + * included). + * + * @var list, instanceId: string}> + */ + public array $starts = []; + + /** @var array number of calls by {@see ProcessEngineCall} value */ + private array $calls = []; + + /** @var array by {@see ProcessEngineCall} value */ + private array $failures = []; + + private ?\Throwable $crashAfterNextStart = null; + + /** @var array by instance id */ + private array $instances = []; + + private int $instanceCounter = 0; + + public function __construct(private readonly bool $checkConnection = true) + { + } + + /** Forgets everything: calls, failures, deployments, starts and instances. */ + public function reset(): void + { + $this->deployments = []; + $this->starts = []; + $this->calls = []; + $this->failures = []; + $this->crashAfterNextStart = null; + $this->instances = []; + $this->instanceCounter = 0; + } + + /** The number of calls of one kind, or of all kinds when $call is null. */ + public function calls(?ProcessEngineCall $call = null): int + { + return null === $call ? array_sum($this->calls) : $this->calls[$call->value] ?? 0; + } + + /** + * Makes $call fail with $failure: every following call, or only the next + * $times calls. + */ + public function failOn(ProcessEngineCall $call, ProcessEngineFailure $failure, ?int $times = null): self + { + $this->failures[$call->value] = ['failure' => $failure, 'times' => $times]; + + return $this; + } + + /** + * Makes the next start throw after it created its instance; by default a + * {@see ProcessEngineException} with the reason `engine_unreachable` (no + * answer after the engine started the instance). + */ + public function crashAfterNextStart(?\Throwable $throwable = null): self + { + $this->crashAfterNextStart = $throwable ?? ProcessEngineException::of(ProcessEngineFailure::EngineUnreachable, ProcessEngineCall::Start); + + return $this; + } + + /** Marks a started instance as finished. */ + public function finish(string $instanceId): void + { + $entry = $this->instances[$instanceId] ?? throw new \LogicException(\sprintf('No instance "%s".', $instanceId)); + $instance = $entry['instance']; + $this->instances[$instanceId]['instance'] = new ProcessInstance($instance->id, $instance->businessKey, true, $instance->variables); + } + + /** + * Every instance, running and finished, in the order of their start. + * + * @return list + */ + public function instances(): array + { + return array_values(array_map(static fn (array $entry): ProcessInstance => $entry['instance'], $this->instances)); + } + + public function deploy(?ApiConfiguration $connection, string $resourceName, string $content, string $processDefinitionKey): ProcessDeployment + { + $connectionKey = $this->enter(ProcessEngineCall::Deploy, $connection); + + $latest = null; + foreach ($this->deployments as $deployment) { + if ($deployment['connection'] === $connectionKey && $deployment['key'] === $processDefinitionKey) { + $latest = $deployment; + } + } + if (null !== $latest && $latest['resourceName'] === $resourceName && $latest['content'] === $content) { + return new ProcessDeployment(false, $latest['deploymentId'], $latest['definitionId'], $latest['version']); + } + + $version = (null === $latest ? 0 : $latest['version']) + 1; + $deploymentId = self::DEPLOYMENT_ID_PREFIX.(\count($this->deployments) + 1); + $definitionId = \sprintf('%s:%d:%s', $processDefinitionKey, $version, $deploymentId); + $this->deployments[] = [ + 'connection' => $connectionKey, + 'resourceName' => $resourceName, + 'content' => $content, + 'key' => $processDefinitionKey, + 'deploymentId' => $deploymentId, + 'definitionId' => $definitionId, + 'version' => $version, + ]; + + return new ProcessDeployment(true, $deploymentId, $definitionId, $version); + } + + public function start(?ApiConfiguration $connection, string $processDefinitionKey, string $businessKey, array $variables): string + { + ProcessEngineGuard::variables($variables); + $connectionKey = $this->enter(ProcessEngineCall::Start, $connection); + + $instanceId = self::INSTANCE_ID_PREFIX.++$this->instanceCounter; + $this->instances[$instanceId] = [ + 'connection' => $connectionKey, + 'key' => $processDefinitionKey, + 'instance' => new ProcessInstance($instanceId, $businessKey, false, $variables), + ]; + $this->starts[] = [ + 'connection' => $connectionKey, + 'key' => $processDefinitionKey, + 'businessKey' => $businessKey, + 'variables' => $variables, + 'instanceId' => $instanceId, + ]; + + if (null !== $this->crashAfterNextStart) { + $crash = $this->crashAfterNextStart; + $this->crashAfterNextStart = null; + throw $crash; + } + + return $instanceId; + } + + public function findInstances(?ApiConfiguration $connection, string $processDefinitionKey, string $businessKey): array + { + $connectionKey = $this->enter(ProcessEngineCall::FindInstances, $connection); + + $found = []; + foreach ($this->instances as $entry) { + if ($entry['connection'] === $connectionKey && $entry['key'] === $processDefinitionKey && $entry['instance']->businessKey === $businessKey) { + $found[] = $entry['instance']; + } + } + + return $found; + } + + /** + * Counts the call, applies a configured failure and checks the + * connection; returns the key the fake keeps the connection's state + * under (its UUID, '' without check and connection). + */ + private function enter(ProcessEngineCall $call, ?ApiConfiguration $connection): string + { + $this->calls[$call->value] = ($this->calls[$call->value] ?? 0) + 1; + + $failure = $this->failures[$call->value] ?? null; + if (null !== $failure) { + if (null !== $failure['times']) { + if ($failure['times'] <= 1) { + unset($this->failures[$call->value]); + } else { + $this->failures[$call->value]['times'] = $failure['times'] - 1; + } + } + throw ProcessEngineException::of($failure['failure'], $call); + } + + if ($this->checkConnection) { + $connection = ProcessEngineGuard::connection($connection, FlowableProcessEngine::CONNECTION_TYPE, $call); + } + + return null === $connection ? '' : $connection->getId()->toRfc4122(); + } +} diff --git a/tests/Unit/DependencyInjection/ProcessEngineRegistrationTest.php b/tests/Unit/DependencyInjection/ProcessEngineRegistrationTest.php new file mode 100644 index 0000000..d7f006f --- /dev/null +++ b/tests/Unit/DependencyInjection/ProcessEngineRegistrationTest.php @@ -0,0 +1,81 @@ + FrameworkBundle::class, 'FlowableBundle' => FlowableBundle::class]); + + self::assertSame(FlowableProcessEngine::class, (string) $container->getAlias(ProcessEngineInterface::class)); + self::assertTrue($container->getDefinition(FlowableProcessEngine::class)->isAutowired()); + self::assertFalse($container->hasDefinition(MissingProcessEngine::class)); + } + + public function testTheMissingEngineWithoutFlowableBundle(): void + { + // Installed (a hard requirement), but not registered. + self::assertTrue(class_exists(FlowableBundle::class)); + $container = self::load(['FrameworkBundle' => FrameworkBundle::class]); + + self::assertSame(MissingProcessEngine::class, (string) $container->getAlias(ProcessEngineInterface::class)); + self::assertFalse($container->hasDefinition(FlowableProcessEngine::class)); + } + + public function testTheMissingEngineWithoutTheKernelParameter(): void + { + $container = self::load(null); + + self::assertSame(MissingProcessEngine::class, (string) $container->getAlias(ProcessEngineInterface::class)); + } + + public function testValueObjectsAndTheExceptionAreNoServices(): void + { + $container = self::load(['FlowableBundle' => FlowableBundle::class]); + + foreach ([ProcessDeployment::class, ProcessInstance::class, ProcessEngineException::class] as $class) { + self::assertFalse($container->hasDefinition($class), $class); + } + } + + /** + * @param array|null $bundles `kernel.bundles`, null for none + */ + private static function load(?array $bundles): ContainerBuilder + { + $container = new ContainerBuilder(); + $container->setParameter('kernel.environment', 'test'); + $container->setParameter('kernel.build_dir', sys_get_temp_dir()); + if (null !== $bundles) { + $container->setParameter('kernel.bundles', $bundles); + } + $extension = new WebhookBundle()->getContainerExtension(); + self::assertNotNull($extension); + $extension->load([[]], $container); + + return $container; + } +} diff --git a/tests/Unit/Process/FakeProcessEngineTest.php b/tests/Unit/Process/FakeProcessEngineTest.php new file mode 100644 index 0000000..422a62d --- /dev/null +++ b/tests/Unit/Process/FakeProcessEngineTest.php @@ -0,0 +1,187 @@ +calls()); + + self::assertSame('fake-instance-1', $engine->start($connection, self::KEY, self::BUSINESS_KEY, ['endpoint' => 'a'])); + self::assertSame('fake-instance-2', $engine->start($connection, self::KEY, self::BUSINESS_KEY, ['endpoint' => 'b'])); + $engine->findInstances($connection, self::KEY, self::BUSINESS_KEY); + + self::assertSame(3, $engine->calls()); + self::assertSame(2, $engine->calls(ProcessEngineCall::Start)); + self::assertSame(1, $engine->calls(ProcessEngineCall::FindInstances)); + self::assertSame(0, $engine->calls(ProcessEngineCall::Deploy)); + self::assertSame(['fake-instance-1', 'fake-instance-2'], array_column($engine->starts, 'instanceId')); + self::assertSame([['endpoint' => 'a'], ['endpoint' => 'b']], array_column($engine->starts, 'variables')); + } + + public function testInstancesAreFoundByBusinessKeyWithTheirVariablesRunningAndFinished(): void + { + $engine = new FakeProcessEngine(); + $connection = self::connection(); + $first = $engine->start($connection, self::KEY, self::BUSINESS_KEY, ['endpoint' => 'a']); + $second = $engine->start($connection, self::KEY, self::BUSINESS_KEY, ['endpoint' => 'b']); + $engine->start($connection, self::KEY, 'gitlab:note:1', ['endpoint' => 'a']); + $engine->start($connection, 'other-process', self::BUSINESS_KEY, ['endpoint' => 'a']); + $engine->start(self::connection(), self::KEY, self::BUSINESS_KEY, ['endpoint' => 'a']); + $engine->finish($first); + + $found = $engine->findInstances($connection, self::KEY, self::BUSINESS_KEY); + + self::assertSame( + [[$first, true, 'a'], [$second, false, 'b']], + array_map(static fn ($instance): array => [$instance->id, $instance->finished, $instance->variable('endpoint')], $found), + ); + self::assertCount(5, $engine->instances()); + } + + public function testAFailureIsConfiguredPerCallForeverOrForTheNextCalls(): void + { + $engine = new FakeProcessEngine() + ->failOn(ProcessEngineCall::Start, ProcessEngineFailure::EngineUnreachable, 2) + ->failOn(ProcessEngineCall::FindInstances, ProcessEngineFailure::EngineError); + $connection = self::connection(); + + foreach ([1, 2] as $attempt) { + self::assertSame(ProcessEngineFailure::EngineUnreachable, self::failure(static fn () => $engine->start($connection, self::KEY, self::BUSINESS_KEY, [])), (string) $attempt); + } + self::assertSame('fake-instance-1', $engine->start($connection, self::KEY, self::BUSINESS_KEY, [])); + foreach ([1, 2, 3] as $attempt) { + self::assertSame(ProcessEngineFailure::EngineError, self::failure(static fn () => $engine->findInstances($connection, self::KEY, self::BUSINESS_KEY)), (string) $attempt); + } + + // Failing calls are counted; they created nothing. + self::assertSame(3, $engine->calls(ProcessEngineCall::Start)); + self::assertSame(3, $engine->calls(ProcessEngineCall::FindInstances)); + self::assertCount(1, $engine->starts); + } + + public function testACrashAfterTheStartLeavesAnInstanceThatIsFound(): void + { + $engine = new FakeProcessEngine()->crashAfterNextStart(); + $connection = self::connection(); + + self::assertSame(ProcessEngineFailure::EngineUnreachable, self::failure(static fn () => $engine->start($connection, self::KEY, self::BUSINESS_KEY, ['endpoint' => 'a']))); + + $found = $engine->findInstances($connection, self::KEY, self::BUSINESS_KEY); + self::assertCount(1, $found); + self::assertSame(['fake-instance-1', false, 'a'], [$found[0]->id, $found[0]->finished, $found[0]->variable('endpoint')]); + // Only the next start crashes. + self::assertSame('fake-instance-2', $engine->start($connection, self::KEY, self::BUSINESS_KEY, ['endpoint' => 'b'])); + } + + public function testACrashCanThrowAnyThrowable(): void + { + $engine = new FakeProcessEngine()->crashAfterNextStart(new \RuntimeException('worker killed')); + + try { + $engine->start(self::connection(), self::KEY, self::BUSINESS_KEY, []); + self::fail('No exception.'); + } catch (\RuntimeException $e) { + self::assertSame('worker killed', $e->getMessage()); + } + self::assertCount(1, $engine->instances()); + } + + public function testUnchangedContentIsNotDeployedAgain(): void + { + $engine = new FakeProcessEngine(); + $connection = self::connection(); + + $first = $engine->deploy($connection, 'answer.bpmn20.xml', '', self::KEY); + $again = $engine->deploy($connection, 'answer.bpmn20.xml', '', self::KEY); + $changed = $engine->deploy($connection, 'answer.bpmn20.xml', '', self::KEY); + + self::assertSame([true, 1], [$first->deployed, $first->definitionVersion]); + self::assertSame([false, 1, $first->deploymentId, $first->definitionId], [$again->deployed, $again->definitionVersion, $again->deploymentId, $again->definitionId]); + self::assertSame([true, 2], [$changed->deployed, $changed->definitionVersion]); + self::assertCount(2, $engine->deployments); + self::assertSame(3, $engine->calls(ProcessEngineCall::Deploy)); + } + + public function testTheConnectionIsCheckedLikeTheFlowableEngine(): void + { + $engine = new FakeProcessEngine(); + $gitlab = new ApiConfiguration()->setConfigJson(['type' => 'gitlab', 'endpoint_type' => 'rest']); + + self::assertSame(ProcessEngineFailure::ConnectionMissing, self::failure(static fn () => $engine->start(null, self::KEY, self::BUSINESS_KEY, []))); + self::assertSame(ProcessEngineFailure::ConnectionWrongType, self::failure(static fn () => $engine->findInstances($gitlab, self::KEY, self::BUSINESS_KEY))); + self::assertSame(ProcessEngineFailure::ConnectionInactive, self::failure(static fn () => $engine->deploy(self::connection(false), 'a.bpmn20.xml', '', self::KEY))); + self::assertSame([], $engine->instances()); + + // Without the check, any connection (or none) will do. + self::assertSame('fake-instance-1', new FakeProcessEngine(checkConnection: false)->start(null, self::KEY, self::BUSINESS_KEY, [])); + } + + public function testAStartWithANonScalarVariableIsRejected(): void + { + $engine = new FakeProcessEngine(); + + $this->expectException(\InvalidArgumentException::class); + /* @phpstan-ignore argument.type */ + $engine->start(self::connection(), self::KEY, self::BUSINESS_KEY, ['list' => ['a']]); + } + + public function testResetForgetsEverything(): void + { + $engine = new FakeProcessEngine()->failOn(ProcessEngineCall::Deploy, ProcessEngineFailure::EngineError); + $engine->start(self::connection(), self::KEY, self::BUSINESS_KEY, []); + + $engine->reset(); + + self::assertSame(0, $engine->calls()); + self::assertSame([], $engine->instances()); + self::assertSame([], $engine->starts); + self::assertTrue($engine->deploy(self::connection(), 'a.bpmn20.xml', '', self::KEY)->deployed); + self::assertSame('fake-instance-1', $engine->start(self::connection(), self::KEY, self::BUSINESS_KEY, [])); + } + + /** + * @param \Closure(): mixed $run + */ + private static function failure(\Closure $run): ProcessEngineFailure + { + try { + $run(); + } catch (ProcessEngineException $e) { + return $e->reason; + } + self::fail('No exception.'); + } + + private static function connection(bool $active = true): ApiConfiguration + { + return new ApiConfiguration() + ->setName('engine') + ->setConfigJson(['type' => 'flowable', 'endpoint_type' => 'rest']) + ->setActive($active); + } +} diff --git a/tests/Unit/Process/FlowableProcessEngineTest.php b/tests/Unit/Process/FlowableProcessEngineTest.php new file mode 100644 index 0000000..a427e41 --- /dev/null +++ b/tests/Unit/Process/FlowableProcessEngineTest.php @@ -0,0 +1,410 @@ +'; + private const string BUSINESS_KEY = 'gitlab:note:4711'; + private const string ENGINE_TEXT = 'engine-text-must-not-travel'; + + /** @var list}> client calls: method and arguments */ + private array $requests = []; + + /** @var list the selectors the locator stand-in was asked for */ + private array $resolved = []; + + /** @var array answer per client method: a value, a \Throwable to throw, or a \Closure called with the arguments */ + private array $answers = []; + + private ?\Throwable $resolveFailure = null; + + protected function setUp(): void + { + $this->requests = []; + $this->resolved = []; + $this->answers = []; + $this->resolveFailure = null; + } + + /** + * @return iterable + */ + public static function unusableConnections(): iterable + { + yield 'no connection' => [null, ProcessEngineFailure::ConnectionMissing]; + yield 'another type' => [self::connection('gitlab'), ProcessEngineFailure::ConnectionWrongType]; + yield 'inactive' => [self::connection(active: false), ProcessEngineFailure::ConnectionInactive]; + } + + /** + * @return iterable + */ + public static function unusableConnectionsPerCall(): iterable + { + foreach (ProcessEngineCall::cases() as $call) { + foreach (self::unusableConnections() as $name => [$connection, $failure]) { + yield $call->value.', '.$name => [$call, $connection, $failure]; + } + } + } + + #[DataProvider('unusableConnectionsPerCall')] + public function testTheConnectionIsCheckedBeforeTheLocator(ProcessEngineCall $call, ?ApiConfiguration $connection, ProcessEngineFailure $failure): void + { + $this->assertFailure($call, $failure, fn () => $this->invoke($call, $connection)); + self::assertSame([], $this->resolved); + self::assertSame([], $this->requests); + } + + public function testTheLocatorIsAskedWithTheFullUuidOfTheConnection(): void + { + $connection = self::connection(); + $this->answers['startProcessInstance'] = ['id' => 'instance-1']; + + self::assertSame('instance-1', $this->engine()->start($connection, self::KEY, self::BUSINESS_KEY, [])); + self::assertSame([$connection->getId()->toRfc4122()], $this->resolved); + } + + /** + * @return iterable + */ + public static function locatorFailures(): iterable + { + yield 'secret not decryptable' => [new SecretEncryptionException('Cannot decrypt '.self::ENGINE_TEXT), ProcessEngineFailure::SecretUnreadable]; + yield 'configuration without base_url' => [new BadRequestHttpException('Flowable API configuration is missing base_url or auth_type. '.self::ENGINE_TEXT), ProcessEngineFailure::ConnectionInvalid]; + } + + #[DataProvider('locatorFailures')] + public function testFailuresOfTheLocator(\Throwable $thrown, ProcessEngineFailure $failure): void + { + $this->resolveFailure = $thrown; + + foreach (ProcessEngineCall::cases() as $call) { + $this->assertFailure($call, $failure, fn () => $this->invoke($call, self::connection())); + } + self::assertSame([], $this->requests); + } + + /** + * @return iterable + */ + public static function engineFailures(): iterable + { + $statuses = [ + 'not found' => 404, + 'rejected' => 422, + 'backend error' => 502, + 'unreachable' => 504, + 'other status' => 500, + ]; + $expected = [ + ProcessEngineCall::Start->value => [404 => ProcessEngineFailure::DefinitionNotDeployed, 422 => ProcessEngineFailure::EngineRejected, 502 => ProcessEngineFailure::EngineError, 504 => ProcessEngineFailure::EngineUnreachable, 500 => ProcessEngineFailure::EngineError], + ProcessEngineCall::FindInstances->value => [404 => ProcessEngineFailure::EngineError, 422 => ProcessEngineFailure::EngineRejected, 502 => ProcessEngineFailure::EngineError, 504 => ProcessEngineFailure::EngineUnreachable, 500 => ProcessEngineFailure::EngineError], + ProcessEngineCall::Deploy->value => [404 => ProcessEngineFailure::EngineError, 422 => ProcessEngineFailure::EngineRejected, 502 => ProcessEngineFailure::EngineError, 504 => ProcessEngineFailure::EngineUnreachable, 500 => ProcessEngineFailure::EngineError], + ]; + foreach (ProcessEngineCall::cases() as $call) { + foreach ($statuses as $name => $status) { + // The 0.12.1 messages carry the engine or transport text. + yield $call->value.', '.$name => [$call, new FlowableApiException($status, 'Flowable said: '.self::ENGINE_TEXT), $expected[$call->value][$status]]; + } + yield $call->value.', invalid id from engine data' => [$call, new BadRequestHttpException('Invalid Flowable id '.self::ENGINE_TEXT), ProcessEngineFailure::EngineError]; + yield $call->value.', other exception' => [$call, new \RuntimeException(self::ENGINE_TEXT), ProcessEngineFailure::EngineError]; + } + } + + #[DataProvider('engineFailures')] + public function testFailuresOfTheEngine(ProcessEngineCall $call, \Throwable $thrown, ProcessEngineFailure $failure): void + { + // The first request of each call fails. + $method = match ($call) { + ProcessEngineCall::Deploy => 'listProcessDefinitions', + ProcessEngineCall::Start => 'startProcessInstance', + ProcessEngineCall::FindInstances => 'listProcessInstances', + }; + $this->answers[$method] = $thrown; + + $this->assertFailure($call, $failure, fn () => $this->invoke($call, self::connection())); + self::assertSame($method, $this->requests[0][0] ?? null); + } + + public function testTheStartSendsOnlyTheCallersVariables(): void + { + $this->answers['startProcessInstance'] = ['id' => 'instance-7', 'variables' => [['name' => 'other', 'value' => 'x']]]; + + $id = $this->engine()->start(self::connection(), self::KEY, self::BUSINESS_KEY, [ + 'endpoint' => '0193a1b2-0000-7000-8000-000000000001', + 'small' => 42, + 'large' => 4294967296, + 'ratio' => 0.5, + 'confidential' => false, + ]); + + self::assertSame('instance-7', $id); + self::assertSame([['startProcessInstance', [[ + 'processDefinitionKey' => self::KEY, + 'businessKey' => self::BUSINESS_KEY, + 'variables' => [ + ['name' => 'endpoint', 'type' => 'string', 'value' => '0193a1b2-0000-7000-8000-000000000001'], + ['name' => 'small', 'type' => 'integer', 'value' => 42], + ['name' => 'large', 'type' => 'long', 'value' => 4294967296], + ['name' => 'ratio', 'type' => 'double', 'value' => 0.5], + ['name' => 'confidential', 'type' => 'boolean', 'value' => false], + ], + ]]]], $this->requests); + } + + public function testAStartWithoutVariablesSendsAnEmptyList(): void + { + $this->answers['startProcessInstance'] = ['id' => 'instance-8']; + + $this->engine()->start(self::connection(), self::KEY, self::BUSINESS_KEY, []); + + self::assertSame([], $this->requests[0][1][0]['variables']); + } + + /** + * @return iterable}> + */ + public static function invalidVariables(): iterable + { + yield 'array value' => [['list' => ['a']]]; + yield 'null value' => [['nothing' => null]]; + yield 'object value' => [['object' => new \stdClass()]]; + yield 'integer name' => [[0 => 'value']]; + } + + /** + * @param array $variables + */ + #[DataProvider('invalidVariables')] + public function testAStartWithANonScalarVariableIsRejectedBeforeAnyRequest(array $variables): void + { + try { + /* @phpstan-ignore argument.type */ + $this->engine()->start(self::connection(), self::KEY, self::BUSINESS_KEY, $variables); + self::fail('No exception.'); + } catch (\InvalidArgumentException) { + } + self::assertSame([], $this->resolved); + self::assertSame([], $this->requests); + } + + public function testAStartAnswerWithoutInstanceIdIsAnEngineError(): void + { + $this->answers['startProcessInstance'] = ['businessKey' => self::BUSINESS_KEY]; + + $this->assertFailure(ProcessEngineCall::Start, ProcessEngineFailure::EngineError, fn () => $this->invoke(ProcessEngineCall::Start, self::connection())); + } + + public function testRunningAndFinishedInstancesAreFoundWithTheirVariables(): void + { + $this->answers['listProcessInstances'] = ['data' => [ + // Running, the engine returned its variables inline. + ['id' => 'running', 'businessKey' => self::BUSINESS_KEY, 'ended' => false, 'variables' => [['name' => 'endpoint', 'type' => 'string', 'value' => 'endpoint-a', 'scope' => 'global']]], + ], 'total' => 1]; + $this->answers['listHistoricProcessInstances'] = ['data' => [ + // The same instance in the history, without inline variables. + ['id' => 'running', 'businessKey' => self::BUSINESS_KEY, 'endTime' => null, 'variables' => []], + // Finished; the engine ignored includeProcessVariables. + ['id' => 'finished', 'businessKey' => self::BUSINESS_KEY, 'endTime' => '2026-12-05T10:00:00.000+00:00', 'variables' => []], + // Another business key: the engine ignored the filter. + ['id' => 'foreign', 'businessKey' => 'gitlab:note:1', 'endTime' => null, 'variables' => []], + ], 'total' => 3]; + $this->answers['listHistoricVariables'] = static fn (array $query): array => 'finished' === $query['processInstanceId'] + ? ['data' => [['id' => 'v1', 'processInstanceId' => 'finished', 'variable' => ['name' => 'endpoint', 'type' => 'string', 'value' => 'endpoint-b', 'scope' => 'global']]]] + : ['data' => []]; + + $instances = $this->engine()->findInstances(self::connection(), self::KEY, self::BUSINESS_KEY); + + self::assertCount(2, $instances); + [$running, $finished] = $instances; + self::assertSame(['running', self::BUSINESS_KEY, false, ['endpoint' => 'endpoint-a']], [$running->id, $running->businessKey, $running->finished, $running->variables]); + self::assertSame(['finished', self::BUSINESS_KEY, true, ['endpoint' => 'endpoint-b']], [$finished->id, $finished->businessKey, $finished->finished, $finished->variables]); + self::assertSame('endpoint-b', $finished->variable('endpoint')); + self::assertNull($finished->variable('missing')); + + $query = ['processDefinitionKey' => self::KEY, 'businessKey' => self::BUSINESS_KEY, 'includeProcessVariables' => 'true', 'size' => 100]; + self::assertSame([ + ['listProcessInstances', [$query]], + ['listHistoricProcessInstances', [$query]], + // Only the instance without inline variables. + ['listHistoricVariables', [['processInstanceId' => 'finished', 'excludeTaskVariables' => 'true', 'size' => 100]]], + ], $this->requests); + } + + public function testInstancesOnlyInTheHistoryOrOnlyAtRuntimeAreFound(): void + { + $this->answers['listProcessInstances'] = ['data' => [ + ['id' => 'not-yet-in-history', 'businessKey' => self::BUSINESS_KEY, 'ended' => false, 'variables' => []], + ]]; + $this->answers['listHistoricProcessInstances'] = ['data' => [ + ['id' => 'history-only', 'businessKey' => self::BUSINESS_KEY, 'endTime' => '2026-12-05T10:00:00.000+00:00', 'variables' => [['name' => 'endpoint', 'value' => 'endpoint-c']]], + ]]; + $this->answers['listHistoricVariables'] = ['data' => [['variable' => ['name' => 'endpoint', 'value' => 'endpoint-d']]]]; + + $instances = $this->engine()->findInstances(self::connection(), self::KEY, self::BUSINESS_KEY); + + self::assertSame( + [['not-yet-in-history', false, ['endpoint' => 'endpoint-d']], ['history-only', true, ['endpoint' => 'endpoint-c']]], + array_map(static fn ($instance): array => [$instance->id, $instance->finished, $instance->variables], $instances), + ); + } + + public function testNoInstanceIsAnEmptyList(): void + { + self::assertSame([], $this->engine()->findInstances(self::connection(), self::KEY, self::BUSINESS_KEY)); + self::assertSame(['listProcessInstances', 'listHistoricProcessInstances'], array_column($this->requests, 0)); + } + + public function testUnchangedContentIsNotDeployedAgain(): void + { + $this->answers['listProcessDefinitions'] = ['data' => [['id' => self::KEY.':3:d-3', 'key' => self::KEY, 'version' => 3, 'deploymentId' => 'd-3']]]; + $this->answers['getDeploymentResource'] = self::XML; + + $deployment = $this->engine()->deploy(self::connection(), self::RESOURCE, self::XML, self::KEY); + + self::assertFalse($deployment->deployed); + self::assertSame(['d-3', self::KEY.':3:d-3', 3], [$deployment->deploymentId, $deployment->definitionId, $deployment->definitionVersion]); + self::assertSame([ + ['listProcessDefinitions', [['key' => self::KEY, 'latest' => 'true', 'size' => 1]]], + ['getDeploymentResource', ['d-3', self::RESOURCE]], + ], $this->requests); + } + + /** + * @return iterable, ?string}> + */ + public static function changedDeployments(): iterable + { + $latest = ['data' => [['id' => self::KEY.':3:d-3', 'key' => self::KEY, 'version' => 3, 'deploymentId' => 'd-3']]]; + + yield 'changed content' => [$latest, '']; + yield 'the latest deployment has no resource of that name' => [$latest, null]; + yield 'no definition of the key yet' => [['data' => [], 'total' => 0], null]; + } + + /** + * @param array $latest + */ + #[DataProvider('changedDeployments')] + public function testChangedContentIsDeployed(array $latest, ?string $deployedContent): void + { + $this->answers['listProcessDefinitions'] = static fn (array $query): array => isset($query['latest']) + ? $latest + : ['data' => [['id' => self::KEY.':4:d-4', 'key' => self::KEY, 'version' => 4, 'deploymentId' => 'd-4']]]; + $this->answers['getDeploymentResource'] = $deployedContent; + $this->answers['createDeployment'] = ['id' => 'd-4', 'name' => self::RESOURCE]; + + $deployment = $this->engine()->deploy(self::connection(), self::RESOURCE, self::XML, self::KEY); + + self::assertTrue($deployment->deployed); + self::assertSame(['d-4', self::KEY.':4:d-4', 4], [$deployment->deploymentId, $deployment->definitionId, $deployment->definitionVersion]); + self::assertContains(['createDeployment', [self::RESOURCE, self::XML, ['deployment-name' => self::RESOURCE]]], $this->requests); + self::assertSame(['listProcessDefinitions', [['deploymentId' => 'd-4', 'key' => self::KEY]]], $this->requests[array_key_last($this->requests)]); + } + + public function testADeploymentAnswerWithoutIdIsAnEngineError(): void + { + $this->answers['createDeployment'] = []; + + $this->assertFailure(ProcessEngineCall::Deploy, ProcessEngineFailure::EngineError, fn () => $this->invoke(ProcessEngineCall::Deploy, self::connection())); + } + + private function invoke(ProcessEngineCall $call, ?ApiConfiguration $connection): mixed + { + $engine = $this->engine(); + + return match ($call) { + ProcessEngineCall::Deploy => $engine->deploy($connection, self::RESOURCE, self::XML, self::KEY), + ProcessEngineCall::Start => $engine->start($connection, self::KEY, self::BUSINESS_KEY, ['endpoint' => 'endpoint-a']), + ProcessEngineCall::FindInstances => $engine->findInstances($connection, self::KEY, self::BUSINESS_KEY), + }; + } + + /** + * @param \Closure(): mixed $run + */ + private function assertFailure(ProcessEngineCall $call, ProcessEngineFailure $failure, \Closure $run): void + { + try { + $run(); + self::fail('No exception.'); + } catch (ProcessEngineException $e) { + self::assertSame($failure, $e->reason); + self::assertSame($call, $e->call); + self::assertSame(\sprintf('Process engine call "%s" failed: %s.', $call->value, $failure->value), $e->getMessage()); + self::assertNull($e->getPrevious()); + self::assertStringNotContainsString(self::ENGINE_TEXT, $e->getMessage()); + } + } + + private function engine(): FlowableProcessEngine + { + $client = $this->createStub(FlowableClientInterface::class); + $defaults = [ + 'listProcessDefinitions' => ['data' => []], + 'getDeploymentResource' => null, + 'createDeployment' => ['id' => 'd-1'], + 'startProcessInstance' => ['id' => 'instance-1'], + 'listProcessInstances' => ['data' => []], + 'listHistoricProcessInstances' => ['data' => []], + 'listHistoricVariables' => ['data' => []], + ]; + foreach ($defaults as $method => $default) { + $client->method($method)->willReturnCallback(function (mixed ...$arguments) use ($method, $default): mixed { + $this->requests[] = [$method, $arguments]; + $answer = \array_key_exists($method, $this->answers) ? $this->answers[$method] : $default; + if ($answer instanceof \Throwable) { + throw $answer; + } + + return $answer instanceof \Closure ? $answer(...$arguments) : $answer; + }); + } + + return new FlowableProcessEngine(function (string $selector) use ($client): FlowableClientInterface { + $this->resolved[] = $selector; + if (null !== $this->resolveFailure) { + throw $this->resolveFailure; + } + + return $client; + }); + } + + private static function connection(string $type = FlowableProcessEngine::CONNECTION_TYPE, bool $active = true): ApiConfiguration + { + return new ApiConfiguration() + ->setName('engine') + ->setConfigJson(['type' => $type, 'endpoint_type' => 'rest', 'base_url' => 'https://flowable.example.com', 'auth_type' => 'basic']) + ->setActive($active); + } +} diff --git a/tests/Unit/Process/ProcessEnginePortTest.php b/tests/Unit/Process/ProcessEnginePortTest.php new file mode 100644 index 0000000..7803f66 --- /dev/null +++ b/tests/Unit/Process/ProcessEnginePortTest.php @@ -0,0 +1,71 @@ + $failure->value, ProcessEngineFailure::cases())); + self::assertSame(['deploy', 'start', 'find_instances'], array_map(static fn (ProcessEngineCall $call): string => $call->value, ProcessEngineCall::cases())); + } + + public function testTheExceptionCarriesOnlyTheCategoryAndTheCall(): void + { + $exception = ProcessEngineException::of(ProcessEngineFailure::EngineUnreachable, ProcessEngineCall::Start); + + self::assertSame(ProcessEngineFailure::EngineUnreachable, $exception->reason); + self::assertSame(ProcessEngineCall::Start, $exception->call); + self::assertSame('Process engine call "start" failed: engine_unreachable.', $exception->getMessage()); + self::assertNull($exception->getPrevious()); + self::assertSame(0, $exception->getCode()); + } + + public function testEveryCallOfTheMissingEngineFailsWithEnginePortMissing(): void + { + $engine = new MissingProcessEngine(); + $connection = new ApiConfiguration()->setConfigJson(['type' => 'flowable', 'endpoint_type' => 'rest']); + $calls = [ + ProcessEngineCall::Deploy->value => static fn () => $engine->deploy($connection, 'answer.bpmn20.xml', '', 'answer'), + ProcessEngineCall::Start->value => static fn () => $engine->start($connection, 'answer', 'key', []), + ProcessEngineCall::FindInstances->value => static fn () => $engine->findInstances(null, 'answer', 'key'), + ]; + + foreach ($calls as $call => $run) { + try { + $run(); + self::fail('No exception for '.$call); + } catch (ProcessEngineException $e) { + self::assertSame(ProcessEngineFailure::EnginePortMissing, $e->reason, $call); + self::assertSame($call, $e->call->value); + } + } + } +} From ad08ab8cff5cbe4ffd10a4168e163f6731b6fe58 Mon Sep 17 00:00:00 2001 From: Tobias Munk Date: Sat, 5 Dec 2026 23:21:36 +0000 Subject: [PATCH 4/9] test(process): assert excluded classes as container.excluded markers [*] On an uncompiled container a class excluded by file still has an abstract definition tagged container.excluded, so hasDefinition() is true. The registration test accepts that marker and checks both engine implementations symmetrically. Co-Authored-By: Claude Fable 5.2 --- .../ProcessEngineRegistrationTest.php | 44 +++++++++++++++++-- 1 file changed, 40 insertions(+), 4 deletions(-) diff --git a/tests/Unit/DependencyInjection/ProcessEngineRegistrationTest.php b/tests/Unit/DependencyInjection/ProcessEngineRegistrationTest.php index d7f006f..10eef8d 100644 --- a/tests/Unit/DependencyInjection/ProcessEngineRegistrationTest.php +++ b/tests/Unit/DependencyInjection/ProcessEngineRegistrationTest.php @@ -10,7 +10,10 @@ use Dmstr\Webhook\Process\Flowable\FlowableProcessEngine; use Dmstr\Webhook\Process\MissingProcessEngine; use Dmstr\Webhook\Process\ProcessDeployment; +use Dmstr\Webhook\Process\ProcessEngineCall; use Dmstr\Webhook\Process\ProcessEngineException; +use Dmstr\Webhook\Process\ProcessEngineFailure; +use Dmstr\Webhook\Process\ProcessEngineGuard; use Dmstr\Webhook\Process\ProcessEngineInterface; use Dmstr\Webhook\Process\ProcessInstance; use Dmstr\Webhook\WebhookBundle; @@ -23,6 +26,12 @@ * registered bundles (`kernel.bundles`), not by the installed packages: the * Flowable implementation only with FlowableBundle, the missing * implementation otherwise. No kernel, no database. + * + * The container is not compiled: a class excluded from resource discovery + * is either absent or present as an abstract definition tagged + * `container.excluded` (Symfony's FileLoader registers excluded files that + * way, RemoveAbstractDefinitionsPass drops them at compile time), see + * {@see self::assertNoService()}. */ final class ProcessEngineRegistrationTest extends TestCase { @@ -31,8 +40,9 @@ public function testTheFlowableEngineWithFlowableBundle(): void $container = self::load(['FrameworkBundle' => FrameworkBundle::class, 'FlowableBundle' => FlowableBundle::class]); self::assertSame(FlowableProcessEngine::class, (string) $container->getAlias(ProcessEngineInterface::class)); + self::assertService($container, FlowableProcessEngine::class); self::assertTrue($container->getDefinition(FlowableProcessEngine::class)->isAutowired()); - self::assertFalse($container->hasDefinition(MissingProcessEngine::class)); + self::assertNoService($container, MissingProcessEngine::class); } public function testTheMissingEngineWithoutFlowableBundle(): void @@ -42,7 +52,8 @@ public function testTheMissingEngineWithoutFlowableBundle(): void $container = self::load(['FrameworkBundle' => FrameworkBundle::class]); self::assertSame(MissingProcessEngine::class, (string) $container->getAlias(ProcessEngineInterface::class)); - self::assertFalse($container->hasDefinition(FlowableProcessEngine::class)); + self::assertService($container, MissingProcessEngine::class); + self::assertNoService($container, FlowableProcessEngine::class); } public function testTheMissingEngineWithoutTheKernelParameter(): void @@ -56,11 +67,36 @@ public function testValueObjectsAndTheExceptionAreNoServices(): void { $container = self::load(['FlowableBundle' => FlowableBundle::class]); - foreach ([ProcessDeployment::class, ProcessInstance::class, ProcessEngineException::class] as $class) { - self::assertFalse($container->hasDefinition($class), $class); + foreach ([ProcessDeployment::class, ProcessInstance::class, ProcessEngineException::class, ProcessEngineCall::class, ProcessEngineFailure::class, ProcessEngineGuard::class] as $class) { + self::assertNoService($container, $class); } } + /** + * A usable service: a concrete definition, not one Symfony keeps only as + * a marker of an excluded class. + */ + private static function assertService(ContainerBuilder $container, string $class): void + { + self::assertTrue($container->hasDefinition($class), $class); + $definition = $container->getDefinition($class); + self::assertFalse($definition->isAbstract(), $class); + self::assertFalse($definition->hasTag('container.excluded'), $class); + } + + /** + * Not a service: no definition, or only the abstract `container.excluded` + * marker of Symfony's FileLoader that compilation removes. + */ + private static function assertNoService(ContainerBuilder $container, string $class): void + { + $definition = $container->hasDefinition($class) ? $container->getDefinition($class) : null; + self::assertTrue( + null === $definition || ($definition->isAbstract() && $definition->hasTag('container.excluded')), + $class.' is registered as a service', + ); + } + /** * @param array|null $bundles `kernel.bundles`, null for none */ From d3e86a90d403b0d6f13fb42caf48f8a9f5abda24 Mon Sep 17 00:00:00 2001 From: Tobias Munk Date: Sat, 5 Dec 2026 23:32:41 +0000 Subject: [PATCH 5/9] feat(process): BPMN of the answer process and the command webhook:process:deploy [*] config/bpmn/webhook-answer.bpmn20.xml defines the process webhookAnswer: an external-worker task on the topic webhook-answer, an error boundary event and an external-worker task on webhook-error-answer. AnswerProcess holds key, resource name, topics and error code. The command deploys the definition to the Flowable connections of the process endpoints and uploads nothing when the deployed content is unchanged. Co-Authored-By: Claude Fable 5.2 --- config/bpmn/webhook-answer.bpmn20.xml | 30 +++ config/services.yaml | 5 +- src/Command/ProcessDeployCommand.php | 175 +++++++++++++ src/Process/AnswerProcess.php | 68 ++++++ .../Command/CommandDefinitionsTest.php | 6 +- .../ProcessDeployCommandDatabaseTest.php | 89 +++++++ .../Unit/Command/ProcessDeployCommandTest.php | 231 ++++++++++++++++++ tests/Unit/Process/AnswerProcessTest.php | 191 +++++++++++++++ 8 files changed, 792 insertions(+), 3 deletions(-) create mode 100644 config/bpmn/webhook-answer.bpmn20.xml create mode 100644 src/Command/ProcessDeployCommand.php create mode 100644 src/Process/AnswerProcess.php create mode 100644 tests/Integration/Command/ProcessDeployCommandDatabaseTest.php create mode 100644 tests/Unit/Command/ProcessDeployCommandTest.php create mode 100644 tests/Unit/Process/AnswerProcessTest.php diff --git a/config/bpmn/webhook-answer.bpmn20.xml b/config/bpmn/webhook-answer.bpmn20.xml new file mode 100644 index 0000000..b637283 --- /dev/null +++ b/config/bpmn/webhook-answer.bpmn20.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/config/services.yaml b/config/services.yaml index 91caf61..f95e9fe 100644 --- a/config/services.yaml +++ b/config/services.yaml @@ -47,8 +47,10 @@ services: - '../src/Reply/' # Process engine port: value objects, enums, the exception and the # guard, and the two implementations, of which WebhookBundle - # registers one (FlowableProcessEngine only with FlowableBundle). + # registers one (FlowableProcessEngine only with FlowableBundle); + # the constants of the shipped answer process. - '../src/Process/Flowable/' + - '../src/Process/AnswerProcess.php' - '../src/Process/MissingProcessEngine.php' - '../src/Process/ProcessDeployment.php' - '../src/Process/ProcessEngineCall.php' @@ -97,3 +99,4 @@ services: # - revised 2026-12-03 (GitLab adapter: mention helper excluded from discovery) # - revised 2026-12-04 (GitLab reply client: src/Reply/ excluded from discovery) # - revised 2026-12-05 (process engine port: src/Process/ value objects and implementations excluded from discovery) +# - revised 2026-12-05 (answer process constants excluded from discovery) diff --git a/src/Command/ProcessDeployCommand.php b/src/Command/ProcessDeployCommand.php new file mode 100644 index 0000000..60f7c6e --- /dev/null +++ b/src/Command/ProcessDeployCommand.php @@ -0,0 +1,175 @@ +`, the Flowable connection of that one + * endpoint, whatever its mode; without a connection the target fails + * with `connection_missing`. + * + * One row per target: the connection, the endpoints that use it, the result + * (`deployed`, `unchanged` or `failed: `), deployment id, + * definition id and version. A failed target does not stop the others; the + * output names only the reason category of the engine port, never text of + * the engine, a secret or a payload. + * + * Exit code 0 when every target was deployed or unchanged, and when there is + * no target at all (a note says so; an installation without process + * endpoints has nothing to deploy, and a deployment pipeline must not fail + * on it); 1 when a target failed, the endpoint of `--endpoint` does not + * exist or the resource cannot be read. + */ +#[AsCommand(name: 'webhook:process:deploy', description: 'Deploy the answer process definition to the Flowable connections of the webhook endpoints (idempotent)')] +final class ProcessDeployCommand extends AbstractEndpointCommand +{ + public function __construct( + EntityManagerInterface $entityManager, + private readonly ProcessEngineInterface $processEngine, + ) { + parent::__construct($entityManager); + } + + protected function configure(): void + { + $this->addOption('endpoint', null, InputOption::VALUE_REQUIRED, 'Deploy only to the Flowable connection of this endpoint (slug or UUID)'); + } + + protected function execute(InputInterface $input, OutputInterface $output): int + { + $io = new SymfonyStyle($input, $output); + + $reference = self::stringOption($input, 'endpoint'); + if (null !== $reference) { + $endpoint = $this->findEndpoint($reference); + if (null === $endpoint) { + $io->error(\sprintf('Webhook endpoint "%s" not found.', $reference)); + + return self::FAILURE; + } + $targets = self::targets([$endpoint], true); + } else { + /** @var list $endpoints */ + $endpoints = $this->entityManager->getRepository(WebhookEndpoint::class)->findBy( + ['mode' => EndpointMode::Process->value, 'active' => true], + ['slug' => 'ASC'], + ); + $targets = self::targets($endpoints, false); + $skipped = array_values(array_map( + static fn (WebhookEndpoint $endpoint): string => $endpoint->getSlug(), + array_filter($endpoints, static fn (WebhookEndpoint $endpoint): bool => null === $endpoint->getFlowableConnection()), + )); + if ([] !== $skipped) { + $io->warning(\sprintf('Skipped, no Flowable connection: %s.', implode(', ', $skipped))); + } + } + + if ([] === $targets) { + $io->note('No active webhook endpoint in the mode process has a Flowable connection; nothing to deploy.'); + + return self::SUCCESS; + } + + try { + $content = AnswerProcess::resourceContent(); + } catch (\RuntimeException $e) { + $io->error($e->getMessage()); + + return self::FAILURE; + } + + $io->writeln(\sprintf('Process definition %s (%s):', AnswerProcess::PROCESS_DEFINITION_KEY, AnswerProcess::RESOURCE_NAME)); + + $rows = []; + $counts = ['deployed' => 0, 'unchanged' => 0, 'failed' => 0]; + foreach ($targets as $target) { + $connection = $target['connection']; + $label = self::formatConnection($connection); + $slugs = implode(', ', $target['endpoints']); + try { + $deployment = $this->processEngine->deploy($connection, AnswerProcess::RESOURCE_NAME, $content, AnswerProcess::PROCESS_DEFINITION_KEY); + } catch (ProcessEngineException $e) { + ++$counts['failed']; + $rows[] = [$label, $slugs, 'failed: '.$e->reason->value, '-', '-', '-']; + + continue; + } + + $result = $deployment->deployed ? 'deployed' : 'unchanged'; + ++$counts[$result]; + $rows[] = [ + $label, + $slugs, + $result, + $deployment->deploymentId, + $deployment->definitionId ?? '-', + null === $deployment->definitionVersion ? '-' : (string) $deployment->definitionVersion, + ]; + } + + $io->table(['Connection', 'Endpoints', 'Result', 'Deployment', 'Definition', 'Version'], $rows); + + $summary = \sprintf('%d target(s): %d deployed, %d unchanged, %d failed.', \count($rows), $counts['deployed'], $counts['unchanged'], $counts['failed']); + if (0 < $counts['failed']) { + $io->error($summary); + + return self::FAILURE; + } + $io->success($summary); + + return self::SUCCESS; + } + + /** + * The targets in the order of the endpoints: one per distinct Flowable + * connection with the slugs of its endpoints. An endpoint without a + * connection is a target of its own (null connection) only when + * $withoutConnection is true. + * + * @param list $endpoints + * + * @return list}> + */ + private static function targets(array $endpoints, bool $withoutConnection): array + { + $targets = []; + foreach ($endpoints as $endpoint) { + $connection = $endpoint->getFlowableConnection(); + if (null === $connection && !$withoutConnection) { + continue; + } + $key = null === $connection ? 'endpoint:'.$endpoint->getId() : 'connection:'.$connection->getId(); + $targets[$key] ??= ['connection' => $connection, 'endpoints' => []]; + $targets[$key]['endpoints'][] = $endpoint->getSlug(); + } + + return array_values($targets); + } +} diff --git a/src/Process/AnswerProcess.php b/src/Process/AnswerProcess.php new file mode 100644 index 0000000..86363fe --- /dev/null +++ b/src/Process/AnswerProcess.php @@ -0,0 +1,68 @@ +getDefinition()->getOptionForShortcut('e')->getName()); } - public function testEndpointOptionOfTheRouteCommandsIsLongOnly(): void + public function testEndpointOptionOfTheRouteAndDeployCommandsIsLongOnly(): void { $application = new Application(self::bootKernel()); - foreach (['webhook:route:create', 'webhook:route:delete', 'webhook:route:list', 'webhook:route:show', 'webhook:route:update'] as $name) { + foreach (['webhook:process:deploy', 'webhook:route:create', 'webhook:route:delete', 'webhook:route:list', 'webhook:route:show', 'webhook:route:update'] as $name) { $command = $application->find($name); $command->mergeApplicationDefinition(); self::assertNull($command->getDefinition()->getOption('endpoint')->getShortcut(), $name); @@ -88,3 +89,4 @@ public function testEndpointOptionOfTheRouteCommandsIsLongOnly(): void } // - revised 2026-12-03 (webhook:route:* console twins) +// - revised 2026-12-05 (webhook:process:deploy) diff --git a/tests/Integration/Command/ProcessDeployCommandDatabaseTest.php b/tests/Integration/Command/ProcessDeployCommandDatabaseTest.php new file mode 100644 index 0000000..3eda311 --- /dev/null +++ b/tests/Integration/Command/ProcessDeployCommandDatabaseTest.php @@ -0,0 +1,89 @@ + TestKernel::ENV_FAKE_ENGINE])); + /** @var FakeProcessEngine $engine */ + $engine = self::getContainer()->get(FakeProcessEngine::class); + + $create = self::execute($application, 'webhook:endpoint:create', ['slug' => $slug, '--mode' => 'process', '--secret' => self::SECRET]); + self::assertSame(Command::SUCCESS, $create->getStatusCode(), $create->getDisplay()); + + $unknown = self::execute($application, 'webhook:process:deploy', ['--endpoint' => self::PREFIX.'unknown']); + self::assertSame(Command::FAILURE, $unknown->getStatusCode()); + self::assertSame(0, $engine->calls()); + + // The endpoint has no Flowable connection: the port refuses the + // target with its category, after the command read the resource. + $deploy = self::execute($application, 'webhook:process:deploy', ['--endpoint' => $slug]); + self::assertSame(Command::FAILURE, $deploy->getStatusCode(), $deploy->getDisplay()); + self::assertMatchesRegularExpression('/\b'.preg_quote($slug, '/').'\s+failed: connection_missing\b/', $deploy->getDisplay()); + self::assertSame(1, $engine->calls(ProcessEngineCall::Deploy)); + self::assertSame([], $engine->deployments); + } + + /** + * @param array $input + */ + private static function execute(Application $application, string $name, array $input): CommandTester + { + $tester = new CommandTester($application->find($name)); + $tester->execute($input, ['interactive' => false]); + + return $tester; + } + + private static function cleanUp(): void + { + static::ensureKernelShutdown(); + $kernel = static::bootKernel(['environment' => TestKernel::ENV_FAKE_ENGINE]); + TestDatabase::migrate($kernel); + TestDatabase::removeEndpoints(TestDatabase::connection($kernel), self::PREFIX); + static::ensureKernelShutdown(); + } +} diff --git a/tests/Unit/Command/ProcessDeployCommandTest.php b/tests/Unit/Command/ProcessDeployCommandTest.php new file mode 100644 index 0000000..70c2e1a --- /dev/null +++ b/tests/Unit/Command/ProcessDeployCommandTest.php @@ -0,0 +1,231 @@ +store = new InMemoryWebhookStore(); + $this->engine = new FakeProcessEngine(); + } + + public function testTheFirstRunDeploysAndTheSecondReportsUnchanged(): void + { + $connection = $this->connection('engine-main'); + $this->endpoint('alpha', $connection); + + $first = $this->deploy([]); + self::assertSame(Command::SUCCESS, $first->getStatusCode(), $first->getDisplay()); + $display = self::flat($first->getDisplay()); + self::assertStringContainsString('Process definition '.AnswerProcess::PROCESS_DEFINITION_KEY.' ('.AnswerProcess::RESOURCE_NAME.')', $display); + self::assertMatchesRegularExpression('/\balpha deployed fake-deployment-1 webhookAnswer:1:fake-deployment-1 1\b/', $display); + self::assertStringContainsString('1 target(s): 1 deployed, 0 unchanged, 0 failed.', $display); + + self::assertCount(1, $this->engine->deployments); + $deployment = $this->engine->deployments[0]; + self::assertSame($connection->getId()->toRfc4122(), $deployment['connection']); + self::assertSame(AnswerProcess::RESOURCE_NAME, $deployment['resourceName']); + self::assertSame(AnswerProcess::PROCESS_DEFINITION_KEY, $deployment['key']); + self::assertSame(AnswerProcess::resourceContent(), $deployment['content']); + + $second = $this->deploy([]); + self::assertSame(Command::SUCCESS, $second->getStatusCode(), $second->getDisplay()); + $display = self::flat($second->getDisplay()); + self::assertMatchesRegularExpression('/\balpha unchanged fake-deployment-1 webhookAnswer:1:fake-deployment-1 1\b/', $display); + self::assertStringContainsString('1 target(s): 0 deployed, 1 unchanged, 0 failed.', $display); + self::assertCount(1, $this->engine->deployments); + self::assertSame(2, $this->engine->calls(ProcessEngineCall::Deploy)); + } + + public function testChangedContentDeploysANewVersion(): void + { + $connection = $this->connection('engine-main'); + $this->endpoint('alpha', $connection); + // An earlier release of the definition, deployed before. + $this->engine->deploy($connection, AnswerProcess::RESOURCE_NAME, '', AnswerProcess::PROCESS_DEFINITION_KEY); + + $run = $this->deploy([]); + self::assertSame(Command::SUCCESS, $run->getStatusCode(), $run->getDisplay()); + self::assertMatchesRegularExpression('/\balpha deployed fake-deployment-2 webhookAnswer:2:fake-deployment-2 2\b/', self::flat($run->getDisplay())); + self::assertCount(2, $this->engine->deployments); + self::assertSame(AnswerProcess::resourceContent(), $this->engine->deployments[1]['content']); + + $again = $this->deploy([]); + self::assertSame(Command::SUCCESS, $again->getStatusCode(), $again->getDisplay()); + self::assertMatchesRegularExpression('/\balpha unchanged fake-deployment-2 webhookAnswer:2:fake-deployment-2 2\b/', self::flat($again->getDisplay())); + self::assertCount(2, $this->engine->deployments); + } + + public function testEndpointsSharingAConnectionDeployOnce(): void + { + $shared = $this->connection('engine-shared'); + $other = $this->connection('engine-other'); + $this->endpoint('beta', $shared); + $this->endpoint('alpha', $shared); + $this->endpoint('gamma', $other); + + $run = $this->deploy([]); + + self::assertSame(Command::SUCCESS, $run->getStatusCode(), $run->getDisplay()); + $display = self::flat($run->getDisplay()); + self::assertMatchesRegularExpression('/\balpha, beta deployed fake-deployment-1\b/', $display); + self::assertMatchesRegularExpression('/\bgamma deployed fake-deployment-2\b/', $display); + self::assertStringContainsString('2 target(s): 2 deployed, 0 unchanged, 0 failed.', $display); + self::assertSame(2, $this->engine->calls(ProcessEngineCall::Deploy)); + self::assertSame( + [$shared->getId()->toRfc4122(), $other->getId()->toRfc4122()], + array_column($this->engine->deployments, 'connection'), + ); + } + + public function testAFailingTargetIsReportedAndTheOthersAreStillDeployed(): void + { + $this->endpoint('alpha', $this->connection('engine-down')); + $this->endpoint('beta', $this->connection('engine-off', active: false)); + $up = $this->connection('engine-up'); + $this->endpoint('gamma', $up); + // The first deploy call (alpha) gets no answer. + $this->engine->failOn(ProcessEngineCall::Deploy, ProcessEngineFailure::EngineUnreachable, 1); + + $run = $this->deploy([]); + + self::assertSame(Command::FAILURE, $run->getStatusCode(), $run->getDisplay()); + $display = self::flat($run->getDisplay()); + self::assertMatchesRegularExpression('/\balpha failed: engine_unreachable - - -/', $display); + self::assertMatchesRegularExpression('/\bbeta failed: connection_inactive - - -/', $display); + self::assertMatchesRegularExpression('/\bgamma deployed fake-deployment-1 webhookAnswer:1:fake-deployment-1 1\b/', $display); + self::assertStringContainsString('3 target(s): 1 deployed, 0 unchanged, 2 failed.', $display); + self::assertSame(3, $this->engine->calls(ProcessEngineCall::Deploy)); + self::assertSame([$up->getId()->toRfc4122()], array_column($this->engine->deployments, 'connection')); + // Only the category, never the message of an exception. + self::assertStringNotContainsString('Process engine call', $display); + } + + public function testNoTargetIsANoteAndSucceeds(): void + { + $run = $this->deploy([]); + + self::assertSame(Command::SUCCESS, $run->getStatusCode(), $run->getDisplay()); + self::assertStringContainsString('nothing to deploy', self::flat($run->getDisplay())); + self::assertSame(0, $this->engine->calls()); + } + + public function testOnlyActiveProcessEndpointsWithAConnectionAreTargets(): void + { + $connection = $this->connection('engine-main'); + $this->endpoint('handler-endpoint', $connection, EndpointMode::Handler); + $this->endpoint('inactive-endpoint', $connection)->setActive(false); + $this->endpoint('unconnected-endpoint', null); + + $run = $this->deploy([]); + + self::assertSame(Command::SUCCESS, $run->getStatusCode(), $run->getDisplay()); + $display = self::flat($run->getDisplay()); + self::assertStringContainsString('Skipped, no Flowable connection: unconnected-endpoint.', $display); + self::assertStringContainsString('nothing to deploy', $display); + self::assertSame(0, $this->engine->calls()); + } + + public function testTheEndpointOptionDeploysToThatEndpointOnly(): void + { + $handlerConnection = $this->connection('engine-handler'); + $this->endpoint('handler-endpoint', $handlerConnection, EndpointMode::Handler); + $this->endpoint('alpha', $this->connection('engine-main')); + + $run = $this->deploy(['--endpoint' => 'handler-endpoint']); + + self::assertSame(Command::SUCCESS, $run->getStatusCode(), $run->getDisplay()); + self::assertMatchesRegularExpression('/\bhandler-endpoint deployed fake-deployment-1\b/', self::flat($run->getDisplay())); + self::assertSame([$handlerConnection->getId()->toRfc4122()], array_column($this->engine->deployments, 'connection')); + self::assertSame(1, $this->engine->calls()); + } + + public function testTheEndpointOptionFailsForAnUnknownEndpointOrOneWithoutConnection(): void + { + $endpoint = $this->endpoint('unconnected-endpoint', null); + + $unknown = $this->deploy(['--endpoint' => 'no-such-endpoint']); + self::assertSame(Command::FAILURE, $unknown->getStatusCode()); + self::assertStringContainsString('Webhook endpoint "no-such-endpoint" not found.', self::flat($unknown->getDisplay())); + self::assertSame(0, $this->engine->calls()); + + $missing = $this->deploy(['--endpoint' => (string) $endpoint->getId()]); + self::assertSame(Command::FAILURE, $missing->getStatusCode(), $missing->getDisplay()); + $display = self::flat($missing->getDisplay()); + self::assertMatchesRegularExpression('/\bunconnected-endpoint failed: connection_missing - - -/', $display); + self::assertStringContainsString('1 target(s): 0 deployed, 0 unchanged, 1 failed.', $display); + self::assertSame(1, $this->engine->calls(ProcessEngineCall::Deploy)); + self::assertSame([], $this->engine->deployments); + } + + /** + * @param array $input + */ + private function deploy(array $input): CommandTester + { + $tester = new CommandTester(new ProcessDeployCommand($this->store->entityManager($this), $this->engine)); + $tester->execute($input, ['interactive' => false]); + + return $tester; + } + + private function connection(string $name, bool $active = true): ApiConfiguration + { + $connection = new ApiConfiguration() + ->setName($name) + ->setConfigJson(['type' => 'flowable', 'endpoint_type' => 'rest']) + ->setActive($active); + $this->store->connections[(string) $connection->getId()] = $connection; + + return $connection; + } + + private function endpoint(string $slug, ?ApiConfiguration $flowable, EndpointMode $mode = EndpointMode::Process): WebhookEndpoint + { + return $this->store->stored($slug, self::SECRET, null, $mode)->setFlowableConnection($flowable); + } + + /** + * The output as one line: the line prefix `!` of note blocks dropped, + * every run of white space (line breaks, padding, table spacing) one + * space. + */ + private static function flat(string $display): string + { + return trim((string) preg_replace('/\s+/', ' ', (string) preg_replace('/^\s*!\s?/m', '', $display))); + } +} diff --git a/tests/Unit/Process/AnswerProcessTest.php b/tests/Unit/Process/AnswerProcessTest.php new file mode 100644 index 0000000..4f95f54 --- /dev/null +++ b/tests/Unit/Process/AnswerProcessTest.php @@ -0,0 +1,191 @@ +query('/b:definitions/b:process'); + self::assertNotFalse($processes); + self::assertSame(1, $processes->length); + $process = $processes->item(0); + self::assertInstanceOf(\DOMElement::class, $process); + self::assertSame(AnswerProcess::PROCESS_DEFINITION_KEY, $process->getAttribute('id')); + self::assertSame('true', $process->getAttribute('isExecutable')); + self::assertSame(1, self::countElements($xpath, '/b:definitions/b:process/b:startEvent')); + self::assertSame(2, self::countElements($xpath, '/b:definitions/b:process/b:endEvent')); + } + + public function testTheTasksAreExternalWorkerTasksOnTheTopics(): void + { + $xpath = self::xpath(); + + $tasks = []; + foreach (self::elements($xpath, '//b:serviceTask') as $task) { + self::assertSame('external-worker', $task->getAttributeNS(self::FLOWABLE, 'type'), $task->getAttribute('id')); + $tasks[$task->getAttributeNS(self::FLOWABLE, 'topic')] = $task->getAttribute('id'); + } + ksort($tasks); + + self::assertSame([AnswerProcess::ANSWER_TOPIC, AnswerProcess::ERROR_ANSWER_TOPIC], array_keys($tasks)); + // No task of another kind that a worker would not serve. + self::assertSame(0, self::countElements($xpath, '//b:userTask | //b:scriptTask | //b:sendTask | //b:receiveTask | //b:task | //b:manualTask | //b:businessRuleTask')); + } + + public function testTheErrorBoundaryEventOfTheAnswerTaskLeadsToTheErrorAnswer(): void + { + $xpath = self::xpath(); + $answer = self::task($xpath, AnswerProcess::ANSWER_TOPIC); + $errorAnswer = self::task($xpath, AnswerProcess::ERROR_ANSWER_TOPIC); + + $boundaries = self::elements($xpath, '//b:boundaryEvent'); + self::assertCount(1, $boundaries); + $boundary = $boundaries[0]; + self::assertSame($answer, $boundary->getAttribute('attachedToRef')); + + $definitions = self::elements($xpath, '//b:boundaryEvent/b:errorEventDefinition'); + self::assertCount(1, $definitions); + $errorRef = $definitions[0]->getAttribute('errorRef'); + $errors = self::elements($xpath, \sprintf('/b:definitions/b:error[@id="%s"]', $errorRef)); + self::assertCount(1, $errors, 'The boundary event references a declared error.'); + self::assertSame(AnswerProcess::ERROR_CODE, $errors[0]->getAttribute('errorCode')); + + self::assertSame([$errorAnswer], self::targetsOf($xpath, $boundary->getAttribute('id'))); + // Completed: answer -> end; error answer -> end. + foreach ([$answer, $errorAnswer] as $task) { + $targets = self::targetsOf($xpath, $task); + self::assertCount(1, $targets, $task); + self::assertSame(1, self::countElements($xpath, \sprintf('//b:endEvent[@id="%s"]', $targets[0])), $task); + } + $start = self::elements($xpath, '//b:startEvent')[0]->getAttribute('id'); + self::assertSame([$answer], self::targetsOf($xpath, $start)); + } + + public function testEveryIdIsUniqueAndEveryFlowConnectsElements(): void + { + $xpath = self::xpath(); + + $ids = []; + $nodes = $xpath->query('//@id'); + self::assertNotFalse($nodes); + foreach ($nodes as $node) { + $ids[] = (string) $node->nodeValue; + } + self::assertNotSame([], $ids); + self::assertSame(array_unique($ids), $ids, 'An id is used twice.'); + + $flows = self::elements($xpath, '//b:sequenceFlow'); + self::assertNotSame([], $flows); + foreach ($flows as $flow) { + self::assertContains($flow->getAttribute('sourceRef'), $ids, $flow->getAttribute('id')); + self::assertContains($flow->getAttribute('targetRef'), $ids, $flow->getAttribute('id')); + } + } + + public function testTheDefinitionReadsNoProcessVariable(): void + { + $content = AnswerProcess::resourceContent(); + + self::assertStringNotContainsString('${', $content); + self::assertStringNotContainsString('#{', $content); + self::assertSame(0, self::countElements(self::xpath(), '//b:conditionExpression | //b:dataObject | //b:property | //b:ioSpecification')); + } + + private static function xpath(): \DOMXPath + { + $document = new \DOMDocument(); + $previous = libxml_use_internal_errors(true); + try { + $loaded = $document->loadXML(AnswerProcess::resourceContent(), \LIBXML_NONET); + $errors = array_map(static fn (\LibXMLError $error): string => trim($error->message), libxml_get_errors()); + libxml_clear_errors(); + } finally { + libxml_use_internal_errors($previous); + } + self::assertTrue($loaded, implode('; ', $errors)); + self::assertSame([], $errors); + self::assertSame(self::BPMN, $document->documentElement?->namespaceURI); + + $xpath = new \DOMXPath($document); + $xpath->registerNamespace('b', self::BPMN); + + return $xpath; + } + + /** + * @return list<\DOMElement> + */ + private static function elements(\DOMXPath $xpath, string $expression): array + { + $nodes = $xpath->query($expression); + self::assertNotFalse($nodes, $expression); + $elements = []; + foreach ($nodes as $node) { + self::assertInstanceOf(\DOMElement::class, $node); + $elements[] = $node; + } + + return $elements; + } + + private static function countElements(\DOMXPath $xpath, string $expression): int + { + return \count(self::elements($xpath, $expression)); + } + + /** The id of the service task on $topic. */ + private static function task(\DOMXPath $xpath, string $topic): string + { + $tasks = array_values(array_filter( + self::elements($xpath, '//b:serviceTask'), + static fn (\DOMElement $task): bool => $topic === $task->getAttributeNS(self::FLOWABLE, 'topic'), + )); + self::assertCount(1, $tasks, $topic); + + return $tasks[0]->getAttribute('id'); + } + + /** + * The targets of the sequence flows leaving $id. + * + * @return list + */ + private static function targetsOf(\DOMXPath $xpath, string $id): array + { + return array_map( + static fn (\DOMElement $flow): string => $flow->getAttribute('targetRef'), + self::elements($xpath, \sprintf('//b:sequenceFlow[@sourceRef="%s"]', $id)), + ); + } +} From fbf90dea6f3594e2854ac99dc823b4c7cda1ad4c Mon Sep 17 00:00:00 2001 From: Tobias Munk Date: Sun, 6 Dec 2026 00:04:35 +0000 Subject: [PATCH 6/9] feat(process): start a process instance for a routed event on the transport webhook [*] The intake dispatches one StartProcess message (event id only) after an event became routed and makes no engine call in the request. The handler claims the event (start_claimed_at, one conditional update), looks for an instance with the business key and the endpoint variable, starts the route's process definition otherwise and records started with the instance id. A failure carries only a reason category; after the last retry a listener sets the event to failed with it. The bundle prepends the routing of the message and, unless the application defines it, the transport webhook (in-memory, never sync). A start rejected with 422 is definition_not_deployed when the engine has no definition of the key. Co-Authored-By: Claude Fable 5.2 --- config/services.yaml | 16 + src/Intake/EventStore.php | 201 ++++++- src/Intake/WebhookIntake.php | 50 +- .../Flowable/FlowableProcessEngine.php | 48 +- .../Start/ProcessStartFailedException.php | 44 ++ src/Process/Start/ProcessStartFailure.php | 62 ++ .../Start/ProcessStartFailureListener.php | 85 +++ src/Process/Start/ProcessStartOutcome.php | 39 ++ src/Process/Start/ProcessStartVariables.php | 95 +++ src/Process/Start/ProcessStarter.php | 218 +++++++ src/Process/Start/StartProcess.php | 26 + src/Process/Start/StartProcessHandler.php | 33 + .../UnrecoverableProcessStartException.php | 19 + src/WebhookBundle.php | 67 ++- tests/Integration/ContainerVariantsTest.php | 117 +++- .../Intake/IntakeMatrixDatabaseTestCase.php | 24 + .../Process/ProcessStartDatabaseTest.php | 566 ++++++++++++++++++ .../ProcessStartWithoutEngineDatabaseTest.php | 99 +++ .../Process/StartClaimDatabaseTest.php | 216 +++++++ tests/Kernel/TestKernel.php | 43 +- tests/Support/HostTestMessage.php | 20 + tests/Support/IntakeHarness.php | 24 +- tests/Support/RecordingMessageBus.php | 65 ++ tests/Support/TransportDrain.php | 124 ++++ .../WebhookBundlePrependTest.php | 74 ++- tests/Unit/Intake/Basecamp4LogTest.php | 2 + .../Unit/Intake/EventStoreTransitionTest.php | 31 + .../Intake/IntakeStartDispatchUnitTest.php | 202 +++++++ .../Process/FlowableProcessEngineTest.php | 47 +- .../Start/ProcessStartFailureListenerTest.php | 198 ++++++ .../Process/Start/ProcessStartValuesTest.php | 182 ++++++ 31 files changed, 3006 insertions(+), 31 deletions(-) create mode 100644 src/Process/Start/ProcessStartFailedException.php create mode 100644 src/Process/Start/ProcessStartFailure.php create mode 100644 src/Process/Start/ProcessStartFailureListener.php create mode 100644 src/Process/Start/ProcessStartOutcome.php create mode 100644 src/Process/Start/ProcessStartVariables.php create mode 100644 src/Process/Start/ProcessStarter.php create mode 100644 src/Process/Start/StartProcess.php create mode 100644 src/Process/Start/StartProcessHandler.php create mode 100644 src/Process/Start/UnrecoverableProcessStartException.php create mode 100644 tests/Integration/Process/ProcessStartDatabaseTest.php create mode 100644 tests/Integration/Process/ProcessStartWithoutEngineDatabaseTest.php create mode 100644 tests/Integration/Process/StartClaimDatabaseTest.php create mode 100644 tests/Support/HostTestMessage.php create mode 100644 tests/Support/RecordingMessageBus.php create mode 100644 tests/Support/TransportDrain.php create mode 100644 tests/Unit/Intake/IntakeStartDispatchUnitTest.php create mode 100644 tests/Unit/Process/Start/ProcessStartFailureListenerTest.php create mode 100644 tests/Unit/Process/Start/ProcessStartValuesTest.php diff --git a/config/services.yaml b/config/services.yaml index f95e9fe..4528116 100644 --- a/config/services.yaml +++ b/config/services.yaml @@ -58,6 +58,15 @@ services: - '../src/Process/ProcessEngineFailure.php' - '../src/Process/ProcessEngineGuard.php' - '../src/Process/ProcessInstance.php' + # Process start: the message, the failures, the exceptions, the + # variables and the outcome; services are the starter, the + # message handler and the failure listener. + - '../src/Process/Start/StartProcess.php' + - '../src/Process/Start/ProcessStartFailure.php' + - '../src/Process/Start/ProcessStartFailedException.php' + - '../src/Process/Start/UnrecoverableProcessStartException.php' + - '../src/Process/Start/ProcessStartVariables.php' + - '../src/Process/Start/ProcessStartOutcome.php' # Sliding-window counters of the endpoint rate limit, in the cache pool # `cache.rate_limiter` of FrameworkBundle (configure a shared adapter such @@ -83,6 +92,12 @@ services: arguments: $clock: '@?clock' + # The time of the start claims: the host's `clock` service, as for the + # Standard Webhooks parser; without it the system time. + Dmstr\Webhook\Process\Start\ProcessStarter: + arguments: + $clock: '@?clock' + # Announces the permissions this bundle checks to the permission voter of # the host application (container tag, plain strings; the application maps # them to roles). @@ -100,3 +115,4 @@ services: # - revised 2026-12-04 (GitLab reply client: src/Reply/ excluded from discovery) # - revised 2026-12-05 (process engine port: src/Process/ value objects and implementations excluded from discovery) # - revised 2026-12-05 (answer process constants excluded from discovery) +# - revised 2026-12-05 (process start: value objects excluded from discovery, clock of the starter) diff --git a/src/Intake/EventStore.php b/src/Intake/EventStore.php index 427ec67..9a28736 100644 --- a/src/Intake/EventStore.php +++ b/src/Intake/EventStore.php @@ -30,15 +30,26 @@ * (project, target, note, discussion; kind and id each) go into the same * insert, so they need no second write. * - * {@see self::transition()}: the only way the bundle changes the status of - * a stored event, one conditional `UPDATE … WHERE id = ? AND status = ?` + * {@see self::transition()}: the way the bundle changes the status of a + * stored event, one conditional `UPDATE … WHERE id = ? AND status = ?` * with the origin status (`received` unless the caller names another one). * It never leaves a terminal status and never moves an event to its origin * or back to `received`, so it is race-free: of two concurrent transitions * from the same origin exactly one changes the row. * - * Both are plain DBAL calls with the id bound as type `uuid` (native UUID on - * PostgreSQL, BINARY(16) on MySQL), portable to every Doctrine platform. + * The process start of a routed event + * ({@see \Dmstr\Webhook\Process\Start\ProcessStarter}) reads its columns + * ({@see self::startCandidate()}), claims it for one attempt + * ({@see self::claimStart()}, a lease in `start_claimed_at`; the status + * stays `routed`), releases the claim of a failed attempt + * ({@see self::releaseStart()}), records the instance (`routed` → + * `started`, {@see self::recordStart()}) or ends it (`routed` → `failed`, + * {@see self::failStart()}); each write is one conditional update from + * `routed` without instance. + * + * All are plain DBAL calls with the id bound as type `uuid` (native UUID on + * PostgreSQL, BINARY(16) on MySQL) and timestamps computed in PHP and bound + * as `datetimetz_immutable`, portable to every Doctrine platform. */ final readonly class EventStore { @@ -50,6 +61,9 @@ WebhookEvent::STATUS_HANDLED, ]; + /** The roles of the reference columns (`_kind`, `_id`). */ + private const array REFERENCE_ROLES = ['project', 'target', 'note', 'discussion']; + public function __construct(private EntityManagerInterface $entityManager) { } @@ -135,6 +149,179 @@ public function transition(Uuid $eventId, string $status, ?string $reason = null return (int) $changed > 0; } + /** + * The columns of an event the process start needs, read through DBAL + * (no ORM state, never the payload): `endpoint_id` (as a {@see Uuid}), + * `status`, `route`, `dedupe_key`, `process_instance_id` and the + * reference columns (`_kind`, `_id`); null when the event + * does not exist. + * + * @return array|null + */ + public function startCandidate(Uuid $eventId): ?array + { + $connection = $this->entityManager->getConnection(); + $columns = ['endpoint_id', 'status', 'route', 'dedupe_key', 'process_instance_id']; + foreach (self::REFERENCE_ROLES as $role) { + $columns[] = $role.'_kind'; + $columns[] = $role.'_id'; + } + + $row = $connection->fetchAssociative( + 'SELECT '.implode(', ', $columns).' FROM '.WebhookEvent::TABLE.' WHERE id = :id', + ['id' => $eventId], + ['id' => 'uuid'], + ); + if (false === $row) { + return null; + } + $row['endpoint_id'] = $connection->convertToPHPValue($row['endpoint_id'], 'uuid'); + + return $row; + } + + /** + * Claims a routed event without process instance for one start attempt, + * in one conditional update: + * + * UPDATE webhook_event SET start_claimed_at = :now + * WHERE id = :id AND status = 'routed' AND process_instance_id IS NULL + * AND (start_claimed_at IS NULL OR start_claimed_at < :expired) + * + * with `:expired` = $now minus $leaseSeconds. The status stays `routed` + * until the instance id is recorded ({@see self::recordStart()}), so an + * attempt that dies after its claim leaves an event that a later attempt + * claims again once the lease expired. Of two concurrent claims exactly + * one changes the row. + * + * Affected rows: MySQL counts changed rows, not matched ones, and the + * column has second precision (DATETIME on MySQL, TIMESTAMP(0) on + * PostgreSQL; the bound value carries no fraction). A row matches only + * while its claim is null or older than $now minus the lease (at least + * one second), so the value written ($now) always differs from the + * stored one: every match changes the row and counts on both platforms. + * A second claim in the same second does not match at all, because the + * first one's $now is not older than $now minus the lease. + * + * The timestamps are written and compared in UTC (a MySQL DATETIME stores + * no offset), so workers with different default time zones agree. + * + * @param int $leaseSeconds how long a claim blocks other attempts; at least 1 + * + * @return bool whether this call claimed the event + */ + public function claimStart(Uuid $eventId, \DateTimeImmutable $now, int $leaseSeconds): bool + { + if ($leaseSeconds < 1) { + throw new \InvalidArgumentException('The lease of a start claim must be at least one second.'); + } + $now = self::utc($now); + + $changed = $this->entityManager->getConnection()->executeStatement( + 'UPDATE '.WebhookEvent::TABLE.' SET start_claimed_at = :now' + .' WHERE id = :id AND status = :routed AND process_instance_id IS NULL' + .' AND (start_claimed_at IS NULL OR start_claimed_at < :expired)', + [ + 'now' => $now, + 'id' => $eventId, + 'routed' => WebhookEvent::STATUS_ROUTED, + 'expired' => $now->modify(\sprintf('-%d seconds', $leaseSeconds)), + ], + [ + 'now' => Types::DATETIMETZ_IMMUTABLE, + 'id' => 'uuid', + 'expired' => Types::DATETIMETZ_IMMUTABLE, + ], + ); + + return (int) $changed > 0; + } + + /** + * Gives up the claim of a failed start attempt, so that its retry claims + * the event at once instead of after the lease: + * + * UPDATE webhook_event SET start_claimed_at = NULL + * WHERE id = :id AND status = 'routed' AND process_instance_id IS NULL + * AND start_claimed_at = :claimedAt + * + * Only the attempt's own claim ($claimedAt, the $now of its + * {@see self::claimStart()}) is released, never a later claim of another + * attempt. The value always changes (to null), so the affected rows are + * the matched rows on MySQL too. + * + * @return bool whether this call released the claim + */ + public function releaseStart(Uuid $eventId, \DateTimeImmutable $claimedAt): bool + { + $changed = $this->entityManager->getConnection()->executeStatement( + 'UPDATE '.WebhookEvent::TABLE.' SET start_claimed_at = NULL' + .' WHERE id = :id AND status = :routed AND process_instance_id IS NULL AND start_claimed_at = :claimedAt', + [ + 'id' => $eventId, + 'routed' => WebhookEvent::STATUS_ROUTED, + 'claimedAt' => self::utc($claimedAt), + ], + [ + 'id' => 'uuid', + 'claimedAt' => Types::DATETIMETZ_IMMUTABLE, + ], + ); + + return (int) $changed > 0; + } + + /** + * Records the process instance of a routed event: `routed` → `started` + * with the instance id and the reason cleared; the route and the claim + * stay as they are. One conditional update: + * + * UPDATE webhook_event SET status = 'started', process_instance_id = :instance, reason = NULL + * WHERE id = :id AND status = 'routed' AND process_instance_id IS NULL + * + * The status always changes, so the affected rows are the matched rows + * on MySQL too. Nothing happens when the event is no longer routed + * without instance (e.g. another attempt recorded its instance first). + * + * @param string $processInstanceId the id the engine returned, 1 to 255 characters + * + * @return bool whether this call recorded the instance + */ + public function recordStart(Uuid $eventId, string $processInstanceId): bool + { + if ('' === $processInstanceId || mb_strlen($processInstanceId) > WebhookEvent::MAX_REFERENCE_LENGTH) { + throw new \InvalidArgumentException('A process instance id must have 1 to 255 characters.'); + } + + $changed = $this->entityManager->getConnection()->executeStatement( + 'UPDATE '.WebhookEvent::TABLE.' SET status = :started, process_instance_id = :instance, reason = NULL' + .' WHERE id = :id AND status = :routed AND process_instance_id IS NULL', + [ + 'started' => WebhookEvent::STATUS_STARTED, + 'instance' => $processInstanceId, + 'id' => $eventId, + 'routed' => WebhookEvent::STATUS_ROUTED, + ], + ['id' => 'uuid'], + ); + + return (int) $changed > 0; + } + + /** + * Ends a start that will not be tried again: `routed` → `failed` with + * the reason category (a value of + * {@see \Dmstr\Webhook\Process\Start\ProcessStartFailure}), one + * conditional update from `routed` ({@see self::transition()}). An event + * that meanwhile became `started` stays untouched. + * + * @return bool whether this call changed the event + */ + public function failStart(Uuid $eventId, string $category): bool + { + return $this->transition($eventId, WebhookEvent::STATUS_FAILED, $category, null, WebhookEvent::STATUS_ROUTED); + } + /** The adapter's id, or its SHA-256 hex when it exceeds the column. */ public static function dedupeKey(string $id): string { @@ -170,6 +357,11 @@ private static function referenceColumns(?EventContext $context): array return $columns; } + private static function utc(\DateTimeImmutable $time): \DateTimeImmutable + { + return $time->setTimezone(new \DateTimeZone('UTC')); + } + private static function clipReason(?string $reason): ?string { return null === $reason ? null : mb_substr($reason, 0, WebhookEvent::MAX_REASON_LENGTH); @@ -186,3 +378,4 @@ private static function assertStatus(string $status): void // - revised 2026-12-03 (insert with final status and reason, conditional status transition) // - revised 2026-12-05 (origin status of the conditional transition as a parameter) // - revised 2026-12-05 (references of the event context stored with the insert) +// - revised 2026-12-05 (process start: read, claim, release, record and fail of a routed event) diff --git a/src/Intake/WebhookIntake.php b/src/Intake/WebhookIntake.php index bd33451..8c3c374 100644 --- a/src/Intake/WebhookIntake.php +++ b/src/Intake/WebhookIntake.php @@ -14,13 +14,16 @@ use Dmstr\Webhook\Entity\WebhookEvent; use Dmstr\Webhook\Model\EventDisposition; use Dmstr\Webhook\Model\IgnoreReason; +use Dmstr\Webhook\Process\Start\StartProcess; use Dmstr\Webhook\Routing\EventRouter; use Dmstr\Webhook\Secret\WebhookEndpointSecrets; use Doctrine\ORM\EntityManagerInterface; use Psr\Log\LoggerInterface; use Symfony\Component\DependencyInjection\Attribute\Autowire; use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\Messenger\MessageBusInterface; use Symfony\Component\RemoteEvent\RemoteEvent; +use Symfony\Component\Uid\Uuid; use Symfony\Component\Webhook\Exception\RejectWebhookException; /** @@ -60,13 +63,23 @@ * {@see EventRouter::route()}: `routed` with the route id, or `ignored` * (`no_route`, the budget is used). One conditional update after the * insert ({@see EventStore::transition()}), so at most two writes. + * An event that became `routed` is queued for its process start: one + * {@see StartProcess} message (the event id only) on the message bus, + * routed to the transport {@see \Dmstr\Webhook\WebhookBundle::TRANSPORT}, + * which is never synchronous; the process engine is never called here. * Nothing of this mode reaches a delivery handler. * * Each `ignored` or `routed` decision writes one `info` line on the channel * `webhook` (slug, event id, type, status, reason, route, delivery id; * never the payload). The request path does the lookup, the verification, - * the filter, the limiter and the routing, and at most two writes per - * event; no other I/O. + * the filter, the limiter and the routing, at most two writes per event and, + * for a routed event, the dispatch of one message; no other I/O. + * + * A dispatch that fails (e.g. the transport is down) does not fail the + * delivery: the event stays `routed` without process instance, where the + * catch-up of routed events picks it up later, and one `warning` line on + * the channel `webhook` names slug, event id, delivery id and the class of + * the failure (never its message, which may name the transport's DSN). */ final readonly class WebhookIntake { @@ -88,6 +101,9 @@ /** The `info` line of an event the intake ignored or routed. */ public const string DECISION_MESSAGE = 'Webhook event {status}.'; + /** The `warning` line of a routed event whose start message could not be dispatched. */ + public const string START_NOT_QUEUED_MESSAGE = 'Webhook event routed, its process start not queued.'; + private const int MAX_LOGGED_LENGTH = 255; public function __construct( @@ -100,6 +116,7 @@ public function __construct( private EventFilter $filter, private ActorRateLimiter $actorRateLimiter, private EventRouter $router, + private MessageBusInterface $bus, private LoggerInterface $webhookLogger, #[Autowire(param: 'dmstr_webhook.body_cap')] private int $defaultBodyCap, @@ -209,9 +226,33 @@ private function accept(WebhookEndpoint $endpoint, RemoteEvent $event, string $s } $routeId = $route?->getId()->toRfc4122(); - $this->events->transition($eventId, WebhookEvent::STATUS_ROUTED, null, $routeId); + $routed = $this->events->transition($eventId, WebhookEvent::STATUS_ROUTED, null, $routeId); + + $disposition = $this->decided($request, $endpoint, new EventDisposition($type, $dedupeKey, $eventId, WebhookEvent::STATUS_ROUTED, route: $routeId)); + if ($routed) { + $this->queueStart($request, $endpoint, $eventId); + } + + return $disposition; + } - return $this->decided($request, $endpoint, new EventDisposition($type, $dedupeKey, $eventId, WebhookEvent::STATUS_ROUTED, route: $routeId)); + /** + * Dispatches the {@see StartProcess} message of an event that became + * `routed`. A failed dispatch leaves the event `routed` for the catch-up + * and writes one `warning` line; the delivery is accepted all the same. + */ + private function queueStart(Request $request, WebhookEndpoint $endpoint, Uuid $eventId): void + { + try { + $this->bus->dispatch(new StartProcess($eventId->toRfc4122())); + } catch (\Throwable $e) { + $this->webhookLogger->warning(self::START_NOT_QUEUED_MESSAGE, [ + 'slug' => $endpoint->getSlug(), + 'event_id' => $eventId->toRfc4122(), + 'delivery_id' => self::deliveryId($request), + 'exception_class' => get_debug_type($e), + ]); + } } /** The `info` line of an ignored or routed event; never the payload. */ @@ -313,3 +354,4 @@ private static function clip(string $value): string // - revised 2026-12-03 (endpoint handle request attribute for adapters) // - revised 2026-12-03 (endpoint modes: filter, insert with final status, rate limit per actor, routing, hand-off only in mode handler) // - revised 2026-12-05 (references of the event context passed to the insert) +// - revised 2026-12-05 (process start: one StartProcess message per routed event, a failed dispatch only logged) diff --git a/src/Process/Flowable/FlowableProcessEngine.php b/src/Process/Flowable/FlowableProcessEngine.php index 04032b4..d1140b5 100644 --- a/src/Process/Flowable/FlowableProcessEngine.php +++ b/src/Process/Flowable/FlowableProcessEngine.php @@ -41,7 +41,10 @@ * - engine ({@see FlowableApiException} by its status): 404 → * `definition_not_deployed` for a start (the engine knows no definition of * the key), `engine_error` for the other calls; 422 (the engine answered - * 400) → `engine_rejected`; 504 → `engine_unreachable`; 502 (any other + * 400) → `engine_rejected`, except for a start when the engine lists no + * definition of the key (Flowable answers the start of an undeployed key + * with 400, not 404): `definition_not_deployed`; 504 → + * `engine_unreachable`; 502 (any other * engine status, 401 and 403 included: flowable-bundle tells them apart * only by message text, which is not parsed here) and anything else → * `engine_error`; @@ -98,16 +101,49 @@ public function start(?ApiConfiguration $connection, string $processDefinitionKe $client = $this->client($connection, $call); return $this->call($call, static function () use ($client, $processDefinitionKey, $businessKey, $variables, $call): string { - $instance = $client->startProcessInstance([ - 'processDefinitionKey' => $processDefinitionKey, - 'businessKey' => $businessKey, - 'variables' => self::flowableVariables($variables), - ]); + try { + $instance = $client->startProcessInstance([ + 'processDefinitionKey' => $processDefinitionKey, + 'businessKey' => $businessKey, + 'variables' => self::flowableVariables($variables), + ]); + } catch (FlowableApiException $e) { + if (422 !== $e->getStatusCode()) { + throw $e; + } + throw ProcessEngineException::of(self::rejectedStart($client, $processDefinitionKey), $call); + } return self::nonEmptyString($instance['id'] ?? null) ?? throw ProcessEngineException::of(ProcessEngineFailure::EngineError, $call); }); } + /** + * Why the engine rejected a start (it answered 400, which arrives as + * 422). Flowable answers the start of a key without deployed definition + * with 400, not 404, so the definitions of the key are listed; the + * message text is never parsed. No definition of the key → + * `definition_not_deployed`; a definition, an answer of another shape or + * a failure of the lookup → `engine_rejected`. + */ + private static function rejectedStart(FlowableClientInterface $client, string $processDefinitionKey): ProcessEngineFailure + { + try { + $envelope = $client->listProcessDefinitions([ + 'key' => $processDefinitionKey, + 'latest' => 'true', + 'size' => 1, + ]); + } catch (\Throwable) { + return ProcessEngineFailure::EngineRejected; + } + if (!\is_array($envelope['data'] ?? null)) { + return ProcessEngineFailure::EngineRejected; + } + + return null === self::definition($envelope['data'][0] ?? null) ? ProcessEngineFailure::DefinitionNotDeployed : ProcessEngineFailure::EngineRejected; + } + public function findInstances(?ApiConfiguration $connection, string $processDefinitionKey, string $businessKey): array { $call = ProcessEngineCall::FindInstances; diff --git a/src/Process/Start/ProcessStartFailedException.php b/src/Process/Start/ProcessStartFailedException.php new file mode 100644 index 0000000..77f84d4 --- /dev/null +++ b/src/Process/Start/ProcessStartFailedException.php @@ -0,0 +1,44 @@ +.` + * + * Never with a previous exception and never with the text of the original + * failure: Messenger keeps the message of a failed handler in its log + * records and, as `ErrorDetailsStamp`, in the retried envelope and the + * failure transport; the text of an engine, a transport or the database may + * carry a host, a URL, a secret or parts of a request. + * + * Retried by the transport's retry strategy unless the category is + * unrecoverable: then {@see self::of()} returns an + * {@see UnrecoverableProcessStartException}, which Messenger does not retry. + */ +class ProcessStartFailedException extends \RuntimeException +{ + public const string MESSAGE = 'Process start failed: %s.'; + + public function __construct(public readonly string $category) + { + parent::__construct(\sprintf(self::MESSAGE, $category)); + } + + /** The failure of $category: unrecoverable or retryable ({@see ProcessStartFailure::isRetryable()}). */ + public static function of(string $category): self + { + return ProcessStartFailure::isRetryable($category) ? new self($category) : new UnrecoverableProcessStartException($category); + } + + public function isRetryable(): bool + { + return ProcessStartFailure::isRetryable($this->category); + } +} diff --git a/src/Process/Start/ProcessStartFailure.php b/src/Process/Start/ProcessStartFailure.php new file mode 100644 index 0000000..ae13f64 --- /dev/null +++ b/src/Process/Start/ProcessStartFailure.php @@ -0,0 +1,62 @@ +value, + ProcessEngineFailure::ConnectionWrongType->value, + ProcessEngineFailure::ConnectionInactive->value, + ProcessEngineFailure::ConnectionInvalid->value, + ProcessEngineFailure::SecretUnreadable->value, + ProcessEngineFailure::EnginePortMissing->value, + ProcessEngineFailure::DefinitionNotDeployed->value, + ProcessEngineFailure::EngineRejected->value, + self::ROUTE_MISSING, + self::ENDPOINT_NOT_PROCESS, + ]; + + private function __construct() + { + } + + public static function isRetryable(string $category): bool + { + return !\in_array($category, self::UNRECOVERABLE, true); + } +} diff --git a/src/Process/Start/ProcessStartFailureListener.php b/src/Process/Start/ProcessStartFailureListener.php new file mode 100644 index 0000000..2486a32 --- /dev/null +++ b/src/Process/Start/ProcessStartFailureListener.php @@ -0,0 +1,85 @@ +getEnvelope()->getMessage(); + if (!$message instanceof StartProcess || $event->willRetry() || !Uuid::isValid($message->eventId)) { + return; + } + + $category = self::category($event->getThrowable()); + $context = ['event_id' => $message->eventId, 'category' => $category]; + try { + $failed = $this->events->failStart(Uuid::fromString($message->eventId), $category); + } catch (\Throwable $exception) { + $this->webhookLogger->error(self::NOT_SET_MESSAGE, $context + ['exception_class' => get_debug_type($exception)]); + + return; + } + if ($failed) { + $this->webhookLogger->error(self::FAILED_MESSAGE, $context); + } + } + + /** + * The reason category of a failed start: the one of the + * {@see ProcessStartFailedException} (also wrapped by Messenger), else + * `start_failed`. + */ + public static function category(\Throwable $throwable): string + { + if ($throwable instanceof ProcessStartFailedException) { + return $throwable->category; + } + if ($throwable instanceof HandlerFailedException) { + foreach ($throwable->getWrappedExceptions(ProcessStartFailedException::class, true) as $wrapped) { + if ($wrapped instanceof ProcessStartFailedException) { + return $wrapped->category; + } + } + } + + return ProcessStartFailure::START_FAILED; + } +} diff --git a/src/Process/Start/ProcessStartOutcome.php b/src/Process/Start/ProcessStartOutcome.php new file mode 100644 index 0000000..a9f4c83 --- /dev/null +++ b/src/Process/Start/ProcessStartOutcome.php @@ -0,0 +1,39 @@ + [kind variable, + * id variable]; the role names the `_kind` and `_id` columns + * of `webhook_event`. + */ + public const array REFERENCES = [ + 'project' => ['webhookProjectKind', 'webhookProjectId'], + 'target' => ['webhookTargetKind', 'webhookTargetId'], + 'note' => ['webhookNoteKind', 'webhookNoteId'], + 'discussion' => ['webhookDiscussionKind', 'webhookDiscussionId'], + ]; + + private function __construct() + { + } + + /** + * Every name the bundle sets itself; a route variable of one of these + * names is dropped. + * + * @return list + */ + public static function reservedNames(): array + { + return [self::EVENT_ID, self::ENDPOINT_ID, self::AGENT, ...array_merge(...array_values(self::REFERENCES))]; + } + + /** + * @param array $references the reference columns of the event row (`_kind`, `_id`), as fetched + * @param array $routeVariables the static variables of the route + * + * @return array + */ + public static function of(string $eventId, string $endpointId, array $references, ?string $agent, array $routeVariables): array + { + $variables = []; + foreach ($routeVariables as $name => $value) { + if (\is_string($name) && '' !== $name && \is_scalar($value)) { + $variables[$name] = $value; + } + } + $variables = array_diff_key($variables, array_flip(self::reservedNames())); + + $variables[self::EVENT_ID] = $eventId; + $variables[self::ENDPOINT_ID] = $endpointId; + foreach (self::REFERENCES as $role => [$kindName, $idName]) { + $kind = $references[$role.'_kind'] ?? null; + $id = $references[$role.'_id'] ?? null; + // A role is set only as a pair, as the intake stores it. + if (\is_string($kind) && '' !== $kind && \is_string($id) && '' !== $id) { + $variables[$kindName] = $kind; + $variables[$idName] = $id; + } + } + if (null !== $agent && '' !== $agent) { + $variables[self::AGENT] = $agent; + } + + return $variables; + } +} diff --git a/src/Process/Start/ProcessStarter.php b/src/Process/Start/ProcessStarter.php new file mode 100644 index 0000000..f0247ba --- /dev/null +++ b/src/Process/Start/ProcessStarter.php @@ -0,0 +1,218 @@ +webhookLogger->debug(self::NOTHING_TO_DO_MESSAGE, ['event_id' => null]); + + return ProcessStartOutcome::NothingToDo; + } + $context = ['event_id' => $id->toRfc4122()]; + + $event = $this->events->startCandidate($id); + if (null === $event || WebhookEvent::STATUS_ROUTED !== $event['status'] || null !== $event['process_instance_id']) { + $this->webhookLogger->debug(self::NOTHING_TO_DO_MESSAGE, $context + ['status' => $event['status'] ?? null]); + + return ProcessStartOutcome::NothingToDo; + } + + $claimedAt = $this->clock?->now() ?? new \DateTimeImmutable(); + if (!$this->events->claimStart($id, $claimedAt, $this->leaseSeconds)) { + $this->webhookLogger->debug(self::CLAIM_LOST_MESSAGE, $context); + + return ProcessStartOutcome::ClaimLost; + } + + try { + return $this->startClaimed($id, $event, $context); + } catch (\Throwable $e) { + $failure = match (true) { + $e instanceof ProcessStartFailedException => $e, + $e instanceof ProcessEngineException => ProcessStartFailedException::of($e->reason->value), + default => ProcessStartFailedException::of(ProcessStartFailure::START_FAILED), + }; + try { + $this->events->releaseStart($id, $claimedAt); + } catch (\Throwable) { + // The claim expires after the lease. + } + $this->webhookLogger->warning(self::FAILED_MESSAGE, $context + [ + 'category' => $failure->category, + 'retryable' => $failure->isRetryable(), + 'exception_class' => get_debug_type($e), + ]); + + throw $failure; + } + } + + /** + * Steps 3 to 6 of the class comment, for a claimed event. + * + * @param array $event the columns of {@see EventStore::startCandidate()} + * @param array{event_id: string, slug?: string} $context the log context + */ + private function startClaimed(Uuid $id, array $event, array $context): ProcessStartOutcome + { + $endpoint = $event['endpoint_id'] instanceof Uuid ? $this->entityManager->find(WebhookEndpoint::class, $event['endpoint_id']) : null; + if (!$endpoint instanceof WebhookEndpoint) { + // Deleted with its events since the read. + $this->webhookLogger->debug(self::NOTHING_TO_DO_MESSAGE, $context); + + return ProcessStartOutcome::NothingToDo; + } + $context['slug'] = $endpoint->getSlug(); + if (!$endpoint->isProcessMode()) { + throw ProcessStartFailedException::of(ProcessStartFailure::ENDPOINT_NOT_PROCESS); + } + $route = $this->route($event['route'] ?? null, $endpoint); + + $connection = $endpoint->getFlowableConnection(); + $key = $route->getProcessDefinitionKey(); + $businessKey = (string) $event['dedupe_key']; + $endpointId = $endpoint->getId()->toRfc4122(); + + $instanceId = null; + foreach ($this->engine->findInstances($connection, $key, $businessKey) as $instance) { + if ($endpointId === $instance->variable(ProcessStartVariables::ENDPOINT_ID)) { + $instanceId = $instance->id; + break; + } + } + $found = null !== $instanceId; + $instanceId ??= $this->engine->start( + $connection, + $key, + $businessKey, + ProcessStartVariables::of($id->toRfc4122(), $endpointId, $event, $route->getAgent(), $route->getVariables()), + ); + + $context['instance_id'] = $instanceId; + if (!$this->events->recordStart($id, $instanceId)) { + $this->webhookLogger->warning(self::NOT_RECORDED_MESSAGE, $context); + + return ProcessStartOutcome::NotRecorded; + } + + $this->webhookLogger->info($found ? self::FOUND_MESSAGE : self::STARTED_MESSAGE, $context); + + return $found ? ProcessStartOutcome::FoundExisting : ProcessStartOutcome::Started; + } + + /** + * The route the intake matched, of this endpoint. + * + * @throws ProcessStartFailedException route_missing + */ + private function route(mixed $routeId, WebhookEndpoint $endpoint): WebhookRoute + { + $route = \is_string($routeId) && Uuid::isValid($routeId) ? $this->entityManager->find(WebhookRoute::class, Uuid::fromString($routeId)) : null; + if (!$route instanceof WebhookRoute || !$route->getEndpoint()?->getId()->equals($endpoint->getId())) { + throw ProcessStartFailedException::of(ProcessStartFailure::ROUTE_MISSING); + } + + return $route; + } +} diff --git a/src/Process/Start/StartProcess.php b/src/Process/Start/StartProcess.php new file mode 100644 index 0000000..56d451b --- /dev/null +++ b/src/Process/Start/StartProcess.php @@ -0,0 +1,26 @@ +starter->start($message->eventId); + } +} diff --git a/src/Process/Start/UnrecoverableProcessStartException.php b/src/Process/Start/UnrecoverableProcessStartException.php new file mode 100644 index 0000000..a2024bc --- /dev/null +++ b/src/Process/Start/UnrecoverableProcessStartException.php @@ -0,0 +1,19 @@ + enabled flag; `passthrough` is enabled @@ -100,6 +118,15 @@ final class WebhookBundle extends AbstractBundle * FrameworkBundle's `http_client` unless the host defines this id itself. */ public const string REPLY_HTTP_CLIENT = 'dmstr_webhook.reply_http_client'; + /** Name of the Messenger transport of the process start ({@see StartProcess}). */ + public const string TRANSPORT = 'webhook'; + /** + * DSN of the transport {@see self::TRANSPORT} when the application + * defines none: in memory, so the container builds without + * symfony/doctrine-messenger and the start never runs in the request; + * not durable, see the class comment. + */ + public const string DEFAULT_TRANSPORT_DSN = 'in-memory://'; protected string $extensionAlias = 'dmstr_webhook'; @@ -162,6 +189,15 @@ public function prependExtension(ContainerConfigurator $container, ContainerBuil ], ]); + // The transport of the process start and the routing of its message + // (FrameworkBundle is always there; the check keeps a bare builder + // working). The application's own configuration comes later and wins. + if ($builder->hasExtension('framework')) { + $builder->prependExtensionConfig('framework', [ + 'messenger' => self::messengerConfig($builder->getExtensionConfig('framework')), + ]); + } + // Dedicated log channel; services receive it as `LoggerInterface // $webhookLogger` (named autowiring alias of MonologBundle) or with // #[WithMonologChannel('webhook')]. @@ -219,6 +255,34 @@ static function (ChildDefinition $definition, AsWebhookAdapter $attribute): void $services->alias(ProcessEngineInterface::class, $engine); } + /** + * The prepended `framework.messenger` configuration: {@see StartProcess} + * routed to {@see self::TRANSPORT}, and the transport itself with + * {@see self::DEFAULT_TRANSPORT_DSN} only when none of the given + * `framework` configurations (the application's, loaded before the + * prepend) names a transport {@see self::TRANSPORT}. Both are keyed maps + * that FrameworkBundle merges by key, later configurations winning: the + * application's routing of other messages keeps the routing of + * {@see StartProcess}, and the application may route it elsewhere. + * + * @param list> $frameworkConfigs + * + * @return array{routing: array, transports?: array} + */ + public static function messengerConfig(array $frameworkConfigs): array + { + $messenger = ['routing' => [StartProcess::class => self::TRANSPORT]]; + foreach ($frameworkConfigs as $config) { + $transports = $config['messenger']['transports'] ?? null; + if (\is_array($transports) && \array_key_exists(self::TRANSPORT, $transports)) { + return $messenger; + } + } + $messenger['transports'] = [self::TRANSPORT => self::DEFAULT_TRANSPORT_DSN]; + + return $messenger; + } + /** * Whether FlowableBundle is registered in the kernel (parameter * `kernel.bundles`): only then are its client locator and the channel @@ -264,3 +328,4 @@ public function build(ContainerBuilder $container): void // - revised 2026-12-03 (Basecamp 4 adapter in the class doc) // - revised 2026-12-04 (GitLab reply client: conditional registration, reply transport) // - revised 2026-12-05 (process engine port: Flowable implementation only with FlowableBundle, missing implementation otherwise) +// - revised 2026-12-05 (process start: Messenger transport and routing prepended, class doc) diff --git a/tests/Integration/ContainerVariantsTest.php b/tests/Integration/ContainerVariantsTest.php index bf6d106..6129b2f 100644 --- a/tests/Integration/ContainerVariantsTest.php +++ b/tests/Integration/ContainerVariantsTest.php @@ -18,16 +18,30 @@ use Dmstr\Webhook\Process\Flowable\FlowableProcessEngine; use Dmstr\Webhook\Process\MissingProcessEngine; use Dmstr\Webhook\Process\ProcessEngineInterface; +use Dmstr\Webhook\Process\Start\ProcessStarter; +use Dmstr\Webhook\Process\Start\ProcessStartFailureListener; +use Dmstr\Webhook\Process\Start\StartProcess; +use Dmstr\Webhook\Process\Start\StartProcessHandler; use Dmstr\Webhook\Reply\Gitlab\GitlabReplyClient; use Dmstr\Webhook\Tests\Kernel\TestKernel; use Dmstr\Webhook\Tests\Support\FakeProcessEngine; +use Dmstr\Webhook\Tests\Support\HostTestMessage; +use Dmstr\Webhook\Tests\Support\TransportDrain; use Dmstr\Webhook\WebhookBundle; use Monolog\Logger; +use PHPUnit\Framework\Attributes\DataProvider; use Psr\Clock\ClockInterface; use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase; use Symfony\Component\Clock\MockClock; +use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\HttpClient\MockHttpClient; use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\Messenger\Event\WorkerMessageFailedEvent; +use Symfony\Component\Messenger\MessageBusInterface; +use Symfony\Component\Messenger\Stamp\HandledStamp; +use Symfony\Component\Messenger\Stamp\ReceivedStamp; +use Symfony\Component\Messenger\Transport\InMemory\InMemoryTransport; +use Symfony\Component\Messenger\Transport\Sync\SyncTransport; use Symfony\Component\Webhook\Exception\RejectWebhookException; use Symfony\Contracts\HttpClient\HttpClientInterface; @@ -52,7 +66,13 @@ * - the process engine port is the Flowable implementation only with * FlowableBundle registered, the missing implementation without it although * dmstr/flowable-bundle is installed, and the host's own engine where the - * host defines one. + * host defines one; + * - the start message of a routed event goes to the transport `webhook` + * and is not handled in the request; a received one is handled by the + * bundle's handler, the failure listener and the starter's log channel + * are wired; where the host defines no transport `webhook`, the bundle's + * default (in memory) takes the start message while the host's routing of + * its own messages holds; in no variant is the transport synchronous. */ final class ContainerVariantsTest extends KernelTestCase { @@ -196,6 +216,100 @@ public function testTheHostReplacesTheReplyTransport(): void self::assertInstanceOf(MockHttpClient::class, self::transportOf($container->get(GitlabReplyClient::class))); } + public function testTheStartMessageIsSentToTheTransportWebhookAndNotHandled(): void + { + self::bootKernel(); + $container = self::getContainer(); + $transport = self::inMemory($container->get(TestKernel::TRANSPORT_SERVICE)); + + $eventId = '0193a5b0-0000-7000-8000-0000000000aa'; + $envelope = self::bus()->dispatch(new StartProcess($eventId)); + + self::assertSame([], $envelope->all(HandledStamp::class), 'not handled in the request'); + self::assertSame([$eventId], TransportDrain::eventIds($transport->getSent())); + self::assertSame([], $transport->getAcknowledged()); + } + + public function testTheWorkerSideIsWired(): void + { + self::bootKernel(); + $container = self::getContainer(); + + // A received message is handled: the handler of the bundle runs the + // starter, which has nothing to do for an invalid id (no database). + $envelope = self::bus()->dispatch(new StartProcess('not-a-uuid'), [new ReceivedStamp(TestKernel::MESSENGER_TRANSPORT)]); + $handled = $envelope->all(HandledStamp::class); + self::assertCount(1, $handled); + self::assertInstanceOf(HandledStamp::class, $handled[0]); + self::assertStringStartsWith(StartProcessHandler::class, $handled[0]->getHandlerName()); + + // The failure listener, after Messenger's retry listener. + $dispatcher = $container->get('event_dispatcher'); + self::assertInstanceOf(EventDispatcherInterface::class, $dispatcher); + $listeners = array_filter($dispatcher->getListeners(WorkerMessageFailedEvent::class), static fn (mixed $listener): bool => \is_array($listener) && $listener[0] instanceof ProcessStartFailureListener); + self::assertCount(1, $listeners); + self::assertSame(0, $dispatcher->getListenerPriority(WorkerMessageFailedEvent::class, array_values($listeners)[0])); + + // The starter logs on the channel `webhook`. + $logger = new \ReflectionProperty(ProcessStarter::class, 'webhookLogger')->getValue($container->get(ProcessStarter::class)); + self::assertInstanceOf(Logger::class, $logger); + self::assertSame(WebhookBundle::LOG_CHANNEL, $logger->getName()); + } + + public function testTheBundlesDefaultTransportWhereTheHostDefinesNone(): void + { + self::bootKernel(['environment' => TestKernel::ENV_DEFAULT_TRANSPORT]); + $container = self::getContainer(); + $transport = self::inMemory($container->get(TestKernel::TRANSPORT_SERVICE)); + $host = self::inMemory($container->get(TestKernel::HOST_TRANSPORT_SERVICE)); + self::assertNotSame($transport, $host); + self::assertSame('in-memory://', WebhookBundle::DEFAULT_TRANSPORT_DSN); + + self::bus()->dispatch(new HostTestMessage()); + self::bus()->dispatch(new StartProcess('0193a5b0-0000-7000-8000-0000000000bb')); + + // The host's routing of its own message and the bundle's routing + // of the start message both hold. + self::assertCount(1, $host->getSent()); + self::assertInstanceOf(HostTestMessage::class, $host->getSent()[0]->getMessage()); + self::assertSame(['0193a5b0-0000-7000-8000-0000000000bb'], TransportDrain::eventIds($transport->getSent())); + self::assertCount(1, $transport->getSent()); + } + + /** @return iterable */ + public static function variants(): iterable + { + foreach ([TestKernel::ENV_WITH_VOTER, TestKernel::ENV_NO_CLOCK, TestKernel::ENV_MINIMAL, TestKernel::ENV_FLOWABLE, TestKernel::ENV_FAKE_ENGINE, TestKernel::ENV_DEFAULT_TRANSPORT] as $environment) { + yield $environment => [$environment]; + } + } + + #[DataProvider('variants')] + public function testTheTransportWebhookIsNeverSynchronous(string $environment): void + { + self::bootKernel(['environment' => $environment]); + + $transport = self::getContainer()->get(TestKernel::TRANSPORT_SERVICE); + self::assertNotInstanceOf(SyncTransport::class, $transport); + self::assertInstanceOf(InMemoryTransport::class, $transport); + self::assertInstanceOf(ProcessStarter::class, self::getContainer()->get(ProcessStarter::class)); + } + + private static function bus(): MessageBusInterface + { + $bus = self::getContainer()->get('messenger.default_bus'); + self::assertInstanceOf(MessageBusInterface::class, $bus); + + return $bus; + } + + private static function inMemory(mixed $transport): InMemoryTransport + { + self::assertInstanceOf(InMemoryTransport::class, $transport); + + return $transport; + } + private static function transportOf(mixed $client): HttpClientInterface { self::assertInstanceOf(GitlabReplyClient::class, $client); @@ -236,3 +350,4 @@ private static function signed(string $id, int $timestamp): Request // - revised 2026-12-03 (Basecamp 4 adapter in the minimal variant) // - revised 2026-12-04 (GitLab reply client: library absent, adapter off, default and host transport, minimal without http_client) // - revised 2026-12-05 (process engine port: Flowable with FlowableBundle, missing without it and in the minimal variant, the host's fake) +// - revised 2026-12-06 (process start: routing to the transport webhook, handler and failure listener wired, the bundle's default transport, never synchronous) diff --git a/tests/Integration/Intake/IntakeMatrixDatabaseTestCase.php b/tests/Integration/Intake/IntakeMatrixDatabaseTestCase.php index b98a367..5c18e68 100644 --- a/tests/Integration/Intake/IntakeMatrixDatabaseTestCase.php +++ b/tests/Integration/Intake/IntakeMatrixDatabaseTestCase.php @@ -10,11 +10,14 @@ use ApiPlatform\Symfony\Bundle\Test\Client; use Dmstr\Webhook\Model\EndpointMode; use Dmstr\Webhook\Tests\Kernel\TestDatabase; +use Dmstr\Webhook\Tests\Kernel\TestKernel; use Dmstr\Webhook\Tests\Support\IntakeCase; use Dmstr\Webhook\Tests\Support\IntakeHarness; use Dmstr\Webhook\Tests\Support\RecordingDeliveryHandler; +use Dmstr\Webhook\Tests\Support\TransportDrain; use Doctrine\DBAL\Connection; use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\Messenger\Transport\InMemory\InMemoryTransport; /** * Base of the intake matrix tests against the database (CI only; a @@ -77,9 +80,11 @@ protected function check(IntakeCase $case, EndpointMode $mode, string $label = ' self::assertSame($expected->httpStatus, $response->getStatusCode(), $label.': '.$response->getContent()); $rows = $this->eventRows($slug); $delivered = RecordingDeliveryHandler::deliveriesOf($slug); + $queued = $this->queuedStarts(); if (null === $expected->status) { self::assertSame([], $rows, $label.': no event row'); self::assertSame([], $delivered, $label.': nothing handed over'); + self::assertSame([], $queued, $label.': no start message'); return; } @@ -90,6 +95,9 @@ protected function check(IntakeCase $case, EndpointMode $mode, string $label = ' self::assertSame($expected->reason, $row['reason'], $label.': reason'); self::assertSame(null === $expected->route ? null : ($routes[$expected->route] ?? 'unknown route '.$expected->route), $row['route'], $label.': route'); self::assertSame($case->body, $row['payload'], $label.': raw payload'); + // One start message on the transport `webhook` for a routed event, + // none otherwise; nothing consumes it here. + self::assertSame('routed' === $expected->status ? [TestDatabase::uuid($this->dbal(), $row['id'])] : [], $queued, $label.': start message'); if ($expected->handedOver) { self::assertCount(1, $delivered, $label.': handed over once'); @@ -105,6 +113,21 @@ protected function check(IntakeCase $case, EndpointMode $mode, string $label = ' self::assertCount($expected->handedOver ? 1 : 0, RecordingDeliveryHandler::deliveriesOf($slug), $label.': duplicate, no second hand-over'); } + /** + * The event ids of the start messages the last request sent to the + * transport `webhook` (in memory; the test client resets it before the + * next request). + * + * @return list + */ + protected function queuedStarts(): array + { + $transport = $this->client->getContainer()->get(TestKernel::TRANSPORT_SERVICE); + self::assertInstanceOf(InMemoryTransport::class, $transport); + + return TransportDrain::eventIds($transport->getSent()); + } + /** * The endpoint and routes of a case, created through the admin API; its * slug and the route ids by name. @@ -241,3 +264,4 @@ private static function cleanUp(): void } // - revised 2026-12-03 (steps of the shared sequence runner FixtureSequenceTests) +// - revised 2026-12-05 (one start message on the transport per routed event) diff --git a/tests/Integration/Process/ProcessStartDatabaseTest.php b/tests/Integration/Process/ProcessStartDatabaseTest.php new file mode 100644 index 0000000..1739c2a --- /dev/null +++ b/tests/Integration/Process/ProcessStartDatabaseTest.php @@ -0,0 +1,566 @@ + 'flowable', 'endpoint_type' => 'rest', 'base_url' => 'https://flowable.example.com', 'auth_type' => 'basic']; + + private Application $application; + private FakeProcessEngine $engine; + private TransportDrain $drain; + private string $logFile; + private int $logOffset; + + protected function setUp(): void + { + self::cleanUp(); + $kernel = self::bootKernel(['environment' => TestKernel::ENV_FAKE_ENGINE]); + self::assertInstanceOf(TestKernel::class, $kernel); + $this->application = new Application($kernel); + $engine = self::getContainer()->get(FakeProcessEngine::class); + self::assertInstanceOf(FakeProcessEngine::class, $engine); + $this->engine = $engine; + $this->drain = new TransportDrain(self::getContainer()); + $this->logFile = $kernel->logFile(); + clearstatcache(); + $this->logOffset = is_file($this->logFile) ? (int) filesize($this->logFile) : 0; + } + + protected function tearDown(): void + { + self::cleanUp(); + parent::tearDown(); + } + + /** @return iterable */ + public static function mentions(): iterable + { + yield 'mention on a merge request' => ['note-merge-request-mention', Reference::MERGE_REQUEST, GitlabFixtures::MERGE_REQUEST_IID]; + yield 'mention on an issue' => ['note-issue-mention', Reference::ISSUE, GitlabFixtures::ISSUE_IID]; + } + + #[DataProvider('mentions')] + public function testTheIntakeQueuesAndTheWorkerStartsOneInstanceWithTheAllowedVariables(string $fixture, string $targetKind, int $targetIid): void + { + $connection = $this->connection('main'); + $endpointId = $this->endpoint('mention', $connection); + $routeId = $this->route('mention', ['language=en', 'depth=2', ProcessStartVariables::EVENT_ID.'=spoofed']); + + $eventId = $this->receive('mention', $fixture); + + // The request only queued the start. + self::assertSame(0, $this->engine->calls()); + self::assertSame(WebhookEvent::STATUS_ROUTED, $this->event($eventId)['status']); + self::assertSame([$eventId], $this->drain->sentEventIds()); + + self::assertSame(1, $this->drain->run()); + + self::assertSame([], $this->drain->failures); + self::assertCount(1, $this->engine->starts); + $start = $this->engine->starts[0]; + $event = $this->event($eventId); + self::assertSame(WebhookEvent::STATUS_STARTED, $event['status']); + self::assertNull($event['reason']); + self::assertSame($routeId, $event['route']); + self::assertSame($start['instanceId'], $event['process_instance_id']); + self::assertSame($connection->getId()->toRfc4122(), $start['connection']); + self::assertSame(self::KEY, $start['key']); + self::assertSame($event['dedupe_key'], $start['businessKey']); + + $references = EventReferences::gitlabNote($fixture, $targetKind, $targetIid); + self::assertSame([ + 'language' => 'en', + 'depth' => 2, + 'webhookEventId' => $eventId, + 'webhookEndpointId' => $endpointId, + 'webhookProjectKind' => $references['project_kind'], + 'webhookProjectId' => $references['project_id'], + 'webhookTargetKind' => $references['target_kind'], + 'webhookTargetId' => $references['target_id'], + 'webhookNoteKind' => $references['note_kind'], + 'webhookNoteId' => $references['note_id'], + 'webhookDiscussionKind' => $references['discussion_kind'], + 'webhookDiscussionId' => $references['discussion_id'], + 'webhookAgent' => self::AGENT, + ], $start['variables']); + EventReferences::assertNoGitlabText($start['variables'], $fixture); + self::assertSame(1, $this->engine->calls(ProcessEngineCall::FindInstances)); + self::assertSame(1, $this->engine->calls(ProcessEngineCall::Start)); + } + + public function testTheSameDeliveryAResendAndASecondMessageStartOneInstance(): void + { + $this->endpoint('once', $this->connection('once')); + $this->route('once'); + + $eventId = $this->receive('once', 'note-merge-request-mention'); + self::assertSame(202, $this->intake('once', 'note-merge-request-mention')); + self::assertSame(202, $this->intake('once', 'note-merge-request-mention-resend')); + self::assertSame([$eventId], $this->drain->sentEventIds(), 'one message for the three deliveries'); + $this->drain->run(); + + // The same message again, e.g. from a catch-up or a redelivery. + $bus = self::getContainer()->get('messenger.default_bus'); + self::assertInstanceOf(MessageBusInterface::class, $bus); + $bus->dispatch(new StartProcess($eventId)); + self::assertSame(1, $this->drain->run()); + + self::assertCount(1, $this->engine->starts); + self::assertSame(1, $this->engine->calls(ProcessEngineCall::Start)); + self::assertSame(WebhookEvent::STATUS_STARTED, $this->event($eventId)['status']); + self::assertSame($this->engine->starts[0]['instanceId'], $this->event($eventId)['process_instance_id']); + self::assertSame([], $this->drain->failures); + + // The starter itself: nothing to do for a started event. + self::assertSame(ProcessStartOutcome::NothingToDo, $this->starter()->start($eventId)); + self::assertSame(1, $this->engine->calls(ProcessEngineCall::Start)); + } + + public function testTheConsoleTwinQueuesTheSameStart(): void + { + $this->endpoint('console', $this->connection('console')); + $this->route('console'); + $fixture = 'note-merge-request-mention'; + $headers = []; + foreach (GitlabFixtures::headers($fixture) as $name => $value) { + $headers[] = $name.': '.$value; + } + $file = tempnam(sys_get_temp_dir(), 'webhook'); + self::assertIsString($file); + + try { + file_put_contents($file, GitlabFixtures::body($fixture)); + $deliver = $this->execute('webhook:deliver', ['slug' => self::PREFIX.'console', 'file' => $file, '--header' => $headers]); + } finally { + unlink($file); + } + + self::assertSame(Command::SUCCESS, $deliver->getStatusCode(), $deliver->getDisplay()); + self::assertSame(0, $this->engine->calls()); + $sent = $this->drain->sentEventIds(); + self::assertCount(1, $sent); + self::assertSame(1, $this->drain->run()); + self::assertSame(WebhookEvent::STATUS_STARTED, $this->event($sent[0])['status']); + self::assertCount(1, $this->engine->starts); + } + + public function testTwoEndpointsOnOneConnectionStartOneInstanceEach(): void + { + $connection = $this->connection('shared'); + $first = $this->endpoint('first', $connection); + $this->route('first'); + $second = $this->endpoint('second', $connection); + $this->route('second'); + + $firstEvent = $this->receive('first', 'note-merge-request-mention'); + $secondEvent = $this->receive('second', 'note-merge-request-mention'); + self::assertSame(2, $this->drain->run()); + + // Same connection, definition and business key: the endpoint + // variable tells the instances apart. + self::assertCount(2, $this->engine->starts); + self::assertSame($this->engine->starts[0]['businessKey'], $this->engine->starts[1]['businessKey']); + self::assertSame([$first, $second], array_map(static fn (array $start): mixed => $start['variables'][ProcessStartVariables::ENDPOINT_ID], $this->engine->starts)); + self::assertSame($this->engine->starts[0]['instanceId'], $this->event($firstEvent)['process_instance_id']); + self::assertSame($this->engine->starts[1]['instanceId'], $this->event($secondEvent)['process_instance_id']); + self::assertNotSame($this->event($firstEvent)['process_instance_id'], $this->event($secondEvent)['process_instance_id']); + } + + public function testAnInstanceStartedBeforeACrashIsFoundAndRecordedByTheRetry(): void + { + $this->endpoint('crash', $this->connection('crash')); + $this->route('crash'); + $this->engine->crashAfterNextStart(new \RuntimeException(self::MARKER)); + + $eventId = $this->receive('crash', 'note-merge-request-mention'); + $this->drain->run(); + + // The instance exists, the event does not know it yet; the claim was + // released, so the retry does not wait for the lease. + self::assertCount(1, $this->engine->instances()); + self::assertCount(1, $this->drain->failures); + self::assertTrue($this->drain->failures[0]['willRetry']); + $event = $this->event($eventId); + self::assertSame(WebhookEvent::STATUS_ROUTED, $event['status']); + self::assertNull($event['process_instance_id']); + self::assertNull($event['start_claimed_at']); + $this->assertNoMarker(); + + $this->drain->advance(); + self::assertSame(1, $this->drain->run()); + + self::assertCount(1, $this->engine->starts, 'found, not started again'); + $event = $this->event($eventId); + self::assertSame(WebhookEvent::STATUS_STARTED, $event['status']); + self::assertSame($this->engine->starts[0]['instanceId'], $event['process_instance_id']); + self::assertCount(1, $this->drain->failures); + $this->assertNoMarker(); + } + + public function testATransientFailureIsRetriedWithoutWaitingForTheLease(): void + { + $this->endpoint('transient', $this->connection('transient')); + $this->route('transient'); + $this->engine->failOn(ProcessEngineCall::Start, ProcessEngineFailure::EngineUnreachable, 2); + + $eventId = $this->receive('transient', 'note-merge-request-mention'); + $waited = 0; + $this->drain->run(); + for ($round = 0; $round < 2; ++$round) { + $this->drain->advance(60); + $waited += 60; + $this->drain->run(); + } + + self::assertLessThan(ProcessStarter::LEASE_SECONDS, $waited); + self::assertCount(2, $this->drain->failures); + foreach ($this->drain->failures as $failure) { + self::assertTrue($failure['willRetry']); + } + self::assertSame(3, $this->engine->calls(ProcessEngineCall::Start)); + self::assertCount(1, $this->engine->starts); + self::assertSame(WebhookEvent::STATUS_STARTED, $this->event($eventId)['status']); + } + + /** + * The failure, the category the event ends with, and the attempts until + * Messenger gives up (one for an unrecoverable category; one and three + * retries of the default retry strategy otherwise). + * + * @return iterable + */ + public static function failures(): iterable + { + yield 'no connection' => ['no connection', ProcessEngineFailure::ConnectionMissing->value, 1]; + yield 'connection of another type' => ['wrong type', ProcessEngineFailure::ConnectionWrongType->value, 1]; + yield 'inactive connection' => ['inactive', ProcessEngineFailure::ConnectionInactive->value, 1]; + yield 'definition not deployed' => ['not deployed', ProcessEngineFailure::DefinitionNotDeployed->value, 1]; + yield 'start rejected' => ['rejected', ProcessEngineFailure::EngineRejected->value, 1]; + yield 'engine unreachable' => ['unreachable', ProcessEngineFailure::EngineUnreachable->value, 4]; + yield 'engine error' => ['error', ProcessEngineFailure::EngineError->value, 4]; + } + + #[DataProvider('failures')] + public function testEveryFailureCategoryEndsFailedWithItsReason(string $failure, string $category, int $attempts): void + { + $connection = match ($failure) { + 'no connection' => null, + 'wrong type' => $this->connection('other', ['type' => 'example', 'endpoint_type' => 'rest']), + 'inactive' => $this->connection('inactive', active: false), + default => $this->connection('failing'), + }; + $this->endpoint('failing', $connection); + $this->route('failing'); + match ($failure) { + 'not deployed' => $this->engine->failOn(ProcessEngineCall::Start, ProcessEngineFailure::DefinitionNotDeployed), + 'rejected' => $this->engine->failOn(ProcessEngineCall::Start, ProcessEngineFailure::EngineRejected), + 'unreachable' => $this->engine->failOn(ProcessEngineCall::Start, ProcessEngineFailure::EngineUnreachable), + 'error' => $this->engine->failOn(ProcessEngineCall::Start, ProcessEngineFailure::EngineError), + default => null, + }; + + $eventId = $this->receive('failing', 'note-merge-request-mention'); + for ($round = 0; $round < 6; ++$round) { + $this->drain->run(); + $this->drain->advance(60); + } + + $event = $this->event($eventId); + self::assertSame(WebhookEvent::STATUS_FAILED, $event['status']); + self::assertSame($category, $event['reason']); + self::assertNull($event['process_instance_id']); + self::assertSame([], $this->engine->starts); + self::assertCount($attempts, $this->drain->failures); + foreach ($this->drain->failures as $index => $attempt) { + self::assertSame($index < $attempts - 1, $attempt['willRetry'], 'attempt '.($index + 1)); + self::assertInstanceOf(HandlerFailedException::class, $attempt['throwable']); + $wrapped = $attempt['throwable']->getPrevious(); + self::assertInstanceOf(ProcessStartFailedException::class, $wrapped); + self::assertSame($category, $wrapped->category); + self::assertSame(1 === $attempts, $wrapped instanceof UnrecoverableProcessStartException); + self::assertNull($wrapped->getPrevious()); + } + self::assertStringContainsString($category, $this->log()); + } + + public function testAnEventWhoseRouteWentAwayFailsAtOnce(): void + { + $this->endpoint('changed', $this->connection('changed')); + $routeId = $this->route('changed'); + $eventId = $this->receive('changed', 'note-merge-request-mention'); + // The route went away after the routing (and out of the identity map). + $this->dbal()->executeStatement('DELETE FROM webhook_route WHERE id = ?', [Uuid::fromString($routeId)], ['uuid']); + $this->entityManager()->clear(); + + $this->drain->run(); + + self::assertSame(WebhookEvent::STATUS_FAILED, $this->event($eventId)['status']); + self::assertSame(ProcessStartFailure::ROUTE_MISSING, $this->event($eventId)['reason']); + self::assertCount(1, $this->drain->failures); + self::assertSame(0, $this->engine->calls()); + } + + /** The test kernel's process start, for direct calls. */ + private function starter(): ProcessStarter + { + $starter = self::getContainer()->get(ProcessStarter::class); + self::assertInstanceOf(ProcessStarter::class, $starter); + + return $starter; + } + + /** + * A connection named with {@see self::PREFIX}, persisted. + * + * @param array $config + */ + private function connection(string $name, array $config = self::FLOWABLE, bool $active = true): ApiConfiguration + { + $connection = new ApiConfiguration() + ->setName(self::PREFIX.$name.'-'.bin2hex(random_bytes(3))) + ->setConfigJson($config) + ->setActive($active); + $entityManager = $this->entityManager(); + $entityManager->persist($connection); + $entityManager->flush(); + + return $connection; + } + + private function entityManager(): EntityManagerInterface + { + $entityManager = self::getContainer()->get('doctrine.orm.entity_manager'); + self::assertInstanceOf(EntityManagerInterface::class, $entityManager); + + return $entityManager; + } + + /** + * A GitLab endpoint in mode `process` as in the fixture matrix (the bot + * as own identity, the author of the fixtures on the allowlist), created + * with the console; its id (RFC 4122). + */ + private function endpoint(string $name, ?ApiConfiguration $connection): string + { + $input = [ + 'slug' => self::PREFIX.$name, + '--source-type' => 'gitlab', + '--mode' => 'process', + '--secret' => GitlabFixtures::TOKEN, + '--actor-id' => GitlabFixtures::BOT_ID, + '--actor-handle' => GitlabFixtures::BOT_HANDLE, + '--allowed-actor-ids' => GitlabFixtures::ANN_ID, + ]; + if (null !== $connection) { + $input['--flowable-connection'] = $connection->getId()->toRfc4122(); + } + $create = $this->execute('webhook:endpoint:create', $input); + self::assertSame(Command::SUCCESS, $create->getStatusCode(), $create->getDisplay()); + + return TestDatabase::endpointId($this->dbal(), self::PREFIX.$name); + } + + /** + * The one catch-all route of the endpoint, created with the console; + * its id (RFC 4122). + * + * @param list $variables + */ + private function route(string $endpoint, array $variables = []): string + { + $input = [ + 'name' => 'all', + '--endpoint' => self::PREFIX.$endpoint, + '--process-definition-key' => self::KEY, + '--agent' => self::AGENT, + ]; + if ([] !== $variables) { + $input['--variable'] = $variables; + } + $create = $this->execute('webhook:route:create', $input); + self::assertSame(Command::SUCCESS, $create->getStatusCode(), $create->getDisplay()); + + $id = $this->dbal()->fetchOne( + 'SELECT r.id FROM webhook_route r JOIN webhook_endpoint e ON e.id = r.endpoint_id WHERE e.slug = ?', + [self::PREFIX.$endpoint], + ); + self::assertNotFalse($id); + + return TestDatabase::uuid($this->dbal(), $id); + } + + /** Delivers a GitLab fixture through the kernel's intake; its one routed event (RFC 4122). */ + private function receive(string $endpoint, string $fixture): string + { + $outcome = $this->intakeService()->receive(self::request($endpoint, $fixture), self::PREFIX.$endpoint); + + self::assertSame(202, $outcome->statusCode()); + self::assertCount(1, $outcome->events); + $eventId = $outcome->events[0]->eventId; + self::assertNotNull($eventId); + self::assertSame(WebhookEvent::STATUS_ROUTED, $this->event($eventId->toRfc4122())['status']); + + return $eventId->toRfc4122(); + } + + /** Delivers a GitLab fixture through the kernel's intake; the HTTP status. */ + private function intake(string $endpoint, string $fixture): int + { + return $this->intakeService()->receive(self::request($endpoint, $fixture), self::PREFIX.$endpoint)->statusCode(); + } + + /** The request of a GitLab fixture, as the HTTP path hands it to the intake. */ + private static function request(string $endpoint, string $fixture): Request + { + $request = Request::create('/webhook/'.self::PREFIX.$endpoint, 'POST', server: ['REMOTE_ADDR' => '127.0.0.1'], content: GitlabFixtures::body($fixture)); + foreach (GitlabFixtures::headers($fixture) as $name => $value) { + $request->headers->set($name, $value); + } + + return $request; + } + + private function intakeService(): WebhookIntake + { + $intake = self::getContainer()->get(WebhookIntake::class); + self::assertInstanceOf(WebhookIntake::class, $intake); + + return $intake; + } + + /** + * The start columns of an event. + * + * @return array{status: string, reason: ?string, route: ?string, dedupe_key: string, process_instance_id: ?string, start_claimed_at: mixed} + */ + private function event(string $eventId): array + { + $row = $this->dbal()->fetchAssociative( + 'SELECT status, reason, route, dedupe_key, process_instance_id, start_claimed_at FROM webhook_event WHERE id = ?', + [Uuid::fromString($eventId)], + ['uuid'], + ); + self::assertIsArray($row, 'No event '.$eventId); + + /** @var array{status: string, reason: ?string, route: ?string, dedupe_key: string, process_instance_id: ?string, start_claimed_at: mixed} $row */ + return $row; + } + + /** The marker of the engine text is nowhere: not in an exception, a stamp of the transport or the log file. */ + private function assertNoMarker(): void + { + foreach ($this->drain->failures as $failure) { + for ($throwable = $failure['throwable']; null !== $throwable; $throwable = $throwable->getPrevious()) { + self::assertStringNotContainsString(self::MARKER, $throwable->getMessage()); + } + } + foreach ($this->drain->transport()->getSent() as $envelope) { + foreach ($envelope->all(ErrorDetailsStamp::class) as $stamp) { + self::assertInstanceOf(ErrorDetailsStamp::class, $stamp); + self::assertStringNotContainsString(self::MARKER, $stamp->getExceptionMessage()); + self::assertStringNotContainsString(self::MARKER, (string) $stamp->getFlattenException()?->getAsString()); + } + } + self::assertStringNotContainsString(self::MARKER, $this->log()); + } + + /** What this test wrote to the log file of the kernel. */ + private function log(): string + { + clearstatcache(); + + return is_file($this->logFile) ? (string) file_get_contents($this->logFile, false, null, $this->logOffset) : ''; + } + + /** + * @param array $input + */ + private function execute(string $name, array $input): CommandTester + { + $tester = new CommandTester($this->application->find($name)); + $tester->execute($input, ['interactive' => false]); + + return $tester; + } + + private function dbal(): Connection + { + $kernel = self::$kernel; + self::assertNotNull($kernel); + + return TestDatabase::connection($kernel); + } + + private static function cleanUp(): void + { + static::ensureKernelShutdown(); + $kernel = static::bootKernel(['environment' => TestKernel::ENV_FAKE_ENGINE]); + TestDatabase::migrate($kernel); + $connection = TestDatabase::connection($kernel); + TestDatabase::removeEndpoints($connection, self::PREFIX); + $connection->executeStatement('DELETE FROM dmstr_api_configuration WHERE name LIKE ?', [self::PREFIX.'%']); + static::ensureKernelShutdown(); + } +} diff --git a/tests/Integration/Process/ProcessStartWithoutEngineDatabaseTest.php b/tests/Integration/Process/ProcessStartWithoutEngineDatabaseTest.php new file mode 100644 index 0000000..11d0df0 --- /dev/null +++ b/tests/Integration/Process/ProcessStartWithoutEngineDatabaseTest.php @@ -0,0 +1,99 @@ + TestKernel::ENV_MINIMAL]); + $application = new Application($kernel); + $dbal = TestDatabase::connection($kernel); + $slug = self::PREFIX.'endpoint'; + foreach ([ + ['webhook:endpoint:create', ['slug' => $slug, '--mode' => 'process', '--secret' => self::SECRET]], + ['webhook:route:create', ['name' => 'all', '--endpoint' => $slug, '--process-definition-key' => 'answer-mention']], + ] as [$name, $input]) { + $tester = new CommandTester($application->find($name)); + $tester->execute($input, ['interactive' => false]); + self::assertSame(Command::SUCCESS, $tester->getStatusCode(), $tester->getDisplay()); + } + $routeId = $dbal->fetchOne('SELECT r.id FROM webhook_route r JOIN webhook_endpoint e ON e.id = r.endpoint_id WHERE e.slug = ?', [$slug]); + self::assertNotFalse($routeId); + $eventId = TestDatabase::insertEvent($dbal, TestDatabase::endpointId($dbal, $slug), 'minimal-'.bin2hex(random_bytes(4))); + $dbal->update(WebhookEvent::TABLE, [ + 'status' => WebhookEvent::STATUS_ROUTED, + 'route' => TestDatabase::uuid($dbal, $routeId), + ], ['id' => Uuid::fromString($eventId)], ['id' => 'uuid']); + + $bus = self::getContainer()->get('messenger.default_bus'); + self::assertInstanceOf(MessageBusInterface::class, $bus); + $bus->dispatch(new StartProcess($eventId)); + $drain = new TransportDrain(self::getContainer()); + self::assertSame([$eventId], $drain->sentEventIds()); + self::assertSame(1, $drain->run()); + + self::assertCount(1, $drain->failures); + self::assertFalse($drain->failures[0]['willRetry']); + $throwable = $drain->failures[0]['throwable']; + self::assertInstanceOf(HandlerFailedException::class, $throwable); + self::assertInstanceOf(UnrecoverableProcessStartException::class, $throwable->getPrevious()); + $row = $dbal->fetchAssociative('SELECT status, reason, process_instance_id FROM webhook_event WHERE id = ?', [Uuid::fromString($eventId)], ['uuid']); + self::assertSame([ + 'status' => WebhookEvent::STATUS_FAILED, + 'reason' => ProcessEngineFailure::EnginePortMissing->value, + 'process_instance_id' => null, + ], $row); + } + + private static function cleanUp(): void + { + static::ensureKernelShutdown(); + $kernel = static::bootKernel(['environment' => TestKernel::ENV_MINIMAL]); + TestDatabase::migrate($kernel); + TestDatabase::removeEndpoints(TestDatabase::connection($kernel), self::PREFIX); + static::ensureKernelShutdown(); + } +} diff --git a/tests/Integration/Process/StartClaimDatabaseTest.php b/tests/Integration/Process/StartClaimDatabaseTest.php new file mode 100644 index 0000000..37f0323 --- /dev/null +++ b/tests/Integration/Process/StartClaimDatabaseTest.php @@ -0,0 +1,216 @@ +get(EventStore::class); + self::assertInstanceOf(EventStore::class, $events); + $this->events = $events; + + $create = new CommandTester(new Application($kernel)->find('webhook:endpoint:create')); + $create->execute(['slug' => self::PREFIX.'endpoint', '--mode' => 'process', '--secret' => self::SECRET], ['interactive' => false]); + self::assertSame(Command::SUCCESS, $create->getStatusCode(), $create->getDisplay()); + $this->endpointId = TestDatabase::endpointId($this->dbal(), self::PREFIX.'endpoint'); + } + + protected function tearDown(): void + { + self::cleanUp(); + parent::tearDown(); + } + + public function testOneClaimPerLease(): void + { + $event = $this->routedEvent(); + $now = new \DateTimeImmutable(self::NOW); + + self::assertTrue($this->events->claimStart($event, $now, self::LEASE), 'first claim'); + self::assertFalse($this->events->claimStart($event, $now, self::LEASE), 'second claim in the same second'); + self::assertFalse($this->events->claimStart($event, $now->modify('+1 second'), self::LEASE)); + self::assertFalse($this->events->claimStart($event, $now->modify('+'.(self::LEASE - 1).' seconds'), self::LEASE)); + self::assertFalse($this->events->claimStart($event, $now->modify('+'.self::LEASE.' seconds'), self::LEASE), 'not older than the lease'); + self::assertTrue($this->events->claimStart($event, $now->modify('+'.(self::LEASE + 1).' seconds'), self::LEASE), 'expired lease'); + self::assertFalse($this->events->claimStart($event, $now->modify('+'.(self::LEASE + 1).' seconds'), self::LEASE), 'the new claim holds'); + self::assertSame(WebhookEvent::STATUS_ROUTED, $this->row($event)['status']); + } + + public function testTheTimeZoneOfTheCallerDoesNotMatter(): void + { + $event = $this->routedEvent(); + $now = new \DateTimeImmutable(self::NOW); + + // The same instant in another zone. + self::assertTrue($this->events->claimStart($event, $now->setTimezone(new \DateTimeZone('America/New_York')), self::LEASE)); + self::assertFalse($this->events->claimStart($event, $now->setTimezone(new \DateTimeZone('Asia/Tokyo'))->modify('+'.(self::LEASE - 1).' seconds'), self::LEASE)); + self::assertTrue($this->events->claimStart($event, $now->setTimezone(new \DateTimeZone('Asia/Tokyo'))->modify('+'.(self::LEASE + 1).' seconds'), self::LEASE)); + } + + public function testOnlyARoutedEventWithoutInstanceIsClaimed(): void + { + $now = new \DateTimeImmutable(self::NOW); + $received = Uuid::fromString(TestDatabase::insertEvent($this->dbal(), $this->endpointId, 'received-'.bin2hex(random_bytes(4)))); + self::assertFalse($this->events->claimStart($received, $now, self::LEASE)); + + $started = $this->routedEvent(); + self::assertTrue($this->events->recordStart($started, 'instance-1')); + self::assertFalse($this->events->claimStart($started, $now, self::LEASE)); + + self::assertFalse($this->events->claimStart(Uuid::v7(), $now, self::LEASE), 'unknown event'); + } + + public function testAReleaseGivesUpOnlyTheOwnClaim(): void + { + $event = $this->routedEvent(); + $first = new \DateTimeImmutable(self::NOW); + $second = $first->modify('+'.(self::LEASE + 1).' seconds'); + + self::assertTrue($this->events->claimStart($event, $first, self::LEASE)); + self::assertTrue($this->events->claimStart($event, $second, self::LEASE), 'a later attempt after the lease'); + // The first attempt fails late: its release must not free the second claim. + self::assertFalse($this->events->releaseStart($event, $first)); + self::assertFalse($this->events->claimStart($event, $second->modify('+1 second'), self::LEASE)); + + self::assertTrue($this->events->releaseStart($event, $second)); + self::assertNull($this->row($event)['start_claimed_at']); + self::assertTrue($this->events->claimStart($event, $second, self::LEASE), 'claimed again at once'); + } + + public function testTheInstanceIsRecordedOnceAndOnlyFromRouted(): void + { + $event = $this->routedEvent(); + self::assertTrue($this->events->claimStart($event, new \DateTimeImmutable(self::NOW), self::LEASE)); + + self::assertTrue($this->events->recordStart($event, 'instance-1')); + self::assertFalse($this->events->recordStart($event, 'instance-2')); + self::assertFalse($this->events->failStart($event, 'engine_error')); + self::assertFalse($this->events->releaseStart($event, new \DateTimeImmutable(self::NOW))); + + $row = $this->row($event); + self::assertSame(WebhookEvent::STATUS_STARTED, $row['status']); + self::assertSame('instance-1', $row['process_instance_id']); + self::assertNull($row['reason']); + self::assertNotNull($row['start_claimed_at'], 'the claim stays as a trace'); + + $received = Uuid::fromString(TestDatabase::insertEvent($this->dbal(), $this->endpointId, 'received-'.bin2hex(random_bytes(4)))); + self::assertFalse($this->events->recordStart($received, 'instance-3')); + self::assertSame(WebhookEvent::STATUS_RECEIVED, $this->row($received)['status']); + } + + public function testGivingUpFailsARoutedEventWithTheCategory(): void + { + $event = $this->routedEvent(); + + self::assertTrue($this->events->failStart($event, 'definition_not_deployed')); + self::assertFalse($this->events->failStart($event, 'engine_error')); + self::assertFalse($this->events->recordStart($event, 'instance-1')); + + $row = $this->row($event); + self::assertSame(WebhookEvent::STATUS_FAILED, $row['status']); + self::assertSame('definition_not_deployed', $row['reason']); + self::assertNull($row['process_instance_id']); + } + + public function testTheArgumentsAreChecked(): void + { + $event = $this->routedEvent(); + + foreach ([ + static fn (EventStore $events) => $events->claimStart($event, new \DateTimeImmutable(self::NOW), 0), + static fn (EventStore $events) => $events->recordStart($event, ''), + static fn (EventStore $events) => $events->recordStart($event, str_repeat('i', WebhookEvent::MAX_REFERENCE_LENGTH + 1)), + ] as $index => $call) { + try { + $call($this->events); + self::fail('No exception for call '.$index); + } catch (\InvalidArgumentException) { + } + } + self::assertSame(WebhookEvent::STATUS_ROUTED, $this->row($event)['status']); + self::assertNull($this->row($event)['start_claimed_at']); + self::assertTrue($this->events->recordStart($event, str_repeat('i', WebhookEvent::MAX_REFERENCE_LENGTH))); + } + + /** A new event of the endpoint in the status `routed`, inserted through DBAL. */ + private function routedEvent(): Uuid + { + $id = TestDatabase::insertEvent($this->dbal(), $this->endpointId, 'routed-'.bin2hex(random_bytes(4))); + $this->dbal()->update(WebhookEvent::TABLE, ['status' => WebhookEvent::STATUS_ROUTED], ['id' => Uuid::fromString($id)], ['id' => 'uuid']); + + return Uuid::fromString($id); + } + + /** + * @return array{status: string, reason: ?string, process_instance_id: ?string, start_claimed_at: mixed} + */ + private function row(Uuid $eventId): array + { + $row = $this->dbal()->fetchAssociative( + 'SELECT status, reason, process_instance_id, start_claimed_at FROM webhook_event WHERE id = ?', + [$eventId], + ['uuid'], + ); + self::assertIsArray($row); + + /** @var array{status: string, reason: ?string, process_instance_id: ?string, start_claimed_at: mixed} $row */ + return $row; + } + + private function dbal(): Connection + { + $kernel = self::$kernel; + self::assertNotNull($kernel); + + return TestDatabase::connection($kernel); + } + + private static function cleanUp(): void + { + static::ensureKernelShutdown(); + $kernel = static::bootKernel(); + TestDatabase::migrate($kernel); + TestDatabase::removeEndpoints(TestDatabase::connection($kernel), self::PREFIX); + static::ensureKernelShutdown(); + } +} diff --git a/tests/Kernel/TestKernel.php b/tests/Kernel/TestKernel.php index c505a6f..416d692 100644 --- a/tests/Kernel/TestKernel.php +++ b/tests/Kernel/TestKernel.php @@ -18,8 +18,10 @@ use Dmstr\Webhook\Adapter\GitlabParser; use Dmstr\Webhook\DependencyInjection\OptionalLibraries; use Dmstr\Webhook\Process\ProcessEngineInterface; +use Dmstr\Webhook\Process\Start\ProcessStarter; use Dmstr\Webhook\Reply\Gitlab\GitlabReplyClient; use Dmstr\Webhook\Tests\Support\FakeProcessEngine; +use Dmstr\Webhook\Tests\Support\HostTestMessage; use Dmstr\Webhook\Tests\Support\RecordingDeliveryHandler; use Dmstr\Webhook\WebhookBundle; use Doctrine\Bundle\DoctrineBundle\DoctrineBundle; @@ -85,7 +87,10 @@ * reach its limit; tests use random slugs). Messenger (a hard requirement * of the bundle) with the host's transport {@see self::MESSENGER_TRANSPORT} * in memory ({@see self::MESSENGER_TRANSPORT_DSN}), as a host overrides the - * transport; no routing. + * transport, and the bundle's default retry strategy; the routing of the + * start message is the bundle's prepend. Nothing consumes the transport: + * tests read it (public service {@see self::TRANSPORT_SERVICE}) and run its + * messages themselves ({@see \Dmstr\Webhook\Tests\Support\TransportDrain}). * - The `clock` service is a {@see MockClock} frozen at * {@see self::FROZEN_NOW}; the Standard Webhooks adapter takes it for its * replay window, so signatures built with {@see self::frozenNow()} are @@ -143,12 +148,17 @@ * - {@see self::ENV_FAKE_ENGINE}: the host replaces the process engine port * with the in-memory {@see FakeProcessEngine} (public service * {@see FakeProcessEngine}, the alias {@see ProcessEngineInterface} points - * to it), without FlowableBundle. + * to it), without FlowableBundle; + * - {@see self::ENV_DEFAULT_TRANSPORT}: the host defines no transport + * {@see self::MESSENGER_TRANSPORT}, so the bundle's default is used, and + * routes a message of its own ({@see HostTestMessage}) to its transport + * {@see self::HOST_TRANSPORT} (in memory, public service + * {@see self::HOST_TRANSPORT_SERVICE}). * * Where the GitLab reply client is registered, {@see self::process()} makes * it public, as a consumer of the host would keep it, so the tests can fetch * it; the same for the alias {@see ProcessEngineInterface} of the process - * engine port. + * engine port, the {@see ProcessStarter} and the Messenger transports. * * Cache and logs live under the system temp directory, one directory per * variant, so a test run leaves no files in the repository. @@ -166,10 +176,17 @@ final class TestKernel extends Kernel implements CompilerPassInterface public const string ENV_REPLY_TRANSPORT = 'test_reply_transport'; public const string ENV_FLOWABLE = 'test_flowable'; public const string ENV_FAKE_ENGINE = 'test_fake_engine'; + public const string ENV_DEFAULT_TRANSPORT = 'test_default_transport'; /** The host's Messenger transport of the process start, in memory. */ public const string MESSENGER_TRANSPORT = 'webhook'; public const string MESSENGER_TRANSPORT_DSN = 'in-memory://'; + /** The service id of the transport {@see self::MESSENGER_TRANSPORT} (public in every variant). */ + public const string TRANSPORT_SERVICE = 'messenger.transport.'.self::MESSENGER_TRANSPORT; + + /** The host's own transport of {@see self::ENV_DEFAULT_TRANSPORT}, for {@see HostTestMessage}. */ + public const string HOST_TRANSPORT = 'host_async'; + public const string HOST_TRANSPORT_SERVICE = 'messenger.transport.'.self::HOST_TRANSPORT; public const string API_PREFIX = '/api'; @@ -299,10 +316,16 @@ public function process(ContainerBuilder $container): void if ($container->hasDefinition(GitlabReplyClient::class)) { $container->getDefinition(GitlabReplyClient::class)->setPublic(true); } - // Nothing of the bundle uses the process engine port yet. + // The engine port, the starter (used by the message handler only) + // and the transports, so the tests can fetch them. if ($container->hasAlias(ProcessEngineInterface::class)) { $container->getAlias(ProcessEngineInterface::class)->setPublic(true); } + foreach ([ProcessStarter::class, self::TRANSPORT_SERVICE, self::HOST_TRANSPORT_SERVICE] as $id) { + if ($container->hasDefinition($id)) { + $container->getDefinition($id)->setPublic(true); + } + } // As in a host without symfony/clock: FrameworkBundle registers no // `clock` service then. Runs after the bundle's own passes and @@ -357,11 +380,14 @@ private function configureContainer(ContainerConfigurator $container): void 'remote_event' => ['enabled' => false], 'lock' => self::ENV_MINIMAL === $this->environment ? false : 'flock', 'http_client' => ['enabled' => self::ENV_MINIMAL !== $this->environment], - 'messenger' => [ - 'transports' => [ - self::MESSENGER_TRANSPORT => self::MESSENGER_TRANSPORT_DSN, + 'messenger' => self::ENV_DEFAULT_TRANSPORT === $this->environment + ? [ + 'transports' => [self::HOST_TRANSPORT => self::MESSENGER_TRANSPORT_DSN], + 'routing' => [HostTestMessage::class => self::HOST_TRANSPORT], + ] + : [ + 'transports' => [self::MESSENGER_TRANSPORT => self::MESSENGER_TRANSPORT_DSN], ], - ], 'cache' => [ 'app' => 'cache.adapter.array', 'pools' => [ @@ -559,3 +585,4 @@ private static function attributeMapping(string $class, string $prefix): array // - revised 2026-12-03 (Basecamp 4 adapter enabled) // - revised 2026-12-04 (GitLab reply client: variants without library, with the adapter off, with the host's transport, minimal without http_client) // - revised 2026-12-05 (process engine port: variants with FlowableBundle and with the fake engine, Messenger with an in-memory transport) +// - revised 2026-12-05 (process start: variant with the bundle's default transport, public starter and transports) diff --git a/tests/Support/HostTestMessage.php b/tests/Support/HostTestMessage.php new file mode 100644 index 0000000..1081da0 --- /dev/null +++ b/tests/Support/HostTestMessage.php @@ -0,0 +1,20 @@ +events = new EventStore($this->entityManager); $this->transition = new EventStatusTransition($this->events); $this->actorRateLimiter = new ActorRateLimiter(new SlidingWindowLimiter(new InMemoryStorage())); + $this->bus = new RecordingMessageBus(); $this->intake = new WebhookIntake( $this->entityManager, new WebhookAdapterRegistry(new ServiceLocator($adapters + self::adapters($this->clock))), @@ -102,6 +108,7 @@ public function __construct(TestCase $test, array $handlers = [], array $adapter new EventFilter(), $this->actorRateLimiter, new EventRouter($this->entityManager, new RouteMatcher()), + $this->bus, $logger, self::BODY_CAP, self::RATE_LIMIT, @@ -216,8 +223,10 @@ public function check(IntakeCase $case, EndpointMode $mode, string $label = ''): $expected = $case->expectation($mode); $slug = 'case-'.$mode->value.'-'.bin2hex(random_bytes(4)); [$endpoint, $routes] = $this->endpointFor($case, $mode, $slug); + $before = \count($this->bus->startEventIds()); $outcome = $this->deliver($slug, $case->headers, $case->body, $case->pathSecret); + $started = \array_slice($this->bus->startEventIds(), $before); Assert::assertSame($expected->httpStatus, $outcome->statusCode(), $label.': HTTP status'); if (202 === $expected->httpStatus) { @@ -228,6 +237,7 @@ public function check(IntakeCase $case, EndpointMode $mode, string $label = ''): if (null === $expected->status) { Assert::assertSame([], $rows, $label.': no event row'); Assert::assertSame([], $delivered, $label.': nothing handed over'); + Assert::assertSame([], $started, $label.': no start message'); return; } @@ -239,6 +249,8 @@ public function check(IntakeCase $case, EndpointMode $mode, string $label = ''): Assert::assertSame(null === $expected->route ? null : ($routes[$expected->route] ?? 'unknown route '.$expected->route), $row['route'] ?? null, $label.': route'); Assert::assertSame($case->body, $row['payload'], $label.': raw payload'); Assert::assertCount($expected->writes(), $this->store->writesOf((string) $row['id']), $label.': writes'); + // Exactly one start message for a routed event, with its id only. + Assert::assertSame(WebhookEvent::STATUS_ROUTED === $expected->status ? [(string) $row['id']] : [], $started, $label.': start message'); if ($expected->handedOver) { Assert::assertCount(1, $delivered, $label.': handed over once'); @@ -248,14 +260,17 @@ public function check(IntakeCase $case, EndpointMode $mode, string $label = ''): Assert::assertSame([], $delivered, $label.': nothing handed over'); } - // The same request again: a duplicate, nothing written, nothing handed over. + // The same request again: a duplicate, nothing written, nothing handed + // over, no start message. $writes = \count($this->store->writes); + $messages = \count($this->bus->messages); $again = $this->deliver($slug, $case->headers, $case->body, $case->pathSecret); Assert::assertSame(202, $again->statusCode(), $label.': duplicate'); Assert::assertCount(1, $this->store->rowsOf($endpoint), $label.': duplicate, no second row'); Assert::assertCount($writes, $this->store->writes, $label.': duplicate, no write'); Assert::assertCount($expected->handedOver ? 1 : 0, RecordingDeliveryHandler::deliveriesOf($slug), $label.': duplicate, no second hand-over'); Assert::assertTrue($again->events[0]->isDuplicate(), $label.': duplicate disposition'); + Assert::assertCount($messages, $this->bus->messages, $label.': duplicate, no start message'); } /** @@ -277,3 +292,4 @@ public static function decoded(string $body): array // - revised 2026-12-03 (GitLab adapter registered) // - revised 2026-12-03 (Basecamp 4 adapter registered) +// - revised 2026-12-05 (recording message bus, start message per routed event in check()) diff --git a/tests/Support/RecordingMessageBus.php b/tests/Support/RecordingMessageBus.php new file mode 100644 index 0000000..a0f0e33 --- /dev/null +++ b/tests/Support/RecordingMessageBus.php @@ -0,0 +1,65 @@ + the messages dispatched successfully, in order */ + public array $messages = []; + + /** Every dispatch, failed ones included. */ + public int $attempts = 0; + + private ?\Throwable $failure = null; + + public function dispatch(object $message, array $stamps = []): Envelope + { + ++$this->attempts; + if (null !== $this->failure) { + throw $this->failure; + } + $this->messages[] = $message; + + return Envelope::wrap($message, $stamps); + } + + /** Makes every following dispatch throw $failure; null dispatches again. */ + public function failWith(?\Throwable $failure): self + { + $this->failure = $failure; + + return $this; + } + + /** + * The event ids of the dispatched start messages, in order. + * + * @return list + */ + public function startEventIds(): array + { + $ids = []; + foreach ($this->messages as $message) { + if ($message instanceof StartProcess) { + $ids[] = $message->eventId; + } + } + + return $ids; + } +} diff --git a/tests/Support/TransportDrain.php b/tests/Support/TransportDrain.php new file mode 100644 index 0000000..d972b13 --- /dev/null +++ b/tests/Support/TransportDrain.php @@ -0,0 +1,124 @@ + */ + public array $failures = []; + + public function __construct(private readonly ContainerInterface $container) + { + } + + public function transport(): InMemoryTransport + { + $transport = $this->container->get(TestKernel::TRANSPORT_SERVICE); + Assert::assertInstanceOf(InMemoryTransport::class, $transport); + + return $transport; + } + + /** + * The event ids of every start message sent to the transport so far + * (retries included), in order. + * + * @return list + */ + public function sentEventIds(): array + { + return self::eventIds($this->transport()->getSent()); + } + + /** + * Handles every available message; returns the number of messages the + * worker took from the transport. + */ + public function run(int $limit = 20): int + { + $bus = $this->container->get('messenger.default_bus'); + Assert::assertInstanceOf(MessageBusInterface::class, $bus); + $dispatcher = $this->container->get('event_dispatcher'); + Assert::assertInstanceOf(EventDispatcherInterface::class, $dispatcher); + + $handled = 0; + $onRunning = static function (WorkerRunningEvent $event) use (&$handled, $limit): void { + if (!$event->isWorkerIdle()) { + ++$handled; + } + if ($event->isWorkerIdle() || $handled >= $limit) { + $event->getWorker()->stop(); + } + }; + // After Messenger's retry listener (priority 100), which decides willRetry(). + $onFailed = function (WorkerMessageFailedEvent $event): void { + $this->failures[] = ['throwable' => $event->getThrowable(), 'willRetry' => $event->willRetry()]; + }; + $dispatcher->addListener(WorkerRunningEvent::class, $onRunning); + $dispatcher->addListener(WorkerMessageFailedEvent::class, $onFailed, -100); + try { + new Worker([TestKernel::MESSENGER_TRANSPORT => $this->transport()], $bus, $dispatcher)->run(['sleep' => 0]); + } finally { + $dispatcher->removeListener(WorkerRunningEvent::class, $onRunning); + $dispatcher->removeListener(WorkerMessageFailedEvent::class, $onFailed); + } + + return $handled; + } + + /** Moves the frozen clock of the test kernel on, past the delay of a retry. */ + public function advance(int $seconds = 60): void + { + $clock = $this->container->get('clock'); + Assert::assertInstanceOf(MockClock::class, $clock); + $clock->sleep($seconds); + } + + /** + * @param iterable $envelopes + * + * @return list + */ + public static function eventIds(iterable $envelopes): array + { + $ids = []; + foreach ($envelopes as $envelope) { + $message = $envelope->getMessage(); + if ($message instanceof StartProcess) { + $ids[] = $message->eventId; + } + } + + return $ids; + } +} diff --git a/tests/Unit/DependencyInjection/WebhookBundlePrependTest.php b/tests/Unit/DependencyInjection/WebhookBundlePrependTest.php index c339063..deb8530 100644 --- a/tests/Unit/DependencyInjection/WebhookBundlePrependTest.php +++ b/tests/Unit/DependencyInjection/WebhookBundlePrependTest.php @@ -6,14 +6,19 @@ namespace Dmstr\Webhook\Tests\Unit\DependencyInjection; +use Dmstr\Webhook\Process\Start\StartProcess; use Dmstr\Webhook\WebhookBundle; use PHPUnit\Framework\TestCase; +use Symfony\Bundle\FrameworkBundle\DependencyInjection\FrameworkExtension; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface; /** * What the bundle prepends to the configuration of other extensions: its - * Doctrine mapping and its migrations path, and nothing for API Platform. + * Doctrine mapping and its migrations path, nothing for API Platform, and + * for Messenger the routing of the start message to the transport `webhook` + * plus that transport (in memory, never `sync://`) only where the + * application defines none. * Runs the extension's prepend step on a bare ContainerBuilder; no kernel, * no database. */ @@ -50,11 +55,74 @@ public function testDoctrineMappingAndMigrationsPathArePrepended(): void self::assertArrayHasKey('Dmstr\\Webhook\\Migrations', $migrations[0]['migrations_paths']); } - private static function prepend(): ContainerBuilder + public function testABareBuilderGetsNoFrameworkConfiguration(): void + { + self::assertSame([], self::prepend()->getExtensionConfig('framework')); + } + + public function testTheRoutingAndTheDefaultTransportArePrependedWhereTheHostDefinesNone(): void + { + $framework = self::prepend([['messenger' => [ + 'transports' => ['async' => 'doctrine://default'], + 'routing' => ['App\\Message\\Other' => 'async'], + ]]])->getExtensionConfig('framework'); + + // The prepend comes first, the application's configuration after it. + self::assertCount(2, $framework); + self::assertSame(['messenger' => [ + 'routing' => [StartProcess::class => WebhookBundle::TRANSPORT], + 'transports' => [WebhookBundle::TRANSPORT => WebhookBundle::DEFAULT_TRANSPORT_DSN], + ]], $framework[0]); + } + + public function testOnlyTheRoutingIsPrependedWhereTheHostDefinesTheTransport(): void + { + $framework = self::prepend([ + ['secret' => 'x'], + ['messenger' => ['transports' => [WebhookBundle::TRANSPORT => 'doctrine://default?queue_name=webhook']]], + ])->getExtensionConfig('framework'); + + self::assertCount(3, $framework); + self::assertSame(['messenger' => ['routing' => [StartProcess::class => WebhookBundle::TRANSPORT]]], $framework[0]); + } + + public function testTheMessengerConfiguration(): void + { + self::assertSame('webhook', WebhookBundle::TRANSPORT); + self::assertStringStartsNotWith('sync://', WebhookBundle::DEFAULT_TRANSPORT_DSN); + self::assertStringStartsNotWith('doctrine://', WebhookBundle::DEFAULT_TRANSPORT_DSN); + self::assertSame([ + 'routing' => [StartProcess::class => 'webhook'], + 'transports' => ['webhook' => WebhookBundle::DEFAULT_TRANSPORT_DSN], + ], WebhookBundle::messengerConfig([])); + self::assertSame([ + 'routing' => [StartProcess::class => 'webhook'], + 'transports' => ['webhook' => WebhookBundle::DEFAULT_TRANSPORT_DSN], + ], WebhookBundle::messengerConfig([['messenger' => ['transports' => ['other' => 'in-memory://']]], ['messenger' => false], ['lock' => 'flock']])); + // A transport `webhook` in any of the configurations, also with options. + self::assertSame(['routing' => [StartProcess::class => 'webhook']], WebhookBundle::messengerConfig([ + ['secret' => 'x'], + ['messenger' => ['transports' => ['webhook' => ['dsn' => 'redis://localhost/webhook', 'retry_strategy' => ['max_retries' => 5]]]]], + ])); + } + + /** + * Runs the prepend step; with $framework, FrameworkBundle's extension is + * registered and holds these configurations of the application first. + * + * @param list>|null $framework + */ + private static function prepend(?array $framework = null): ContainerBuilder { $container = new ContainerBuilder(); $container->setParameter('kernel.environment', 'test'); $container->setParameter('kernel.build_dir', sys_get_temp_dir()); + if (null !== $framework) { + $container->registerExtension(new FrameworkExtension()); + foreach ($framework as $config) { + $container->loadFromExtension('framework', $config); + } + } $extension = (new WebhookBundle())->getContainerExtension(); self::assertInstanceOf(PrependExtensionInterface::class, $extension); $extension->prepend($container); @@ -62,3 +130,5 @@ private static function prepend(): ContainerBuilder return $container; } } + +// - revised 2026-12-06 (framework.messenger: routing of the start message, default transport only without the host's) diff --git a/tests/Unit/Intake/Basecamp4LogTest.php b/tests/Unit/Intake/Basecamp4LogTest.php index 97c181b..53582b0 100644 --- a/tests/Unit/Intake/Basecamp4LogTest.php +++ b/tests/Unit/Intake/Basecamp4LogTest.php @@ -31,6 +31,7 @@ use Dmstr\Webhook\Routing\RouteMatcher; use Dmstr\Webhook\Tests\Support\InMemoryWebhookStore; use Dmstr\Webhook\Tests\Support\RecordingDeliveryHandler; +use Dmstr\Webhook\Tests\Support\RecordingMessageBus; use Monolog\Formatter\LineFormatter; use Monolog\Formatter\NormalizerFormatter; use Monolog\Handler\TestHandler; @@ -345,6 +346,7 @@ private function build(): void new EventFilter(), new ActorRateLimiter(new SlidingWindowLimiter(new InMemoryStorage())), new EventRouter($entityManager, new RouteMatcher()), + new RecordingMessageBus(), $this->logger, 1048576, 60, diff --git a/tests/Unit/Intake/EventStoreTransitionTest.php b/tests/Unit/Intake/EventStoreTransitionTest.php index ad8d80f..1069abb 100644 --- a/tests/Unit/Intake/EventStoreTransitionTest.php +++ b/tests/Unit/Intake/EventStoreTransitionTest.php @@ -101,6 +101,37 @@ public function testThePublicTransitionLeavesARoutedEventUntouched(): void self::assertSame(['insert'], $this->harness->store->writesOf($routed)); } + public function testThePublicTransitionLeavesAStartedEventUntouchedAndStillHandlesAReceivedOne(): void + { + $started = $this->event(WebhookEvent::STATUS_STARTED); + $before = $this->harness->row($started); + + self::assertFalse($this->harness->transition->handled($started)); + self::assertFalse($this->harness->transition->ignored($started->toRfc4122(), 'x')); + self::assertFalse($this->harness->transition->failed($started, 'x')); + // Giving a start up touches only a routed event. + self::assertFalse($this->harness->events->failStart($started, 'engine_error')); + self::assertSame($before, $this->harness->row($started)); + self::assertSame(['insert'], $this->harness->store->writesOf($started)); + + // The delivery handlers' path (mode handler) is unchanged. + $received = $this->event(WebhookEvent::STATUS_RECEIVED); + self::assertTrue($this->harness->transition->handled($received)); + self::assertSame(WebhookEvent::STATUS_HANDLED, $this->harness->row($received)['status']); + } + + public function testGivingAStartUpFailsARoutedEventOnceWithTheCategory(): void + { + $routed = $this->event(WebhookEvent::STATUS_ROUTED); + + self::assertTrue($this->harness->events->failStart($routed, 'definition_not_deployed')); + self::assertFalse($this->harness->events->failStart($routed, 'engine_error')); + + self::assertSame(WebhookEvent::STATUS_FAILED, $this->harness->row($routed)['status']); + self::assertSame('definition_not_deployed', $this->harness->row($routed)['reason']); + self::assertSame(['insert', 'update'], $this->harness->store->writesOf($routed)); + } + /** * @return iterable */ diff --git a/tests/Unit/Intake/IntakeStartDispatchUnitTest.php b/tests/Unit/Intake/IntakeStartDispatchUnitTest.php new file mode 100644 index 0000000..f5b7fbd --- /dev/null +++ b/tests/Unit/Intake/IntakeStartDispatchUnitTest.php @@ -0,0 +1,202 @@ +harness = new IntakeHarness($this); + } + + /** @return iterable */ + public static function mentions(): iterable + { + yield 'mention on a merge request' => ['note-merge-request-mention']; + yield 'mention on an issue' => ['note-issue-mention']; + } + + #[DataProvider('mentions')] + public function testARoutedEventDispatchesOneStartMessageWithItsIdOnly(string $fixture): void + { + $this->gitlabEndpoint('start-routed', EndpointMode::Process); + + $outcome = $this->harness->deliver('start-routed', GitlabFixtures::headers($fixture), GitlabFixtures::body($fixture)); + + self::assertSame(202, $outcome->statusCode()); + $eventId = $outcome->events[0]->eventId; + self::assertNotNull($eventId); + self::assertSame(WebhookEvent::STATUS_ROUTED, $this->harness->row($eventId)['status']); + self::assertCount(1, $this->harness->bus->messages); + $message = $this->harness->bus->messages[0]; + self::assertInstanceOf(StartProcess::class, $message); + self::assertSame($eventId->toRfc4122(), $message->eventId); + // The message carries the event id and nothing else. + self::assertSame(['eventId' => $eventId->toRfc4122()], get_object_vars($message)); + } + + public function testTheConsoleTwinDispatchesTheSameStartMessage(): void + { + $endpoint = $this->gitlabEndpoint('start-console', EndpointMode::Process); + $fixture = 'note-merge-request-mention'; + $file = tempnam(sys_get_temp_dir(), 'webhook'); + self::assertIsString($file); + $headers = []; + foreach (GitlabFixtures::headers($fixture) as $name => $value) { + $headers[] = $name.': '.$value; + } + $command = new CommandTester(new WebhookDeliverCommand($this->harness->intake, $this->harness->handOff)); + + try { + file_put_contents($file, GitlabFixtures::body($fixture)); + self::assertSame(0, $command->execute(['slug' => 'start-console', 'file' => $file, '--header' => $headers])); + } finally { + unlink($file); + } + + $rows = $this->harness->store->rowsOf($endpoint); + self::assertCount(1, $rows); + self::assertSame(WebhookEvent::STATUS_ROUTED, $rows[0]['status']); + self::assertSame([(string) $rows[0]['id']], $this->harness->bus->startEventIds()); + } + + public function testModeHandlerDispatchesNothing(): void + { + $this->gitlabEndpoint('start-handler', EndpointMode::Handler); + + $outcome = $this->harness->deliver('start-handler', GitlabFixtures::headers('note-merge-request-mention'), GitlabFixtures::body('note-merge-request-mention')); + + self::assertSame(202, $outcome->statusCode()); + self::assertSame(0, $this->harness->bus->attempts); + } + + public function testAnIgnoredEventDispatchesNothing(): void + { + $this->gitlabEndpoint('start-ignored', EndpointMode::Process, [GitlabFixtures::OTHER_ID]); + + $outcome = $this->harness->deliver('start-ignored', GitlabFixtures::headers('note-merge-request-mention'), GitlabFixtures::body('note-merge-request-mention')); + + self::assertSame(202, $outcome->statusCode()); + $eventId = $outcome->events[0]->eventId; + self::assertNotNull($eventId); + self::assertSame(WebhookEvent::STATUS_IGNORED, $this->harness->row($eventId)['status']); + self::assertSame(0, $this->harness->bus->attempts); + } + + public function testADuplicateAndAResendDispatchNoSecondMessage(): void + { + $this->gitlabEndpoint('start-duplicate', EndpointMode::Process); + + foreach (['note-merge-request-mention', 'note-merge-request-mention', 'note-merge-request-mention-resend'] as $fixture) { + self::assertSame(202, $this->harness->deliver('start-duplicate', GitlabFixtures::headers($fixture), GitlabFixtures::body($fixture))->statusCode(), $fixture); + } + + self::assertCount(1, $this->harness->bus->startEventIds()); + self::assertSame(1, $this->harness->bus->attempts); + } + + public function testAFailedDispatchIsLoggedAndTheDeliveryIsAcceptedAllTheSame(): void + { + $this->gitlabEndpoint('start-bus-down', EndpointMode::Process); + $this->harness->bus->failWith(new \RuntimeException('Transport down: '.self::MARKER)); + $fixture = 'note-merge-request-mention'; + + $outcome = $this->harness->deliver('start-bus-down', GitlabFixtures::headers($fixture), GitlabFixtures::body($fixture)); + + self::assertSame(202, $outcome->statusCode()); + self::assertSame('{"status":"accepted"}', $outcome->toResponse()->getContent()); + $eventId = $outcome->events[0]->eventId; + self::assertNotNull($eventId); + $row = $this->harness->row($eventId); + self::assertSame(WebhookEvent::STATUS_ROUTED, $row['status']); + self::assertNull($row['reason']); + self::assertSame(1, $this->harness->bus->attempts); + self::assertSame([], $this->harness->bus->messages); + + $warnings = array_values(array_filter( + $this->harness->log->getRecords(), + static fn ($record): bool => $record->level->isHigherThan(Level::Info), + )); + self::assertCount(1, $warnings); + self::assertSame(Level::Warning, $warnings[0]->level); + self::assertSame(WebhookIntake::START_NOT_QUEUED_MESSAGE, $warnings[0]->message); + self::assertSame('start-bus-down', $warnings[0]->context['slug']); + self::assertSame($eventId->toRfc4122(), $warnings[0]->context['event_id']); + self::assertSame(\RuntimeException::class, $warnings[0]->context['exception_class']); + + $logged = ''; + foreach ($this->harness->log->getRecords() as $record) { + $logged .= $record->message.json_encode($record->context, \JSON_THROW_ON_ERROR | \JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_UNICODE)."\n"; + } + self::assertStringNotContainsString(self::MARKER, $logged); + foreach (GitlabFixtures::texts(GitlabFixtures::payload($fixture)) as $text) { + if (\strlen($text) >= 8) { + self::assertStringNotContainsString($text, $logged); + } + } + } + + public function testTheBusIsUsedAgainOnceItIsBack(): void + { + $this->gitlabEndpoint('start-bus-back', EndpointMode::Process); + $this->harness->bus->failWith(new \RuntimeException('down')); + $this->harness->deliver('start-bus-back', GitlabFixtures::headers('note-merge-request-mention'), GitlabFixtures::body('note-merge-request-mention')); + $this->harness->bus->failWith(null); + + $outcome = $this->harness->deliver('start-bus-back', GitlabFixtures::headers('note-issue-mention'), GitlabFixtures::body('note-issue-mention')); + + $eventId = $outcome->events[0]->eventId; + self::assertNotNull($eventId); + self::assertSame([$eventId->toRfc4122()], $this->harness->bus->startEventIds()); + } + + /** + * A GitLab endpoint as in the fixture matrix: the bot as own identity, + * the author of the fixtures on the allowlist (unless $allowed says + * otherwise), one catch-all route. + * + * @param list $allowed + */ + private function gitlabEndpoint(string $slug, EndpointMode $mode, array $allowed = [GitlabFixtures::ANN_ID]): WebhookEndpoint + { + $endpoint = $this->harness->endpoint($slug, GitlabParser::SOURCE, GitlabFixtures::TOKEN, $mode, [ + 'actorId' => GitlabFixtures::BOT_ID, + 'actorHandle' => GitlabFixtures::BOT_HANDLE, + 'allowedActorIds' => $allowed, + ]); + $this->harness->store->route($endpoint, 'all'); + + return $endpoint; + } +} diff --git a/tests/Unit/Process/FlowableProcessEngineTest.php b/tests/Unit/Process/FlowableProcessEngineTest.php index a427e41..0c5237c 100644 --- a/tests/Unit/Process/FlowableProcessEngineTest.php +++ b/tests/Unit/Process/FlowableProcessEngineTest.php @@ -126,7 +126,9 @@ public static function engineFailures(): iterable 'other status' => 500, ]; $expected = [ - ProcessEngineCall::Start->value => [404 => ProcessEngineFailure::DefinitionNotDeployed, 422 => ProcessEngineFailure::EngineRejected, 502 => ProcessEngineFailure::EngineError, 504 => ProcessEngineFailure::EngineUnreachable, 500 => ProcessEngineFailure::EngineError], + // A rejected start asks for the definitions of the key; the stub + // lists none by default ({@see self::testARejectedStartAsksWhetherTheDefinitionExists()}). + ProcessEngineCall::Start->value => [404 => ProcessEngineFailure::DefinitionNotDeployed, 422 => ProcessEngineFailure::DefinitionNotDeployed, 502 => ProcessEngineFailure::EngineError, 504 => ProcessEngineFailure::EngineUnreachable, 500 => ProcessEngineFailure::EngineError], ProcessEngineCall::FindInstances->value => [404 => ProcessEngineFailure::EngineError, 422 => ProcessEngineFailure::EngineRejected, 502 => ProcessEngineFailure::EngineError, 504 => ProcessEngineFailure::EngineUnreachable, 500 => ProcessEngineFailure::EngineError], ProcessEngineCall::Deploy->value => [404 => ProcessEngineFailure::EngineError, 422 => ProcessEngineFailure::EngineRejected, 502 => ProcessEngineFailure::EngineError, 504 => ProcessEngineFailure::EngineUnreachable, 500 => ProcessEngineFailure::EngineError], ]; @@ -217,6 +219,49 @@ public function testAStartWithANonScalarVariableIsRejectedBeforeAnyRequest(array self::assertSame([], $this->requests); } + /** + * The answer of the definition lookup after a start the engine rejected + * with 400 (422): a value, or a \Throwable the lookup throws. + * + * @return iterable + */ + public static function definitionLookups(): iterable + { + yield 'no definition of the key' => [['data' => []], ProcessEngineFailure::DefinitionNotDeployed]; + yield 'a definition of the key' => [['data' => [['id' => self::KEY.':1:d-1', 'deploymentId' => 'd-1', 'version' => 1]]], ProcessEngineFailure::EngineRejected]; + yield 'an answer without data' => [['total' => 0], ProcessEngineFailure::EngineRejected]; + yield 'the lookup is rejected' => [new FlowableApiException(422, 'Flowable said: '.self::ENGINE_TEXT), ProcessEngineFailure::EngineRejected]; + yield 'the lookup is unreachable' => [new FlowableApiException(504, 'Flowable said: '.self::ENGINE_TEXT), ProcessEngineFailure::EngineRejected]; + yield 'the lookup fails otherwise' => [new \RuntimeException(self::ENGINE_TEXT), ProcessEngineFailure::EngineRejected]; + } + + /** + * Flowable answers the start of a key without deployed definition with + * 400 (422 here), not 404; whether the definition exists decides the + * category, never the message text. + */ + #[DataProvider('definitionLookups')] + public function testARejectedStartAsksWhetherTheDefinitionExists(mixed $lookup, ProcessEngineFailure $failure): void + { + $this->answers['startProcessInstance'] = new FlowableApiException(422, 'Flowable said: no deployed process definition found with key '.self::ENGINE_TEXT); + $this->answers['listProcessDefinitions'] = $lookup; + + $this->assertFailure(ProcessEngineCall::Start, $failure, fn () => $this->invoke(ProcessEngineCall::Start, self::connection())); + self::assertSame(['startProcessInstance', 'listProcessDefinitions'], array_column($this->requests, 0)); + self::assertSame([['key' => self::KEY, 'latest' => 'true', 'size' => 1]], $this->requests[1][1]); + } + + public function testOnlyARejectedStartAsksForTheDefinition(): void + { + foreach ([404 => ProcessEngineFailure::DefinitionNotDeployed, 502 => ProcessEngineFailure::EngineError, 504 => ProcessEngineFailure::EngineUnreachable] as $status => $failure) { + $this->requests = []; + $this->answers['startProcessInstance'] = new FlowableApiException($status, 'Flowable said: '.self::ENGINE_TEXT); + + $this->assertFailure(ProcessEngineCall::Start, $failure, fn () => $this->invoke(ProcessEngineCall::Start, self::connection())); + self::assertSame(['startProcessInstance'], array_column($this->requests, 0), (string) $status); + } + } + public function testAStartAnswerWithoutInstanceIdIsAnEngineError(): void { $this->answers['startProcessInstance'] = ['businessKey' => self::BUSINESS_KEY]; diff --git a/tests/Unit/Process/Start/ProcessStartFailureListenerTest.php b/tests/Unit/Process/Start/ProcessStartFailureListenerTest.php new file mode 100644 index 0000000..065303b --- /dev/null +++ b/tests/Unit/Process/Start/ProcessStartFailureListenerTest.php @@ -0,0 +1,198 @@ +harness = new IntakeHarness($this); + $this->listener = new ProcessStartFailureListener($this->harness->events, new Logger('webhook', [$this->harness->log])); + } + + public function testAGivenUpStartFailsTheRoutedEventWithItsCategory(): void + { + $eventId = $this->routedEvent(); + $message = new StartProcess($eventId->toRfc4122()); + + ($this->listener)($this->failed($message, $this->wrapped($message, ProcessStartFailedException::of(ProcessEngineFailure::DefinitionNotDeployed->value)))); + + $row = $this->harness->row($eventId); + self::assertSame(WebhookEvent::STATUS_FAILED, $row['status']); + self::assertSame(ProcessEngineFailure::DefinitionNotDeployed->value, $row['reason']); + $errors = $this->errors(); + self::assertCount(1, $errors); + self::assertSame(ProcessStartFailureListener::FAILED_MESSAGE, $errors[0]->message); + self::assertSame(['event_id' => $eventId->toRfc4122(), 'category' => ProcessEngineFailure::DefinitionNotDeployed->value], $errors[0]->context); + } + + public function testAnUnwrappedFailureIsReadToo(): void + { + $eventId = $this->routedEvent(); + $message = new StartProcess($eventId->toRfc4122()); + + ($this->listener)($this->failed($message, ProcessStartFailedException::of(ProcessEngineFailure::EngineUnreachable->value))); + + self::assertSame(ProcessEngineFailure::EngineUnreachable->value, $this->harness->row($eventId)['reason']); + } + + public function testARetryPendingLeavesTheEventRouted(): void + { + $eventId = $this->routedEvent(); + $message = new StartProcess($eventId->toRfc4122()); + $event = $this->failed($message, $this->wrapped($message, ProcessStartFailedException::of(ProcessEngineFailure::EngineUnreachable->value))); + $event->setForRetry(); + + ($this->listener)($event); + + self::assertSame(WebhookEvent::STATUS_ROUTED, $this->harness->row($eventId)['status']); + self::assertSame([], $this->errors()); + } + + public function testAnotherMessageIsIgnored(): void + { + $eventId = $this->routedEvent(); + $writes = \count($this->harness->store->writes); + + ($this->listener)($this->failed(new HostTestMessage($eventId->toRfc4122()), new \RuntimeException('other'))); + + self::assertSame(WebhookEvent::STATUS_ROUTED, $this->harness->row($eventId)['status']); + self::assertCount($writes, $this->harness->store->writes); + self::assertSame([], $this->errors()); + } + + public function testAnInvalidEventIdIsIgnored(): void + { + $writes = \count($this->harness->store->writes); + + ($this->listener)($this->failed(new StartProcess('not-a-uuid'), ProcessStartFailedException::of(ProcessStartFailure::START_FAILED))); + + self::assertCount($writes, $this->harness->store->writes); + self::assertSame([], $this->errors()); + } + + public function testAStartedEventStaysStarted(): void + { + $eventId = $this->routedEvent(); + self::assertTrue($this->harness->events->transition($eventId, WebhookEvent::STATUS_STARTED, null, null, WebhookEvent::STATUS_ROUTED)); + $message = new StartProcess($eventId->toRfc4122()); + + ($this->listener)($this->failed($message, $this->wrapped($message, ProcessStartFailedException::of(ProcessEngineFailure::EngineError->value)))); + + $row = $this->harness->row($eventId); + self::assertSame(WebhookEvent::STATUS_STARTED, $row['status']); + self::assertNull($row['reason']); + self::assertSame([], $this->errors()); + } + + public function testAnyOtherThrowableIsStartFailedWithoutItsMessage(): void + { + $eventId = $this->routedEvent(); + $message = new StartProcess($eventId->toRfc4122()); + + ($this->listener)($this->failed($message, $this->wrapped($message, new \RuntimeException(self::MARKER)))); + + $row = $this->harness->row($eventId); + self::assertSame(WebhookEvent::STATUS_FAILED, $row['status']); + self::assertSame(ProcessStartFailure::START_FAILED, $row['reason']); + $logged = ''; + foreach ($this->harness->log->getRecords() as $record) { + $logged .= $record->message.json_encode($record->context, \JSON_THROW_ON_ERROR)."\n"; + } + self::assertStringNotContainsString(self::MARKER, $logged); + self::assertStringContainsString(ProcessStartFailure::START_FAILED, $logged); + } + + public function testTheCategoryOfAThrowable(): void + { + $message = new StartProcess(Uuid::v7()->toRfc4122()); + $failure = ProcessStartFailedException::of(ProcessStartFailure::ROUTE_MISSING); + + self::assertSame(ProcessStartFailure::ROUTE_MISSING, ProcessStartFailureListener::category($failure)); + self::assertSame(ProcessStartFailure::ROUTE_MISSING, ProcessStartFailureListener::category($this->wrapped($message, $failure))); + // Messenger nests a handler failure of a nested dispatch. + self::assertSame(ProcessStartFailure::ROUTE_MISSING, ProcessStartFailureListener::category($this->wrapped($message, $this->wrapped($message, $failure)))); + self::assertSame(ProcessStartFailure::START_FAILED, ProcessStartFailureListener::category(new \LogicException(self::MARKER))); + self::assertSame(ProcessStartFailure::START_FAILED, ProcessStartFailureListener::category($this->wrapped($message, new \LogicException(self::MARKER)))); + } + + /** + * A GitLab process endpoint with one catch-all route and the mention of + * the fixtures delivered to it: `routed`. + */ + private function routedEvent(): Uuid + { + $slug = 'listener-'.bin2hex(random_bytes(4)); + $endpoint = $this->harness->endpoint($slug, GitlabParser::SOURCE, GitlabFixtures::TOKEN, EndpointMode::Process, [ + 'actorId' => GitlabFixtures::BOT_ID, + 'actorHandle' => GitlabFixtures::BOT_HANDLE, + 'allowedActorIds' => [GitlabFixtures::ANN_ID], + ]); + $this->harness->store->route($endpoint, 'all'); + + $outcome = $this->harness->receive($slug, GitlabFixtures::headers('note-merge-request-mention'), GitlabFixtures::body('note-merge-request-mention')); + + self::assertSame(202, $outcome->statusCode()); + $eventId = $outcome->events[0]->eventId; + self::assertNotNull($eventId); + self::assertSame(WebhookEvent::STATUS_ROUTED, $this->harness->row($eventId)['status']); + + return $eventId; + } + + private function failed(object $message, \Throwable $throwable): WorkerMessageFailedEvent + { + return new WorkerMessageFailedEvent(new Envelope($message), 'webhook', $throwable); + } + + private function wrapped(object $message, \Throwable $throwable): HandlerFailedException + { + return new HandlerFailedException(new Envelope($message), ['handler' => $throwable]); + } + + /** @return list */ + private function errors(): array + { + return array_values(array_filter( + $this->harness->log->getRecords(), + static fn (LogRecord $record): bool => $record->level->isHigherThan(Level::Warning), + )); + } +} diff --git a/tests/Unit/Process/Start/ProcessStartValuesTest.php b/tests/Unit/Process/Start/ProcessStartValuesTest.php new file mode 100644 index 0000000..02f2b1f --- /dev/null +++ b/tests/Unit/Process/Start/ProcessStartValuesTest.php @@ -0,0 +1,182 @@ + self::EVENT_ID], get_object_vars($message)); + // Serialisable for a durable transport, and back. + self::assertEquals($message, unserialize(serialize($message))); + } + + /** @return iterable */ + public static function categories(): iterable + { + foreach (ProcessEngineFailure::cases() as $failure) { + yield $failure->value => [$failure->value, \in_array($failure, [ProcessEngineFailure::EngineUnreachable, ProcessEngineFailure::EngineError], true)]; + } + yield ProcessStartFailure::ROUTE_MISSING => [ProcessStartFailure::ROUTE_MISSING, false]; + yield ProcessStartFailure::ENDPOINT_NOT_PROCESS => [ProcessStartFailure::ENDPOINT_NOT_PROCESS, false]; + yield ProcessStartFailure::START_FAILED => [ProcessStartFailure::START_FAILED, true]; + } + + #[DataProvider('categories')] + public function testEachCategoryIsEitherRetriedOrGivenUpAtOnce(string $category, bool $retryable): void + { + $exception = ProcessStartFailedException::of($category); + + self::assertSame($retryable, ProcessStartFailure::isRetryable($category)); + self::assertSame($retryable, $exception->isRetryable()); + self::assertSame(!$retryable, $exception instanceof UnrecoverableExceptionInterface); + self::assertSame(!$retryable, $exception instanceof UnrecoverableProcessStartException); + self::assertSame($category, $exception->category); + self::assertSame(\sprintf(ProcessStartFailedException::MESSAGE, $category), $exception->getMessage()); + self::assertSame('Process start failed: '.$category.'.', $exception->getMessage()); + self::assertNull($exception->getPrevious()); + self::assertSame(0, $exception->getCode()); + } + + public function testEveryEngineFailureHasADecision(): void + { + $retried = array_values(array_filter( + array_map(static fn (ProcessEngineFailure $failure): string => $failure->value, ProcessEngineFailure::cases()), + ProcessStartFailure::isRetryable(...), + )); + + self::assertSame([ProcessEngineFailure::EngineError->value, ProcessEngineFailure::EngineUnreachable->value], $retried); + } + + public function testTheVariablesAreExactlyTheAllowedSet(): void + { + $variables = ProcessStartVariables::of(self::EVENT_ID, self::ENDPOINT_ID, [ + 'project_kind' => 'project', + 'project_id' => '101', + 'target_kind' => 'merge_request', + 'target_id' => '12', + 'note_kind' => 'note', + 'note_id' => '5001', + 'discussion_kind' => null, + 'discussion_id' => null, + 'status' => 'routed', + 'payload' => '{"note":"free text"}', + ], 'agent-example', [ + 'channel' => 'gitlab', + 'priority' => 3, + 'urgent' => true, + 'weight' => 1.5, + ]); + + self::assertSame([ + 'channel' => 'gitlab', + 'priority' => 3, + 'urgent' => true, + 'weight' => 1.5, + 'webhookEventId' => self::EVENT_ID, + 'webhookEndpointId' => self::ENDPOINT_ID, + 'webhookProjectKind' => 'project', + 'webhookProjectId' => '101', + 'webhookTargetKind' => 'merge_request', + 'webhookTargetId' => '12', + 'webhookNoteKind' => 'note', + 'webhookNoteId' => '5001', + 'webhookAgent' => 'agent-example', + ], $variables); + } + + public function testTheBundlesOwnNamesWinOverRouteVariables(): void + { + $route = []; + foreach (ProcessStartVariables::reservedNames() as $name) { + $route[$name] = 'from-the-route'; + } + + $variables = ProcessStartVariables::of(self::EVENT_ID, self::ENDPOINT_ID, [], null, $route); + + self::assertSame([ + ProcessStartVariables::EVENT_ID => self::EVENT_ID, + ProcessStartVariables::ENDPOINT_ID => self::ENDPOINT_ID, + ], $variables); + } + + public function testOnlyNamedScalarRouteVariablesAreKept(): void + { + $variables = ProcessStartVariables::of(self::EVENT_ID, self::ENDPOINT_ID, [], '', [ + 0 => 'positional', + '' => 'empty name', + 'list' => ['a', 'b'], + 'object' => new \stdClass(), + 'null' => null, + 'kept' => 'yes', + ]); + + self::assertSame([ + 'kept' => 'yes', + ProcessStartVariables::EVENT_ID => self::EVENT_ID, + ProcessStartVariables::ENDPOINT_ID => self::ENDPOINT_ID, + ], $variables); + } + + public function testAReferenceIsSetOnlyAsAPair(): void + { + $variables = ProcessStartVariables::of(self::EVENT_ID, self::ENDPOINT_ID, [ + 'project_kind' => 'project', + 'project_id' => null, + 'target_kind' => null, + 'target_id' => '12', + 'note_kind' => '', + 'note_id' => '1', + 'discussion_kind' => 'discussion', + 'discussion_id' => 'abc', + ], null, []); + + self::assertSame([ + ProcessStartVariables::EVENT_ID => self::EVENT_ID, + ProcessStartVariables::ENDPOINT_ID => self::ENDPOINT_ID, + 'webhookDiscussionKind' => 'discussion', + 'webhookDiscussionId' => 'abc', + ], $variables); + } + + public function testTheReservedNamesAreTheBundlesNames(): void + { + self::assertSame([ + 'webhookEventId', + 'webhookEndpointId', + 'webhookAgent', + 'webhookProjectKind', + 'webhookProjectId', + 'webhookTargetKind', + 'webhookTargetId', + 'webhookNoteKind', + 'webhookNoteId', + 'webhookDiscussionKind', + 'webhookDiscussionId', + ], ProcessStartVariables::reservedNames()); + } +} From bf6d850fb378a0899fee1066d470915667da0ed1 Mon Sep 17 00:00:00 2001 From: Tobias Munk Date: Sun, 6 Dec 2026 00:18:35 +0000 Subject: [PATCH 7/9] feat(process): catch up routed events without a process instance [*] ProcessStartCatchUp starts routed events without instance that were received between catch_up.min_age (300 s) and catch_up.max_age (86400 s) and whose claim is empty or expired, directly through the starter and not through the transport. An unrecoverable failure sets the event to failed, a retryable one leaves it routed for the next run. The command webhook:process:catch-up wraps it, with a limit and a dry run. The bundle ships no schedule; the application calls the service. Co-Authored-By: Claude Fable 5.2 --- config/services.yaml | 16 +- src/Command/ProcessCatchUpCommand.php | 134 ++++ src/Intake/EventStore.php | 84 +- src/Process/Start/ProcessStartCatchUp.php | 198 +++++ .../Start/ProcessStartCatchUpResult.php | 61 ++ src/WebhookBundle.php | 45 +- .../Command/CommandDefinitionsTest.php | 14 + .../ProcessStartCatchUpDatabaseTest.php | 756 ++++++++++++++++++ tests/Kernel/TestKernel.php | 38 +- .../WebhookBundleConfigurationTest.php | 78 +- 10 files changed, 1410 insertions(+), 14 deletions(-) create mode 100644 src/Command/ProcessCatchUpCommand.php create mode 100644 src/Process/Start/ProcessStartCatchUp.php create mode 100644 src/Process/Start/ProcessStartCatchUpResult.php create mode 100644 tests/Integration/Process/ProcessStartCatchUpDatabaseTest.php diff --git a/config/services.yaml b/config/services.yaml index 4528116..e4a0e81 100644 --- a/config/services.yaml +++ b/config/services.yaml @@ -59,14 +59,16 @@ services: - '../src/Process/ProcessEngineGuard.php' - '../src/Process/ProcessInstance.php' # Process start: the message, the failures, the exceptions, the - # variables and the outcome; services are the starter, the - # message handler and the failure listener. + # variables, the outcome and the result of a catch-up run; + # services are the starter, the message handler, the failure + # listener and the catch-up. - '../src/Process/Start/StartProcess.php' - '../src/Process/Start/ProcessStartFailure.php' - '../src/Process/Start/ProcessStartFailedException.php' - '../src/Process/Start/UnrecoverableProcessStartException.php' - '../src/Process/Start/ProcessStartVariables.php' - '../src/Process/Start/ProcessStartOutcome.php' + - '../src/Process/Start/ProcessStartCatchUpResult.php' # Sliding-window counters of the endpoint rate limit, in the cache pool # `cache.rate_limiter` of FrameworkBundle (configure a shared adapter such @@ -98,6 +100,15 @@ services: arguments: $clock: '@?clock' + # The catch-up of routed events without process instance (public API, the + # application schedules it): the clock as for the starter, the window + # from the configuration `dmstr_webhook.catch_up`. + Dmstr\Webhook\Process\Start\ProcessStartCatchUp: + arguments: + $clock: '@?clock' + $minAgeSeconds: '%dmstr_webhook.catch_up.min_age%' + $maxAgeSeconds: '%dmstr_webhook.catch_up.max_age%' + # Announces the permissions this bundle checks to the permission voter of # the host application (container tag, plain strings; the application maps # them to roles). @@ -116,3 +127,4 @@ services: # - revised 2026-12-05 (process engine port: src/Process/ value objects and implementations excluded from discovery) # - revised 2026-12-05 (answer process constants excluded from discovery) # - revised 2026-12-05 (process start: value objects excluded from discovery, clock of the starter) +# - revised 2026-12-06 (process start catch-up: result excluded from discovery, clock and window of the service) diff --git a/src/Command/ProcessCatchUpCommand.php b/src/Command/ProcessCatchUpCommand.php new file mode 100644 index 0000000..602a483 --- /dev/null +++ b/src/Command/ProcessCatchUpCommand.php @@ -0,0 +1,134 @@ +` when the event was set to `failed`, `retrying: ` + * when it stays `routed` for the next run), then the counts. The output + * names only reason categories, never text of the engine, a secret or a + * payload. + * + * Exit code 0 when no event failed permanently, also when some stay + * `routed` after a retryable failure (a warning names them; the next run + * tries again, and a schedule must not alarm on every run while the engine + * is down) and when there is nothing to catch up; 1 when an event was set + * to `failed` (an operator has to fix its connection, route or definition; + * the event is not selected again, so a schedule alarms once per event) or + * the limit is invalid. + */ +#[AsCommand(name: 'webhook:process:catch-up', description: 'Start the process of routed webhook events without process instance (catch-up of lost or failed dispatches)')] +final class ProcessCatchUpCommand extends Command +{ + public function __construct(private readonly ProcessStartCatchUp $catchUp) + { + parent::__construct(); + } + + protected function configure(): void + { + $this + ->addOption('limit', 'l', InputOption::VALUE_REQUIRED, 'Maximum number of events', (string) ProcessStartCatchUp::DEFAULT_LIMIT) + ->addOption('dry-run', null, InputOption::VALUE_NONE, 'List the events that would be started; claim and start nothing'); + } + + protected function execute(InputInterface $input, OutputInterface $output): int + { + $io = new SymfonyStyle($input, $output); + + $limit = filter_var($input->getOption('limit'), \FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]); + if (false === $limit) { + $io->error('--limit must be a positive integer.'); + + return self::FAILURE; + } + $dryRun = (bool) $input->getOption('dry-run'); + + $io->writeln(\sprintf( + 'Routed events without process instance, received %d to %d seconds ago%s:', + $this->catchUp->minAgeSeconds, + $this->catchUp->maxAgeSeconds, + $dryRun ? ' (dry run)' : '', + )); + + if ($dryRun) { + $candidates = $this->catchUp->candidates($limit); + if ([] === $candidates) { + $io->note('No routed event without process instance to catch up.'); + + return self::SUCCESS; + } + $io->table(['Event'], array_map(static fn (Uuid $id): array => [$id->toRfc4122()], $candidates)); + $io->note(\sprintf('Dry run: %d event(s) would be started; nothing was claimed or started.', \count($candidates))); + + return self::SUCCESS; + } + + $result = $this->catchUp->run($limit); + if (0 === $result->selected) { + $io->note('No routed event without process instance to catch up.'); + + return self::SUCCESS; + } + + $rows = []; + foreach ($result->results as $eventId => $eventResult) { + $rows[] = [$eventId, $eventResult]; + } + $io->table(['Event', 'Result'], $rows); + + $summary = self::summary($result); + if ($result->hasFailures()) { + $io->error($summary); + + return self::FAILURE; + } + if (0 < $result->retryingCount()) { + $io->warning($summary); + + return self::SUCCESS; + } + $io->success($summary); + + return self::SUCCESS; + } + + private static function summary(ProcessStartCatchUpResult $result): string + { + return \sprintf( + '%d event(s): %d started, %d found existing, %d nothing to do, %d claim lost, %d not recorded, %d failed, %d left for the next run.', + $result->selected, + $result->started, + $result->foundExisting, + $result->nothingToDo, + $result->claimLost, + $result->notRecorded, + $result->failedCount(), + $result->retryingCount(), + ); + } +} diff --git a/src/Intake/EventStore.php b/src/Intake/EventStore.php index 9a28736..f1b5362 100644 --- a/src/Intake/EventStore.php +++ b/src/Intake/EventStore.php @@ -45,7 +45,9 @@ * ({@see self::releaseStart()}), records the instance (`routed` → * `started`, {@see self::recordStart()}) or ends it (`routed` → `failed`, * {@see self::failStart()}); each write is one conditional update from - * `routed` without instance. + * `routed` without instance. The catch-up of the process start selects the + * routed events without instance that no attempt holds + * ({@see self::startCatchUpCandidates()}). * * All are plain DBAL calls with the id bound as type `uuid` (native UUID on * PostgreSQL, BINARY(16) on MySQL) and timestamps computed in PHP and bound @@ -322,6 +324,85 @@ public function failStart(Uuid $eventId, string $category): bool return $this->transition($eventId, WebhookEvent::STATUS_FAILED, $category, null, WebhookEvent::STATUS_ROUTED); } + /** + * The routed events without process instance that the catch-up of the + * process start may start ({@see \Dmstr\Webhook\Process\Start\ProcessStartCatchUp}), + * oldest first, in one SELECT: + * + * SELECT id FROM webhook_event + * WHERE status = 'routed' AND process_instance_id IS NULL + * AND received_at <= :youngest AND received_at >= :oldest + * AND (start_claimed_at IS NULL OR start_claimed_at < :expired) + * ORDER BY received_at ASC, id ASC + * LIMIT :limit + * + * with `:youngest` = $now minus $minAgeSeconds (a younger event is still + * the first dispatch's), `:oldest` = $now minus $maxAgeSeconds (an older + * event is never started retroactively) and `:expired` = $now minus + * $leaseSeconds (an unexpired claim belongs to a running attempt). The + * limit goes through the platform (`setMaxResults()`), never dialect SQL. + * + * Reading claims nothing: the start of each event claims it itself + * ({@see self::claimStart()}), so an event selected here and started by + * another attempt meanwhile is harmless. + * + * Time zones: `start_claimed_at` is written and compared in UTC, as in + * {@see self::claimStart()}; `received_at` is written by + * {@see self::insert()} in PHP's default time zone, so its bounds are + * bound in that zone (a MySQL DATETIME stores no offset; PostgreSQL + * compares instants either way). + * + * @param int $minAgeSeconds the minimum age of an event, at least 1 + * @param int $maxAgeSeconds the age limit of an event, greater than $minAgeSeconds + * @param int $leaseSeconds how long a claim blocks other attempts, at least 1 + * @param int $limit the maximum number of events, at least 1 + * + * @return list + */ + public function startCatchUpCandidates(\DateTimeImmutable $now, int $minAgeSeconds, int $maxAgeSeconds, int $leaseSeconds, int $limit): array + { + if ($minAgeSeconds < 1 || $maxAgeSeconds <= $minAgeSeconds) { + throw new \InvalidArgumentException('The minimum age must be at least one second and below the age limit.'); + } + if ($leaseSeconds < 1) { + throw new \InvalidArgumentException('The lease of a start claim must be at least one second.'); + } + if ($limit < 1) { + throw new \InvalidArgumentException('The limit must be at least one.'); + } + $local = $now->setTimezone(new \DateTimeZone(date_default_timezone_get())); + $utc = self::utc($now); + + $connection = $this->entityManager->getConnection(); + $ids = $connection->createQueryBuilder() + ->select('id') + ->from(WebhookEvent::TABLE) + ->where('status = :routed') + ->andWhere('process_instance_id IS NULL') + ->andWhere('received_at <= :youngest') + ->andWhere('received_at >= :oldest') + ->andWhere('(start_claimed_at IS NULL OR start_claimed_at < :expired)') + ->orderBy('received_at', 'ASC') + ->addOrderBy('id', 'ASC') + ->setMaxResults($limit) + ->setParameter('routed', WebhookEvent::STATUS_ROUTED) + ->setParameter('youngest', $local->modify(\sprintf('-%d seconds', $minAgeSeconds)), Types::DATETIMETZ_IMMUTABLE) + ->setParameter('oldest', $local->modify(\sprintf('-%d seconds', $maxAgeSeconds)), Types::DATETIMETZ_IMMUTABLE) + ->setParameter('expired', $utc->modify(\sprintf('-%d seconds', $leaseSeconds)), Types::DATETIMETZ_IMMUTABLE) + ->executeQuery() + ->fetchFirstColumn(); + + $candidates = []; + foreach ($ids as $id) { + $uuid = $connection->convertToPHPValue($id, 'uuid'); + if ($uuid instanceof Uuid) { + $candidates[] = $uuid; + } + } + + return $candidates; + } + /** The adapter's id, or its SHA-256 hex when it exceeds the column. */ public static function dedupeKey(string $id): string { @@ -379,3 +460,4 @@ private static function assertStatus(string $status): void // - revised 2026-12-05 (origin status of the conditional transition as a parameter) // - revised 2026-12-05 (references of the event context stored with the insert) // - revised 2026-12-05 (process start: read, claim, release, record and fail of a routed event) +// - revised 2026-12-06 (process start: selection of the catch-up candidates) diff --git a/src/Process/Start/ProcessStartCatchUp.php b/src/Process/Start/ProcessStartCatchUp.php new file mode 100644 index 0000000..aac8f29 --- /dev/null +++ b/src/Process/Start/ProcessStartCatchUp.php @@ -0,0 +1,198 @@ + + */ + public function candidates(?int $limit = null): array + { + return $this->events->startCatchUpCandidates( + $this->clock?->now() ?? new \DateTimeImmutable(), + $this->minAgeSeconds, + $this->maxAgeSeconds, + $this->leaseSeconds, + $limit ?? self::DEFAULT_LIMIT, + ); + } + + /** + * Starts the selected events (see the class comment). Throws only when + * the selection itself fails (e.g. the database is down); the failure + * of one event is counted in the result. + * + * @param int|null $limit at most this many events, {@see self::DEFAULT_LIMIT} when null; at least 1 + */ + public function run(?int $limit = null): ProcessStartCatchUpResult + { + $counts = array_fill_keys(array_map(static fn (ProcessStartOutcome $outcome): string => $outcome->value, ProcessStartOutcome::cases()), 0); + $failed = []; + $retrying = []; + $results = []; + + $candidates = $this->candidates($limit); + foreach ($candidates as $id) { + $eventId = $id->toRfc4122(); + try { + $outcome = $this->starter->start($id); + ++$counts[$outcome->value]; + $results[$eventId] = $outcome->value; + + continue; + } catch (ProcessStartFailedException $e) { + $category = $e->category; + $retryable = $e->isRetryable(); + } catch (\Throwable $e) { + // Before the claim (reading or claiming the event): the + // starter neither logged nor categorised it. + $category = ProcessStartFailure::START_FAILED; + $retryable = true; + $this->webhookLogger->warning(ProcessStarter::FAILED_MESSAGE, [ + 'event_id' => $eventId, + 'category' => $category, + 'retryable' => true, + 'exception_class' => get_debug_type($e), + ]); + } + + $context = ['event_id' => $eventId, 'category' => $category]; + if ($retryable) { + $retrying[$category] = ($retrying[$category] ?? 0) + 1; + $results[$eventId] = ProcessStartCatchUpResult::RETRYING.': '.$category; + $this->webhookLogger->info(self::RETRYING_MESSAGE, $context); + + continue; + } + + $failed[$category] = ($failed[$category] ?? 0) + 1; + $results[$eventId] = ProcessStartCatchUpResult::FAILED.': '.$category; + try { + if ($this->events->failStart($id, $category)) { + $this->webhookLogger->error(self::FAILED_MESSAGE, $context); + } + } catch (\Throwable $exception) { + $this->webhookLogger->error(self::NOT_SET_MESSAGE, $context + ['exception_class' => get_debug_type($exception)]); + } + } + + ksort($failed); + ksort($retrying); + $result = new ProcessStartCatchUpResult( + selected: \count($candidates), + started: $counts[ProcessStartOutcome::Started->value], + foundExisting: $counts[ProcessStartOutcome::FoundExisting->value], + nothingToDo: $counts[ProcessStartOutcome::NothingToDo->value], + claimLost: $counts[ProcessStartOutcome::ClaimLost->value], + notRecorded: $counts[ProcessStartOutcome::NotRecorded->value], + failed: $failed, + retrying: $retrying, + results: $results, + ); + + $summary = [ + 'selected' => $result->selected, + 'started' => $result->started, + 'found_existing' => $result->foundExisting, + 'nothing_to_do' => $result->nothingToDo, + 'claim_lost' => $result->claimLost, + 'not_recorded' => $result->notRecorded, + 'failed' => $result->failedCount(), + 'retrying' => $result->retryingCount(), + ]; + if (0 < $result->selected) { + $this->webhookLogger->info(self::SUMMARY_MESSAGE, $summary); + } else { + $this->webhookLogger->debug(self::SUMMARY_MESSAGE, $summary); + } + + return $result; + } +} diff --git a/src/Process/Start/ProcessStartCatchUpResult.php b/src/Process/Start/ProcessStartCatchUpResult.php new file mode 100644 index 0000000..6be7dc7 --- /dev/null +++ b/src/Process/Start/ProcessStartCatchUpResult.php @@ -0,0 +1,61 @@ + $failed number of events set to `failed` by unrecoverable category + * @param array $retrying number of events left `routed` by retryable category + * @param array $results per event id (RFC 4122), in the order of the run: a {@see ProcessStartOutcome} value, or `failed: ` / `retrying: ` + */ + public function __construct( + public int $selected = 0, + public int $started = 0, + public int $foundExisting = 0, + public int $nothingToDo = 0, + public int $claimLost = 0, + public int $notRecorded = 0, + public array $failed = [], + public array $retrying = [], + public array $results = [], + ) { + } + + /** The number of events that ended `failed` (unrecoverable categories). */ + public function failedCount(): int + { + return array_sum($this->failed); + } + + /** The number of events left `routed` after a retryable failure. */ + public function retryingCount(): int + { + return array_sum($this->retrying); + } + + /** Whether an event ended `failed` in this run: something an operator has to fix. */ + public function hasFailures(): bool + { + return 0 < $this->failedCount(); + } +} diff --git a/src/WebhookBundle.php b/src/WebhookBundle.php index 1d84e6d..7ab1db5 100644 --- a/src/WebhookBundle.php +++ b/src/WebhookBundle.php @@ -16,6 +16,8 @@ use Dmstr\Webhook\Process\Flowable\FlowableProcessEngine; use Dmstr\Webhook\Process\MissingProcessEngine; use Dmstr\Webhook\Process\ProcessEngineInterface; +use Dmstr\Webhook\Process\Start\ProcessStartCatchUp; +use Dmstr\Webhook\Process\Start\ProcessStarter; use Dmstr\Webhook\Process\Start\StartProcess; use Dmstr\Webhook\Reply\Gitlab\GitlabReplyClient; use Gitlab\Client as GitlabClient; @@ -101,6 +103,18 @@ * Parameter `dmstr_webhook.body_cap`. * - `rate_limit`: default deliveries per minute and endpoint for endpoints * without their own limit. Parameter `dmstr_webhook.rate_limit`. + * - `catch_up.min_age`, `catch_up.max_age`: the window of the catch-up of + * routed events without process instance ({@see ProcessStartCatchUp}, + * command `webhook:process:catch-up`), the age since the event was + * received in seconds: at least 300 (5 minutes) and at most 86400 (24 + * hours) by default. `max_age` must exceed `min_age` and the lease of a + * start claim ({@see ProcessStarter::LEASE_SECONDS}): a claim blocks the + * catch-up until it expired, so a shorter window would never reach an + * event whose start attempt died. Parameters + * `dmstr_webhook.catch_up.min_age` and `dmstr_webhook.catch_up.max_age`. + * The bundle ships no schedule: the application runs + * {@see ProcessStartCatchUp::run()} itself (e.g. from a Scheduler + * message handler). */ final class WebhookBundle extends AbstractBundle { @@ -159,6 +173,30 @@ public function configure(DefinitionConfigurator $definition): void ->min(1) ->defaultValue(self::DEFAULT_RATE_LIMIT) ->end() + ->arrayNode('catch_up') + ->info('Window of the catch-up of routed events without process instance (ProcessStartCatchUp, command webhook:process:catch-up), in seconds of age since the event was received.') + ->addDefaultsIfNotSet() + ->children() + ->integerNode('min_age') + ->info('Minimum age: a younger event is left to its first dispatch.') + ->min(1) + ->defaultValue(ProcessStartCatchUp::DEFAULT_MIN_AGE) + ->end() + ->integerNode('max_age') + ->info('Age limit: an older event is never started by the catch-up. Greater than min_age and than the lease of a start claim (600 seconds).') + ->min(1) + ->defaultValue(ProcessStartCatchUp::DEFAULT_MAX_AGE) + ->end() + ->end() + ->validate() + ->ifTrue(static fn (array $catchUp): bool => $catchUp['max_age'] <= $catchUp['min_age']) + ->thenInvalid('The age limit max_age must be greater than the minimum age min_age: %s.') + ->end() + ->validate() + ->ifTrue(static fn (array $catchUp): bool => $catchUp['max_age'] <= ProcessStarter::LEASE_SECONDS) + ->thenInvalid('The age limit max_age must be greater than the lease of a start claim ('.ProcessStarter::LEASE_SECONDS.' seconds), or an event whose start attempt died is never caught up: %s.') + ->end() + ->end() ->end(); } @@ -209,7 +247,7 @@ public function prependExtension(ContainerConfigurator $container, ContainerBuil } /** - * @param array{adapters: array, body_cap: int, rate_limit: int} $config + * @param array{adapters: array, body_cap: int, rate_limit: int, catch_up: array{min_age: int, max_age: int}} $config */ public function loadExtension(array $config, ContainerConfigurator $container, ContainerBuilder $builder): void { @@ -221,7 +259,9 @@ public function loadExtension(array $config, ContainerConfigurator $container, C ->set('dmstr_webhook.adapters', $adapters) ->set('dmstr_webhook.enabled_adapters', $enabledAdapters) ->set('dmstr_webhook.body_cap', $config['body_cap']) - ->set('dmstr_webhook.rate_limit', $config['rate_limit']); + ->set('dmstr_webhook.rate_limit', $config['rate_limit']) + ->set('dmstr_webhook.catch_up.min_age', $config['catch_up']['min_age']) + ->set('dmstr_webhook.catch_up.max_age', $config['catch_up']['max_age']); $builder->registerAttributeForAutoconfiguration( AsWebhookAdapter::class, @@ -329,3 +369,4 @@ public function build(ContainerBuilder $container): void // - revised 2026-12-04 (GitLab reply client: conditional registration, reply transport) // - revised 2026-12-05 (process engine port: Flowable implementation only with FlowableBundle, missing implementation otherwise) // - revised 2026-12-05 (process start: Messenger transport and routing prepended, class doc) +// - revised 2026-12-06 (process start catch-up: configuration of its window) diff --git a/tests/Integration/Command/CommandDefinitionsTest.php b/tests/Integration/Command/CommandDefinitionsTest.php index e3138f9..2593116 100644 --- a/tests/Integration/Command/CommandDefinitionsTest.php +++ b/tests/Integration/Command/CommandDefinitionsTest.php @@ -28,6 +28,7 @@ final class CommandDefinitionsTest extends KernelTestCase 'webhook:endpoint:update', 'webhook:event:list', 'webhook:event:show', + 'webhook:process:catch-up', 'webhook:process:deploy', 'webhook:route:create', 'webhook:route:delete', @@ -75,6 +76,18 @@ public function testEndpointOptionOfTheEventListIsLongOnly(): void self::assertSame('env', $command->getDefinition()->getOptionForShortcut('e')->getName()); } + public function testTheOptionsOfTheCatchUpCommand(): void + { + $command = new Application(self::bootKernel())->find('webhook:process:catch-up'); + $command->mergeApplicationDefinition(); + $definition = $command->getDefinition(); + + self::assertSame('l', $definition->getOption('limit')->getShortcut()); + self::assertSame('100', $definition->getOption('limit')->getDefault()); + self::assertFalse($definition->getOption('dry-run')->acceptValue()); + self::assertNull($definition->getOption('dry-run')->getShortcut()); + } + public function testEndpointOptionOfTheRouteAndDeployCommandsIsLongOnly(): void { $application = new Application(self::bootKernel()); @@ -90,3 +103,4 @@ public function testEndpointOptionOfTheRouteAndDeployCommandsIsLongOnly(): void // - revised 2026-12-03 (webhook:route:* console twins) // - revised 2026-12-05 (webhook:process:deploy) +// - revised 2026-12-06 (webhook:process:catch-up) diff --git a/tests/Integration/Process/ProcessStartCatchUpDatabaseTest.php b/tests/Integration/Process/ProcessStartCatchUpDatabaseTest.php new file mode 100644 index 0000000..0d1bcb3 --- /dev/null +++ b/tests/Integration/Process/ProcessStartCatchUpDatabaseTest.php @@ -0,0 +1,756 @@ + 'flowable', 'endpoint_type' => 'rest', 'base_url' => 'https://flowable.example.com', 'auth_type' => 'basic']; + + private Application $application; + private string $logFile; + private int $logOffset; + + protected function setUp(): void + { + self::cleanUp(); + $this->boot(TestKernel::ENV_FAKE_ENGINE); + } + + protected function tearDown(): void + { + self::cleanUp(); + parent::tearDown(); + } + + public function testARoutedEventWithoutInstanceInTheWindowIsStartedExactlyOnce(): void + { + $connection = $this->connection('once'); + $endpointId = $this->endpoint('once', $connection); + $routeId = $this->route('once'); + $eventId = $this->event($endpointId, $routeId, 600); + + $first = $this->catchUp()->run(); + + self::assertSame(1, $first->selected); + self::assertSame(1, $first->started); + self::assertSame([$eventId => 'started'], $first->results); + self::assertSame([], $first->failed); + self::assertSame([], $first->retrying); + self::assertFalse($first->hasFailures()); + $engine = $this->engine(); + self::assertCount(1, $engine->starts); + $start = $engine->starts[0]; + $row = $this->row($eventId); + self::assertSame(WebhookEvent::STATUS_STARTED, $row['status']); + self::assertSame($start['instanceId'], $row['process_instance_id']); + self::assertSame($row['dedupe_key'], $start['businessKey']); + self::assertSame(self::KEY, $start['key']); + self::assertSame($connection->getId()->toRfc4122(), $start['connection']); + self::assertSame($eventId, $start['variables'][ProcessStartVariables::EVENT_ID]); + self::assertSame($endpointId, $start['variables'][ProcessStartVariables::ENDPOINT_ID]); + // Directly through the starter, not through the transport. + self::assertSame([], $this->drain()->sentEventIds()); + + $second = $this->catchUp()->run(); + + self::assertSame(0, $second->selected); + self::assertSame([], $second->results); + self::assertSame(1, $engine->calls(ProcessEngineCall::Start)); + self::assertSame(1, $engine->calls(ProcessEngineCall::FindInstances)); + } + + public function testTheDefaultWindowIsBoundedByTheMinimumAgeAndTheAgeLimit(): void + { + $endpointId = $this->endpoint('window', $this->connection('window')); + $routeId = $this->route('window'); + $catchUp = $this->catchUp(); + self::assertSame(ProcessStartCatchUp::DEFAULT_MIN_AGE, $catchUp->minAgeSeconds); + self::assertSame(ProcessStartCatchUp::DEFAULT_MAX_AGE, $catchUp->maxAgeSeconds); + + $ages = [-60, 0, 299, 300, 86400, 86401]; + $events = []; + foreach ($ages as $age) { + $events[$age] = $this->event($endpointId, $routeId, $age); + } + + // Oldest first; both bounds are inclusive. + self::assertSame([$events[86400], $events[300]], self::ids($catchUp->candidates())); + + $result = $catchUp->run(); + + self::assertSame(2, $result->selected); + self::assertSame(2, $result->started); + self::assertSame([$events[86400] => 'started', $events[300] => 'started'], $result->results); + foreach ([-60, 0, 299, 86401] as $age) { + $row = $this->row($events[$age]); + self::assertSame(WebhookEvent::STATUS_ROUTED, $row['status'], 'age '.$age); + self::assertNull($row['process_instance_id'], 'age '.$age); + self::assertNull($row['start_claimed_at'], 'age '.$age); + } + self::assertSame(2, $this->engine()->calls(ProcessEngineCall::Start)); + } + + public function testTheConfiguredWindowIsUsed(): void + { + $this->boot(TestKernel::ENV_CATCH_UP); + $endpointId = $this->endpoint('configured', $this->connection('configured')); + $routeId = $this->route('configured'); + $catchUp = $this->catchUp(); + self::assertSame(TestKernel::CATCH_UP_MIN_AGE, $catchUp->minAgeSeconds); + self::assertSame(TestKernel::CATCH_UP_MAX_AGE, $catchUp->maxAgeSeconds); + // 120 is too young for the default minimum age (300), 3601 within + // the default age limit (86400): only the configuration decides. + $events = []; + foreach ([59, 60, 120, 3600, 3601] as $age) { + $events[$age] = $this->event($endpointId, $routeId, $age); + } + + self::assertSame([$events[3600], $events[120], $events[60]], self::ids($catchUp->candidates())); + $result = $catchUp->run(); + self::assertSame(3, $result->started); + self::assertSame(WebhookEvent::STATUS_ROUTED, $this->row($events[59])['status']); + self::assertSame(WebhookEvent::STATUS_ROUTED, $this->row($events[3601])['status']); + } + + public function testAnUnexpiredClaimIsLeftAndAnExpiredOneIsStartedOnce(): void + { + $endpointId = $this->endpoint('lease', $this->connection('lease')); + $routeId = $this->route('lease'); + $lease = ProcessStarter::LEASE_SECONDS; + // A running attempt; an attempt that died; one whose claim expires in a second. + $running = $this->event($endpointId, $routeId, 900, claimAge: 100); + $died = $this->event($endpointId, $routeId, 800, claimAge: $lease + 1); + $expiring = $this->event($endpointId, $routeId, 700, claimAge: $lease); + + self::assertSame([$died], self::ids($this->catchUp()->candidates())); + $first = $this->catchUp()->run(); + + self::assertSame([$died => 'started'], $first->results); + self::assertSame(WebhookEvent::STATUS_STARTED, $this->row($died)['status']); + self::assertSame(WebhookEvent::STATUS_ROUTED, $this->row($running)['status']); + self::assertNotNull($this->row($running)['start_claimed_at']); + self::assertSame(WebhookEvent::STATUS_ROUTED, $this->row($expiring)['status']); + self::assertSame(0, $this->catchUp()->run()->selected); + self::assertSame(1, $this->engine()->calls(ProcessEngineCall::Start)); + + $this->clock()->sleep(1); + + self::assertSame([$expiring => 'started'], $this->catchUp()->run()->results); + self::assertSame(WebhookEvent::STATUS_ROUTED, $this->row($running)['status']); + self::assertSame(2, $this->engine()->calls(ProcessEngineCall::Start)); + self::assertCount(2, $this->engine()->starts); + } + + public function testTheCatchUpFirstLeavesTheMessageNothingToDo(): void + { + $this->endpoint('catch-up-first', $this->connection('catch-up-first')); + $this->route('catch-up-first'); + $eventId = $this->receive('catch-up-first', 'note-merge-request-mention'); + $drain = $this->drain(); + self::assertSame([$eventId], $drain->sentEventIds()); + // Fresh events belong to the first dispatch. + self::assertSame([], $this->catchUp()->candidates()); + $this->setAge($eventId, 600); + + self::assertSame([$eventId => 'started'], $this->catchUp()->run()->results); + self::assertSame(1, $drain->run()); + + self::assertSame([], $drain->failures); + $engine = $this->engine(); + self::assertSame(1, $engine->calls(ProcessEngineCall::Start)); + self::assertCount(1, $engine->instances()); + $row = $this->row($eventId); + self::assertSame(WebhookEvent::STATUS_STARTED, $row['status']); + self::assertSame($engine->starts[0]['instanceId'], $row['process_instance_id']); + self::assertStringContainsString(ProcessStarter::NOTHING_TO_DO_MESSAGE, $this->log()); + } + + public function testTheMessageFirstLeavesTheCatchUpNothingToSelect(): void + { + $this->endpoint('message-first', $this->connection('message-first')); + $this->route('message-first'); + $eventId = $this->receive('message-first', 'note-merge-request-mention'); + $this->setAge($eventId, 600); + + self::assertSame(1, $this->drain()->run()); + self::assertSame(WebhookEvent::STATUS_STARTED, $this->row($eventId)['status']); + + self::assertSame([], $this->catchUp()->candidates()); + self::assertSame(0, $this->catchUp()->run()->selected); + self::assertSame(1, $this->engine()->calls(ProcessEngineCall::Start)); + self::assertSame(1, $this->engine()->calls(ProcessEngineCall::FindInstances)); + self::assertCount(1, $this->engine()->instances()); + } + + public function testTheInstanceOfAHandlerThatDiedAfterTheEngineStartIsRecorded(): void + { + $connection = $this->connection('died'); + $endpointId = $this->endpoint('died', $connection); + $routeId = $this->route('died'); + $eventId = $this->event($endpointId, $routeId, 900, claimAge: ProcessStarter::LEASE_SECONDS + 1); + // The engine started the instance; the handler died before it wrote the id. + $engine = $this->engine(); + $instanceId = $engine->start($connection, self::KEY, $this->row($eventId)['dedupe_key'], [ + ProcessStartVariables::EVENT_ID => $eventId, + ProcessStartVariables::ENDPOINT_ID => $endpointId, + ]); + + $result = $this->catchUp()->run(); + + self::assertSame([$eventId => 'found_existing'], $result->results); + self::assertSame(1, $result->foundExisting); + self::assertSame(0, $result->started); + self::assertSame(1, $engine->calls(ProcessEngineCall::Start), 'found, not started again'); + $row = $this->row($eventId); + self::assertSame(WebhookEvent::STATUS_STARTED, $row['status']); + self::assertSame($instanceId, $row['process_instance_id']); + } + + public function testOnlyRoutedEventsWithoutInstanceAreSelected(): void + { + $connection = $this->connection('statuses'); + $endpointId = $this->endpoint('statuses', $connection); + $routeId = $this->route('statuses'); + $handlerEndpointId = $this->plainEndpoint('handler', 'handler'); + + $others = [ + 'handled at a handler endpoint' => $this->event($handlerEndpointId, null, 600, WebhookEvent::STATUS_HANDLED), + 'received at a handler endpoint' => $this->event($handlerEndpointId, null, 600, WebhookEvent::STATUS_RECEIVED), + 'received' => $this->event($endpointId, null, 600, WebhookEvent::STATUS_RECEIVED), + 'ignored' => $this->event($endpointId, null, 600, WebhookEvent::STATUS_IGNORED), + 'started' => $this->event($endpointId, $routeId, 600, WebhookEvent::STATUS_STARTED, instanceId: 'instance-started'), + 'failed' => $this->event($endpointId, $routeId, 600, WebhookEvent::STATUS_FAILED), + 'routed with an instance' => $this->event($endpointId, $routeId, 600, instanceId: 'instance-routed'), + ]; + $routed = $this->event($endpointId, $routeId, 600); + + self::assertSame([$routed], self::ids($this->catchUp()->candidates())); + self::assertSame([$routed => 'started'], $this->catchUp()->run()->results); + + foreach ($others as $name => $eventId) { + self::assertNull($this->row($eventId)['start_claimed_at'], $name); + } + self::assertSame(WebhookEvent::STATUS_HANDLED, $this->row($others['handled at a handler endpoint'])['status']); + self::assertSame(WebhookEvent::STATUS_IGNORED, $this->row($others['ignored'])['status']); + self::assertSame('instance-started', $this->row($others['started'])['process_instance_id']); + self::assertSame('instance-routed', $this->row($others['routed with an instance'])['process_instance_id']); + self::assertSame(1, $this->engine()->calls(ProcessEngineCall::Start)); + self::assertSame(1, $this->engine()->calls(ProcessEngineCall::FindInstances)); + } + + public function testAnUnrecoverableFailureFailsTheEventAtOnce(): void + { + $endpointId = $this->endpoint('unrecoverable', $this->connection('unrecoverable')); + $routeId = $this->route('unrecoverable'); + $eventId = $this->event($endpointId, $routeId, 600); + $this->engine()->failOn(ProcessEngineCall::Start, ProcessEngineFailure::DefinitionNotDeployed); + + $result = $this->catchUp()->run(); + + self::assertSame(['definition_not_deployed' => 1], $result->failed); + self::assertSame([], $result->retrying); + self::assertSame([$eventId => 'failed: definition_not_deployed'], $result->results); + self::assertTrue($result->hasFailures()); + $row = $this->row($eventId); + self::assertSame(WebhookEvent::STATUS_FAILED, $row['status']); + self::assertSame(ProcessEngineFailure::DefinitionNotDeployed->value, $row['reason']); + self::assertNull($row['process_instance_id']); + self::assertStringContainsString('Webhook process start catch-up gave up', $this->log()); + + self::assertSame(0, $this->catchUp()->run()->selected); + self::assertSame(1, $this->engine()->calls(ProcessEngineCall::Start)); + } + + public function testARetryableFailureLeavesTheEventRoutedForTheNextRun(): void + { + $endpointId = $this->endpoint('retryable', $this->connection('retryable')); + $routeId = $this->route('retryable'); + $eventId = $this->event($endpointId, $routeId, 600); + $this->engine()->failOn(ProcessEngineCall::Start, ProcessEngineFailure::EngineUnreachable, 1); + + $first = $this->catchUp()->run(); + + self::assertSame([], $first->failed); + self::assertSame(['engine_unreachable' => 1], $first->retrying); + self::assertSame([$eventId => 'retrying: engine_unreachable'], $first->results); + self::assertFalse($first->hasFailures()); + $row = $this->row($eventId); + self::assertSame(WebhookEvent::STATUS_ROUTED, $row['status']); + self::assertNull($row['reason']); + self::assertNull($row['start_claimed_at'], 'the starter released its claim'); + + // The engine is back: the next run starts it, without waiting for a lease. + $second = $this->catchUp()->run(); + + self::assertSame([$eventId => 'started'], $second->results); + self::assertSame(WebhookEvent::STATUS_STARTED, $this->row($eventId)['status']); + self::assertSame(2, $this->engine()->calls(ProcessEngineCall::Start)); + self::assertCount(1, $this->engine()->starts); + } + + public function testOneFailingEventDoesNotStopTheOthersAndNothingLeaks(): void + { + $inactiveId = $this->endpoint('inactive', $this->connection('inactive', active: false)); + $inactiveRoute = $this->route('inactive'); + $crashId = $this->endpoint('crash', $this->connection('crash')); + $crashRoute = $this->route('crash'); + $fineId = $this->endpoint('fine', $this->connection('fine')); + $fineRoute = $this->route('fine'); + $payload = '{"note":"'.self::MARKER.'"}'; + $inactive = $this->event($inactiveId, $inactiveRoute, 900, payload: $payload); + $crash = $this->event($crashId, $crashRoute, 800, payload: $payload); + $fine = $this->event($fineId, $fineRoute, 700, payload: $payload); + // The first start call (the inactive connection fails before it) + // creates the instance and dies with a text of its own. + $this->engine()->crashAfterNextStart(new \RuntimeException(self::MARKER.' '.GitlabFixtures::TOKEN)); + + $run = $this->execute('webhook:process:catch-up', []); + + self::assertSame(Command::FAILURE, $run->getStatusCode(), $run->getDisplay()); + $display = self::flat($run->getDisplay()); + self::assertStringContainsString($inactive.' failed: connection_inactive', $display); + self::assertStringContainsString($crash.' retrying: start_failed', $display); + self::assertStringContainsString($fine.' started', $display); + self::assertStringContainsString('3 event(s): 1 started, 0 found existing, 0 nothing to do, 0 claim lost, 0 not recorded, 1 failed, 1 left for the next run.', $display); + self::assertSame(WebhookEvent::STATUS_FAILED, $this->row($inactive)['status']); + self::assertSame(ProcessEngineFailure::ConnectionInactive->value, $this->row($inactive)['reason']); + self::assertSame(WebhookEvent::STATUS_ROUTED, $this->row($crash)['status']); + self::assertNull($this->row($crash)['reason']); + self::assertSame(WebhookEvent::STATUS_STARTED, $this->row($fine)['status']); + + // The crashed one is found by the next run, not started again. + $again = $this->execute('webhook:process:catch-up', []); + + self::assertSame(Command::SUCCESS, $again->getStatusCode(), $again->getDisplay()); + $display .= ' '.self::flat($again->getDisplay()); + self::assertStringContainsString($crash.' found_existing', $display); + self::assertStringContainsString('1 event(s): 0 started, 1 found existing, 0 nothing to do, 0 claim lost, 0 not recorded, 0 failed, 0 left for the next run.', $display); + self::assertSame(WebhookEvent::STATUS_STARTED, $this->row($crash)['status']); + self::assertSame(2, $this->engine()->calls(ProcessEngineCall::Start)); + self::assertCount(2, $this->engine()->instances()); + + // No engine text, payload or secret in the output, a reason or the log. + $reasons = implode(' ', array_map(fn (string $id): string => (string) $this->row($id)['reason'], [$inactive, $crash, $fine])); + foreach ([self::MARKER, GitlabFixtures::TOKEN] as $secret) { + self::assertStringNotContainsString($secret, $display); + self::assertStringNotContainsString($secret, $reasons); + self::assertStringNotContainsString($secret, $this->log()); + } + self::assertStringContainsString('start_failed', $this->log()); + } + + public function testWithoutEngineARoutedEventFailsWithEnginePortMissing(): void + { + $this->boot(TestKernel::ENV_MINIMAL); + $endpointId = $this->plainEndpoint('minimal', 'process'); + $routeId = $this->route('minimal'); + $eventId = $this->event($endpointId, $routeId, 600); + + $result = $this->catchUp()->run(); + + self::assertSame([ProcessEngineFailure::EnginePortMissing->value => 1], $result->failed); + self::assertSame([$eventId => 'failed: engine_port_missing'], $result->results); + $row = $this->row($eventId); + self::assertSame(WebhookEvent::STATUS_FAILED, $row['status']); + self::assertSame(ProcessEngineFailure::EnginePortMissing->value, $row['reason']); + self::assertNull($row['process_instance_id']); + } + + public function testTheDryRunListsAndChangesNothing(): void + { + $endpointId = $this->endpoint('dry-run', $this->connection('dry-run')); + $routeId = $this->route('dry-run'); + $older = $this->event($endpointId, $routeId, 900); + $newer = $this->event($endpointId, $routeId, 600); + $young = $this->event($endpointId, $routeId, 10); + + $run = $this->execute('webhook:process:catch-up', ['--dry-run' => true]); + + self::assertSame(Command::SUCCESS, $run->getStatusCode(), $run->getDisplay()); + $display = self::flat($run->getDisplay()); + self::assertStringContainsString('Routed events without process instance, received 300 to 86400 seconds ago (dry run):', $display); + self::assertMatchesRegularExpression('/'.preg_quote($older, '/').'.*'.preg_quote($newer, '/').'/', $display); + self::assertStringNotContainsString($young, $display); + self::assertStringContainsString('Dry run: 2 event(s) would be started; nothing was claimed or started.', $display); + self::assertSame(0, $this->engine()->calls()); + foreach ([$older, $newer, $young] as $eventId) { + $row = $this->row($eventId); + self::assertSame(WebhookEvent::STATUS_ROUTED, $row['status']); + self::assertNull($row['start_claimed_at']); + } + + // The dry run with a limit lists the oldest. + $limited = $this->execute('webhook:process:catch-up', ['--dry-run' => true, '--limit' => '1']); + self::assertSame(Command::SUCCESS, $limited->getStatusCode()); + $display = self::flat($limited->getDisplay()); + self::assertStringContainsString($older, $display); + self::assertStringNotContainsString($newer, $display); + self::assertSame(0, $this->engine()->calls()); + } + + public function testTheCommandRespectsTheLimitAndReportsTheCounts(): void + { + $endpointId = $this->endpoint('limit', $this->connection('limit')); + $routeId = $this->route('limit'); + $first = $this->event($endpointId, $routeId, 900); + $second = $this->event($endpointId, $routeId, 800); + $third = $this->event($endpointId, $routeId, 700); + + $run = $this->execute('webhook:process:catch-up', ['--limit' => '2']); + + self::assertSame(Command::SUCCESS, $run->getStatusCode(), $run->getDisplay()); + $display = self::flat($run->getDisplay()); + self::assertStringContainsString('Routed events without process instance, received 300 to 86400 seconds ago:', $display); + self::assertStringContainsString($first.' started', $display); + self::assertStringContainsString($second.' started', $display); + self::assertStringNotContainsString($third, $display); + self::assertStringContainsString('2 event(s): 2 started, 0 found existing, 0 nothing to do, 0 claim lost, 0 not recorded, 0 failed, 0 left for the next run.', $display); + self::assertSame(WebhookEvent::STATUS_ROUTED, $this->row($third)['status']); + self::assertSame(2, $this->engine()->calls(ProcessEngineCall::Start)); + + $rest = $this->execute('webhook:process:catch-up', []); + self::assertSame(Command::SUCCESS, $rest->getStatusCode(), $rest->getDisplay()); + self::assertStringContainsString('1 event(s): 1 started,', self::flat($rest->getDisplay())); + + $nothing = $this->execute('webhook:process:catch-up', []); + self::assertSame(Command::SUCCESS, $nothing->getStatusCode(), $nothing->getDisplay()); + self::assertStringContainsString('No routed event without process instance to catch up.', self::flat($nothing->getDisplay())); + self::assertSame(3, $this->engine()->calls(ProcessEngineCall::Start)); + + foreach (['0', '-1', 'abc', '1.5'] as $invalid) { + $wrong = $this->execute('webhook:process:catch-up', ['--limit' => $invalid]); + self::assertSame(Command::FAILURE, $wrong->getStatusCode(), $invalid); + self::assertStringContainsString('--limit must be a positive integer.', self::flat($wrong->getDisplay()), $invalid); + } + self::assertSame(3, $this->engine()->calls(ProcessEngineCall::Start)); + } + + public function testARetryableFailureExitsZeroWithAWarning(): void + { + $endpointId = $this->endpoint('warning', $this->connection('warning')); + $routeId = $this->route('warning'); + $eventId = $this->event($endpointId, $routeId, 600); + $this->engine()->failOn(ProcessEngineCall::Start, ProcessEngineFailure::EngineError); + + $run = $this->execute('webhook:process:catch-up', []); + + self::assertSame(Command::SUCCESS, $run->getStatusCode(), $run->getDisplay()); + $display = self::flat($run->getDisplay()); + self::assertStringContainsString('[WARNING]', $display); + self::assertStringContainsString($eventId.' retrying: engine_error', $display); + self::assertStringContainsString('1 event(s): 0 started, 0 found existing, 0 nothing to do, 0 claim lost, 0 not recorded, 0 failed, 1 left for the next run.', $display); + self::assertSame(WebhookEvent::STATUS_ROUTED, $this->row($eventId)['status']); + } + + /** + * Boots the kernel of $environment for the rest of the test; the log + * offset starts at the current end of its log file. + */ + private function boot(string $environment): void + { + static::ensureKernelShutdown(); + $kernel = self::bootKernel(['environment' => $environment]); + self::assertInstanceOf(TestKernel::class, $kernel); + TestDatabase::migrate($kernel); + $this->application = new Application($kernel); + $this->logFile = $kernel->logFile(); + clearstatcache(); + $this->logOffset = is_file($this->logFile) ? (int) filesize($this->logFile) : 0; + } + + private function catchUp(): ProcessStartCatchUp + { + $catchUp = self::getContainer()->get(ProcessStartCatchUp::class); + self::assertInstanceOf(ProcessStartCatchUp::class, $catchUp); + + return $catchUp; + } + + private function engine(): FakeProcessEngine + { + $engine = self::getContainer()->get(FakeProcessEngine::class); + self::assertInstanceOf(FakeProcessEngine::class, $engine); + + return $engine; + } + + private function drain(): TransportDrain + { + return new TransportDrain(self::getContainer()); + } + + private function clock(): MockClock + { + $clock = self::getContainer()->get('clock'); + self::assertInstanceOf(MockClock::class, $clock); + + return $clock; + } + + /** + * A connection named with {@see self::PREFIX}, persisted. + * + * @param array $config + */ + private function connection(string $name, array $config = self::FLOWABLE, bool $active = true): ApiConfiguration + { + $connection = new ApiConfiguration() + ->setName(self::PREFIX.$name.'-'.bin2hex(random_bytes(3))) + ->setConfigJson($config) + ->setActive($active); + $entityManager = self::getContainer()->get('doctrine.orm.entity_manager'); + self::assertInstanceOf(EntityManagerInterface::class, $entityManager); + $entityManager->persist($connection); + $entityManager->flush(); + + return $connection; + } + + /** + * A GitLab endpoint in mode `process` as in the fixture matrix (the bot + * as own identity, the author of the fixtures on the allowlist), created + * with the console; its id (RFC 4122). + */ + private function endpoint(string $name, ApiConfiguration $connection): string + { + $create = $this->execute('webhook:endpoint:create', [ + 'slug' => self::PREFIX.$name, + '--source-type' => 'gitlab', + '--mode' => 'process', + '--secret' => GitlabFixtures::TOKEN, + '--actor-id' => GitlabFixtures::BOT_ID, + '--actor-handle' => GitlabFixtures::BOT_HANDLE, + '--allowed-actor-ids' => GitlabFixtures::ANN_ID, + '--flowable-connection' => $connection->getId()->toRfc4122(), + ]); + self::assertSame(Command::SUCCESS, $create->getStatusCode(), $create->getDisplay()); + + return TestDatabase::endpointId($this->dbal(), self::PREFIX.$name); + } + + /** A `passthrough` endpoint without connection in $mode, created with the console; its id (RFC 4122). */ + private function plainEndpoint(string $name, string $mode): string + { + $create = $this->execute('webhook:endpoint:create', ['slug' => self::PREFIX.$name, '--mode' => $mode, '--secret' => self::PLAIN_SECRET]); + self::assertSame(Command::SUCCESS, $create->getStatusCode(), $create->getDisplay()); + + return TestDatabase::endpointId($this->dbal(), self::PREFIX.$name); + } + + /** The one catch-all route of the endpoint, created with the console; its id (RFC 4122). */ + private function route(string $endpoint): string + { + $create = $this->execute('webhook:route:create', [ + 'name' => 'all', + '--endpoint' => self::PREFIX.$endpoint, + '--process-definition-key' => self::KEY, + '--agent' => self::AGENT, + ]); + self::assertSame(Command::SUCCESS, $create->getStatusCode(), $create->getDisplay()); + + $id = $this->dbal()->fetchOne( + 'SELECT r.id FROM webhook_route r JOIN webhook_endpoint e ON e.id = r.endpoint_id WHERE e.slug = ?', + [self::PREFIX.$endpoint], + ); + self::assertNotFalse($id); + + return TestDatabase::uuid($this->dbal(), $id); + } + + /** + * An event of the endpoint, inserted through DBAL, received $age seconds + * before the frozen clock (negative: after it), in $status with the + * route; with $claimAge a claim that many seconds old, with $instanceId + * a process instance. Its id (RFC 4122). + */ + private function event(string $endpointId, ?string $routeId, int $age, string $status = WebhookEvent::STATUS_ROUTED, ?int $claimAge = null, ?string $instanceId = null, string $payload = '{}'): string + { + $id = TestDatabase::insertEvent($this->dbal(), $endpointId, 'catch-up-'.bin2hex(random_bytes(6)), $payload); + $now = $this->clock()->now(); + $this->dbal()->update(WebhookEvent::TABLE, [ + 'status' => $status, + 'route' => $routeId, + 'process_instance_id' => $instanceId, + 'start_claimed_at' => null === $claimAge ? null : $now->setTimezone(new \DateTimeZone('UTC'))->modify(\sprintf('-%d seconds', $claimAge)), + ], ['id' => Uuid::fromString($id)], [ + 'id' => 'uuid', + 'start_claimed_at' => Types::DATETIMETZ_IMMUTABLE, + ]); + $this->setAge($id, $age); + + return $id; + } + + /** + * Sets `received_at` of an event to $age seconds before the frozen + * clock, in PHP's default time zone, as the intake writes it. + */ + private function setAge(string $eventId, int $age): void + { + $receivedAt = $this->clock()->now() + ->setTimezone(new \DateTimeZone(date_default_timezone_get())) + ->modify(\sprintf('%+d seconds', -$age)); + $this->dbal()->update( + WebhookEvent::TABLE, + ['received_at' => $receivedAt], + ['id' => Uuid::fromString($eventId)], + ['id' => 'uuid', 'received_at' => Types::DATETIMETZ_IMMUTABLE], + ); + } + + /** Delivers a GitLab fixture through the kernel's intake; its one routed event (RFC 4122). */ + private function receive(string $endpoint, string $fixture): string + { + $request = Request::create('/webhook/'.self::PREFIX.$endpoint, 'POST', server: ['REMOTE_ADDR' => '127.0.0.1'], content: GitlabFixtures::body($fixture)); + foreach (GitlabFixtures::headers($fixture) as $name => $value) { + $request->headers->set($name, $value); + } + $intake = self::getContainer()->get(WebhookIntake::class); + self::assertInstanceOf(WebhookIntake::class, $intake); + $outcome = $intake->receive($request, self::PREFIX.$endpoint); + + self::assertSame(202, $outcome->statusCode()); + self::assertCount(1, $outcome->events); + $eventId = $outcome->events[0]->eventId; + self::assertNotNull($eventId); + self::assertSame(WebhookEvent::STATUS_ROUTED, $this->row($eventId->toRfc4122())['status']); + + return $eventId->toRfc4122(); + } + + /** + * The start columns of an event. + * + * @return array{status: string, reason: ?string, dedupe_key: string, process_instance_id: ?string, start_claimed_at: mixed} + */ + private function row(string $eventId): array + { + $row = $this->dbal()->fetchAssociative( + 'SELECT status, reason, dedupe_key, process_instance_id, start_claimed_at FROM webhook_event WHERE id = ?', + [Uuid::fromString($eventId)], + ['uuid'], + ); + self::assertIsArray($row, 'No event '.$eventId); + + /** @var array{status: string, reason: ?string, dedupe_key: string, process_instance_id: ?string, start_claimed_at: mixed} $row */ + return $row; + } + + /** + * @param list $ids + * + * @return list + */ + private static function ids(array $ids): array + { + return array_map(static fn (Uuid $id): string => $id->toRfc4122(), $ids); + } + + /** What this test wrote to the log file of the kernel. */ + private function log(): string + { + clearstatcache(); + + return is_file($this->logFile) ? (string) file_get_contents($this->logFile, false, null, $this->logOffset) : ''; + } + + /** + * The output as one line: the line prefix `!` of note blocks dropped, + * every run of white space (line breaks, padding, table spacing) one + * space. + */ + private static function flat(string $display): string + { + return trim((string) preg_replace('/\s+/', ' ', (string) preg_replace('/^\s*!\s?/m', '', $display))); + } + + /** + * @param array $input + */ + private function execute(string $name, array $input): CommandTester + { + $tester = new CommandTester($this->application->find($name)); + $tester->execute($input, ['interactive' => false]); + + return $tester; + } + + private function dbal(): Connection + { + $kernel = self::$kernel; + self::assertNotNull($kernel); + + return TestDatabase::connection($kernel); + } + + private static function cleanUp(): void + { + static::ensureKernelShutdown(); + $kernel = static::bootKernel(['environment' => TestKernel::ENV_FAKE_ENGINE]); + TestDatabase::migrate($kernel); + $connection = TestDatabase::connection($kernel); + TestDatabase::removeEndpoints($connection, self::PREFIX); + $connection->executeStatement('DELETE FROM dmstr_api_configuration WHERE name LIKE ?', [self::PREFIX.'%']); + static::ensureKernelShutdown(); + } +} diff --git a/tests/Kernel/TestKernel.php b/tests/Kernel/TestKernel.php index 416d692..9e5394b 100644 --- a/tests/Kernel/TestKernel.php +++ b/tests/Kernel/TestKernel.php @@ -18,6 +18,7 @@ use Dmstr\Webhook\Adapter\GitlabParser; use Dmstr\Webhook\DependencyInjection\OptionalLibraries; use Dmstr\Webhook\Process\ProcessEngineInterface; +use Dmstr\Webhook\Process\Start\ProcessStartCatchUp; use Dmstr\Webhook\Process\Start\ProcessStarter; use Dmstr\Webhook\Reply\Gitlab\GitlabReplyClient; use Dmstr\Webhook\Tests\Support\FakeProcessEngine; @@ -149,6 +150,10 @@ * with the in-memory {@see FakeProcessEngine} (public service * {@see FakeProcessEngine}, the alias {@see ProcessEngineInterface} points * to it), without FlowableBundle; + * - {@see self::ENV_CATCH_UP}: as {@see self::ENV_FAKE_ENGINE}, with a + * non-default window of the catch-up of the process start + * (`dmstr_webhook.catch_up`: {@see self::CATCH_UP_MIN_AGE}, + * {@see self::CATCH_UP_MAX_AGE}); * - {@see self::ENV_DEFAULT_TRANSPORT}: the host defines no transport * {@see self::MESSENGER_TRANSPORT}, so the bundle's default is used, and * routes a message of its own ({@see HostTestMessage}) to its transport @@ -158,7 +163,8 @@ * Where the GitLab reply client is registered, {@see self::process()} makes * it public, as a consumer of the host would keep it, so the tests can fetch * it; the same for the alias {@see ProcessEngineInterface} of the process - * engine port, the {@see ProcessStarter} and the Messenger transports. + * engine port, the {@see ProcessStarter}, the {@see ProcessStartCatchUp} + * and the Messenger transports. * * Cache and logs live under the system temp directory, one directory per * variant, so a test run leaves no files in the repository. @@ -177,6 +183,12 @@ final class TestKernel extends Kernel implements CompilerPassInterface public const string ENV_FLOWABLE = 'test_flowable'; public const string ENV_FAKE_ENGINE = 'test_fake_engine'; public const string ENV_DEFAULT_TRANSPORT = 'test_default_transport'; + public const string ENV_CATCH_UP = 'test_catch_up'; + + /** `dmstr_webhook.catch_up.min_age` of {@see self::ENV_CATCH_UP} (the default is 300). */ + public const int CATCH_UP_MIN_AGE = 60; + /** `dmstr_webhook.catch_up.max_age` of {@see self::ENV_CATCH_UP} (the default is 86400). */ + public const int CATCH_UP_MAX_AGE = 3600; /** The host's Messenger transport of the process start, in memory. */ public const string MESSENGER_TRANSPORT = 'webhook'; @@ -281,6 +293,12 @@ public function hasMonolog(): bool return self::ENV_MINIMAL !== $this->environment; } + /** Whether the host replaces the process engine port with the {@see FakeProcessEngine}. */ + public function hasFakeEngine(): bool + { + return \in_array($this->environment, [self::ENV_FAKE_ENGINE, self::ENV_CATCH_UP], true); + } + /** Whether FlowableBundle is registered (it needs MonologBundle). */ public function hasFlowable(): bool { @@ -316,12 +334,13 @@ public function process(ContainerBuilder $container): void if ($container->hasDefinition(GitlabReplyClient::class)) { $container->getDefinition(GitlabReplyClient::class)->setPublic(true); } - // The engine port, the starter (used by the message handler only) - // and the transports, so the tests can fetch them. + // The engine port, the starter (used by the message handler only), + // the catch-up (used by its command only) and the transports, so + // the tests can fetch them. if ($container->hasAlias(ProcessEngineInterface::class)) { $container->getAlias(ProcessEngineInterface::class)->setPublic(true); } - foreach ([ProcessStarter::class, self::TRANSPORT_SERVICE, self::HOST_TRANSPORT_SERVICE] as $id) { + foreach ([ProcessStarter::class, ProcessStartCatchUp::class, self::TRANSPORT_SERVICE, self::HOST_TRANSPORT_SERVICE] as $id) { if ($container->hasDefinition($id)) { $container->getDefinition($id)->setPublic(true); } @@ -480,11 +499,15 @@ private function configureContainer(ContainerConfigurator $container): void 'relation_labels' => ['enabled' => true], ]); - $container->extension('dmstr_webhook', [ + $webhook = [ 'adapters' => self::ENV_GITLAB_OFF === $this->environment ? array_replace(self::ADAPTERS, [GitlabParser::SOURCE => false]) : self::ADAPTERS, - ]); + ]; + if (self::ENV_CATCH_UP === $this->environment) { + $webhook['catch_up'] = ['min_age' => self::CATCH_UP_MIN_AGE, 'max_age' => self::CATCH_UP_MAX_AGE]; + } + $container->extension('dmstr_webhook', $webhook); if ($this->hasMonolog()) { $container->extension('monolog', [ @@ -533,7 +556,7 @@ private function configureContainer(ContainerConfigurator $container): void $services->set(WebhookBundle::REPLY_HTTP_CLIENT, MockHttpClient::class); } - if (self::ENV_FAKE_ENGINE === $this->environment) { + if ($this->hasFakeEngine()) { // The host's own engine port; its definitions win over the // bundle's alias. $services->set(FakeProcessEngine::class)->public(); @@ -586,3 +609,4 @@ private static function attributeMapping(string $class, string $prefix): array // - revised 2026-12-04 (GitLab reply client: variants without library, with the adapter off, with the host's transport, minimal without http_client) // - revised 2026-12-05 (process engine port: variants with FlowableBundle and with the fake engine, Messenger with an in-memory transport) // - revised 2026-12-05 (process start: variant with the bundle's default transport, public starter and transports) +// - revised 2026-12-06 (process start catch-up: variant with a non-default window, public catch-up service) diff --git a/tests/Unit/DependencyInjection/WebhookBundleConfigurationTest.php b/tests/Unit/DependencyInjection/WebhookBundleConfigurationTest.php index 5f49d9e..ae74439 100644 --- a/tests/Unit/DependencyInjection/WebhookBundleConfigurationTest.php +++ b/tests/Unit/DependencyInjection/WebhookBundleConfigurationTest.php @@ -6,17 +6,25 @@ namespace Dmstr\Webhook\Tests\Unit\DependencyInjection; +use Dmstr\Webhook\Process\Start\ProcessStartCatchUp; +use Dmstr\Webhook\Process\Start\ProcessStartCatchUpResult; +use Dmstr\Webhook\Process\Start\ProcessStarter; use Dmstr\Webhook\WebhookBundle; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException; use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\ContainerInterface; +use Symfony\Component\DependencyInjection\Reference; /** * The bundle configuration `dmstr_webhook` and the container parameters it * publishes: only `passthrough` is enabled by default, the body cap * defaults to and is capped at 1 MiB, the rate limit defaults to 60 per - * minute. Loads the extension into a bare ContainerBuilder; no kernel, no - * database. + * minute, the window of the process start catch-up defaults to 300 seconds + * (minimum age) to 86400 seconds (age limit), and the age limit must exceed + * the minimum age and the lease of a start claim. Loads the extension into + * a bare ContainerBuilder; no kernel, no database. */ final class WebhookBundleConfigurationTest extends TestCase { @@ -28,6 +36,70 @@ public function testDefaults(): void self::assertSame(['passthrough'], $container->getParameter('dmstr_webhook.enabled_adapters')); self::assertSame(1048576, $container->getParameter('dmstr_webhook.body_cap')); self::assertSame(60, $container->getParameter('dmstr_webhook.rate_limit')); + self::assertSame(300, $container->getParameter('dmstr_webhook.catch_up.min_age')); + self::assertSame(86400, $container->getParameter('dmstr_webhook.catch_up.max_age')); + self::assertSame(300, ProcessStartCatchUp::DEFAULT_MIN_AGE); + self::assertSame(86400, ProcessStartCatchUp::DEFAULT_MAX_AGE); + } + + public function testTheCatchUpServiceGetsTheWindowFromTheConfiguration(): void + { + $container = self::load(['catch_up' => ['min_age' => 60, 'max_age' => 3600]]); + + self::assertSame(60, $container->getParameter('dmstr_webhook.catch_up.min_age')); + self::assertSame(3600, $container->getParameter('dmstr_webhook.catch_up.max_age')); + $definition = $container->getDefinition(ProcessStartCatchUp::class); + self::assertSame('%dmstr_webhook.catch_up.min_age%', $definition->getArgument('$minAgeSeconds')); + self::assertSame('%dmstr_webhook.catch_up.max_age%', $definition->getArgument('$maxAgeSeconds')); + $clock = $definition->getArgument('$clock'); + self::assertInstanceOf(Reference::class, $clock); + self::assertSame('clock', (string) $clock); + self::assertSame(ContainerInterface::IGNORE_ON_INVALID_REFERENCE, $clock->getInvalidBehavior()); + self::assertTrue($definition->isAutowired()); + self::assertFalse($definition->hasTag('container.excluded')); + + // The result is a value object: no definition, or only the abstract + // `container.excluded` marker of an uncompiled container. + $result = $container->hasDefinition(ProcessStartCatchUpResult::class) ? $container->getDefinition(ProcessStartCatchUpResult::class) : null; + self::assertTrue(null === $result || ($result->isAbstract() && $result->hasTag('container.excluded'))); + } + + public function testOneBoundOfTheCatchUpWindowKeepsTheOtherDefault(): void + { + $container = self::load(['catch_up' => ['min_age' => 120]]); + + self::assertSame(120, $container->getParameter('dmstr_webhook.catch_up.min_age')); + self::assertSame(86400, $container->getParameter('dmstr_webhook.catch_up.max_age')); + } + + /** @return iterable}> */ + public static function invalidCatchUpWindows(): iterable + { + yield 'minimum age zero' => [['min_age' => 0]]; + yield 'negative minimum age' => [['min_age' => -1]]; + yield 'age limit zero' => [['max_age' => 0]]; + yield 'age limit below the minimum age' => [['min_age' => 3600, 'max_age' => 1800]]; + yield 'age limit equal to the minimum age' => [['min_age' => 3600, 'max_age' => 3600]]; + yield 'age limit equal to the lease' => [['min_age' => 60, 'max_age' => ProcessStarter::LEASE_SECONDS]]; + yield 'age limit below the default minimum age' => [['max_age' => 200]]; + yield 'not an integer' => [['min_age' => '5 minutes']]; + } + + /** + * @param array $catchUp + */ + #[DataProvider('invalidCatchUpWindows')] + public function testAnInvalidCatchUpWindowIsRejected(array $catchUp): void + { + $this->expectException(InvalidConfigurationException::class); + self::load(['catch_up' => $catchUp]); + } + + public function testAnAgeLimitJustAboveTheLeaseIsAccepted(): void + { + $container = self::load(['catch_up' => ['min_age' => 60, 'max_age' => ProcessStarter::LEASE_SECONDS + 1]]); + + self::assertSame(ProcessStarter::LEASE_SECONDS + 1, $container->getParameter('dmstr_webhook.catch_up.max_age')); } public function testAdaptersAreSwitchedPerSource(): void @@ -74,3 +146,5 @@ private static function load(array $config): ContainerBuilder return $container; } } + +// - revised 2026-12-06 (window of the process start catch-up) From cf3fca85dad274967923514d0b503cbe928e6409 Mon Sep 17 00:00:00 2001 From: Tobias Munk Date: Sun, 6 Dec 2026 00:30:41 +0000 Subject: [PATCH 8/9] docs: process start, catch-up and answer process, changelog for 0.4.0, workflow against both flowable-bundle bounds [*] README, CLAUDE.md and the changelog describe the asynchronous process start, the transport webhook an application has to define, the reason categories, the engine port, the answer process, both commands and the upgrade from 0.3.x with the check query for routed events. The workflow runs four jobs: MySQL and PostgreSQL against dmstr/flowable-bundle 0.12.1 and 0.14.0, with an assertion of the installed version. The suggestions for symfony/http-client and symfony/security-bundle go, both come with dmstr/flowable-bundle now. Co-Authored-By: Claude Fable 5.2 --- .github/workflows/tests.yml | 26 ++- CHANGELOG.md | 64 ++++++++ CLAUDE.md | 19 ++- README.md | 307 +++++++++++++++++++++++++++++++++--- composer.json | 4 +- 5 files changed, 391 insertions(+), 29 deletions(-) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 4cbca19..7bf3783 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -17,12 +17,17 @@ jobs: matrix: php: ["8.5"] database: [postgresql, mysql] + # Both bounds of the constraint of dmstr/flowable-bundle in + # composer.json (>=0.12.1 <0.15), as exact versions: the step "Pin" + # installs this version and the step after it fails the job when + # another one is installed. + flowable_bundle: ["0.12.1", "0.14.0"] include: - database: postgresql database_url: "postgresql://app:app@127.0.0.1:5432/webhook_test?serverVersion=16&charset=utf8" - database: mysql database_url: "mysql://app:app@127.0.0.1:3306/webhook_test?serverVersion=8.0.40&charset=utf8mb4" - name: PHPUnit (PHP ${{ matrix.php }}, ${{ matrix.database }}) + name: PHPUnit (PHP ${{ matrix.php }}, ${{ matrix.database }}, flowable-bundle ${{ matrix.flowable_bundle }}) # PostgreSQL runs as a service container in every job (services cannot # depend on the matrix); the MySQL job starts MySQL itself below, because @@ -90,6 +95,24 @@ jobs: - run: composer install --no-interaction --no-progress + # Without a composer.lock in the repository, the install resolves the + # highest allowed versions; this partial update moves only + # dmstr/flowable-bundle (and its own dependencies where needed) to the + # version of the matrix. For the upper bound it changes nothing. + - name: Pin dmstr/flowable-bundle ${{ matrix.flowable_bundle }} + run: >- + composer update dmstr/flowable-bundle + --with "dmstr/flowable-bundle:${{ matrix.flowable_bundle }}" + --with-dependencies --no-interaction --no-progress + + - name: Assert dmstr/flowable-bundle ${{ matrix.flowable_bundle }} is installed + env: + EXPECTED: ${{ matrix.flowable_bundle }} + run: | + composer show dmstr/flowable-bundle | grep -E '^(name|versions) *:' + composer show dmstr/flowable-bundle \ + | grep -Eq "^versions *: \* ${EXPECTED//./\\.}\$" + - name: Unit tests run: vendor/bin/phpunit --testsuite unit @@ -97,3 +120,4 @@ jobs: run: vendor/bin/phpunit --testsuite integration # - revised 2026-12-01 (matrix over PostgreSQL 16 and MySQL 8.0) +# - revised 2026-12-06 (matrix over both bounds of dmstr/flowable-bundle, 0.12.1 and 0.14.0, with a version assertion) diff --git a/CHANGELOG.md b/CHANGELOG.md index 68074fa..d7312e1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,69 @@ All notable changes to this bundle. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versions follow [SemVer](https://semver.org/) and come from the Git tags. +## [0.4.0] - Unreleased + +Routed events start a process: in the mode `process`, every event that becomes `routed` is started asynchronously as one instance of the route's process definition in Flowable, through a new engine port, and the event ends `started` with the process instance id or `failed` with a reason category. Action is needed on upgrade: a migration, a durable Messenger transport with a worker, FlowableBundle, the deployed process definition and a schedule for the catch-up, and a check of the events that are `routed` already. + +Upgrade notes: + +- Run the migrations (`php bin/console doctrine:migrations:migrate`). The new migration `Dmstr\Webhook\Migrations\Version20261205225504` adds nine nullable columns to `webhook_event` (`start_claimed_at` and the reference columns `project_kind`, `project_id`, `target_kind`, `target_id`, `note_kind`, `note_id`, `discussion_kind`, `discussion_id`) and writes no row; existing events keep empty references. +- Define the Messenger transport `webhook` in the application with a durable DSN, and consume it with a worker (`php bin/console messenger:consume webhook`). The bundle routes `Process\Start\StartProcess` to `webhook`, and defines the transport itself only when the application does not, with the DSN `in-memory://`: its messages live only in the memory of the process that dispatched them, so without an own transport nothing is started by the worker and every routed event waits for the catch-up. Never use `sync://`, which would start the process inside the webhook request. A Doctrine transport needs `symfony/doctrine-messenger` (suggested, not required): + + ```yaml + # config/packages/messenger.yaml + framework: + messenger: + transports: + webhook: + dsn: 'doctrine://default?queue_name=webhook' + retry_strategy: + max_retries: 5 + delay: 60000 + multiplier: 2 + ``` + +- Register `Dmstr\Flowable\FlowableBundle` in the kernel if it is not registered yet (it is installed with the bundle now, but installed is not registered; it binds the log channel `flowable` and therefore needs MonologBundle; see the README of `dmstr/flowable-bundle` for what else it needs, and note that it brings its own API resources and permissions). Without it the engine port is `Process\MissingProcessEngine`, and every start fails at once with `engine_port_missing`. +- Deploy the answer process definition to the Flowable connections of the endpoints (`php bin/console webhook:process:deploy`, idempotent, e.g. in every deployment), give every endpoint in the mode `process` a Flowable connection (`flowableConnection`, an `ApiConfiguration` of the type `flowable`), and make sure every route names a deployed process definition key in `processDefinitionKey` (the shipped one is `webhookAnswer`). A start of a key that is not deployed fails with `definition_not_deployed`, an endpoint without connection with `connection_missing`; both set the event to `failed` without retry. +- Schedule the catch-up (`Process\Start\ProcessStartCatchUp::run()`, or the command `webhook:process:catch-up`), e.g. every five minutes from a Scheduler message handler of the application; the bundle ships no schedule. It starts routed events without process instance whose dispatch was lost, between `dmstr_webhook.catch_up.min_age` (300 seconds by default) and `dmstr_webhook.catch_up.max_age` (86400 seconds by default) after they were received. +- Existing data: events that are `routed` without a process instance when you upgrade, the result of 0.2.0 to 0.3.0, which stopped at `routed`, are not dispatched again, but the catch-up selects them. Those received within `catch_up.max_age` (24 hours by default) before a catch-up run WILL be started by it, or set to `failed` with a category where the start cannot work (e.g. `route_missing` for a deleted route, `connection_missing`, `definition_not_deployed`, `engine_port_missing`); older ones stay `routed` and are never touched by the catch-up. List both groups before upgrading; replace the cutoff with the time of the first catch-up run minus `catch_up.max_age`, in UTC: + + ```sql + SELECT dedupe_key, type, route, received_at, + CASE WHEN received_at >= '2026-12-06 08:00:00' + THEN 'started by the catch-up' + ELSE 'left untouched' END AS on_upgrade + FROM webhook_event + WHERE status = 'routed' AND process_instance_id IS NULL + ORDER BY received_at; + ``` + + After the upgrade, `php bin/console webhook:process:catch-up --dry-run` lists the events the next run would start (at most `--limit`, 100 by default) without claiming or starting anything. If the retroactive start is unwanted, either schedule the catch-up only once those events are older than `catch_up.max_age` (24 hours after the upgrade with the default; events routed after the upgrade are still within the window then), or set `catch_up.max_age` low for the first day (it must exceed `catch_up.min_age` and the claim lease of 600 seconds, so at least 601) and raise it only once the events from before the upgrade are older than the raised value. The bundle offers no operation that moves a `routed` event to another status. +- Application code that constructs `WebhookIntake` itself (instead of through the container) has to pass a `MessageBusInterface` after `EventRouter` (see Changed). + +### Added + +- Asynchronous process start of routed events. After the conditional update to `routed` succeeded, the intake dispatches one `Process\Start\StartProcess` message (the event id only: no payload, no note text, no endpoint data) on the transport `webhook` (`WebhookBundle::TRANSPORT`) and calls no engine. `Process\Start\StartProcessHandler` runs `Process\Start\ProcessStarter::start()` in the worker: it reads the event (never the payload) and does nothing for an event that does not exist, is not `routed` or has a process instance, so late and duplicate messages are harmless; claims it with one conditional update of `start_claimed_at` (lease `ProcessStarter::LEASE_SECONDS`, 600 seconds; the status stays `routed`); loads the endpoint and the matched route; asks the engine for instances of the route's definition key with the event's dedupe key as business key, running and finished, and records one whose variable `webhookEndpointId` is this endpoint instead of starting another (the instance of an attempt that died after the engine started it; the same note at another endpoint has its own instance); otherwise starts the definition on the endpoint's Flowable connection with the business key and the process variables below; and records the instance: `routed` → `started` with `processInstanceId`. A failure releases the claim and throws `Process\Start\ProcessStartFailedException` with the reason category only; Messenger retries it with the transport's retry strategy, unless the category is unrecoverable (`Process\Start\UnrecoverableProcessStartException`). After the last attempt, or at once for an unrecoverable category, `Process\Start\ProcessStartFailureListener` (on `WorkerMessageFailedEvent`) sets the event to `failed` with the category as `reason`. A dispatch that fails in the request leaves the event `routed` for the catch-up and writes one `warning` line on the channel `webhook` (`START_NOT_QUEUED_MESSAGE`, with the exception class only); the delivery is accepted all the same. +- The process engine port `Process\ProcessEngineInterface` with the calls `deploy()` (idempotent: unchanged content of the latest definition of the key deploys nothing), `start()` (scalar variables only) and `findInstances()` (running and finished, with their variables), the value objects `ProcessDeployment` and `ProcessInstance`, `ProcessEngineGuard` (the connection checks every implementation makes first: present, of its type, active) and `ProcessEngineException`, which carries only a `ProcessEngineFailure` and a `ProcessEngineCall`, never the original exception or text of the engine. Implementations: `Process\Flowable\FlowableProcessEngine` over the client locator of `dmstr/flowable-bundle` (connection type `flowable`), registered only when FlowableBundle is registered in the kernel, and `Process\MissingProcessEngine` otherwise, whose every call fails with `engine_port_missing`. An application may alias the interface to an implementation of its own. +- Reason categories, public API and stored as the `reason` of a `failed` event: the values of `Process\ProcessEngineFailure` (`connection_missing`, `connection_wrong_type`, `connection_inactive`, `connection_invalid`, `secret_unreadable`, `engine_port_missing`, `definition_not_deployed`, `engine_rejected`, `engine_error`, `engine_unreachable`) and the constants of `Process\Start\ProcessStartFailure` (`route_missing`, `endpoint_not_process`, `start_failed`). Retried are `engine_unreachable`, `engine_error` and `start_failed`; every other category is in `ProcessStartFailure::UNRECOVERABLE`. +- The process variables of a started instance (`Process\Start\ProcessStartVariables`): `webhookEventId`, `webhookEndpointId`, the references of the event as kind and id pairs (`webhookProjectKind`/`webhookProjectId`, `webhookTargetKind`/`webhookTargetId`, `webhookNoteKind`/`webhookNoteId`, `webhookDiscussionKind`/`webhookDiscussionId`, only those the event has), `webhookAgent` (the route's agent, when it has one) and the route's static variables except those with one of these reserved names. Identifiers and admin-configured values only: the note text, the payload, a title or a description are never a process variable; a worker reads the text from the stored event by `webhookEventId`. +- The answer process the bundle ships as BPMN, `config/bpmn/webhook-answer.bpmn20.xml`, with its public names in `Process\AnswerProcess`: the process definition key `webhookAnswer` (`PROCESS_DEFINITION_KEY`), the external worker task on the topic `webhook-answer` (`ANSWER_TOPIC`), an error boundary event that catches the BPMN error code `WEBHOOK_ANSWER_FAILED` (`ERROR_CODE`) and leads to the external worker task on the topic `webhook-error-answer` (`ERROR_ANSWER_TOPIC`). The definition reads no process variable. No worker for these topics ships in this release: a started instance waits at the answer task. +- The command `webhook:process:deploy [--endpoint=]`: deploys the answer process to each distinct Flowable connection of the active endpoints in the mode `process` (endpoints without a connection are named in a warning and skipped), or to the connection of one endpoint, through the engine port; one row per connection with the result `deployed`, `unchanged` or `failed: `. Exit code 0 also when there is nothing to deploy, 1 when a target failed, the endpoint does not exist or the resource cannot be read. +- The catch-up of the process start, `Process\Start\ProcessStartCatchUp` (public API; `run(?int $limit)` returns a `ProcessStartCatchUpResult`, `candidates(?int $limit)` lists without starting): starts the events that are `routed` without process instance, received between `min_age` and `max_age` ago, whose claim is empty or expired, oldest first, at most 100 per run by default, directly through `ProcessStarter` and not through the transport. An unrecoverable category sets the event to `failed` at once, a retryable one leaves it `routed` for the next run until it leaves the window. Configuration `dmstr_webhook.catch_up.min_age` (default 300 seconds) and `dmstr_webhook.catch_up.max_age` (default 86400 seconds, greater than `min_age` and than the claim lease of 600 seconds), published as the container parameters of the same names. The console twin `webhook:process:catch-up [--limit=100] [--dry-run]` prints one row per event and the counts; exit code 1 only when an event was set to `failed` or the limit is invalid. +- Fields of `WebhookEvent`, in the admin resource `/api/admin/webhook_events` and its list group: `startClaimedAt` (when a start attempt last claimed the routed event) and the references of the event context, `projectKind`, `projectId`, `targetKind`, `targetId`, `noteKind`, `noteId`, `discussionKind` and `discussionId` (identifiers only, never a text of the source object), written once with the insert by the intake. `processInstanceId` is now set by the process start. +- The migration `Dmstr\Webhook\Migrations\Version20261205225504` (Schema API, portable) with the columns of these fields. +- `EventStore` methods of the process start, each one conditional statement: `startCandidate()`, `claimStart()`, `releaseStart()`, `recordStart()`, `failStart()` and `startCatchUpCandidates()`. +- Kernel variants and test support for the process start: FlowableBundle registered, the in-memory `FakeProcessEngine` as the host's engine, the bundle's default transport, a non-default catch-up window, a recording message bus for the intake without kernel and a drain of the in-memory transport through a real Messenger worker. The workflow runs every job against both bounds of `dmstr/flowable-bundle`, 0.12.1 and 0.14.0, on PostgreSQL and MySQL. +- README sections on the process start, the transport and worker, the claim and idempotency, process variables, reason categories, the engine port, the answer process, the catch-up and the two commands. + +### Changed + +- New hard requirements: `dmstr/flowable-bundle` (`>=0.12.1 <0.15`) and `symfony/messenger` (`^7.4`). Through `dmstr/flowable-bundle` come, among others, `dmstr/openapi-json-schema-bundle`, `opis/json-schema`, `symfony/http-client`, `symfony/security-bundle`, `symfony/expression-language`, `symfony/object-mapper`, `symfony/yaml` and `psr/log` 3. The suggestions `symfony/http-client` and `symfony/security-bundle` are dropped, since both are now always installed; `symfony/doctrine-messenger` is a new suggestion. The Flowable implementation of the engine port still loads only when FlowableBundle is registered in the kernel. +- `WebhookIntake` takes a `Symfony\Component\Messenger\MessageBusInterface` after `EventRouter`, and dispatches one `StartProcess` per event that became `routed`; the request path still makes at most two writes per event and no engine call. +- `EventStore::transition()` takes the origin status as a new last parameter `$from` (default `received`, so existing calls keep their meaning); the conditional update is `WHERE id = ? AND status = ?`. `EventStore::insert()` takes the event context as a new last parameter and stores its references. `EventStatusTransition` still only leaves `received`. +- The bundle prepends `framework.messenger`: the routing of `StartProcess` to `webhook`, and the transport `webhook` with `in-memory://` only when the application defines no transport of that name; the application's own configuration wins. +- The intake's `routed` is no longer the end of the line in the mode `process`: see Added. The statuses `started` and `failed` are now set by the bundle for routed events; there is no new status. + ## [0.3.0] - 2026-12-04 No action is needed on upgrade: the new client loads only when its library is installed and the adapter `gitlab` is enabled, and there is no migration. @@ -143,3 +206,4 @@ Initial public release. + diff --git a/CLAUDE.md b/CLAUDE.md index 13a7e1a..7766b14 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -4,7 +4,7 @@ This is a public open-source package maintained under github.com/dmstr. -Symfony bundle for incoming webhooks: endpoints per source (slug, encrypted write-only secret, IP allowlist, limits) with an audited admin API for API Platform and console twins, the intake `POST /webhook/{slug}/{secret?}` with source adapters on the `RequestParserInterface` of `symfony/webhook`, an event trail aligned with CloudEvents, endpoint modes (`process`: filters, rate limit per actor and routes; `handler`: hand-off to the application's delivery handlers after the response) and a Monolog processor that keeps secrets out of the logs. See `README.md` for the concepts. +Symfony bundle for incoming webhooks: endpoints per source (slug, encrypted write-only secret, IP allowlist, limits) with an audited admin API for API Platform and console twins, the intake `POST /webhook/{slug}/{secret?}` with source adapters on the `RequestParserInterface` of `symfony/webhook`, an event trail aligned with CloudEvents, endpoint modes (`process`: filters, rate limit per actor, routes and the asynchronous process start of routed events on the Messenger transport `webhook` through a process engine port, with the shipped answer process BPMN and a catch-up; `handler`: hand-off to the application's delivery handlers after the response) and a Monolog processor that keeps secrets out of the logs. See `README.md` for the concepts. ## Language policy @@ -15,12 +15,14 @@ Symfony bundle for incoming webhooks: endpoints per source (slug, encrypted writ PHP >= 8.5 (see `composer.json`). The PHPUnit suite (configuration `phpunit.dist.xml`) has two test suites: - `unit` (`tests/Unit`): no kernel, no database. Run it with `vendor/bin/phpunit --testsuite unit`. -- `integration` (`tests/Integration`): boots the test kernel in `tests/Kernel` (neutral test roles, a stand-in permission voter, a frozen `clock`). Tests in the group `database` need PostgreSQL or MySQL 8 from `DATABASE_URL` (PostgreSQL by default in `phpunit.dist.xml`; the database name must end with `_test`); the schema is created by running the migrations, the bundle's own ones included. The workflow `Tests` (`.github/workflows/tests.yml`) runs both suites, group `database` included, as a matrix on PostgreSQL 16 and MySQL 8.0. Without a server, run `vendor/bin/phpunit --testsuite integration --exclude-group database`. +- `integration` (`tests/Integration`): boots the test kernel in `tests/Kernel` (neutral test roles, a stand-in permission voter, a frozen `clock`). Tests in the group `database` need PostgreSQL or MySQL 8 from `DATABASE_URL` (PostgreSQL by default in `phpunit.dist.xml`; the database name must end with `_test`); the schema is created by running the migrations, the bundle's own ones included. The workflow `Tests` (`.github/workflows/tests.yml`) runs both suites, group `database` included, as a matrix of four jobs: PostgreSQL 16 and MySQL 8.0, each with both bounds of the `dmstr/flowable-bundle` constraint (0.12.1 and 0.14.0, pinned by a partial `composer update … --with` after the lock-free install and asserted with `composer show`). When the constraint changes, change the matrix versions with it. Without a server, run `vendor/bin/phpunit --testsuite integration --exclude-group database`. Test helpers live only under `tests/`. The intake is tested through a data-driven matrix: `tests/Support/IntakeCase.php` (one row: endpoint configuration, request, expected result per mode), `IntakeExpectation.php`, `IntakeHarness.php` (the real intake over an in-memory store, no kernel) and `IntakeMatrix.php` (the source-neutral rows); the same rows run against the database in `tests/Integration/Intake/IntakeMatrixDatabaseTest.php`. Test adapters live in `tests/Kernel/` (`ContextTestAdapter`, `ActorlessTestAdapter`, `FilterAttributesTestAdapter`); a source adapter with fixtures adds its rows in its own provider with the same row shape. Its fixtures live in `tests/Fixtures//`, one delivery per YAML file (`origin`, `headers`, `body`), loaded through the source-neutral `tests/Support/FixtureSet.php` and turned into rows through `tests/Support/FixtureMatrix.php` (the source's default endpoint and, for a path secret source, the secret path segment of every request); the traits `tests/Support/FixtureSequenceTests.php` and `IntakeHarnessSequences.php` run a source's sequences without database, and `tests/Integration/Intake/IntakeMatrixDatabaseTestCase.php` runs rows and sequences against the database. `origin` is `captured` (a recorded delivery with neutral values), `documented ()` (built from the source's documentation, every value invented) or `derived from ()` (`FixtureSet::ORIGIN_PATTERN`). Two sources do so: GitLab (`tests/Fixtures/gitlab/`, captured GitLab 15.11 deliveries and fixtures derived from them; `tests/Support/GitlabFixtures.php`, `GitlabMatrix.php`) and Basecamp 4 (`tests/Fixtures/basecamp4/`, built from the Basecamp API documentation, so every fixture is documented or derived and none is captured; `tests/Support/Basecamp4Fixtures.php`, `Basecamp4Matrix.php`). Mark a fixture `captured` only when it is anonymised from a real delivery. `tests/Unit/Intake/Basecamp4LogTest.php` checks the raw log records of Basecamp 4 deliveries without the redaction processor (no path secret, no request path, no payload text) and proves its detector with a leaking test adapter. Fixtures are public: never copy a raw capture or any of its values into `tests/Fixtures/`; use neutral values (`example.com` hosts, invented ids, names, UUIDs, SHAs and texts). `tests/Unit/Fixtures/FixtureAnonymisationTest.php` has one definition per source (`sources()`: fixture set, allowed hosts, header values, captures variable, structural values; a new source adds one entry, and every fixture file must belong to a source). It enforces structural rules always and, with the source's variable pointing to a local directory of raw captures (kept outside the repository; `WEBHOOK_RAW_CAPTURES_DIR` for GitLab, `WEBHOOK_RAW_CAPTURES_DIR_BASECAMP4` for Basecamp 4), fails on any captured value found in a fixture of any source; run it locally whenever fixtures change. +The process start is tested without a real engine: `tests/Support/FakeProcessEngine.php` (in memory, counts every call, `failOn()`, `crashAfterNextStart()`), `TransportDrain.php` (runs the in-memory transport `webhook` of the test kernel through a real Messenger worker with the retry and failure listeners; advance the frozen clock between attempts), `RecordingMessageBus.php` (the intake's bus without kernel, `failWith()` for a transport that is down) and `EventReferences.php` (the reference columns and the check that none holds payload text). Kernel variants of `tests/Kernel/TestKernel.php`: `ENV_FLOWABLE` (FlowableBundle registered, with MonologBundle; the Flowable engine port), `ENV_FAKE_ENGINE` (the host aliases the port to the fake), `ENV_CATCH_UP` (the fake and a non-default catch-up window), `ENV_DEFAULT_TRANSPORT` (no host transport `webhook`, so the bundle's default; the host routes a message of its own elsewhere); every variant except `ENV_FLOWABLE` leaves FlowableBundle installed but unregistered, so the port is `MissingProcessEngine` unless the variant aliases it to the fake. The fake's call count is how a test proves that the intake makes no engine call. + Replay-window tests build their Standard Webhooks signatures with the time of a frozen clock (`MockClock`), never with `time()`; only the test of the system-time fallback uses `time()`. ## Layout @@ -28,18 +30,27 @@ Replay-window tests build their Standard Webhooks signatures with the time of a - `src/Model/`: the source-neutral value objects and enums of the adapter contract and the intake (`EventContext`, `Actor`, `Reference`, `EventFacts`, `Fact`, `FilterAttributes`, `AttributeKind`, `EndpointMode`, `IgnoreReason`, `EventDisposition`); excluded from service discovery. - `src/Intake/`: the intake, its filters (`EventFilter`), limiters (`EndpointRateLimiter`, `ActorRateLimiter` over `SlidingWindowLimiter`), storage (`EventStore`), hand-off (`DeliveryHandOff`) and `EventStatusTransition`. - `src/Routing/`: `EventRouter` and `RouteMatcher`, the route of an event in the mode `process`. +- `src/Process/`: the process engine port (`ProcessEngineInterface`, `ProcessEngineGuard`, `ProcessEngineException` with `ProcessEngineFailure` and `ProcessEngineCall`, the value objects `ProcessDeployment` and `ProcessInstance`), its implementations `Flowable/FlowableProcessEngine` and `MissingProcessEngine`, and `AnswerProcess` (the public names of the shipped BPMN); all excluded from discovery, and `WebhookBundle` registers one implementation and aliases the interface to it. +- `src/Process/Start/`: the process start of routed events: the message `StartProcess` (event id only), `StartProcessHandler`, `ProcessStarter` (claim, second check, start, record), `ProcessStartFailureListener`, `ProcessStartVariables`, `ProcessStartFailure` (the start's own categories and `UNRECOVERABLE`), the exceptions, `ProcessStartOutcome`, and the catch-up `ProcessStartCatchUp` with `ProcessStartCatchUpResult`. +- `config/bpmn/`: the BPMN of the answer process (`webhook-answer.bpmn20.xml`), deployed by `webhook:process:deploy`. +- `src/Command/`: the console twins, the delivery twin `webhook:deliver`, and the process commands `webhook:process:deploy` and `webhook:process:catch-up`. ## Invariants - The namespace `Dmstr\Webhook`, the bundle class `WebhookBundle`, the configuration root `dmstr_webhook`, the container parameters `dmstr_webhook.*`, the tags `dmstr_webhook.adapter` and `dmstr_webhook.delivery_handler`, the route `dmstr_webhook_intake`, the console command names (prefix `webhook:`), the log channel `webhook`, the table names `webhook_endpoint`, `webhook_event` and `webhook_route`, the endpoint modes `process` and `handler`, the event statuses and the ignore reasons (`IgnoreReason`) are public API. -- Migration classes never change once released (`Version20261127220000`, `Version20261201180000`, `Version20261203182500`): applications store the class name; a schema change gets a new migration. The first one references `dmstr_api_configuration`; they sort after `Dmstr\ApiConfiguration\Migrations` by class name and need no custom comparator (guarded by `tests/Integration/Migration/MigrationOrderTest.php`). A new migration keeps a timestamp later than the existing ones. +- Migration classes never change once released (`Version20261127220000`, `Version20261201180000`, `Version20261203182500`, `Version20261205225504`): applications store the class name; a schema change gets a new migration. The first one references `dmstr_api_configuration`; they sort after `Dmstr\ApiConfiguration\Migrations` by class name and need no custom comparator (guarded by `tests/Integration/Migration/MigrationOrderTest.php`). A new migration keeps a timestamp later than the existing ones. - The bundle checks only permissions with `is_granted()`: the constants of `Dmstr\Webhook\Security\WebhookPermissions`, tagged `za7_core.permission` in `config/services.yaml`. No `ROLE_*` name is checked in `src/` or `config/`; the host application maps permissions to roles through its own voter. The tag name `za7_core.permission` stays. A new permission gets a constant, a tag, a test and a README update in the same change. - The bundle never prepends `api_platform.mapping.paths`: API Platform adds the host application's default resource directories only while that list is empty, so a prepended path drops the host's own resources. The bundle's resources are discovered through the registered bundle (`src/Entity`); guarded by `tests/Unit/DependencyInjection/WebhookBundlePrependTest.php` and `tests/Integration/WebhookWiringTest.php`. -- Hard requirements stay minimal: monolog, the lock component, the clock component, the security bundle and the audit-log bundle are optional (`suggest`), and the container must build without them; `clock` and `lock.factory` are optional references. +- Hard requirements stay minimal, and every hard one has a reason: `dmstr/flowable-bundle` (`>=0.12.1 <0.15`, the client of the Flowable engine port; 0.15 needs other major versions of the api-configuration and utils bundles) and `symfony/messenger` (the transport of the process start) are hard since 0.4.0; through `dmstr/flowable-bundle` come `symfony/http-client` and `symfony/security-bundle`, so those are no suggestions anymore. Monolog, the lock component, the clock component, the audit-log bundle and `symfony/doctrine-messenger` stay optional (`suggest`), and the container must build without them; `clock` and `lock.factory` are optional references, and the bundle's default transport `webhook` is `in-memory://`, never `sync://` and never a Doctrine DSN. A hard Composer dependency is no bundle registration: the Flowable implementation loads only when FlowableBundle is registered in the kernel (`kernel.bundles`, `WebhookBundle::registersFlowableEngine()`), because FlowableBundle's services bind the channel `flowable` of MonologBundle; otherwise the port is `MissingProcessEngine` (`engine_port_missing`). The minimal kernel variant (no MonologBundle) therefore never registers FlowableBundle. - Components that depend on a suggested package (today `Dmstr\Webhook\Reply\Gitlab\GitlabReplyClient` on `m4tthumphrey/php-gitlab-api`) load only when the package is installed and the matching adapter is enabled: one decision, `WebhookBundle::loadsOptionalComponent()`, with the library check in `DependencyInjection\OptionalLibraries` (never a second `class_exists()` elsewhere). Such classes stay out of resource discovery (`src/Reply/` is excluded in `config/services.yaml`), so the container builds without the package; their HTTP transport is the service `dmstr_webhook.reply_http_client`, and without one they are removed. `tests/Integration/ContainerVariantsTest.php` proves it (package absent through `new OptionalLibraries([...])` in the test kernel, adapter off, adapter on, no `http_client`); a new optional component adds its variants there. +- The intake makes no engine call: for an event that became `routed` it only dispatches one `StartProcess` message (the event id only) to the transport `webhook`; a failed dispatch is logged with the exception class and leaves the event to the catch-up. Everything engine-related runs in the worker or the catch-up, through `ProcessEngineInterface` only. +- The status stays `routed` until the process instance id is written; the claim of a start attempt is the lease column `start_claimed_at`, not a status. No new event status exists for the process start (statuses are public API); every write of the start is one conditional update from `routed` without instance. +- Failures of the process start travel as reason categories only (`ProcessEngineFailure`, `ProcessStartFailure`; public API, stored as `reason`): `ProcessEngineException` and `ProcessStartFailedException` never carry a previous exception or engine, transport or database text, because Messenger serialises the exception chain into `ErrorDetailsStamp`, the failure transport and its log records. Log lines name the category and the exception class, never a message. Process variables are identifiers and admin-configured values only (`ProcessStartVariables`); the note text and the payload never become one. +- On an uncompiled `ContainerBuilder` (a unit test that loads the extension without compiling), a class excluded from resource discovery by file still has an abstract definition tagged `container.excluded`, so `hasDefinition()` is true; assert "not a service" as no definition or that marker (see `tests/Unit/DependencyInjection/ProcessEngineRegistrationTest.php`). - Secrets never appear in responses (only the mask `********`), exception messages, console output or logs; the payload of an event is in no serialization group. No text of a source object (e.g. a note body) enters the event context, route variables or log lines; it stays in the stored payload. + diff --git a/README.md b/README.md index e43c8d2..85bee55 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ # dmstr/webhook-bundle -Symfony bundle for incoming webhooks. Each source gets an endpoint under its own URL `/webhook/{slug}` with an encrypted, write-only secret, an optional sender IP allowlist and its own limits. The intake verifies a delivery, stores each event exactly once per endpoint and dedupe key, and answers immediately. What happens to a stored event depends on the endpoint's mode: in the mode `process` the bundle filters it, applies a rate limit per actor and routes it to a process; in the mode `handler` it hands it to the application's delivery handlers after the response. Endpoints, routes and the accepted deliveries (events) are managed through an audited admin API for API Platform and through console twins. Events carry CloudEvents-aligned fields, and source adapters implement `Dmstr\Webhook\Adapter\WebhookAdapterInterface`, an extension of the `RequestParserInterface` of `symfony/webhook`. +Symfony bundle for incoming webhooks. Each source gets an endpoint under its own URL `/webhook/{slug}` with an encrypted, write-only secret, an optional sender IP allowlist and its own limits. The intake verifies a delivery, stores each event exactly once per endpoint and dedupe key, and answers immediately. What happens to a stored event depends on the endpoint's mode: in the mode `process` the bundle filters it, applies a rate limit per actor, routes it to a process and starts that process asynchronously in a process engine (Flowable through `dmstr/flowable-bundle`); in the mode `handler` it hands it to the application's delivery handlers after the response. Endpoints, routes and the accepted deliveries (events) are managed through an audited admin API for API Platform and through console twins. Events carry CloudEvents-aligned fields, and source adapters implement `Dmstr\Webhook\Adapter\WebhookAdapterInterface`, an extension of the `RequestParserInterface` of `symfony/webhook`. - [Requirements](#requirements) - [Installation and wiring](#installation-and-wiring) @@ -14,6 +14,7 @@ Symfony bundle for incoming webhooks. Each source gets an endpoint under its own - [Filters and reasons](#filters-and-reasons) - [Rate limit per actor](#rate-limit-per-actor) - [Routes](#routes) +- [Process start](#process-start) - [Delivery handlers](#delivery-handlers) - [Adapters](#adapters) - [GitLab reply client](#gitlab-reply-client) @@ -23,6 +24,7 @@ Symfony bundle for incoming webhooks. Each source gets an endpoint under its own - [Trusted proxies](#trusted-proxies) - [Console commands](#console-commands) - [Writing an own adapter](#writing-an-own-adapter) +- [Upgrade from 0.3.x](#upgrade-from-03x) - [Upgrade from 0.1.x](#upgrade-from-01x) - [Not built yet](#not-built-yet) - [Tests](#tests) @@ -35,15 +37,17 @@ Symfony bundle for incoming webhooks. Each source gets an endpoint under its own - `symfony/rate-limiter` (sliding windows per endpoint and per endpoint and actor) with the cache pool `cache.rate_limiter` of FrameworkBundle (`symfony/cache`, which FrameworkBundle installs); `symfony/lock` (recommended) keeps concurrent deliveries of one endpoint from overshooting the limits - `psr/clock`; with `symfony/clock` (optional) FrameworkBundle registers the service `clock`, which the Standard Webhooks adapter then uses for its replay window (system time without it) - `symfony/console` for the console commands +- `symfony/messenger` 7.4 for the asynchronous [process start](#process-start), with a durable transport `webhook` and a worker of the application (e.g. a Doctrine transport through `symfony/doctrine-messenger`, suggested) +- `dmstr/flowable-bundle` `>=0.12.1 <0.15` (tested with 0.12.1 and 0.14.0) for the Flowable implementation of the process engine port; installed with the bundle, but it only takes effect when `Dmstr\Flowable\FlowableBundle` is registered in the kernel (see [Messenger transport and FlowableBundle](#messenger-transport-and-flowablebundle)). It also brings `symfony/http-client` and `symfony/security-bundle` - `monolog/monolog` 3 with `symfony/monolog-bundle` (recommended) for the log channel `webhook` and the secret redaction processor - `dmstr/api-platform-utils-bundle` for the encryption of the secret (`Dmstr\ApiPlatformUtils\Service\CredentialEncryption`, key `CREDENTIALS_ENCRYPTION_KEY`) - `dmstr/api-configuration-bundle` for the connections an endpoint references (`flowableConnection`, `replyConnection`) - `gedmo/doctrine-extensions` (endpoints and routes are `Loggable`); changes are audited when the application registers a loggable listener, for example through `dmstr/doctrine-audit-log-bundle` -- `symfony/security-bundle` for the firewall of the intake and the `is_granted()` checks of the admin API +- `symfony/security-bundle` (installed with `dmstr/flowable-bundle`) for the firewall of the intake and the `is_granted()` checks of the admin API - a permission voter that decides the permission strings of the bundle (see [Permissions](#permissions)) -- optional, for the [GitLab reply client](#gitlab-reply-client) only: `m4tthumphrey/php-gitlab-api` (`^12.1.1`), `symfony/http-client` and a PSR-17 implementation such as `nyholm/psr7`; all three are suggestions, not requirements +- optional, for the [GitLab reply client](#gitlab-reply-client) only: `m4tthumphrey/php-gitlab-api` (`^12.1.1`) and a PSR-17 implementation such as `nyholm/psr7`, both suggestions, not requirements, and `symfony/http-client` (installed with `dmstr/flowable-bundle`) -The bundle requires neither a process engine nor a specific platform bundle; a reference to a process engine is only a connection record, and a route names its process by a definition key. +The process engine is reached only through the bundle's engine port `Dmstr\Webhook\Process\ProcessEngineInterface` (see [Engine port](#engine-port)); the shipped implementation needs FlowableBundle registered, and an application may supply another implementation. A Flowable engine is addressed through a connection record (`flowableConnection` of an endpoint), and a route names its process by a definition key. ## Installation and wiring @@ -88,6 +92,8 @@ The migration `Dmstr\Webhook\Migrations\Version20261201180000` sets the collatio The migration `Dmstr\Webhook\Migrations\Version20261203182500` adds the column `webhook_endpoint.mode` (every existing endpoint gets `process`, see [Upgrade from 0.1.x](#upgrade-from-01x)) and creates the table `webhook_route`. +The migration `Dmstr\Webhook\Migrations\Version20261205225504` adds nine nullable columns to `webhook_event` without writing a row: `start_claimed_at` (the claim of a start attempt, see [Process start](#process-start)) and the references of the event context, kind and id per role (`project_kind`, `project_id`, `target_kind`, `target_id`, `note_kind`, `note_id`, `discussion_kind`, `discussion_id`). Existing events keep empty references; mind the events that are `routed` already, see [Upgrade from 0.3.x](#upgrade-from-03x). + ### Intake route Import the routes of the bundle, which define the intake `POST /webhook/{slug}/{secret}` (route name `dmstr_webhook_intake`, `secret` optional): @@ -113,6 +119,39 @@ framework: The admin resources come with the API Platform routes of the application (`/api/admin/webhook_endpoints`, `/api/admin/webhook_routes` and `/api/admin/webhook_events` when API Platform is mounted at `/api`). +### Messenger transport and FlowableBundle + +The [process start](#process-start) of routed events runs on the Messenger transport `webhook` (`WebhookBundle::TRANSPORT`), never in the webhook request. The bundle prepends `framework.messenger` with the routing of its message `Dmstr\Webhook\Process\Start\StartProcess` to `webhook`, and defines the transport itself only when the application does not, with the DSN `in-memory://` (`WebhookBundle::DEFAULT_TRANSPORT_DSN`). That default keeps the messages in the memory of the process that dispatched them, so the container builds without a transport package, but nothing is started by a worker: every routed event then waits for the [catch-up](#catch-up). The application therefore has three things to do: + +1. Define the transport `webhook` with a durable DSN and a retry strategy. Never use `sync://`: the start would then run inside the webhook request. A Doctrine transport needs `symfony/doctrine-messenger` (suggested, not required): + + ```yaml + # config/packages/messenger.yaml + framework: + messenger: + transports: + webhook: + dsn: 'doctrine://default?queue_name=webhook' + retry_strategy: + max_retries: 5 + delay: 60000 + multiplier: 2 + ``` + + The application's configuration wins over the prepended one: it may also route `StartProcess` to another transport, and its routing of other messages keeps the bundle's routing of `StartProcess`. +2. Consume the transport with a worker, e.g. `php bin/console messenger:consume webhook` next to the application's other transports. +3. Register FlowableBundle, which is installed with the bundle but not registered by it: + + ```php + // config/bundles.php + return [ + // ... + Dmstr\Flowable\FlowableBundle::class => ['all' => true], + ]; + ``` + + FlowableBundle binds the log channel `flowable` and therefore needs MonologBundle; see the README of `dmstr/flowable-bundle` for its other requirements, its own API resources and its permissions. Only when it is registered (the parameter `kernel.bundles` names it) is the engine port the Flowable implementation; without it every start fails with `engine_port_missing` and every event that reaches the start ends `failed`. + ### Firewall and access control The intake authenticates the sender with the endpoint's secret, not with a user token. Give `/webhook/` its own stateless firewall without an authenticator, before the main firewall, and a public access rule bound to `POST` before any catch-all rule: @@ -162,6 +201,9 @@ dmstr_webhook: standard_webhooks: false # off by default body_cap: 1048576 # default request body cap in bytes rate_limit: 60 # default deliveries per minute and endpoint + catch_up: + min_age: 300 # seconds; younger routed events are left to their first dispatch + max_age: 86400 # seconds; older routed events are never started by the catch-up ``` | Key | Type | Default | Meaning | @@ -169,8 +211,10 @@ dmstr_webhook: | `adapters` | map of source name to bool | `{passthrough: true}` | Enabled flag per source adapter. `passthrough` is enabled unless set to `false`; every other source is disabled unless set to `true`. A disabled adapter registers no service, and an endpoint's `sourceType` must name an enabled source (422 otherwise). | | `body_cap` | int, 1 to 1048576 | `1048576` (1 MiB) | Request body cap for endpoints without their own `bodyCap`. 1 MiB is also the hard upper bound, because the reverse proxy caps every webhook body at 1 MiB (see [Log redaction](#log-redaction)). | | `rate_limit` | int, at least 1 | `60` | Deliveries per minute (sliding window) for endpoints without their own `rateLimit`. | +| `catch_up.min_age` | int, at least 1 | `300` (5 minutes) | Minimum age, since it was received, of an event the [catch-up](#catch-up) starts; a younger event is left to its first dispatch. | +| `catch_up.max_age` | int, greater than `min_age` and than 600 | `86400` (24 hours) | Age limit of an event the catch-up starts; an older event is never started by it. It must exceed the claim lease of 600 seconds (`ProcessStarter::LEASE_SECONDS`), or an event whose start attempt died would leave the window before its claim expires; the container build fails otherwise. | -The values are also published as container parameters: `dmstr_webhook.adapters` (the full map), `dmstr_webhook.enabled_adapters` (list of enabled source names), `dmstr_webhook.body_cap` and `dmstr_webhook.rate_limit`. The rate limit per actor has no bundle default to configure; it is the endpoint field `actorRateLimit` (default 20). +The values are also published as container parameters: `dmstr_webhook.adapters` (the full map), `dmstr_webhook.enabled_adapters` (list of enabled source names), `dmstr_webhook.body_cap`, `dmstr_webhook.rate_limit`, `dmstr_webhook.catch_up.min_age` and `dmstr_webhook.catch_up.max_age`. The rate limit per actor has no bundle default to configure; it is the endpoint field `actorRateLimit` (default 20). ## Endpoints @@ -190,7 +234,7 @@ The values are also published as container parameters: `dmstr_webhook.adapters` | `allowedActorIds` | list of strings | `[]` | actor ids in the source that may trigger processing, applied in the mode `process`; an empty list allows nobody, see [Filters and reasons](#filters-and-reasons) | | `actorRateLimit` | int, 1 to 10000 | `20` | events per actor and hour, applied in the mode `process`, see [Rate limit per actor](#rate-limit-per-actor) | | `ipAllowlist` | list of strings | `[]` | sender addresses and CIDR ranges, IPv4 or IPv6 (`192.0.2.10`, `192.0.2.0/24`, `2001:db8::/32`); a non-empty list rejects other senders with 403, an empty list filters nothing | -| `flowableConnection` | IRI or null | null | the connection (`dmstr/api-configuration-bundle`) later processing runs on | +| `flowableConnection` | IRI or null | null | the connection (`dmstr/api-configuration-bundle`, `type` `flowable`, active) the [process start](#process-start) and `webhook:process:deploy` use; an endpoint in the mode `process` without one cannot start a process (`connection_missing`) | | `replyConnection` | IRI or null | null | the connection answers are posted with | | `classifierAgent` | string or null | null | id or IRI of an optional classifier agent; a plain string, no association | | `bodyCap` | int or null | null | request body cap in bytes, 1 to 1048576; null takes `dmstr_webhook.body_cap` | @@ -221,6 +265,7 @@ Both modes share the checks of the [intake](#intake) (404, 403, 413, 429, 401) a 3. The [rate limit per actor](#rate-limit-per-actor) counts the event. Over the budget, the event becomes `ignored` with `actor_rate_limited`. 4. The [routes](#routes) of the endpoint are matched. The first matching route makes the event `routed` with the route's id in `route`; without a match it becomes `ignored` with `no_route`. 5. Steps 3 and 4 end in one conditional update, so an event is written at most twice. Nothing of this mode reaches a delivery handler. +6. An event that became `routed` is queued for its [process start](#process-start): one message with the event id on the transport `webhook`. The request makes no call to the process engine; a worker starts the route's process and sets the event to `started` or `failed`. **Mode `handler`**: the application decides. @@ -266,7 +311,7 @@ Step 5 also rejects a `secret` path segment on an endpoint whose adapter does no Every rejection answers its status code with the JSON body `{"status":"rejected","reason":""}`, where `` is `unknown_endpoint` (404), `ip_not_allowed` (403), `body_too_large` (413), `rate_limited` (429) or `verification_failed` (401). -A verified delivery is answered `202 Accepted` with `{"status":"accepted"}`, whatever happens to its events: stored, duplicate, ignored by a filter or routed. Each event is stored once per (endpoint, dedupe key); a duplicate gets the same answer and stores nothing. This also holds for two identical deliveries arriving at the same time (unique index on `endpoint_id` and `dedupe_key`; a unique violation counts as a duplicate). An adapter that returns no event (null) gets the same answer too, so the response never tells a sender anything about earlier deliveries or about the filters. What happens to each event after the verification depends on the [endpoint mode](#endpoint-modes); the request path does the lookup, the verification, the filters, the rate limit per actor and the routing, with at most two writes per event (see [Events](#events)) and no other I/O. New events of an endpoint in the mode `handler` are passed to the [delivery handlers](#delivery-handlers) after the response. +A verified delivery is answered `202 Accepted` with `{"status":"accepted"}`, whatever happens to its events: stored, duplicate, ignored by a filter or routed. Each event is stored once per (endpoint, dedupe key); a duplicate gets the same answer and stores nothing. This also holds for two identical deliveries arriving at the same time (unique index on `endpoint_id` and `dedupe_key`; a unique violation counts as a duplicate). An adapter that returns no event (null) gets the same answer too, so the response never tells a sender anything about earlier deliveries or about the filters. What happens to each event after the verification depends on the [endpoint mode](#endpoint-modes); the request path does the lookup, the verification, the filters, the rate limit per actor and the routing, with at most two writes per event (see [Events](#events)) and, for an event that became `routed`, the dispatch of one message for its [process start](#process-start); no other I/O, and no call to the process engine. New events of an endpoint in the mode `handler` are passed to the [delivery handlers](#delivery-handlers) after the response. **Rate limit before verification.** The endpoint's limit is consumed after the IP allowlist and the body cap but before the verification, so a party that knows the slug and passes the IP allowlist can use up the budget with unverified requests and delay genuine deliveries with 429 (some senders disable a hook after repeated 4xx answers). This is a decided trade-off of the fixed check order. The mitigation is the IP allowlist, because the requests it rejects never reach the limiter: set it wherever the source publishes its sender addresses. The [rate limit per actor](#rate-limit-per-actor) is a second, separate limit that never rejects a delivery. @@ -317,8 +362,8 @@ A route is a routing rule of an endpoint in the mode `process` (`Dmstr\Webhook\E | `name` | string | required | at most 100 characters, unique per endpoint | | `eventType` | string or null | null | the event type (CloudEvents `type` as the adapter reports it) the route matches exactly; null or empty matches any type | | `filters` | map of attribute name to string, integer or boolean | `{}` | every entry must equal the event's attribute of that name; an empty map adds no condition; at most 50 entries; only attributes the endpoint's adapter declares, see below | -| `processDefinitionKey` | string | required | key of the process definition to start, at most 255 characters | -| `variables` | map of name to string, integer or boolean | `{}` | process variables passed with a matching event; names of letters, digits and underscores, not starting with a digit, at most 64 characters; at most 50 entries | +| `processDefinitionKey` | string | required | key of the process definition to start, at most 255 characters; the definition must be deployed on the endpoint's Flowable connection (the shipped one is `webhookAnswer`, see [Answer process](#answer-process)) | +| `variables` | map of name to string, integer or boolean | `{}` | process variables of the instance a matching event starts (a variable named like one the bundle sets itself is dropped, see [Process variables](#process-variables)); names of letters, digits and underscores, not starting with a digit, at most 64 characters; at most 50 entries | | `agent` | string or null | null | optional agent the process uses, as id or IRI | | `priority` | int, -1000000 to 1000000 | `0` | lower is tried first | | `active` | bool | `true` | an inactive route never matches | @@ -332,7 +377,7 @@ A route is a routing rule of an endpoint in the mode `process` (`Dmstr\Webhook\E **Validation against the adapter.** Each adapter declares the attributes a route may filter on, by name and kind (`string`, `integer` or `boolean`; see [Writing an own adapter](#writing-an-own-adapter)). Creating or changing a route checks every filter against the declaration of the endpoint's adapter: a filter on an undeclared attribute, or with a value of another kind, is rejected with 422 at `filters[]`, and the message lists the declared names. Filters on an endpoint whose source type is not an enabled adapter are rejected at `filters`. The GitLab adapter declares `project_id`, `project_path`, `noteable_type`, `target_iid` and `action` (see [GitLab](#gitlab)), the Basecamp 4 adapter `kind`, `project_id` and `recording_type` (see [Basecamp 4](#basecamp-4)); the other shipped adapters declare no attributes, so their routes can only use `eventType`. -**Result on the event.** A matching route sets the event to `routed` and stores the route's id (a UUID string, no foreign key) in the event's `route`; the id stays when the route is renamed or deleted. Without a match the event is `ignored` with `no_route`. Starting the process of a `routed` event is not part of the bundle yet (see [Not built yet](#not-built-yet)). +**Result on the event.** A matching route sets the event to `routed` and stores the route's id (a UUID string, no foreign key) in the event's `route`; the id stays when the route is renamed or deleted. Without a match the event is `ignored` with `no_route`. A `routed` event then goes to its [process start](#process-start), which reads the route again by this id: a route deleted in between ends the event `failed` with `route_missing`, and a changed route starts with its current definition key, agent and variables. Example: @@ -345,6 +390,151 @@ curl --request POST "https://app.example.com/api/admin/webhook_routes" \ The console twins are listed under [Console commands](#console-commands). +## Process start + +In the mode `process`, every event that becomes `routed` starts one instance of its route's process definition in the process engine, asynchronously and at most once per event (`Dmstr\Webhook\Process\Start\`). Before you use it, wire the transport, the worker and FlowableBundle (see [Messenger transport and FlowableBundle](#messenger-transport-and-flowablebundle)), deploy the process definition (`webhook:process:deploy`, see [Process commands](#process-commands)) and schedule the [catch-up](#catch-up). + +1. **Dispatch in the request.** After the conditional update to `routed` succeeded, the intake dispatches one `StartProcess` message on the transport `webhook`. The message carries only the event id: no payload, no note text, no endpoint data, so neither a transport nor its failure records hold anything of the source. The request makes no call to the process engine. A dispatch that fails (e.g. the transport is down) does not fail the delivery: the event stays `routed`, one `warning` line goes to the channel `webhook` (slug, event id, delivery id and the exception class, never its message), and the catch-up starts the event later. +2. **Read.** `StartProcessHandler` runs `ProcessStarter::start()` in the worker. It reads the event's columns (never the payload); an event that does not exist, is not `routed` or has a process instance ends here as "nothing to do", which makes late and duplicate messages harmless. +3. **Claim.** One conditional update sets `start_claimed_at` while the event is `routed`, has no process instance and no unexpired claim. The claim is a lease of 600 seconds (`ProcessStarter::LEASE_SECONDS`); an attempt that does not get it ends here (`claim_lost`). The status stays `routed`. +4. **Endpoint and route.** The endpoint and the route the intake matched are loaded again: a deleted route fails with `route_missing`, an endpoint that left the mode `process` with `endpoint_not_process`. +5. **Second check.** The engine is asked for the instances of the route's `processDefinitionKey` whose business key is the event's dedupe key, running and finished, with their variables. An instance whose variable `webhookEndpointId` is this endpoint is the instance of an earlier attempt that died after the engine started it: it is recorded, nothing is started (`found_existing`). Instances of other endpoints with the same business key (the same note delivered to two endpoints) do not count. +6. **Start.** Otherwise the latest definition of the key is started on the endpoint's `flowableConnection`, with the dedupe key as business key and the [process variables](#process-variables). +7. **Record.** One conditional update sets the event from `routed` to `started` with the instance id in `processInstanceId` and clears `reason`; `route` and the claim stay. If the event changed meanwhile (no longer `routed` without instance), nothing is recorded (`not_recorded`). + +A failure in steps 4 to 7 releases the attempt's own claim, so a retry can claim the event at once, and throws `ProcessStartFailedException` with the [reason category](#reason-categories) only. Messenger retries it with the transport's retry strategy, unless the category cannot change on a retry: then it is an `UnrecoverableProcessStartException`, which Messenger does not retry. When Messenger gives the message up (after the last retry, or at once for an unrecoverable category), `ProcessStartFailureListener` sets the event from `routed` to `failed` with the category as `reason`; an event that became `started` meanwhile stays untouched. Neither the exception nor anything Messenger stores about it (the message, `ErrorDetailsStamp` in a failure transport, log records) carries text of the engine, the transport, a secret or the payload. + +**Guarantees.** + +- One message per event: the intake dispatches only when its own update to `routed` changed the row, and a duplicate delivery writes and dispatches nothing. +- One instance per event and endpoint: concurrent attempts (a message delivered twice, a retry and the catch-up) are serialised by the claim; an attempt that died between the engine's start and the record is covered by the second check once its claim expired. This holds as far as the engine lists the instance of the first attempt by business key; the Flowable implementation asks both the runtime and the history. +- The status stays `routed` until the instance id is written: no new status exists, and a crashed attempt leaves an event the next attempt or the catch-up can claim once the lease expired. +- Failures travel as categories only, see [Reason categories](#reason-categories). + +**Log lines** on the channel `webhook` (event id, endpoint slug, instance id, category, exception class; never the payload, a note text, a secret or engine text): `info` for a started or found instance, `debug` for nothing to do and a lost claim, `warning` for a failed attempt and an instance that could not be recorded, `error` when an event is set to `failed`. + +### Process variables + +A started instance gets these variables (`Dmstr\Webhook\Process\Start\ProcessStartVariables`) and nothing else: + +| Variable | Value | +| --- | --- | +| `webhookEventId` | the event id (RFC 4122) | +| `webhookEndpointId` | the endpoint id (RFC 4122); two endpoints that receive the same note share the business key, and this variable tells their instances apart | +| `webhookProjectKind`, `webhookProjectId` | the project reference of the event, when it has one | +| `webhookTargetKind`, `webhookTargetId` | the target reference (e.g. `merge_request` and its `iid`), when it has one | +| `webhookNoteKind`, `webhookNoteId` | the note reference, when it has one | +| `webhookDiscussionKind`, `webhookDiscussionId` | the discussion reference, when it has one | +| `webhookAgent` | the route's `agent`, when it has one | +| the route's `variables` | the static values of the matched route, except those named like a variable above (the bundle's own values win, also where the event has no value for them) | + +The references are the ones stored with the event (see [Events](#events)), set only as a pair of kind and id. Values are scalars only; the Flowable implementation sends them as `string`, `integer` (32 bits), `long`, `double` or `boolean`. + +**The note text and the payload never become variables.** Neither does a title, a description or any other text of the source: the variables are identifiers and values an administrator configured. A worker that needs the text reads it from the stored event by `webhookEventId`. + +### Reason categories + +Every failure of a start is one of these categories, stored as the `reason` of an event that ends `failed`. They are public API (`Dmstr\Webhook\Process\ProcessEngineFailure` and the constants of `Dmstr\Webhook\Process\Start\ProcessStartFailure`) and never contain text of the engine, the transport, a secret or a payload. + +| Category | Meaning | Retried | +| --- | --- | --- | +| `connection_missing` | the endpoint has no Flowable connection (none set, or deleted) | no | +| `connection_wrong_type` | the connection is not of the type the engine needs (`flowable`) | no | +| `connection_inactive` | the connection is switched off | no | +| `connection_invalid` | no client can be built from the connection (e.g. no `base_url` or `auth_type`) | no | +| `secret_unreadable` | a stored secret of the connection cannot be decrypted (changed or missing credential key) | no | +| `engine_port_missing` | no engine implementation is registered (FlowableBundle not registered in the kernel) | no | +| `definition_not_deployed` | the engine knows no process definition of the route's key | no | +| `engine_rejected` | the engine refused the request as invalid (Flowable answered 400) | no | +| `engine_error` | any other answer of the engine, a rejected login of the connection's credentials (401, 403) and an answer of an unexpected shape included | yes | +| `engine_unreachable` | no answer (connection refused, timeout) | yes | +| `route_missing` | the route the intake matched no longer exists | no | +| `endpoint_not_process` | the endpoint is no longer in the mode `process` | no | +| `start_failed` | anything else (e.g. the database) | yes | + +"Retried" means: in the worker by the transport's retry strategy, and by the catch-up in its next run while the event is in its window. A category that is not retried ends the event `failed` at once (`ProcessStartFailure::UNRECOVERABLE`), without using up the retries; fix the cause (connection, deployment, route) for the events that follow, because a `failed` event is not started again. A retried category ends the event `failed` after the last retry of its message. + +### Engine port + +`Dmstr\Webhook\Process\ProcessEngineInterface` is the only way the bundle talks to a process engine. It has three calls, each addressed by a connection (an `ApiConfiguration`, null for none): + +- `deploy($connection, $resourceName, $content, $processDefinitionKey): ProcessDeployment`: deploys one BPMN resource, unless the latest definition of the key was deployed with the same resource name and content (then nothing is deployed and `deployed` is false), so deploying unchanged content twice creates no new definition version. +- `start($connection, $processDefinitionKey, $businessKey, $variables): string`: starts the latest definition of the key and returns the instance id; scalar variables only (`\InvalidArgumentException` otherwise). +- `findInstances($connection, $processDefinitionKey, $businessKey): list`: the running and finished instances with exactly this business key, each with its variables. + +Every failure is a `ProcessEngineException` with a `ProcessEngineFailure` (`reason`) and the `ProcessEngineCall` (`call`) only: the original exception is never attached and its message never copied, because Messenger serialises the whole exception chain of a failed message. + +The bundle registers one implementation and aliases the interface to it: `Dmstr\Webhook\Process\Flowable\FlowableProcessEngine` when FlowableBundle is registered in the kernel, `Dmstr\Webhook\Process\MissingProcessEngine` otherwise. The Flowable implementation checks the connection first (present, type `flowable`, active; `ProcessEngineGuard::connection()`), resolves the Flowable client of `dmstr/flowable-bundle` with the full UUID of the connection, and maps the client's failures to categories by HTTP status, never by message text. To supply another engine, implement the interface (check the connection with `ProcessEngineGuard::connection()` and the variables with `ProcessEngineGuard::variables()`, throw only `ProcessEngineException`) and point the alias to it; the application's definition wins over the bundle's: + +```yaml +# config/services.yaml +services: + Dmstr\Webhook\Process\ProcessEngineInterface: '@App\Process\OwnProcessEngine' +``` + +### Answer process + +The bundle ships the BPMN of an answer process, `./config/bpmn/webhook-answer.bpmn20.xml`, with its public names in `Dmstr\Webhook\Process\AnswerProcess`: + +| Constant | Value | Meaning | +| --- | --- | --- | +| `PROCESS_DEFINITION_KEY` | `webhookAnswer` | the key a route names in `processDefinitionKey` | +| `RESOURCE_NAME` | `webhook-answer.bpmn20.xml` | the file name, also the resource and deployment name in the engine | +| `ANSWER_TOPIC` | `webhook-answer` | topic of the answer task, an external worker task | +| `ERROR_ANSWER_TOPIC` | `webhook-error-answer` | topic of the error-answer task, an external worker task | +| `ERROR_CODE` | `WEBHOOK_ANSWER_FAILED` | the BPMN error a worker of the answer topic raises when it gives up | + +The flow: start, the answer task (topic `webhook-answer`), end `Answered`. An error boundary event on the answer task catches `WEBHOOK_ANSWER_FAILED` and leads to the error-answer task (topic `webhook-error-answer`), end `Failed`. The definition reads no process variable. `AnswerProcess::resourcePath()` and `resourceContent()` give the file and its XML. + +No worker for these topics ships in this release: a started instance waits at the answer task until a worker of the application completes it (e.g. an external worker of `dmstr/flowable-bundle`), and the event stays `started`. + +### Catch-up + +`Dmstr\Webhook\Process\Start\ProcessStartCatchUp` is the safety net for a `StartProcess` message that was never dispatched, got lost (e.g. the default in-memory transport) or whose handler died mid-start. It selects the events that are `routed` without process instance, were received at least `catch_up.min_age` and at most `catch_up.max_age` ago (see [Configuration reference](#configuration-reference); 5 minutes and 24 hours by default) and have an empty or expired claim, oldest first, at most 100 per run by default, and runs each through `ProcessStarter::start()` directly, not through the transport. The minimum age leaves a fresh event to its first dispatch; the age limit keeps old events from a retroactive start: an event that leaves the window still `routed` is never touched by the catch-up again. An unrecoverable category sets the event to `failed` at once; a retryable one leaves it `routed` for the next run. One failing event never stops the others. + +- `run(?int $limit = null): ProcessStartCatchUpResult` starts the selection and returns the counts per outcome (`started`, `foundExisting`, `nothingToDo`, `claimLost`, `notRecorded`), the failures per category (`failed`, events set to `failed`; `retrying`, events left `routed`), the result per event and `hasFailures()`. It throws only when the selection itself fails. +- `candidates(?int $limit = null): list` lists what a run would start, without claiming or starting anything. +- The command `webhook:process:catch-up` runs it by hand (see [Process commands](#process-commands)). + +The bundle ships no schedule. Run the catch-up regularly from the application, e.g. every five minutes with a Symfony Scheduler message and its handler: + +```php +use Dmstr\Webhook\Process\Start\ProcessStartCatchUp; +use Symfony\Component\Messenger\Attribute\AsMessageHandler; +use Symfony\Component\Scheduler\Attribute\AsSchedule; +use Symfony\Component\Scheduler\RecurringMessage; +use Symfony\Component\Scheduler\Schedule; +use Symfony\Component\Scheduler\ScheduleProviderInterface; + +final class CatchUpWebhookProcessStarts +{ +} + +#[AsMessageHandler] +final readonly class CatchUpWebhookProcessStartsHandler +{ + public function __construct(private ProcessStartCatchUp $catchUp) + { + } + + public function __invoke(CatchUpWebhookProcessStarts $message): void + { + $this->catchUp->run(); + } +} + +#[AsSchedule('webhook')] +final class WebhookSchedule implements ScheduleProviderInterface +{ + public function getSchedule(): Schedule + { + return new Schedule()->add(RecurringMessage::every('5 minutes', new CatchUpWebhookProcessStarts())); + } +} +``` + +Consume the schedule with a worker (`php bin/console messenger:consume scheduler_webhook`). A cron entry with `php bin/console webhook:process:catch-up` does the same. + ## Delivery handlers The seam for endpoints in the mode `handler` is `Dmstr\Webhook\Intake\DeliveryHandlerInterface`: @@ -626,14 +816,22 @@ No exception of the library or the HTTP client is chained; a message names the o | `type` | CloudEvents `type`, as the adapter names it (e.g. `webhook.passthrough`, see [Adapters](#adapters)) | | `time` | CloudEvents `time`: when the event happened according to the source (a `WebhookRemoteEvent` of the adapter), null if the source does not say | | `status` | see below | -| `reason` | why the event has its status: an [ignore reason](#filters-and-reasons), `handler_exception: `, or the reason a delivery handler gave | +| `reason` | why the event has its status: an [ignore reason](#filters-and-reasons), a [reason category](#reason-categories) of a failed process start, `handler_exception: `, or the reason a delivery handler gave | | `dedupeKey` | the idempotency key, unique per endpoint: the id of the adapter's event, or its SHA-256 hex when it is longer than 255 characters | | `route` | the id of the route that matched (`routed`); no foreign key, kept when the route is renamed or deleted | -| `processInstanceId`, `replyReference`, `error` | reserved for later processing | +| `processInstanceId` | the id of the process instance the [process start](#process-start) started or found (`started`) | +| `startClaimedAt` | when a start attempt last claimed the routed event; null while none did | +| `projectKind`, `projectId` | the project reference of the event context, e.g. `project` and its id; null without one | +| `targetKind`, `targetId` | the object the event is about, e.g. `merge_request`, `issue` or `recording` and its id in the source; null without one | +| `noteKind`, `noteId` | the triggering note or comment; null without one | +| `discussionKind`, `discussionId` | the thread the note belongs to; null without one | +| `replyReference`, `error` | reserved for later processing | | `receivedAt` | when the delivery was accepted | The raw payload is stored but is in no serialization group: neither the list nor the item response contains it, and neither do the console commands. +The references are written once, with the insert by the intake, from the event context of the adapter (see [Event context](#event-context)): identifiers only, never a text of the source object, and only where kind and id fit their columns (50 and 255 characters). Events stored before 0.4.0 have none. + ### Statuses and life cycle | Status | Meaning | Set by | @@ -642,8 +840,9 @@ The raw payload is stored but is in no serialization group: neither the list nor | `ignored` | passed over, with a reason | the intake (filters, rate limit per actor, no route) or a delivery handler | | `routed` | a route matched; `route` holds its id | the intake, mode `process` | | `handled` | a delivery handler of the application processed the event | the application, mode `handler` | -| `failed` | processing failed, with a reason | a delivery handler, or the bundle when a handler throws | -| `started`, `completed` | reserved for the processing of routed events, which is not built yet | nothing in the bundle sets them | +| `started` | a process instance runs (or ran) for the routed event; `processInstanceId` holds its id | the [process start](#process-start), mode `process` | +| `failed` | processing failed, with a reason | a delivery handler, the bundle when a handler throws, or the process start with a [reason category](#reason-categories) | +| `completed` | reserved for the end of the process of a routed event | nothing in the bundle sets it | Life cycle per mode and the number of writes to `webhook_event` per event: @@ -653,10 +852,10 @@ Life cycle per mode and the number of writes to `webhook_event` per event: | duplicate (either mode) | the earlier event is unchanged | 0 | | filtered by reasons 1 to 6 (in the mode `handler` only `own_actor`) | `ignored` with the reason | 1 (insert with the final status) | | mode `process`, over the rate limit per actor or no matching route | `received`, then `ignored` with `actor_rate_limited` or `no_route` | 2 (insert, one conditional update) | -| mode `process`, matching route | `received`, then `routed` with the route id | 2 (insert, one conditional update) | +| mode `process`, matching route | `received`, then `routed` with the route id | 2 (insert, one conditional update); the process start in the worker then writes the claim and `started` or `failed`, each one conditional update | | mode `handler`, new event | `received`, then `handled`, `ignored` or `failed` by the application | 1 (insert); the terminal status is one more conditional update by the application, or by the bundle when a handler throws | -Nothing in the bundle moves a `routed` event further, and `EventStatusTransition` only leaves `received`. +Only the process start moves a `routed` event further, to `started` or `failed`; `EventStatusTransition` only leaves `received`. ## Audit and logging @@ -665,6 +864,7 @@ Nothing in the bundle moves a `routed` event further, and `EventStatusTransition - **Rejected deliveries** are not stored. Each writes exactly one `warning` line on the log channel `webhook` with `slug`, `ip`, `reason` and `delivery_id` (the sender's delivery id from the first of the headers `webhook-id`, `X-Gitlab-Event-UUID` and `X-Request-Id` that is set), never the secret or the payload. Reasons: `unknown_endpoint`, `ip_not_allowed`, `body_too_large`, `rate_limited`, `verification_failed`, the same as in the response body. - **Decisions of the intake**: every event the intake sets to `ignored` or `routed` writes one `info` line on the channel `webhook` with `slug`, `event_id`, `type`, `status`, `reason`, `route` and `delivery_id`, never the payload. - **Failed hand-overs** write one `error` line on the channel `webhook` per failing handler (see [Delivery handlers](#delivery-handlers)). +- **Process starts** write their lines on the channel `webhook` with event id, slug, instance id and category, never engine text: a dispatch that failed in the request (`warning`), each attempt in the worker or the catch-up (`info` started or found, `debug` nothing to do, `warning` failed), an event set to `failed` (`error`) and the summary of a catch-up run (`info`, `debug` when it selected nothing); see [Process start](#process-start). The bundle registers the channel when MonologBundle is installed. In production, give it its own handler: a `fingers_crossed` main handler drops info and warning lines unless an error follows, so the rejection and decision lines would be lost. @@ -754,8 +954,10 @@ Console twins of the admin API, with the same validation and the same secret sem | `webhook:event:list [--endpoint=] [--status=] [--type=] [--dedupe-key=] [--limit=50]` | `GET /api/admin/webhook_events` | | `webhook:event:show ` | `GET /api/admin/webhook_events/{id}` | | `webhook:deliver [--header="Name: Value"]... [--secret=] [--ip=
]` | `POST /webhook/{slug}[/{secret}]` | +| `webhook:process:deploy [--endpoint=]` | no API twin; deploys the [answer process](#answer-process) | +| `webhook:process:catch-up [--limit=100] [--dry-run]` | no API twin; runs the [catch-up](#catch-up) | -`` is a slug or a full UUID. The `webhook:*` options have no shortcuts that collide with the global options of the console application (`-h`, `-q`, `-v`, `-V`, `-n`, `-e`): `--endpoint` is long-only everywhere, because `-e` is `--env`; the remaining shortcuts are `-l` for `--limit` of the list commands and `-f` for `--force` of `webhook:endpoint:delete` and `webhook:route:delete`. +`` is a slug or a full UUID. The `webhook:*` options have no shortcuts that collide with the global options of the console application (`-h`, `-q`, `-v`, `-V`, `-n`, `-e`): `--endpoint` is long-only everywhere, because `-e` is `--env`; the remaining shortcuts are `-l` for `--limit` of the list commands and of `webhook:process:catch-up`, and `-f` for `--force` of `webhook:endpoint:delete` and `webhook:route:delete`. ### Endpoint commands @@ -802,7 +1004,7 @@ php bin/console webhook:route:delete mention --endpoint=acme --force - `--header="Name: Value"` sets one request header and is repeatable; `X-Forwarded-*` and `Forwarded` headers given this way are dropped, so the sender address never comes from a header. - `--secret` is the secret path segment (path strategy only), `--ip` the sender address checked against the IP allowlist (default `127.0.0.1`). - Per event it prints `event ` with ` reason=` for an ignored event or ` route=` for a routed one, or `duplicate (stored before, nothing written)`. -- For an endpoint in the mode `handler` it ends with `Handed over to the delivery handlers: event(s).`; for the mode `process` with `Endpoint mode "process": nothing is handed over to the delivery handlers.` +- For an endpoint in the mode `handler` it ends with `Handed over to the delivery handlers: event(s).`; for the mode `process` with `Endpoint mode "process": nothing is handed over to the delivery handlers.` A routed event is queued for its [process start](#process-start) on the transport `webhook`, as by the HTTP route. - Exit code `0` when the delivery is accepted (also a duplicate or an ignored event), `1` when it is rejected (404, 403, 413, 429, 401), `2` for invalid input (unreadable file, an `--ip` that is no IPv4 or IPv6 address, a `--header` without `Name: Value`). ```bash @@ -812,6 +1014,43 @@ echo '{"build": 42}' | php bin/console webhook:deliver ci-builds - --header="X-W Like `--secret=`, a `--header` value with a token lands in the shell history and the process list; use it for tests and diagnosis. +### Process commands + +`webhook:process:deploy` deploys the [answer process](#answer-process) through the [engine port](#engine-port) to Flowable connections, each connection once. Without options, the targets are the distinct `flowableConnection`s of the active endpoints in the mode `process`; such endpoints without a connection are named in a warning and skipped. With `--endpoint=`, the target is the connection of that one endpoint, whatever its mode; without a connection that target fails with `connection_missing`. It is idempotent: where the latest definition of `webhookAnswer` already has the same content, the result is `unchanged` and no new definition version is created, so it can run in every deployment. + +```console +$ php bin/console webhook:process:deploy +Process definition webhookAnswer (webhook-answer.bpmn20.xml): + ---------------------------------------------------------- ------------- ---------- ------------ ------------------------- --------- + Connection Endpoints Result Deployment Definition Version + ---------------------------------------------------------- ------------- ---------- ------------ ------------------------- --------- + flowable-main (0193a5c4-7e2b-7c1d-9f3e-2a4b6c8d0e1f) acme, docs deployed 12501 webhookAnswer:1:12504 1 + ---------------------------------------------------------- ------------- ---------- ------------ ------------------------- --------- + + [OK] 1 target(s): 1 deployed, 0 unchanged, 0 failed. +``` + +- One row per connection with the endpoints that use it and the result `deployed`, `unchanged` or `failed: `; a failed target does not stop the others. The output names only the category, never text of the engine or a secret. +- Exit code `0` when every target was deployed or unchanged, and when there is no target at all (a note says so, so a deployment pipeline of an installation without process endpoints does not fail); `1` when a target failed, the endpoint of `--endpoint` does not exist or the BPMN resource cannot be read. + +`webhook:process:catch-up` runs the [catch-up](#catch-up) once: it starts the routed events without process instance in the configured window whose claim is empty or expired, oldest first, through the starter and not through the transport. `--limit` (`-l`, default 100) caps the number of events; `--dry-run` lists the events a run would start and claims and starts nothing. + +```console +$ php bin/console webhook:process:catch-up +Routed events without process instance, received 300 to 86400 seconds ago: + -------------------------------------- ----------------------------- + Event Result + -------------------------------------- ----------------------------- + 0193a5c4-8a10-7d2e-b1c3-5f6a7b8c9d01 started + 0193a5c4-9b21-7e3f-a2d4-6e7f8a9b0c12 retrying: engine_unreachable + -------------------------------------- ----------------------------- + + [WARNING] 2 event(s): 1 started, 0 found existing, 0 nothing to do, 0 claim lost, 0 not recorded, 0 failed, 1 left for the next run. +``` + +- The result per event is a start outcome (`started`, `found_existing`, `nothing_to_do`, `claim_lost`, `not_recorded`), `failed: ` when the event was set to `failed`, or `retrying: ` when it stays `routed` for the next run. +- Exit code `0` when no event was set to `failed`, also when some stay `routed` after a retryable failure (a warning names the count; a schedule should not alarm on every run while the engine is down) and when there is nothing to catch up; `1` when an event was set to `failed` (an operator has to fix its connection, route or definition; the event is not selected again, so a schedule alarms once per event) or `--limit` is not a positive integer. + ## Writing an own adapter An adapter is a service implementing `Dmstr\Webhook\Adapter\WebhookAdapterInterface` and marked with `#[Dmstr\Webhook\Adapter\AsWebhookAdapter('')]`. The interface extends `Symfony\Component\Webhook\Client\RequestParserInterface` with two methods: @@ -930,6 +1169,29 @@ Rules for an adapter: - Do no processing in the parser; the request path ends with storing and deciding on the event, and source-specific work belongs in a [delivery handler](#delivery-handlers). - Add the header that carries the credential to the access-log filter of the reverse proxy and, unless it is one the shipped processor knows, to a redaction processor of the application (see [Log redaction](#log-redaction)). +## Upgrade from 0.3.x + +0.4.0 starts the process of routed events; read the upgrade notes of 0.4.0 in [CHANGELOG.md](./CHANGELOG.md) before deploying it. In short: + +1. **Run the migrations.** `Dmstr\Webhook\Migrations\Version20261205225504` adds the claim and reference columns to `webhook_event`. +2. **Define the transport `webhook`** with a durable DSN and consume it with a worker, and **register FlowableBundle** (see [Messenger transport and FlowableBundle](#messenger-transport-and-flowablebundle)). +3. **Deploy the process definition** with `webhook:process:deploy`, give every endpoint in the mode `process` a Flowable connection, and make the routes name a deployed key in `processDefinitionKey`. +4. **Schedule the catch-up** (see [Catch-up](#catch-up)). +5. **Check the events that are `routed` already.** 0.3.x stopped at `routed`. The catch-up starts such events received within `catch_up.max_age` (24 hours by default) before its run, or sets them `failed` where a start cannot work (e.g. `route_missing`, `connection_missing`, `definition_not_deployed`); older ones stay `routed` untouched. List both groups before upgrading, with the cutoff set to the time of the first catch-up run minus `catch_up.max_age`, in UTC: + + ```sql + SELECT dedupe_key, type, route, received_at, + CASE WHEN received_at >= '2026-12-06 08:00:00' + THEN 'started by the catch-up' + ELSE 'left untouched' END AS on_upgrade + FROM webhook_event + WHERE status = 'routed' AND process_instance_id IS NULL + ORDER BY received_at; + ``` + + After the upgrade, `webhook:process:catch-up --dry-run` lists what the next run would start. To avoid the retroactive start, schedule the catch-up only once those events are older than `catch_up.max_age`, or keep `catch_up.max_age` low (at least 601 seconds, above the claim lease) until they are. +6. **Changed constructors.** Application code that builds `WebhookIntake` itself has to pass a `MessageBusInterface` after `EventRouter`. + ## Upgrade from 0.1.x 0.2.0 breaks 0.1.x installations; read this before deploying it. @@ -949,7 +1211,9 @@ Rules for an adapter: ## Not built yet -- Starting the process of a `routed` event (the statuses `started` and `completed`, and the event fields `processInstanceId`, `replyReference` and `error`): the bundle stops at `routed`. +- A worker of the [answer process](#answer-process) (topics `webhook-answer` and `webhook-error-answer`): a started instance waits at the answer task until the application completes it. +- The end of a started process on the event: the status `completed` and the event fields `replyReference` and `error` are not set by the bundle; an event stays `started`. +- A way to start a `failed` event again, or to resolve a `routed` event without a start. - Answering in the source on its own: the bundle ships the [GitLab reply client](#gitlab-reply-client), but nothing in the bundle calls it; the application decides when to answer. - A detail view of an event with its payload. - A retention purge of old events. @@ -960,7 +1224,7 @@ Rules for an adapter: The PHPUnit suites live in this repository (configuration `./phpunit.dist.xml`, PHPUnit 12 or 13): - `unit` (`./tests/Unit`): no kernel, no database; the intake, the filters, the limiters, the router, the adapters, the console twins and the container wiring against stubs and in-memory doubles (`./tests/Support`). -- `integration` (`./tests/Integration`): boots the test kernel `./tests/Kernel/TestKernel.php`, a minimal host application with the dependency bundles, header-based test authentication (`X-Test-User`, `X-Test-Roles`) with neutral test roles (`./tests/Kernel/TestRoles.php`, `ROLE_WEBHOOK_ADMIN`) and a test permission voter that maps the bundle's permissions to them, a frozen `clock` (`MockClock`) for the Standard Webhooks replay window, test adapters with an event context, and the log channels `webhook` and `request` in a test log file. Kernel variants cover a host without the `clock` service, without a lock factory, MonologBundle and `http_client`, and the GitLab reply client without its library (simulated by building the bundle with `new OptionalLibraries([Gitlab\Client::class])`), with the adapter `gitlab` disabled, enabled, and with the host's own reply transport. Tests in the group `database` need PostgreSQL or MySQL 8 from `DATABASE_URL` (PostgreSQL by default in `phpunit.dist.xml`; the database name must end with `_test`, because one test drops every table); `./tests/Kernel/TestDatabase.php` creates the schema once per process by running all registered migrations, the bundle's own ones included, and one test runs them on an empty database to prove their order. The same tests run on both platforms; the few statements that cannot be portable branch on the DBAL platform. +- `integration` (`./tests/Integration`): boots the test kernel `./tests/Kernel/TestKernel.php`, a minimal host application with the dependency bundles, header-based test authentication (`X-Test-User`, `X-Test-Roles`) with neutral test roles (`./tests/Kernel/TestRoles.php`, `ROLE_WEBHOOK_ADMIN`) and a test permission voter that maps the bundle's permissions to them, a frozen `clock` (`MockClock`) for the Standard Webhooks replay window, test adapters with an event context, and the log channels `webhook` and `request` in a test log file. Kernel variants cover a host without the `clock` service, without a lock factory, MonologBundle and `http_client`, and the GitLab reply client without its library (simulated by building the bundle with `new OptionalLibraries([Gitlab\Client::class])`), with the adapter `gitlab` disabled, enabled, and with the host's own reply transport; for the process start, a host with FlowableBundle registered (the Flowable engine port), the in-memory engine `./tests/Support/FakeProcessEngine.php` as the host's engine, the bundle's default transport, and a catch-up window other than the default. The test kernel's transport `webhook` is in memory; `./tests/Support/TransportDrain.php` runs its messages through a real Messenger worker with the retry and failure listeners, and `./tests/Support/RecordingMessageBus.php` records the dispatches of the intake without kernel. Tests in the group `database` need PostgreSQL or MySQL 8 from `DATABASE_URL` (PostgreSQL by default in `phpunit.dist.xml`; the database name must end with `_test`, because one test drops every table); `./tests/Kernel/TestDatabase.php` creates the schema once per process by running all registered migrations, the bundle's own ones included, and one test runs them on an empty database to prove their order. The same tests run on both platforms; the few statements that cannot be portable branch on the DBAL platform. The intake is covered by a data-driven matrix: each row (`./tests/Support/IntakeCase.php`) is an endpoint configuration, one request and the expected status, reason, route and hand-over in each mode (`./tests/Support/IntakeExpectation.php`). `./tests/Support/IntakeHarness.php` runs a row without kernel and database (the real intake over an in-memory store), the group `database` runs the same rows against the database. The source-neutral rows (`./tests/Support/IntakeMatrix.php`) use the test adapters `./tests/Kernel/ContextTestAdapter.php` (context from the JSON body), `./tests/Kernel/ActorlessTestAdapter.php` (a source without actor and facts) and `./tests/Kernel/FilterAttributesTestAdapter.php` (one declared attribute of each kind). A source adapter with fixtures adds its rows in its own data provider with the same row shape. Its fixtures are YAML files under `./tests/Fixtures//`, one delivery per file with `origin`, `headers` and `body`, loaded through `./tests/Support/FixtureSet.php`; `origin` is `captured` (a recorded delivery with neutral values), `documented ()` (built from the source's documentation, every value invented, for a source without recorded deliveries) or `derived from ()` (single values of another fixture of the same source changed). `./tests/Support/FixtureMatrix.php` turns fixtures into rows with the source's default endpoint and, for a path secret source, the secret path segment of every request; the traits `./tests/Support/FixtureSequenceTests.php` and `./tests/Support/IntakeHarnessSequences.php` run a source's sequences (several deliveries to one endpoint, then the event rows in order) without database, and `./tests/Integration/Intake/IntakeMatrixDatabaseTestCase.php` runs them against the database. Two sources have fixtures: GitLab (`./tests/Support/GitlabFixtures.php`, `./tests/Support/GitlabMatrix.php`), whose fixtures are captured GitLab 15.11 deliveries with neutral values or derived from them, and Basecamp 4 (`./tests/Support/Basecamp4Fixtures.php`, `./tests/Support/Basecamp4Matrix.php`), whose fixtures are all documented or derived, none captured. `./tests/Unit/Fixtures/FixtureAnonymisationTest.php` guards the anonymisation with one definition per source: structural rules on every fixture (only the source's `example.com` hosts, no redaction placeholders, no avatar service, ASCII only, a valid `origin`, the source's headers with fixture values only), and, when the source's environment variable points to a local directory of raw captures (never committed; `WEBHOOK_RAW_CAPTURES_DIR` for GitLab, `WEBHOOK_RAW_CAPTURES_DIR_BASECAMP4` for Basecamp 4), a check that no value of those captures occurs in any fixture of any source; without the variable that check is skipped. `./tests/Unit/Intake/Basecamp4LogTest.php` runs Basecamp 4 deliveries through the intake with a logger without the redaction processor and fails if a raw log record carries the secret path segment, the request path or any text of the payload; a deliberately leaking test adapter proves that the check detects a leak. @@ -975,7 +1239,7 @@ DATABASE_URL='postgresql://app:app@127.0.0.1:5432/webhook_test?serverVersion=16& DATABASE_URL='mysql://app:app@127.0.0.1:3306/webhook_test?serverVersion=8.0.40&charset=utf8mb4' vendor/bin/phpunit ``` -`composer install` needs both `pdo_pgsql` and `pdo_mysql` (development requirements). CI is the GitHub Action `./.github/workflows/tests.yml` (PHP 8.5 with `pdo_pgsql` and `pdo_mysql`), a matrix of two jobs that run both suites including the group `database`: one against the service container `postgres:16`, one against `mysql:8.0` with the character set and collation above. +`composer install` needs both `pdo_pgsql` and `pdo_mysql` (development requirements). CI is the GitHub Action `./.github/workflows/tests.yml` (PHP 8.5 with `pdo_pgsql` and `pdo_mysql`), a matrix of four jobs that run both suites including the group `database`: against the service container `postgres:16` and against `mysql:8.0` with the character set and collation above, each with both bounds of `dmstr/flowable-bundle`, 0.12.1 and 0.14.0. Without a `composer.lock` in the repository the install resolves the highest allowed versions; a partial `composer update dmstr/flowable-bundle --with dmstr/flowable-bundle:` then pins the version of the job, and the job fails when `composer show` reports another one. ## License @@ -989,3 +1253,4 @@ MIT, see [LICENSE](LICENSE). + diff --git a/composer.json b/composer.json index 42b9472..b6f1546 100644 --- a/composer.json +++ b/composer.json @@ -74,10 +74,8 @@ "symfony/cache": "Provides the cache pool `cache.rate_limiter` of FrameworkBundle, which holds the sliding-window counters of the endpoint rate limit (FrameworkBundle installs it; use a shared adapter such as Redis when several PHP containers serve the intake).", "symfony/clock": "Registers the `clock` service of FrameworkBundle, which the Standard Webhooks adapter then uses for its replay window (system time without it); tests freeze it with `MockClock`.", "symfony/doctrine-messenger": "Provides the Doctrine transport (`doctrine://`) of Symfony Messenger, e.g. for the transport the process start of routed events runs on.", - "symfony/http-client": "Provides the HTTP transport of the GitLab reply client (through its `Psr18Client`); tests replace it with `MockHttpClient`.", "symfony/lock": "Lets the endpoint rate limiter lock its sliding window, so concurrent deliveries of one endpoint do not overshoot the limit.", - "symfony/monolog-bundle": "Registers the log channel `webhook` the bundle writes rejected deliveries and failed hand-offs to, and the secret redaction processor.", - "symfony/security-bundle": "Provides the firewall the intake needs and the `is_granted()` checks of the admin API resources." + "symfony/monolog-bundle": "Registers the log channel `webhook` the bundle writes rejected deliveries and failed hand-offs to, and the secret redaction processor." }, "autoload": { "psr-4": { From 572f7a68f95fb24e463c5f3fcb900866f84dc997 Mon Sep 17 00:00:00 2001 From: Tobias Munk Date: Sun, 6 Dec 2026 09:13:02 +0000 Subject: [PATCH 9/9] docs(changelog): release date of 0.4.0 [*] Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d7312e1..fdf566c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ All notable changes to this bundle. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versions follow [SemVer](https://semver.org/) and come from the Git tags. -## [0.4.0] - Unreleased +## [0.4.0] - 2026-12-06 Routed events start a process: in the mode `process`, every event that becomes `routed` is started asynchronously as one instance of the route's process definition in Flowable, through a new engine port, and the event ends `started` with the process instance id or `failed` with a reason category. Action is needed on upgrade: a migration, a durable Messenger transport with a worker, FlowableBundle, the deployed process definition and a schedule for the catch-up, and a check of the events that are `routed` already. @@ -207,3 +207,4 @@ Initial public release. +