Repository navigation
fix(transport): mint an eventId the caller did not supply - #9
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. finalizeIngestEvent covers the DuckBugProvider pipeline, and three live paths go around it — calling the service directly, sending with skipPrivacyPipeline (which DuckSDK itself uses), and a beforeSend hook that returns an event without the field. sendLog and sendError are the transport's choke point, so the id is ensured there. Lower down is not meaningful: postJsonWithRetry already holds either a single item or a batch array. An existing id is never overwritten; a blank one is replaced. Four existing tests asserted that the request body equalled exactly the object the caller passed. That was pinning the bug — any place to insert an id changes the body. They now compare against the caller's fields plus an eventId, so the caller's own data is still matched exactly. Worth knowing: ensureEventId throws where crypto.randomUUID is absent, which until now could only happen on the finalizeIngestEvent path and can now happen on skipPrivacyPipeline too. Dropping the id silently in an error tracker is worse, so the throw stays — but softening it is a decision for all three SDKs at once, not for this one.
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.
Зачем
Ingest дедуплицирует событие по
eventId— первичный ключ иON CONFLICT DO NOTHING, без TTL. Но поле необязательно: если payload приходит без него, сервер чеканит свежий id на каждый запрос, и ретрай сохраняет событие дважды. То есть гарантия, на которую опирается только что сведённая политика ретраев, держалась на вызывающем.finalizeIngestEventзакрывает конвейерDuckBugProvider, но мимо него проходят три живых пути:sendLog(event, { skipPrivacyPipeline: true })— им пользуется самDuckSDK;beforeSend-хук, вернувший событие без поля.Где вставлено
sendLogиsendError— choke point транспорта. Ниже вставлять бессмысленно: вpostJsonWithRetryприходит уже либо один item, либо массив батча.Существующий
eventIdне перезаписывается, заменяется только пустой.Правка теста, о которой надо сказать прямо
Четыре существующих теста утверждали, что тело запроса равно ровно тому объекту, что дал вызывающий. Это фиксировало баг: любое место вставки id меняет тело. Теперь сравнение идёт с полями вызывающего плюс
eventId, то есть собственные данные вызывающего по-прежнему проверяются точно.Красный до правки
Формат проверяется не на глаз: тесты матчат значение регуляркой серверного правила
uuid4(строчные, версия 4, вариант RFC), плюс закреплено, что два подряд события получают разные id.Что стоит знать
ensureEventIdбросает, если в рантайме нетcrypto.randomUUID. Раньше это могло прилететь только на путиfinalizeIngestEvent, теперь — и наskipPrivacyPipeline. Поведение оставлено: тихо ронять id в трекере ошибок хуже. Но это расширение зоны броска, и если нужна мягкая деградация — решать надо сразу для трёх SDK, а не здесь.Граница гарантии: она стоит до транспорта. Прямой вызов
HTTPTransport.Sendв обход провайдера по-прежнему не защищён, и это правильная граница — транспорт не должен править данные события.Гейты
lint(biome ci, 84 файла) → 0 ·typecheck(tsc --noEmit) → 0 ·test(bun test) → 0,153 pass, 0 fail.Оговорка по среде:
bunна хосте нет, а установленныеnode_modulesсобраны под linux-arm64 из контейнера. Чтобы прогнать гейты,bunиbiomeпоставлены в скретчпад, ни репозиторий, ни глобальные пакеты не трогались. Версияbunне та, что в CI-образе.Та же щель в PHP
DuckBugProvider::preparePayloadснимает приватные секции, зовётbeforeSend, чистит null — и ни разу не касаетсяeventId. Единственный генератор приватный и вызывается только изClient::buildBasePayload(). Интеграции (Monolog, Laravel, Symfony, PSR-15) идут через ядро и потому закрыты, а прямойDuckBugProvider::create($dsn)->captureEvent(...)— нет. Заводится отдельно.🤖 Generated with Claude Code