Skip to content

fix(provider): mint an eventId the caller did not supply - #4

Merged
zaytcevcom merged 2 commits into
mainfrom
fix/ensure-event-id
Sep 17, 2026
Merged

zaytcevcom merged 2 commits into
mainfrom
fix/ensure-event-id

Conversation

@zaytcevcom

Copy link
Copy Markdown
Contributor

Третий и последний SDK. Те же правки: duckbug-go#4, duckbug-js#9.

Зачем

Ingest дедуплицирует событие по eventId — первичный ключ и ON CONFLICT DO NOTHING, без TTL. Но поле необязательно: при его отсутствии сервер чеканит свежий UUID на каждый запрос, и ретрай сохраняет событие дважды.

Client ставит id, поэтому все интеграции через ядро — Monolog, Laravel, Symfony, PSR-15 — закрыты. А прямой DuckBugProvider::create($dsn)->captureEvent(...) и beforeSend-хук, удаливший поле, — нет. При дефолтном maxRetries = 2 это дубликаты.

Где вставлено

preparePayload — единственная точка, мимо которой payload не проходит. Вставка последним действием: после beforeSend и после чистки null, потому что хук, удаляющий поле, иначе открывает щель заново. На это есть отдельный тест. Бейл «beforeSend вернул null» остался выше.

Пригодный id вызывающего не трогается; непригодный (нет, пустая строка, пробелы, не строка) заменяется — ingest такие всё равно отвергает четырёхсотым.

generateEventId стал публичным, а не продублирован в провайдере: собрать payload руками — легальный сценарий, и тогда вызывающему нужно чем заполнить поле. Это прямой перевод core.NewEventID из Go, чтобы три SDK читались одинаково.

Красный до правки

1) testMintsEventIdWhenCallerOmitsIt — Failed asserting that an array has the key 'eventId'.
2) testRestoresEventIdDroppedByBeforeSend — Failed asserting that an array has the key 'eventId'.
3) testReplacesEventIdIngestWouldReject / empty string — Failed asserting that 0 is identical to 1.
Error: testMintsDistinctEventIdsPerEvent — Undefined array key "eventId"
Tests: 10, Assertions: 24, Errors: 1, Failures: 3.       exit=2

Формат проверяется ровно серверной регуляркой через preg_match, а не хелпером: assertRegExp/assertMatchesRegularExpression разъехались между PHPUnit 7.5 и 9.6, а в CI живут обе.

Гейты

PHP 8.4 PHP 7.1
composer lint 0 (73 файла)
composer test 0 (49 тестов / 321 ассерт) 0 (PHPUnit 7.5)
composer validate --strict 0 (корень + 8 пакетов)
php-cs-fixer --dry-run 8
psalm 2

Два последних красные и на нетронутом origin/main — тот же набор из 23 файлов у cs-fixer и те же 96 ошибок у psalm, набор «файл + тип» до и после правки идентичен побайтово. В моих файлах ни одной новой хунки.

Зеркала в packages/core/ пересинхронизированы, cmp по каждому файлу → 0, PackageManifestTest зелёный.

Находка: гейты этого репозитория не работают, и этого не видно

.github/workflows/ci.yml на main падает за 0 секунд с «workflow file issue» — то есть quality-джоба не выполняется вовсе, а зелёным светит отдельный workflow DEV. Причина локальной красноты: у vimeo/psalm и friendsofphp/php-cs-fixer открытые констрейнты (>=4.30, >=3.3), lock не закоммичен, а CI делает composer update — приезжает psalm 6.17 и свежий cs-fixer с правилами, под которые код не писался.

Чинить это в рамках щели с eventId я не стал, но доказал, что мой дифф не добавляет ни одной находки. Заведено отдельно.

Отличие от Go, которое стоит знать

В Go есть гард «пустой payload → не отправляем», в PHP его нет — единственный бейл это beforeSend, вернувший null. То есть Event::log([]) и раньше улетал как {}, а теперь улетит как {"eventId": ...}. Формально событие из одного eventId родиться может, но не из-за этой вставки, а потому что гарда в этом SDK не было изначально. Добавлять новый гард здесь не стал — скажите, если надо.

🤖 Generated with Claude Code

Ingest deduplicates on eventId, but the field is optional: a payload that
arrives without one gets a fresh id minted per request, so a retry stores
the event twice. Client sets the id, so every integration that goes through
the core — Monolog, Laravel, Symfony, PSR-15 — was covered, while calling
DuckBugProvider::create($dsn)->captureEvent(...) directly was not. With the
default maxRetries of 2, that means duplicates.

preparePayload is the one place a payload cannot avoid, and the id goes in
as its last act: after beforeSend and after stripNullValues, because a hook
that drops the field would otherwise reopen the gap. There is a test for
exactly that. The beforeSend-returned-null bail stays above it.

An existing usable id is left alone; a missing, blank or non-string one is
replaced, since ingest rejects those with 400 anyway.

generateEventId becomes public rather than being duplicated in the provider:
assembling a payload by hand is a legitimate scenario, and then the caller
needs something to fill the field with. This mirrors core.NewEventID in the
Go SDK, so the three read the same.

The tests match the server's own uuid4 rule with preg_match rather than an
assertion helper, because those diverged between PHPUnit 7.5 and 9.6 and
both run in CI, and they pin that two consecutive events get different ids.
CI runs a newer php-cs-fixer than the local run did, and its
phpdoc_order puts @throws before @return. The check failed on this
file alone; every other finding in the job predates this branch.
@zaytcevcom
zaytcevcom merged commit be8e981 into main Sep 17, 2026
1 check passed
@zaytcevcom
zaytcevcom deleted the fix/ensure-event-id branch September 17, 2026 06:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant