Skip to content

feat: onboard topsort destination - #3913

Merged
aanshi07 merged 15 commits into
developfrom
feat.onboard_topsort_destination
Dec 13, 2024
Merged

aanshi07 merged 15 commits into
developfrom
feat.onboard_topsort_destination

Conversation

@aanshi07

@aanshi07 aanshi07 commented Dec 4, 2024 •

Copy link
Copy Markdown
Contributor

What are the changes introduced in this PR?

Onboarded topsort destination

What is the related Linear task?

Resolves INT-2661

Doc: https://api.docs.topsort.com/api-reference/events/report-events

Please explain the objectives of your changes below

Put down any required details on the broader aspect of your changes. If there are any dependent changes, mandatorily mention them here

Any changes to existing capabilities/behaviour, mention the reason & what are the changes ?

N/A

Any new dependencies introduced with this change?

N/A

Any new generic utility introduced or modified. Please explain the changes.

N/A

Any technical or performance related pointers to consider with the change?

N/A

@coderabbitai review


Developer checklist

  • My code follows the style guidelines of this project

  • No breaking changes are being introduced.

  • All related docs linked with the PR?

  • All changes manually tested?

  • Any documentation changes needed with this change?

  • Is the PR limited to 10 file changes?

  • Is the PR limited to one linear task?

  • Are relevant unit and component test-cases added in new readability format?

Reviewer checklist

  • Is the type of change in the PR title appropriate as per the changes?

  • Verified that there are no credentials or confidential data exposed with the changes.

@aanshi07
aanshi07 requested a review from utsabc December 4, 2024 01:33
@aanshi07 aanshi07 self-assigned this Dec 4, 2024
@codecov

codecov Bot commented Dec 4, 2024 •

Copy link
Copy Markdown

Codecov Report

Attention: Patch coverage is 92.56757% with 11 lines in your changes missing coverage. Please review.

Project coverage is 90.50%. Comparing base (275e971) to head (e8ee4f3).
Report is 31 commits behind head on develop.

Files with missing lines Patch % Lines
src/v0/destinations/topsort/transform.js 89.23% 7 Missing ⚠️
src/v0/destinations/topsort/utils.js 89.28% 3 Missing ⚠️
src/v0/util/index.js 75.00% 1 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #3913      +/-   ##
===========================================
+ Coverage    90.47%   90.50%   +0.02%     
===========================================
  Files          615      620       +5     
  Lines        32320    32518     +198     
  Branches      7677     7710      +33     
===========================================
+ Hits         29242    29429     +187     
- Misses        2822     2865      +43     
+ Partials       256      224      -32     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Comment thread src/v0/destinations/topsort/config.js Resolved
Comment thread src/v0/destinations/topsort/utils.js Resolved
@aanshi07
aanshi07 requested a review from sandeepdsvs December 11, 2024 05:42
aanshi07 and others added 5 commits December 11, 2024 14:15
- moved impressions and clicks logic into its own file
- moved purchase related logic into its own file
Comment thread test/integrations/testTypes.ts Resolved
Comment thread test/integrations/testUtils.ts Resolved
@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

@sonarqubecloud

Copy link
Copy Markdown

@aanshi07
aanshi07 marked this pull request as ready for review December 13, 2024 08:47
@aanshi07
aanshi07 requested review from a team and sivashanmukh as code owners December 13, 2024 08:47
@aanshi07
aanshi07 requested review from a team and krishna2020 December 13, 2024 08:47
Comment thread test/integrations/testTypes.ts Resolved

