Repository navigation
fix(provider): mint an eventId the caller did not supply - #4
Merged
Merged
Conversation
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Третий и последний 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 читались одинаково.Красный до правки
Формат проверяется ровно серверной регуляркой через
preg_match, а не хелпером:assertRegExp/assertMatchesRegularExpressionразъехались между PHPUnit 7.5 и 9.6, а в CI живут обе.Гейты
composer lintcomposer testcomposer validate --strictphp-cs-fixer --dry-runpsalmДва последних красные и на нетронутом
origin/main— тот же набор из 23 файлов у cs-fixer и те же 96 ошибок у psalm, набор «файл + тип» до и после правки идентичен побайтово. В моих файлах ни одной новой хунки.Зеркала в
packages/core/пересинхронизированы,cmpпо каждому файлу → 0,PackageManifestTestзелёный.Находка: гейты этого репозитория не работают, и этого не видно
.github/workflows/ci.ymlнаmainпадает за 0 секунд с «workflow file issue» — то есть quality-джоба не выполняется вовсе, а зелёным светит отдельный workflowDEV. Причина локальной красноты: у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