Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 25 additions & 1 deletion .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -90,10 +95,29 @@ 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

- name: Integration tests (kernel and ${{ matrix.database }}, group database included)
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)
65 changes: 65 additions & 0 deletions CHANGELOG.md

Large diffs are not rendered by default.

19 changes: 15 additions & 4 deletions CLAUDE.md

Large diffs are not rendered by default.

307 changes: 286 additions & 21 deletions README.md

Large diffs are not rendered by default.

7 changes: 4 additions & 3 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -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",
Expand Down Expand Up @@ -71,10 +73,9 @@
"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/http-client": "Provides the HTTP transport of the GitLab reply client (through its `Psr18Client`); tests replace it with `MockHttpClient`.",
"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/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": {
Expand Down
30 changes: 30 additions & 0 deletions config/bpmn/webhook-answer.bpmn20.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- file generated with AI assistance: Claude Code - 2026-12-05 23:27:24 UTC -->
<definitions xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL"
xmlns:flowable="http://flowable.org/bpmn"
targetNamespace="https://github.com/dmstr/webhook-bundle">
<!--
The answer process of a routed webhook event (Dmstr\Webhook\Process\AnswerProcess):
start -> answer (external worker, topic webhook-answer) -> answered.
A worker that gives up raises the BPMN error WEBHOOK_ANSWER_FAILED;
the boundary event on the answer task catches it and leads to
errorAnswer (external worker, topic webhook-error-answer) -> failed.
The definition reads no process variable: the worker takes what it
needs from the stored event, never from text in the process.
-->
<error id="answerError" name="Answer failed" errorCode="WEBHOOK_ANSWER_FAILED"/>
<process id="webhookAnswer" name="Webhook answer" isExecutable="true">
<startEvent id="start" name="Event routed"/>
<sequenceFlow id="toAnswer" sourceRef="start" targetRef="answer"/>
<serviceTask id="answer" name="Answer" flowable:type="external-worker" flowable:topic="webhook-answer"/>
<sequenceFlow id="toAnswered" sourceRef="answer" targetRef="answered"/>
<endEvent id="answered" name="Answered"/>
<boundaryEvent id="answerFailed" name="Answer failed" attachedToRef="answer" cancelActivity="true">
<errorEventDefinition errorRef="answerError"/>
</boundaryEvent>
<sequenceFlow id="toErrorAnswer" sourceRef="answerFailed" targetRef="errorAnswer"/>
<serviceTask id="errorAnswer" name="Error answer" flowable:type="external-worker" flowable:topic="webhook-error-answer"/>
<sequenceFlow id="toFailed" sourceRef="errorAnswer" targetRef="failed"/>
<endEvent id="failed" name="Failed"/>
</process>
</definitions>
43 changes: 43 additions & 0 deletions config/services.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,30 @@ 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);
# 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'
- '../src/Process/ProcessEngineException.php'
- '../src/Process/ProcessEngineFailure.php'
- '../src/Process/ProcessEngineGuard.php'
- '../src/Process/ProcessInstance.php'
# Process start: the message, the failures, the exceptions, the
# 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
Expand All @@ -70,6 +94,21 @@ 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'

# 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).
Expand All @@ -85,3 +124,7 @@ 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)
# - 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)
83 changes: 83 additions & 0 deletions migrations/Version20261205225504.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
<?php

// file generated with AI assistance: Claude Code - 2026-12-05 22:55:04 UTC

declare(strict_types=1);

namespace Dmstr\Webhook\Migrations;

use Doctrine\DBAL\Platforms\AbstractMySQLPlatform;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\DBAL\Types\Types;
use Doctrine\Migrations\AbstractMigration;

/**
* Process start of routed events: the columns of `webhook_event` for the
* claim of a start attempt and the references of the event context
* ({@see \Dmstr\Webhook\Entity\WebhookEvent}).
*
* - `start_claimed_at`: when a start attempt claimed the routed event (the
* lease); the process instance id has its column since
* `Version20261127220000`.
* - `project_kind`/`project_id`, `target_kind`/`target_id`,
* `note_kind`/`note_id`, `discussion_kind`/`discussion_id`: the
* references of the event context, kind and id per role.
*
* Every column is nullable without a default: existing events have neither
* a claim nor stored references, so the migration adds columns only and
* writes no row.
*
* No index: the catch-up of routed events without instance selects by
* `status`, which `idx_webhook_event_status` covers, and `routed` is a
* transient status (an event leaves it when its instance starts or the
* start fails), so the few rows it selects are filtered by `received_at`,
* `process_instance_id` and `start_claimed_at` without another index.
*
* Written with the Schema API, so it runs on every platform Doctrine
* supports. Order: it changes the table of `Version20261127220000`, which
* sorts before this class.
*/
final class Version20261205225504 extends AbstractMigration
{
private const string TABLE = 'webhook_event';
/** Length of a reference kind (`WebhookEvent::MAX_REFERENCE_KIND_LENGTH` when written). */
private const int KIND_LENGTH = 50;
/** Length of a reference id (`WebhookEvent::MAX_REFERENCE_LENGTH` when written). */
private const int ID_LENGTH = 255;
private const array ROLES = ['project', 'target', 'note', 'discussion'];
private const string CLAIM_COLUMN = 'start_claimed_at';

public function getDescription(): string
{
return 'Add webhook_event.start_claimed_at and the reference columns of the event context (of dmstr/webhook-bundle)';
}

/**
* DDL on MySQL commits implicitly, so a transaction there would protect
* nothing; PostgreSQL adds all columns or none.
*/
public function isTransactional(): bool
{
return !$this->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);
}
}
134 changes: 134 additions & 0 deletions src/Command/ProcessCatchUpCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
<?php

// file generated with AI assistance: Claude Code - 2026-12-06 00:10:58 UTC

declare(strict_types=1);

namespace Dmstr\Webhook\Command;

use Dmstr\Webhook\Process\Start\ProcessStartCatchUp;
use Dmstr\Webhook\Process\Start\ProcessStartCatchUpResult;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\Uid\Uuid;

/**
* Console twin of the catch-up of the process start
* ({@see ProcessStartCatchUp}): starts the routed events without process
* instance between the configured minimum age and age limit whose claim is
* empty or expired, oldest first, directly through the starter (not through
* the transport `webhook`).
*
* Options: `--limit` (at most this many events, default
* {@see ProcessStartCatchUp::DEFAULT_LIMIT}) and `--dry-run` (lists the
* events a run would start; claims nothing and calls nothing on the engine).
*
* One row per event: its id and the result (a start outcome, `failed:
* <category>` when the event was set to `failed`, `retrying: <category>`
* 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(),
);
}
}
Loading
Loading