@sandeepdsvs sandeepdsvs left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@aanshi07
aanshi07 merged commit 227419f into develop Dec 13, 2024
@aanshi07
aanshi07 deleted the feat.onboard_topsort_destination branch December 13, 2024 09:12
ItsSudip added a commit that referenced this pull request Sep 25, 2026
…tionalAttribution (#5606)

## What are the changes introduced in this PR?

Three fixes to the Topsort destination, which has not been modified
since it was onboarded in
#3913. We own the Topsort Events API, so where this describes API
behaviour it comes from the
server implementation rather than our published docs. Each commit is
self-contained and can be
reviewed independently — happy to split into separate PRs if you'd
prefer.

**1. `fix(topsort): make event ids deterministic so retries are
idempotent`**

Each event's `id` is the idempotency key — we use it to recognise a
redelivery and discard it, so a
retried event must carry the same `id` as the first attempt.
`purchase.js` and
`impressions-and-clicks.js` generated it with `generateUUID()` on the
product-array path, so a
RudderStack retry after a 5xx or 429 re-sent the same events under new
ids and we counted them
again. The single-product paths already used `message.messageId` and
were correct, so the two paths
disagreed with each other.

Purchases now use `message.messageId`; impressions and clicks fanned out
from `properties.products`
use `` `${message.messageId}-${index}` ``, since one message produces
one event per product.

This commit also reshapes the per-event code into
`buildTopsortEvents(message, destination)`, which
returns the events a message maps to rather than mutating a shared
`finalPayloads` accumulator
threaded through three modules. That is a prerequisite for commit 3,
which needs a per-event
transform.

**2. `feat(topsort): drop the additionalAttribution mapping`**

We have moved away from per-event additional attribution — the products
eligible for attribution on
a banner campaign are declared at campaign creation and resolved on our
side. The API still accepts
the field, so nothing breaks; we would rather the destination stopped
implying it is part of the
integration.

**3. `feat(topsort): chunk requests at the Events API per-array cap`**

The API binds `max=50` on each of the `impressions`, `clicks` and
`purchases` arrays independently
and rejects the whole request past that. `processRouterDest` merged an
entire router batch into one
request with no chunking, so a large enough batch was rejected in full —
and since the router
returns a single success response covering all metadata, every event in
the batch was lost rather
than just the overflow. There is no per-item result array on our side,
so there is no
partial-success path to fall back on.

This is easier to hit than 50 suggests: an impression or click carrying
a `products` array fans out
to one event per product, so six input events with ten products each
already produce sixty
impressions.

Ported to the native batching framework. The body is three independently
capped arrays rather than
one flat array, so `ChunkBatchStrategy` can't express it — `wrapBody`
receives only the bodies, not
the group key. Each payload is instead tagged with an `internalGroupKey`
of `impressions`, `clicks`
or `purchases`, and a `CustomBatchStrategy` reads that back, chunks at
`MAX_BATCH_SIZE` via
`chunkPayloads`, and wraps as `{[type]: bodies}`.

## What is the related Linear task?

None — external contribution from Topsort. Happy to have one filed if
that helps tracking.

## Please explain the objectives of your changes below

The first and third are the ones that matter. Without them, retries
duplicate events (inflating
impressions, clicks, purchases and attributed revenue) and sufficiently
large batches are dropped
entirely under load. Both affect data our billing runs against.

`processRouterDest` and `process` remain exported and functional. They
are the fallback for any
workspace not enrolled through
`TOPSORT_BATCHING_FRAMEWORK_ENABLED_WORKSPACE_IDS`, so this can be
rolled out per workspace before GA. We have deliberately **not** set
`batching: true` in
`features.ts`, since that would move every workspace at once — we would
suggest validating against
a real workspace first, and we can supply one.

### Any changes to existing capabilities/behaviour, mention the reason &
what are the changes?

Three, all intentional.

1. **Event ids are derived from `messageId` rather than random.** This
is the fix. It changes the
wire value of `id` for events carrying a `products` array, and probably
warrants a release note.
2. **Impressions and clicks fanned out from a `products` array get
distinct ids** (`-0`, `-1`, …).
Previously each got an independently random id in production; under the
test mock they all got
the *same* constant, which would have collided on our dedup key had it
reached the API.
3. **A mixed batch now becomes up to three requests instead of one.**
That is the cost of making
   the per-array cap enforceable, and we think it is the right trade.

One bug fixed incidentally: when every event in a batch failed,
`processRouterDest` still returned
a success response wrapping `{impressions: [], clicks: [], purchases:
[]}`, which we reject with
`at least one event must be present`. The framework emits no request for
an empty group.

### Any new dependencies introduced with this change?

N/A

### Any new generic utility introduced or modified. Please explain the
changes.

None generic. Within the destination, `utils.addFinalPayload` is removed
— it existed only to push
into the accumulator that no longer exists.

### Any technical or performance related pointers to consider with the
change?

`test/integrations/destinations/topsort/mocks.ts` is removed and the
fixtures now assert real
values.

That mock could not work. It called `jest.spyOn(utils, 'generateUUID')`,
but the destination modules
do `const { generateUUID } = require('../../util')` — a CommonJS
destructure copies the value at
require time, so replacing the property afterwards has no effect unless
the module happens to be
loaded *after* the spy is installed. The full suite produces that
ordering and passes; running the
destination alone does not:

```
$ npm run test:ts -- component --destination=topsort   # on develop
Tests:       4 failed, 9 passed, 13 total
```

After this PR the same command reports `13 passed, 13 total`, and does
so because the values are
genuinely deterministic rather than because a spy won a race.

New coverage in `routerTransform.test.ts` (8 tests) includes the three
cases that pin the chunking
fix: 70 events of one type splitting into 50 + 20; six events carrying
ten products each producing
sixty impressions across multiple requests, none over the cap; and seven
events carrying eight
products each (56 impressions), where the cap falls *inside* a job's
fan-out rather than on an
input-event boundary.

That last case is the one worth calling out. When a job's events
straddle two chunks, both chunks
share its jobId, so `combineBatchRequestsWithSameJobIds` folds them into
a single response whose
`batchedRequest` is an **array** of requests. The cap is still honoured
(50 + 6) and every job is
accounted for exactly once — but it is a different response shape, and
the first two cases above
happen to pick counts whose boundary lands on an input-event edge, so
neither reaches it.

<hr>

### Developer checklist

- [x] My code follows the style guidelines of this project

- [ ] **No breaking changes are being introduced.** — see "changes to
existing behaviour"; the wire
value of `id` changes for events carrying a `products` array. That is
the fix.

- [x] All related docs linked with the PR?

- [x] All changes manually tested?

- [ ] Any documentation changes needed with this change?

- [x] Is the PR limited to 10 file changes?

- [ ] Is the PR limited to one linear task? — three related fixes to one
destination, one commit
      each. Glad to split them if you'd rather review separately.

- [x] Are relevant unit and component test-cases added in **new
readability format**?

### Reviewer checklist

- [x] Is the type of change in the PR title appropriate as per the
changes?

- [x] Verified that there are no credentials or confidential data
exposed with the changes.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
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.

5 participants