Repository navigation
refactor: postscript utils functions - #4562
Conversation
|
Note Other AI code review bot(s) detectedCodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review. Summary by CodeRabbit
WalkthroughReplaces Postscript custom-events endpoint with /events; renames lookup response field Changes
Sequence Diagram(s)sequenceDiagram
participant Processor as Rudder Processor
participant Utils as Postscript Utils
participant API as Postscript API
participant Logger as Logger
Processor->>Utils: performSubscriberLookup(events[])
Utils->>API: GET /v2/subscribers?phone_number__in=...
API-->>Utils: 200 { subscribers: [...] } / 4xx/5xx
alt success
Utils->>Utils: map subscribers by phone_number -> event mapping
Utils-->>Processor: mapping with exists/subscriber info
else error
Utils->>Logger: logger.warn("PostScript subscriber lookup failed", ...)
Utils-->>Processor: mapping marking events as non-existing
end
sequenceDiagram
participant Processor as Rudder Processor
participant Utils as Postscript Utils
Processor->>Utils: buildCustomEventPayload(message)
Utils->>Utils: format timestamp -> occurred_at
Utils->>Utils: include email, phone, sanitized properties
Utils-->>Processor: event payload
Processor->>Utils: buildSubscriberPayload(message, mapping, opts)
Utils->>Utils: compute exclusions, extract custom fields (traits/context), sanitize
Utils-->>Processor: subscriber payload
Estimated code review effort🎯 4 (Complex) | ⏱️ ~35 minutes Possibly related PRs
Suggested reviewers
Tip 🔌 Remote MCP (Model Context Protocol) integration is now available!Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats. ✨ Finishing Touches
🧪 Generate unit tests
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
Status, Documentation and Community
|
3402457 to
f13aa10
Compare
|
Allure Test reports for this run are available at:
|
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## develop #4562 +/- ##
===========================================
+ Coverage 91.63% 91.80% +0.17%
===========================================
Files 643 642 -1
Lines 34020 33908 -112
Branches 8048 8022 -26
===========================================
- Hits 31174 31130 -44
+ Misses 2588 2548 -40
+ Partials 258 230 -28 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Actionable comments posted: 1
🔭 Outside diff range comments (7)
src/v0/destinations/postscript/utils.ts (5)
46-51: Don't send partner key header when unsetCurrently, the header is included with an undefined value. Prefer omitting the header entirely to avoid sending a literal "undefined" value through the adapter.
Apply this diff:
-export const buildHeaders = (apiKey: string): PostscriptHeaders => ({ - 'Content-type': 'application/json', - Accept: 'application/json', - Authorization: `Bearer ${apiKey}`, - 'X-Postscript-Partner-Key': process.env.POSTSCRIPT_PARTNER_API_KEY, -}); +export const buildHeaders = (apiKey: string): PostscriptHeaders => { + const headers: PostscriptHeaders = { + 'Content-type': 'application/json', + Accept: 'application/json', + Authorization: `Bearer ${apiKey}`, + }; + if (process.env.POSTSCRIPT_PARTNER_API_KEY) { + headers['X-Postscript-Partner-Key'] = process.env.POSTSCRIPT_PARTNER_API_KEY; + } + return headers; +};
60-69: Required-fields check: make lookup more resilient across traits/contextUsing getFieldValueFromMessage(message, field) assumes MESSAGE_MAPPING has the key (e.g., "email"). Add fallbacks to traits/context.traits and avoid treating empty strings as present.
Apply this diff:
export const validateRequiredFields = (message: RudderMessage, requiredFields: string[]): void => { const missingFields = requiredFields.filter((field) => { - const value = getFieldValueFromMessage(message, field); - return !value; + // Try standard mapping first + const candidates = [ + getFieldValueFromMessage(message, field), + getFieldValueFromMessage(message, `traits.${field}`), + getFieldValueFromMessage(message, `context.traits.${field}`), + ]; + const value = candidates.find((v) => v !== null && v !== undefined && v !== ''); + return value === undefined || value === null || value === ''; }); if (missingFields.length > 0) { throw new Error(`Missing required fields: ${missingFields.join(', ')}`); } };
109-116: Avoid setting shopify_customer_id to NaNIf the external ID is a non-numeric value (e.g., mocks returning same value for all types), Number() yields NaN, which leaks into the payload. Only set when it’s a finite number.
Apply this diff:
- if (shopifyCustomerId) { - payload.shopify_customer_id = Number(shopifyCustomerId); - } + if (shopifyCustomerId !== null && shopifyCustomerId !== undefined) { + const shopifyIdNum = Number(shopifyCustomerId); + if (Number.isFinite(shopifyIdNum)) { + payload.shopify_customer_id = shopifyIdNum; + } + }
216-234: Lookup should support both phone and email; deduplicate paramsCurrently, only phone_number__in is used and identifierType isn’t respected. Support email__in too, and de-duplicate values to avoid redundant params.
Apply this diff:
- // Extract phone numbers from events for batch lookup - const phoneNumbers = events - .map((event) => event.identifierValue) - .filter((phone) => phone) as string[]; + // Extract identifiers by type + const phoneNumbers = Array.from( + new Set( + events + .filter((e) => e.identifierType === 'phone') + .map((e) => e.identifierValue) + .filter(Boolean) as string[], + ), + ); + const emails = Array.from( + new Set( + events + .filter((e) => e.identifierType === 'email') + .map((e) => e.identifierValue) + .filter(Boolean) as string[], + ), + ); - if (phoneNumbers.length === 0) { + if (phoneNumbers.length === 0 && emails.length === 0) { return []; } try { // Build lookup request with PostScript's filter parameters const headers = buildHeaders(apiKey); const params = new URLSearchParams(); - // https://developers.postscript.io/reference/get-subscribers - phoneNumbers.forEach((phone) => { - params.append('phone_number__in', phone); - }); + // https://developers.postscript.io/reference/get-subscribers + phoneNumbers.forEach((phone) => params.append('phone_number__in', phone)); + emails.forEach((email) => params.append('email__in', email));
257-269: Respect identifierType and match on email when appropriateThe result always reports identifierType as phone and only matches by phone_number. Use the event’s identifierType to determine the match field and return type.
Apply this diff:
- return events.map((event) => { - const phone = event.identifierValue; - - // Find existing subscriber by phone - const existingSubscriber = subscribers.find((sub) => phone && sub.phone_number === phone); - - return { - exists: !!existingSubscriber, - subscriberId: existingSubscriber?.id, - identifierValue: phone ?? '', - identifierType: 'phone' as const, - }; - }); + return events.map((event) => { + const identifierValue = event.identifierValue ?? ''; + const type = event.identifierType === 'email' ? 'email' : 'phone'; + + let existingSubscriber: typeof subscribers[number] | undefined; + if (type === 'phone') { + existingSubscriber = subscribers.find((sub) => sub.phone_number === identifierValue); + } else { + existingSubscriber = subscribers.find((sub) => sub.email === identifierValue); + } + + return { + exists: !!existingSubscriber, + subscriberId: existingSubscriber?.id, + identifierValue, + identifierType: type as 'phone' | 'email', + }; + });src/v0/destinations/postscript/utils.test.ts (2)
136-153: Adjust header test to expect omission (not undefined) when partner key is unsetWith the proposed header change, the partner key header shouldn’t be present at all if the env var is missing.
Apply this diff:
- expect(headers).toEqual({ - 'Content-type': 'application/json', - Accept: 'application/json', - Authorization: 'Bearer test_api_key_123', - 'X-Postscript-Partner-Key': undefined, - }); + expect(headers).toEqual({ + 'Content-type': 'application/json', + Accept: 'application/json', + Authorization: 'Bearer test_api_key_123', + });
275-311: Avoid asserting NaN for shopify_customer_idPer the payload fix, shopify_customer_id will only be set when numeric. Update the expectation to omit this field when not present.
Apply this diff:
expect(payload).toEqual({ phone_number: '+1234567890', email: '[email protected]', external_id: 'sub_123', - shopify_customer_id: NaN, });
🧹 Nitpick comments (5)
src/v0/destinations/postscript/utils.ts (1)
141-147: Type customPropertiesPayload for clarityMinor typing improvement for maintainability.
Apply this diff:
- const customPropertiesPayload = {}; + const customPropertiesPayload: Record<string, unknown> = {};src/v0/destinations/postscript/utils.test.ts (4)
654-667: Keep subscriberId expectation consistent (undefined vs omitted)performSubscriberLookup returns subscriberId: undefined for non-matches. Align this test with the function’s shape for consistency.
Apply this diff:
expect(results).toEqual([ - { exists: false, identifierValue: '+1234567890', identifierType: 'phone' }, - { exists: false, identifierValue: '+0987654321', identifierType: 'phone' }, + { exists: false, subscriberId: undefined, identifierValue: '+1234567890', identifierType: 'phone' }, + { exists: false, subscriberId: undefined, identifierValue: '+0987654321', identifierType: 'phone' }, ]);
724-729: Update test fixture endpoint to /events to match configThe config now exports /events. Keep test inputs in sync to avoid confusion.
Apply this diff:
{ eventType: 'track', - endpoint: 'https://api.postscript.io/api/v2/custom-events', + endpoint: 'https://api.postscript.io/api/v2/events', method: 'POST', payload: { type: 'Purchase' }, metadata: { jobId: 2 }, },
360-363: Mocking the JSON mapping mid-test likely has no effectjest.doMock after the module under test has already imported the JSON won’t affect the in-memory subscriberMapping. The test already controls mapping via constructPayload and generateExclusionList; consider removing this to reduce confusion.
22-33: Optional: tighten mocks to only what’s assertedGood move to limit mocking scope. As a further cleanup, remove unused mocked logger methods or add assertions for warn in the lookup error path to make the mock purposeful.
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these settings in your CodeRabbit configuration.
⛔ Files ignored due to path filters (2)
test/integrations/destinations/postscript/router/mixedEventsTestData.tsis excluded by!**/test/**test/integrations/destinations/postscript/router/trackTestData.tsis excluded by!**/test/**
📒 Files selected for processing (4)
src/v0/destinations/postscript/config.ts(1 hunks)src/v0/destinations/postscript/types.ts(1 hunks)src/v0/destinations/postscript/utils.test.ts(16 hunks)src/v0/destinations/postscript/utils.ts(5 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
src/v0/destinations/postscript/utils.ts (2)
src/v0/util/index.js (3)
getFieldValueFromMessage(687-693)formatTimeStamp(390-399)removeUndefinedAndNullValues(55-55)src/v0/destinations/postscript/types.ts (1)
PostscriptCustomEventPayload(92-100)
src/v0/destinations/postscript/utils.test.ts (2)
src/types/rudderEvents.ts (1)
RudderMessage(43-43)src/v0/destinations/postscript/utils.ts (2)
validateRequiredFields(60-69)buildCustomEventPayload(166-201)
🪛 Gitleaks (8.27.2)
src/v0/destinations/postscript/utils.test.ts
90-90: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.
(generic-api-key)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
- GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image AMD64
- GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image ARM64
- GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image ARM64
- GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image AMD64
- GitHub Check: Code Coverage
- GitHub Check: test_and_publish
🔇 Additional comments (8)
src/v0/destinations/postscript/config.ts (1)
12-12: Endpoint path update to /events looks correctSwitching to /events aligns with Postscript’s current custom events API. No issues spotted in this file.
src/v0/destinations/postscript/types.ts (2)
130-136: Renaming lookup response field to subscribers matches downstream usageThe change to subscribers: PostscriptSubscriberResponse[] is consistent with utils.performSubscriberLookup.
130-136: Confirmed — no remaining usages of Postscript lookup.data; code reads from.subscribersChecked the repo for Postscript lookup response usages. Findings (short):
- src/v0/destinations/postscript/types.ts — PostscriptLookupResponse exposes
subscribers: PostscriptSubscriberResponse[].- src/v0/destinations/postscript/utils.ts — lookup code casts to PostscriptLookupResponse and uses
lookupData.subscribers(e.g., lines ~253–254).- src/v0/destinations/postscript/transform.ts — contains
if (result.success && result.data) { processedEvents.push(result.data); }(lines ~206–207). Thisresult.datais for processed events, not the Postscript lookup response.Action: No fixes required for the lookup response change. Suggestion: consider renaming generic
result.data(in transform) to a clearer name (e.g.,result.payloadorresult.processed) to avoid future confusion between generic.dataand the Postscript-specific.subscribers.src/v0/destinations/postscript/utils.ts (2)
174-185: Timestamp handling for occurred_at is on pointUsing formatTimeStamp with 'YYYY-MM-DD HH:mm:ss.SSS' aligns with the expected Postscript format.
187-195: Double-check fallback identifier semanticsYou’re falling back to setting subscriber_id = userId when no external IDs exist. Verify this matches Postscript semantics; in many APIs, userId should map to external_id instead of subscriber_id if it’s not a Postscript subscriber ID.
Would you confirm via the Postscript docs whether user-origin IDs should populate external_id (preferred) rather than subscriber_id when no Postscript ID is present? If needed, I can provide a patch to switch the fallback.
src/v0/destinations/postscript/utils.test.ts (3)
596-637: Nice: request verification for the exact URL queryAsserting the exact query string with multiple phone_number__in params prevents regressions in encoding and parameterization.
490-551: Great coverage on timestamp formatting casesThe occurred_at format assertions across ISO variants are thorough.
90-101: Gitleaks false-positive on test keys; add ignore or use clearly fake patternsStatic analysis flagged a generic API key. These are test-only values, but consider:
- Prefixing with obvious non-secret markers (e.g., dummy_, test_) or
- Adding a gitleaks allowlist entry for these test files/strings.
|
Allure Test reports for this run are available at:
|
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
src/v0/destinations/postscript/utils.ts (1)
121-140: Consider simplifying the exclusion list constructionThe current implementation builds exclusions in two separate loops with different logic branches. This could be simplified for better maintainability.
Consider consolidating the exclusion list building:
- // Create a comprehensive exclusion list for traits extraction - const traitsExclusions = new Set(); - - // Add all field names from the mapping configuration - subscriberMapping.forEach((mapping) => { - if (Array.isArray(mapping.sourceKeys)) { - mapping.sourceKeys.forEach((sourceKey) => { - if (sourceKey.startsWith('traits.')) { - // Extract the field name after 'traits.' - traitsExclusions.add(sourceKey.replace('traits.', '')); - } - }); - } else if (mapping.sourceFromGenericMap) { - // For generic map fields, exclude the sourceKeys directly - traitsExclusions.add(mapping.sourceKeys); - } - }); - - // Convert Set to Array for extractCustomFields - const allExclusions = [...exclusionFields, ...Array.from(traitsExclusions)]; + // Build comprehensive exclusion list from mapping configuration + const traitsExclusions = subscriberMapping.reduce((acc, mapping) => { + if (Array.isArray(mapping.sourceKeys)) { + mapping.sourceKeys.forEach((sourceKey) => { + if (sourceKey.startsWith('traits.')) { + acc.add(sourceKey.replace('traits.', '')); + } + }); + } else if (mapping.sourceFromGenericMap) { + acc.add(mapping.sourceKeys); + } + return acc; + }, new Set()); + + const allExclusions = [...exclusionFields, ...traitsExclusions];
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these settings in your CodeRabbit configuration.
📒 Files selected for processing (2)
src/v0/destinations/postscript/utils.test.ts(10 hunks)src/v0/destinations/postscript/utils.ts(5 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2024-07-27T07:02:57.329Z
Learnt from: anantjain45823
PR: rudderlabs/rudder-transformer#2842
File: src/v1/sources/shopify/identifierEventsLayer.test.js:5-40
Timestamp: 2024-07-27T07:02:57.329Z
Learning: The `processIdentifierEvent` function in `identifierEventsLayer.test.js` is designed to succeed for any input, hence no negative test cases are required.
Applied to files:
src/v0/destinations/postscript/utils.test.ts
🧬 Code Graph Analysis (2)
src/v0/destinations/postscript/utils.test.ts (1)
src/v0/destinations/postscript/utils.ts (6)
buildHeaders(46-51)validateRequiredFields(60-69)buildSubscriberPayload(80-155)buildCustomEventPayload(166-201)performSubscriberLookup(212-284)batchResponseBuilder(297-329)
src/v0/destinations/postscript/utils.ts (3)
src/v0/util/index.js (3)
getFieldValueFromMessage(687-693)formatTimeStamp(390-399)removeUndefinedAndNullValues(55-55)src/v0/destinations/postscript/types.ts (2)
PostscriptCustomEventPayload(92-100)PostscriptLookupResponse(129-136)src/v0/destinations/postscript/config.ts (1)
SUBSCRIBERS_ENDPOINT(11-11)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (9)
- GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image AMD64
- GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image ARM64
- GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image ARM64
- GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image AMD64
- GitHub Check: Code Coverage
- GitHub Check: test_and_publish
- GitHub Check: UT Tests
- GitHub Check: Analyze (go)
- GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (7)
src/v0/destinations/postscript/utils.ts (4)
32-33: Good additions for payload building and timestamp formattingThe imports of
isObjectandformatTimeStampare appropriate for the new functionality in building custom event payloads with proper timestamp handling.
60-69: Well-implemented validation functionThe
validateRequiredFieldsfunction provides clean validation logic using the existinggetFieldValueFromMessageutility. The error message clearly lists all missing fields, which will help with debugging.
174-185: Excellent timestamp formatting implementationThe
occurred_atfield is properly formatted using theformatTimeStamputility with the correct format string. The conditional spread syntax ensures the field is only included when a timestamp exists, keeping the payload clean.
225-283: Robust error handling in subscriber lookupThe refactored
performSubscriberLookupfunction properly handles API errors by logging warnings and returning safe defaults. The per-phone lookup approach usingphone_number__inparameters is efficient and aligns with the PostScript API documentation.src/v0/destinations/postscript/utils.test.ts (3)
16-29: Good test isolation with minimal mockingThe refactored mocking strategy that only mocks external dependencies (network and logger) while using real implementations for utility functions is a solid testing approach. This ensures the tests validate actual behavior rather than mock implementations.
275-306: Comprehensive timestamp format testingThe test cases effectively cover various timestamp formats including edge cases like end-of-year timestamps. The structured approach with test case descriptions makes the tests maintainable and clear.
438-475: Well-structured error handling testThe new test case for API error handling properly validates that the function logs warnings and returns safe defaults when the API fails. This ensures graceful degradation in production.
|
Allure Test reports for this run are available at:
|
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (1)
src/v0/destinations/postscript/utils.test.ts (1)
39-65: Ensure environment variable cleanup in unit tests (duplicate of earlier feedback)The test deletes process.env.POSTSCRIPT_PARTNER_API_KEY but doesn’t restore it if an exception occurs, which can leak state across tests.
Apply this diff to wrap the mutation in try/finally:
it('should build headers without partner key when env var is not set', () => { - delete process.env.POSTSCRIPT_PARTNER_API_KEY; - - const apiKey = 'test_api_key_123'; - const headers = buildHeaders(apiKey); - - expect(headers).toMatchObject({ - 'Content-type': 'application/json', - Accept: 'application/json', - Authorization: 'Bearer test_api_key_123', - 'X-Postscript-Partner-Key': undefined, - }); + const originalPartnerKey = process.env.POSTSCRIPT_PARTNER_API_KEY; + try { + delete process.env.POSTSCRIPT_PARTNER_API_KEY; + + const apiKey = 'test_api_key_123'; + const headers = buildHeaders(apiKey); + + expect(headers).toMatchObject({ + 'Content-type': 'application/json', + Accept: 'application/json', + Authorization: 'Bearer test_api_key_123', + 'X-Postscript-Partner-Key': undefined, + }); + } finally { + if (originalPartnerKey !== undefined) { + process.env.POSTSCRIPT_PARTNER_API_KEY = originalPartnerKey; + } else { + delete process.env.POSTSCRIPT_PARTNER_API_KEY; + } + } });
🧹 Nitpick comments (5)
src/v0/destinations/postscript/transform.ts (2)
159-162: Extracting destination from the first input: add a uniformity guard (optional)Assuming all inputs share the same destination is typical, but adding a sanity check can prevent hard-to-debug misroutes if invariants break upstream.
Apply this diff to defensively assert uniform destination IDs:
// Extract destination configuration from first event const { destination } = inputs[0]; const postscriptDestination = destination; + // Optional: assert uniform destination across inputs to avoid cross-destination mixing + const firstDestId = postscriptDestination.ID; + const mixedDest = inputs.some((i) => i.destination?.ID !== firstDestId); + if (mixedDest) { + throw new ConfigurationError('All inputs must target the same Postscript destination instance'); + }
221-244: Index-based correlation of lookup results: add length guard (optional)performSubscriberLookup should return a result per identify event; a defensive check can avoid undefined indexing if upstream logic changes or API returns unexpected shapes.
Consider guarding length mismatch and defaulting to create on missing results:
- const updatedIdentifyEvents = identifyEvents.map((event, index) => { - const lookupResult = lookupResults[index]; + const updatedIdentifyEvents = identifyEvents.map((event, index) => { + const lookupResult = lookupResults[index] ?? { exists: false }; if (lookupResult?.exists) { return { ...event, method: 'PATCH' as const, endpoint: `${SUBSCRIBERS_ENDPOINT}/${lookupResult.subscriberId}`, }; } return { ...event, method: 'POST' as const, endpoint: SUBSCRIBERS_ENDPOINT, }; });src/v0/destinations/postscript/utils.test.ts (3)
34-37: Avoid secret scanner false positives in tests (Gitleaks)Gitleaks flagged a “Generic API Key” here. It’s a benign test value, but prefer obvious dummy strings to prevent CI noise.
Consider changing the setup value:
- process.env.POSTSCRIPT_PARTNER_API_KEY = 'partner_key_123'; + process.env.POSTSCRIPT_PARTNER_API_KEY = 'DUMMY_PARTNER_KEY';And, if needed, add a repository-level allowlist entry for clearly dummy tokens used in tests.
300-313: Note: utils allows unnamed events; router rejects themThis test is valid for buildCustomEventPayload in isolation. Just be aware processTrackEvent in transform.ts throws if message.event is missing, so this payload shape won’t be emitted by router code paths.
If the intention is to keep utils resilient for reuse, add a short comment in the test clarifying the discrepancy to avoid confusion for future maintainers.
517-533: Strengthen header assertions to cover partner key propagation (optional)Since buildHeaders attaches the partner key when set, asserting its presence here increases confidence that batchResponseBuilder wires headers correctly.
Apply this diff to extend assertions:
const responses = batchResponseBuilder(events, mockDestination); expect(responses).toHaveLength(1); expect(responses[0].batchedRequest.headers).toHaveProperty('Authorization'); expect(responses[0].batchedRequest.headers).toHaveProperty('Content-type'); + expect(responses[0].batchedRequest.headers).toHaveProperty('X-Postscript-Partner-Key', 'partner_key_123');
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these settings in your CodeRabbit configuration.
📒 Files selected for processing (4)
src/v0/destinations/postscript/transform.ts(2 hunks)src/v0/destinations/postscript/types.ts(2 hunks)src/v0/destinations/postscript/utils.test.ts(10 hunks)src/v0/destinations/postscript/utils.ts(6 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- src/v0/destinations/postscript/utils.ts
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2024-07-27T07:02:57.329Z
Learnt from: anantjain45823
PR: rudderlabs/rudder-transformer#2842
File: src/v1/sources/shopify/identifierEventsLayer.test.js:5-40
Timestamp: 2024-07-27T07:02:57.329Z
Learning: The `processIdentifierEvent` function in `identifierEventsLayer.test.js` is designed to succeed for any input, hence no negative test cases are required.
Applied to files:
src/v0/destinations/postscript/utils.test.ts
🧬 Code Graph Analysis (2)
src/v0/destinations/postscript/transform.ts (1)
src/v0/destinations/postscript/utils.ts (1)
batchResponseBuilder(300-330)
src/v0/destinations/postscript/utils.test.ts (1)
src/v0/destinations/postscript/utils.ts (6)
buildHeaders(45-52)validateRequiredFields(61-70)buildSubscriberPayload(81-156)buildCustomEventPayload(167-204)performSubscriberLookup(215-287)batchResponseBuilder(300-330)
🪛 Gitleaks (8.27.2)
src/v0/destinations/postscript/utils.test.ts
36-36: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.
(generic-api-key)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (9)
- GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image AMD64
- GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image ARM64
- GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image ARM64
- GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image AMD64
- GitHub Check: Code Coverage
- GitHub Check: UT Tests
- GitHub Check: test_and_publish
- GitHub Check: Analyze (go)
- GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (3)
src/v0/destinations/postscript/types.ts (2)
169-172: Router generics simplification looks goodDropping the connection generic keeps the type surface lean and reflects the actual usage.
115-121: Lookup rename verified — no remaining.datalookup referencesRan the provided grep script against src/v0/destinations/postscript. Summary:
- No matches for
.dataas the lookup response field.subscribersis used consistently (types, utils, and tests).- No
/custom-eventsreferences found.- The only mention of
phone_inis in a comment.Files/locations of interest:
- src/v0/destinations/postscript/types.ts — defines lookup response with
subscribers(lines ~115–121).- src/v0/destinations/postscript/utils.ts — builds phone_number__in params, calls
/subscribers, and readslookupData.subscribers(comments around ~207 and logic ~232–279).- src/v0/destinations/postscript/config.ts — SUBSCRIBERS_ENDPOINT and CUSTOM_EVENTS_ENDPOINT (
/events) set.- Tests updated to expect
subscribers(utils.test.ts, transform.test.ts).Suggestion:
- Update or remove the inline comment in utils.ts that mentions
phone_in(around line ~209) to avoid confusion — the code usesphone_number__in.src/v0/destinations/postscript/transform.ts (1)
256-257: batchResponseBuilder signature change handled correctlyThe updated two-argument call aligns with the refactor in utils; response building remains per-event as intended.
|
Allure Test reports for this run are available at:
|
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (2)
src/v0/destinations/postscript/utils.test.ts (2)
22-24: Update logger mock to be ESM/CJS-safeThe mock only provides named exports which can break consumers that import the logger as a default export, depending on module interop settings.
53-64: Environment variable cleanup needs try-finally protectionThe test modifies a global environment variable but the restoration logic could fail if an exception occurs before the test completes.
🧹 Nitpick comments (2)
src/v0/destinations/postscript/utils.test.ts (2)
28-31: Type assertion for logger may cause issuesThe logger is imported as a default export but then cast to
jest.Mocked<typeof logger>, which may not match the actual structure if the mock doesn't properly expose the default export.Consider updating the logger import and casting to be more explicit:
-import logger from '../../../logger'; - -const mockHandleHttpRequest = handleHttpRequest as jest.MockedFunction<typeof handleHttpRequest>; -const mockLogger = logger as jest.Mocked<typeof logger>; +import * as logger from '../../../logger'; +const mockHandleHttpRequest = handleHttpRequest as jest.MockedFunction<typeof handleHttpRequest>; +const mockLogger = logger.warn as jest.MockedFunction<typeof logger.warn>;
36-36: Consider using a test-specific environment variableThe static analysis tool flagged this as a potential API key exposure. While this is test code, consider using a clearly test-prefixed value to make it obvious this is not a real credential.
- process.env.POSTSCRIPT_PARTNER_API_KEY = 'partner_key_123'; + process.env.POSTSCRIPT_PARTNER_API_KEY = 'test_partner_key_123';
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (3)
src/v0/destinations/postscript/transform.ts(3 hunks)src/v0/destinations/postscript/utils.test.ts(10 hunks)src/v0/destinations/postscript/utils.ts(6 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
- src/v0/destinations/postscript/transform.ts
- src/v0/destinations/postscript/utils.ts
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2024-07-27T07:02:57.329Z
Learnt from: anantjain45823
PR: rudderlabs/rudder-transformer#2842
File: src/v1/sources/shopify/identifierEventsLayer.test.js:5-40
Timestamp: 2024-07-27T07:02:57.329Z
Learning: The `processIdentifierEvent` function in `identifierEventsLayer.test.js` is designed to succeed for any input, hence no negative test cases are required.
Applied to files:
src/v0/destinations/postscript/utils.test.ts
🧬 Code Graph Analysis (1)
src/v0/destinations/postscript/utils.test.ts (4)
src/util/prometheus.js (1)
logger(2-2)src/v0/destinations/postscript/utils.ts (2)
buildHeaders(45-52)validateRequiredFields(61-70)src/types/rudderEvents.ts (1)
RudderMessage(43-43)src/v0/destinations/postscript/types.ts (1)
ProcessedEvent(128-137)
🪛 Gitleaks (8.27.2)
src/v0/destinations/postscript/utils.test.ts
36-36: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.
(generic-api-key)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (9)
- GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image AMD64
- GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image ARM64
- GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image ARM64
- GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image AMD64
- GitHub Check: Code Coverage
- GitHub Check: test_and_publish
- GitHub Check: UT Tests
- GitHub Check: Analyze (javascript-typescript)
- GitHub Check: Analyze (go)
🔇 Additional comments (10)
src/v0/destinations/postscript/utils.test.ts (10)
69-85: Good test coverage for validateRequiredFieldsThe test cases comprehensively cover the new
validateRequiredFieldsfunction, including positive cases (all fields present) and negative cases (missing fields). The inline RudderMessage construction is appropriate for unit tests.
132-138: Excellent property extraction testingThe test properly validates that custom fields are extracted into the
propertiesobject while standard fields are mapped to their correct payload keys. This aligns well with the updated payload construction logic.
177-187: Verify timestamp format expectationsThe test expects
occurred_at: '2025-01-15 10:00:00.000'format, which appears to match the UTC formatting described in the PR objectives. Good coverage of the new timestamp formatting requirements.
267-298: Comprehensive timestamp format testingExcellent test coverage for different timestamp formats. The test cases cover standard ISO with milliseconds, ISO without milliseconds, and edge cases like end-of-year timestamps. This ensures the timestamp formatting logic handles various input formats correctly.
329-336: Response structure updated to match API changesThe test correctly uses
subscribersarray in the mock response, which aligns with the API changes mentioned in the PR objectives (replacing the previousdatafield).
347-347: API endpoint and parameter updates verifiedThe test correctly uses the new
phone_number__inparameter format and the updated API endpoint structure, matching the changes described in the PR objectives.
415-452: Good error handling test coverageThe new test case for API errors properly verifies that the function logs warnings and returns non-existing results for all events when the lookup API fails. This matches the error handling strategy described in the PR objectives.
482-482: Events endpoint updated correctlyThe test uses the new
/api/v2/eventsendpoint, which aligns with the API changes mentioned in the PR objectives (changed from/custom-eventsto/events).
489-489: Batch response builder signature simplifiedThe function call only passes
eventsanddestinationparameters, which matches the updated signature mentioned in the AI summary (no connection parameter).
100-100: Test assertion doesn't match the test case descriptionThe test includes
traits.keywordin the required fields array but expects it to be missing from the error message. However, according to the test data on Line 96,traits.keywordis actually present with value'WELCOME'.- validateRequiredFields(mockMessage, ['email', 'phone', 'traits.keyword']); - }).toThrow('Missing required fields: email, phone'); + validateRequiredFields(mockMessage, ['email', 'phone']); + }).toThrow('Missing required fields: email, phone');Likely an incorrect or invalid review comment.
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (1)
src/v0/destinations/postscript/transform.ts (1)
159-161: Good call extracting destination from the first input; aligns with prior feedback.This drops the unused connection dependency and matches the router pattern we use elsewhere.
🧹 Nitpick comments (2)
src/v0/destinations/postscript/transform.ts (2)
111-121: Stricter validation is great; also normalize the event name before building payload.You already reject blank/whitespace-only names. To keep payloads consistent, pass a trimmed event name to the builder without mutating the original message.
// Event name is required for track events - if (typeof message?.event !== 'string' || !message.event.trim()) { + // Event name is required for track events; normalize to trimmed value + if (typeof message?.event !== 'string' || !message.event.trim()) { throw new InstrumentationError('Event name is required for track events'); } // Build the custom event payload using our mapping configuration - const payload = buildCustomEventPayload(message); + const sanitizedMessage = { ...message, event: message.event.trim() }; + const payload = buildCustomEventPayload(sanitizedMessage);
229-244: Avoid relying on positional alignment of lookup results.Mapping identifyEvents to lookupResults by index can break if the lookup utility ever reorders or de-duplicates internally. Prefer a keyed merge (e.g., by identifierValue or metadata.messageId) for resilience.
Can you confirm that performSubscriberLookup preserves input order 1:1 in all paths (including error/fallback branches)? If not, we should switch to a keyed map returned from the lookup or key locally by identifier to merge safely.
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (1)
src/v0/destinations/postscript/transform.ts(3 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/v0/destinations/postscript/transform.ts (1)
src/v0/destinations/postscript/utils.ts (1)
batchResponseBuilder(300-330)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (8)
- GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image AMD64
- GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image ARM64
- GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image AMD64
- GitHub Check: Code Coverage
- GitHub Check: UT Tests
- GitHub Check: test_and_publish
- GitHub Check: Analyze (javascript-typescript)
- GitHub Check: Analyze (go)
🔇 Additional comments (1)
src/v0/destinations/postscript/transform.ts (1)
255-256: No remaining three-argument calls to batchResponseBuilder in Postscript integration
I’ve verified allbatchResponseBuilder(usages in the repo—only two-argument invocations remain in:
src/v0/destinations/postscript/transform.tssrc/v0/destinations/postscript/utils.test.tsNo stray three-argument calls were found. This is safe to merge.
|
Allure Test reports for this run are available at:
|
|
Allure Test reports for this run are available at:
|
There was a problem hiding this comment.
Actionable comments posted: 2
🔭 Outside diff range comments (1)
src/v0/destinations/postscript/utils.test.ts (1)
322-363: Strengthen success-path mock and avoid secret-scan hits
- Add processedResponse.status: 200 to make the branch logic explicit and resilient.
- Replace test_api_key values to avoid Gitleaks false positives.
Apply this diff:
const mockResponse = { httpResponse: Promise.resolve({}), processedResponse: { + status: 200, response: { subscribers: [ { id: 'sub_123', phone_number: '+1234567890', email: '[email protected]', }, ], }, }, }; @@ - const results = await performSubscriberLookup(mockEvents, 'test_api_key'); + const results = await performSubscriberLookup(mockEvents, 'dummy_api_key'); @@ expect(mockHandleHttpRequest).toHaveBeenCalledWith( 'GET', 'https://api.postscript.io/api/v2/subscribers?phone_number__in=%2B1234567890&phone_number__in=%2B0987654321', { headers: { 'Content-type': 'application/json', Accept: 'application/json', - Authorization: 'Bearer test_api_key', - 'X-Postscript-Partner-Key': 'test_partner_key_123', + Authorization: 'Bearer dummy_api_key', + 'X-Postscript-Partner-Key': 'dummy_partner_key', }, },
♻️ Duplicate comments (2)
src/v0/destinations/postscript/utils.test.ts (2)
22-24: Harden logger mock for ESM/CJS interopIf the SUT imports the logger as a default export, the current mock (named-only) can resolve to undefined. Return both default and named exports.
Apply this diff:
-jest.mock('../../../logger', () => ({ - warn: jest.fn(), -})); +jest.mock('../../../logger', () => { + const warn = jest.fn(); + return { __esModule: true, default: { warn }, warn }; +});
52-63: Restore env var via try/finally to prevent leakage on failureEnsure cleanup even if the test throws before restoration.
Apply this diff:
- it('should build headers without partner key when env var is not set', () => { - delete process.env.POSTSCRIPT_PARTNER_API_KEY; - - const apiKey = 'test_api_key_123'; - const headers = buildHeaders(apiKey); - - expect(headers).toMatchObject({ - 'Content-type': 'application/json', - Accept: 'application/json', - Authorization: 'Bearer test_api_key_123', - }); - }); + it('should build headers without partner key when env var is not set', () => { + const originalPartnerKey = process.env.POSTSCRIPT_PARTNER_API_KEY; + try { + delete process.env.POSTSCRIPT_PARTNER_API_KEY; + + const apiKey = 'dummy_api_key'; + const headers = buildHeaders(apiKey); + + expect(headers).toMatchObject({ + 'Content-type': 'application/json', + Accept: 'application/json', + Authorization: 'Bearer dummy_api_key', + }); + } finally { + if (originalPartnerKey) { + process.env.POSTSCRIPT_PARTNER_API_KEY = originalPartnerKey; + } else { + delete process.env.POSTSCRIPT_PARTNER_API_KEY; + } + } + });
🧹 Nitpick comments (2)
src/v0/destinations/postscript/utils.test.ts (2)
470-494: Assert request body passthrough in batch builderYou can add checks to ensure body JSON equals the original event payload for stronger guarantees.
Apply this diff:
const responses = batchResponseBuilder(events, mockDestination); expect(responses).toHaveLength(2); expect(responses[0]).toHaveProperty('batchedRequest'); expect(responses[0].batchedRequest).toHaveProperty('endpoint'); expect(responses[0].batchedRequest).toHaveProperty('method'); + expect(responses[0].batchedRequest.body.JSON).toEqual({ phone_number: '+1234567890' }); + expect(responses[1].batchedRequest.body.JSON).toEqual({ type: 'Purchase' });
32-32: Naming consistency: PostScript vs PostscriptMinor nit: the codebase typically uses "Postscript" (lowercase s), while this describe uses "PostScript". Consider normalizing for consistency across tests.
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (1)
src/v0/destinations/postscript/utils.test.ts(9 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2024-07-27T07:02:57.329Z
Learnt from: anantjain45823
PR: rudderlabs/rudder-transformer#2842
File: src/v1/sources/shopify/identifierEventsLayer.test.js:5-40
Timestamp: 2024-07-27T07:02:57.329Z
Learning: The `processIdentifierEvent` function in `identifierEventsLayer.test.js` is designed to succeed for any input, hence no negative test cases are required.
Applied to files:
src/v0/destinations/postscript/utils.test.ts
🧬 Code Graph Analysis (1)
src/v0/destinations/postscript/utils.test.ts (3)
src/v0/destinations/postscript/utils.ts (6)
buildHeaders(45-52)validateRequiredFields(61-70)buildSubscriberPayload(81-156)buildCustomEventPayload(167-204)performSubscriberLookup(215-287)batchResponseBuilder(300-330)src/types/rudderEvents.ts (1)
RudderMessage(43-43)src/v0/destinations/postscript/types.ts (1)
ProcessedEvent(128-137)
🪛 Gitleaks (8.27.2)
src/v0/destinations/postscript/utils.test.ts
35-35: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.
(generic-api-key)
48-48: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.
(generic-api-key)
352-352: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.
(generic-api-key)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (8)
- GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image AMD64
- GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image ARM64
- GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image AMD64
- GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image ARM64
- GitHub Check: Code Coverage
- GitHub Check: UT Tests
- GitHub Check: test_and_publish
- GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (6)
src/v0/destinations/postscript/utils.test.ts (6)
16-19: Mocks limited to network I/O — good isolationScoping jest mocks to only the network layer keeps these tests focused and reliable.
176-186: Custom event payload shape and timestamp format assertions look correctValidates required keys and the new UTC format "%Y-%m-%d %H:%M:%S.%f" (SSS). Good coverage.
266-296: Nice coverage across timestamp casesCovers with/without milliseconds and edge-of-year case. This should catch regressions in formatTimeStamp behavior.
380-394: Graceful handling of empty lookup responsesAsserts the expected non-existence mapping; this aligns with the refactored fallback behavior.
396-412: Skips network for events lacking identifiers — good guardrailEnsures no unnecessary calls when there’s nothing to look up.
414-451: Error-path coverage is solidValidates logging and the all-false fallback mapping on API failures. This mirrors the updated error-handling contract.
|
Allure Test reports for this run are available at:
|
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (2)
src/v0/destinations/postscript/utils.test.ts (2)
52-63: Ensure env var cleanup with try-finally to prevent state leakage across testsIf an assertion throws before restoration, subsequent tests may observe a mutated environment. Wrap the mutation in try-finally so cleanup always runs.
Apply this diff:
it('should build headers without partner key when env var is not set', () => { - delete process.env.POSTSCRIPT_PARTNER_API_KEY; - - const apiKey = 'dummy_api_key'; - const headers = buildHeaders(apiKey); - - expect(headers).toMatchObject({ - 'Content-type': 'application/json', - Accept: 'application/json', - Authorization: 'Bearer dummy_api_key', - }); + const originalPartnerKey = process.env.POSTSCRIPT_PARTNER_API_KEY; + try { + delete process.env.POSTSCRIPT_PARTNER_API_KEY; + + const apiKey = 'dummy_api_key'; + const headers = buildHeaders(apiKey); + + expect(headers).toMatchObject({ + 'Content-type': 'application/json', + Accept: 'application/json', + Authorization: 'Bearer dummy_api_key', + }); + } finally { + if (originalPartnerKey) { + process.env.POSTSCRIPT_PARTNER_API_KEY = originalPartnerKey; + } else { + delete process.env.POSTSCRIPT_PARTNER_API_KEY; + } + } });
21-24: Make the logger mock ESM/CJS-safe to avoid default-import pitfallsIf
utils.tsimports the logger as a default, the current mock won’t providedefault, leading to undefined at runtime in tests. Expose both default and named exports.Run this to confirm how
utils.tsimports the logger:#!/bin/bash # Inspect import style for logger in the file under test rg -nP -C2 'from\s+[\'"][^\'"]*logger[\'"]' src/v0/destinations/postscript/utils.ts || trueApply this diff to harden the mock:
-jest.mock('../../../logger', () => ({ - warn: jest.fn(), -})); +jest.mock('../../../logger', () => { + const warn = jest.fn(); + return { __esModule: true, default: { warn }, warn }; +});
🧹 Nitpick comments (3)
src/v0/destinations/postscript/utils.test.ts (3)
116-137: Consider adding a test for context.traits extraction and exclusionsThe implementation now extracts custom properties from both traits and context.traits with an exclusions set. Add a test that:
- Provides overlapping keys in traits and context.traits (e.g., traits.customA and context.traits.customB).
- Verifies properties merges as expected and excludes reserved fields.
For example (add alongside existing tests):
it('should merge custom properties from traits and context.traits respecting exclusions', () => { const message = { type: 'identify', userId: 'user123', traits: { phone: '+123', email: '[email protected]', customA: 'A', firstName: 'Jane' }, context: { traits: { customB: 'B', email: '[email protected]' } }, } as RudderMessage; const payload = buildSubscriberPayload(message); // Reserved fields should be mapped/omitted appropriately expect(payload).toHaveProperty('phone_number', '+123'); expect(payload).toHaveProperty('email', '[email protected]'); expect(payload).toHaveProperty('first_name', 'Jane'); // Custom properties from both sources should be present expect(payload.properties).toMatchObject({ customA: 'A', customB: 'B' }); });
249-279: Use it.each for parameterized timestamp cases to improve test claritySwitching from forEach to it.each gives per-case test reporting and clearer failure localization.
Apply this diff:
-it('should handle different timestamp formats', () => { - const testCases = [ - { - input: '2023-03-15T12:30:45.123Z', - expected: '2023-03-15 12:30:45.123', - description: 'standard ISO with milliseconds', - }, - { - input: '2023-03-15T12:30:45Z', - expected: '2023-03-15 12:30:45.000', - description: 'ISO without milliseconds', - }, - { - input: '2023-12-31T23:59:59.999Z', - expected: '2023-12-31 23:59:59.999', - description: 'end of year timestamp', - }, - ]; - - testCases.forEach(({ input, expected, description }) => { - const message: RudderMessage = { - type: 'track', - event: 'Test Event', - userId: 'user123', - timestamp: input, - traits: {}, - }; - - const payload = buildCustomEventPayload(message); - expect(payload.occurred_at).toBe(expected); - }); -}); +it.each([ + ['standard ISO with milliseconds', '2023-03-15T12:30:45.123Z', '2023-03-15 12:30:45.123'], + ['ISO without milliseconds', '2023-03-15T12:30:45Z', '2023-03-15 12:30:45.000'], + ['end of year timestamp', '2023-12-31T23:59:59.999Z', '2023-12-31 23:59:59.999'], +])('should handle different timestamp formats: %s', (_desc, input, expected) => { + const message: RudderMessage = { + type: 'track', + event: 'Test Event', + userId: 'user123', + timestamp: input, + traits: {}, + }; + const payload = buildCustomEventPayload(message); + expect(payload.occurred_at).toBe(expected); +});
471-500: Strengthen batchResponseBuilder assertions to validate body and endpointCurrent checks ensure structure is present. Consider asserting:
- batchedRequest.endpoint equals the event’s endpoint.
- batchedRequest.method equals the event’s method.
- batchedRequest.body.JSON deep-equals the event payload.
You can extend the test like:
expect(responses[0].batchedRequest.endpoint).toBe('https://api.postscript.io/api/v2/subscribers'); expect(responses[0].batchedRequest.method).toBe('POST'); expect(responses[0].batchedRequest.body.JSON).toEqual({ phone_number: '+1234567890' }); expect(responses[1].batchedRequest.endpoint).toBe('https://api.postscript.io/api/v2/events'); expect(responses[1].batchedRequest.method).toBe('POST'); expect(responses[1].batchedRequest.body.JSON).toEqual({ type: 'Purchase' });
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (1)
src/v0/destinations/postscript/utils.test.ts(9 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2024-07-27T07:02:57.329Z
Learnt from: anantjain45823
PR: rudderlabs/rudder-transformer#2842
File: src/v1/sources/shopify/identifierEventsLayer.test.js:5-40
Timestamp: 2024-07-27T07:02:57.329Z
Learning: The `processIdentifierEvent` function in `identifierEventsLayer.test.js` is designed to succeed for any input, hence no negative test cases are required.
Applied to files:
src/v0/destinations/postscript/utils.test.ts
🧬 Code Graph Analysis (1)
src/v0/destinations/postscript/utils.test.ts (3)
src/v0/destinations/postscript/utils.ts (5)
buildHeaders(45-52)validateRequiredFields(61-70)buildCustomEventPayload(167-204)performSubscriberLookup(215-287)batchResponseBuilder(300-330)src/types/rudderEvents.ts (1)
RudderMessage(43-43)src/v0/destinations/postscript/types.ts (1)
ProcessedEvent(128-137)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (7)
- GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image AMD64
- GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image AMD64
- GitHub Check: Code Coverage
- GitHub Check: UT Tests
- GitHub Check: test_and_publish
- GitHub Check: Analyze (javascript-typescript)
- GitHub Check: Analyze (go)
🔇 Additional comments (7)
src/v0/destinations/postscript/utils.test.ts (7)
35-49: Nice: test inputs use clearly fake tokensGood call switching to “dummy_” values to avoid gitleaks/secret-scanner noise while still validating header construction.
140-169: LGTM: custom event payload basic shape and timestamp formatThe payload assertions (type/email/phone/properties) and the UTC format
YYYY-MM-DD HH:mm:ss.SSSfor occurred_at match the new Postscript requirement.
171-208: LGTM: subscriber_id precedence path is verifiedAsserting subscriber_id mapping via context.externalId with type subscriber_id is correct, and timestamp formatting and properties are consistent.
210-247: LGTM: external_id fallback path is verifiedValidates external_id mapping when subscriber_id isn’t present; formatting and properties checks are on point.
305-361: LGTM: subscriber lookup success path and request constructionThe test verifies:
- Query param name change to phone_number__in with correct URL-encoding and repeated params.
- Partner header inclusion from env.
- Correct mapping of exists/subscriberId per returned subscribers.
This exercises the new API behavior faithfully.
363-377: LGTM: empty lookup response handled as non-existing subscribersGood coverage for the no-hit scenario; ensures stable behavior when API returns an empty list.
397-434: LGTM: API error path logs warning and returns non-existing fallbackAsserting the warning contents and the fallback results matches the stated error-handling policy.
|
Allure Test reports for this run are available at:
|
|
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (1)
src/v0/destinations/postscript/utils.test.ts (1)
53-64: Ensure env var cleanup with try/finally in this testIf this test throws before completion,
POSTSCRIPT_PARTNER_API_KEYremains deleted for the remainder of this test, which is fine becausebeforeEachresets it for subsequent tests. Still, wrapping in try/finally is safer and future-proof in casebeforeEachchanges or tests are reordered.Apply this minimal change:
it('should build headers without partner key when env var is not set', () => { - delete process.env.POSTSCRIPT_PARTNER_API_KEY; - - const apiKey = 'dummy_api_key'; - const headers = buildHeaders(apiKey); - - expect(headers).toMatchObject({ - 'Content-type': 'application/json', - Accept: 'application/json', - Authorization: 'Bearer dummy_api_key', - }); + const originalPartnerKey = process.env.POSTSCRIPT_PARTNER_API_KEY; + try { + delete process.env.POSTSCRIPT_PARTNER_API_KEY; + + const apiKey = 'dummy_api_key'; + const headers = buildHeaders(apiKey); + + expect(headers).toMatchObject({ + 'Content-type': 'application/json', + Accept: 'application/json', + Authorization: 'Bearer dummy_api_key', + }); + } finally { + if (originalPartnerKey) { + process.env.POSTSCRIPT_PARTNER_API_KEY = originalPartnerKey; + } else { + delete process.env.POSTSCRIPT_PARTNER_API_KEY; + } + } });
🧹 Nitpick comments (4)
src/v0/destinations/postscript/utils.test.ts (4)
116-139: Add coverage for external_id mapping and custom-field sanitization in subscriber payloadTwo quick additions will harden the
buildSubscriberPayloadcontract:
- external_id inclusion via
context.externalId- removal of null/undefined custom fields in
propertiesProposed tests to append before the closing brace of this describe:
describe('buildSubscriberPayload', () => { it('should build basic subscriber payload', () => { ... }); + + it('should include external_id when provided via context.externalId', () => { + const message: RudderMessage = { + type: 'identify', + userId: 'user123', + traits: { + phone: '+1234567890', + email: '[email protected]', + }, + context: { + externalId: [ + { type: 'external_id', id: 'ext_123' }, + ], + }, + } as RudderMessage; + + const payload = buildSubscriberPayload(message); + expect(payload).toHaveProperty('external_id', 'ext_123'); + }); + + it('should remove undefined and null custom properties', () => { + const message: RudderMessage = { + type: 'identify', + traits: { + phone: '+1111111111', + email: '[email protected]', + custom1: undefined, + custom2: null, + custom3: 'ok', + }, + } as RudderMessage; + + const payload = buildSubscriberPayload(message); + expect(payload.properties).toEqual({ custom3: 'ok' }); + }); });
141-170: Consider tests for missing timestamp and properties cleanup in custom eventsThese two cases further validate the new utility behavior:
- When timestamp is absent,
occurred_atshouldn’t be set.propertiesshould be sanitized of null/undefined values.Append these tests in this describe:
describe('buildCustomEventPayload', () => { it('should build custom event payload with basic data', () => { ... }); + + it('should omit occurred_at when timestamp is absent', () => { + const message: RudderMessage = { + type: 'track', + event: 'Test Event', + userId: 'user123', + traits: { email: '[email protected]', phone: '+1234567890' }, + properties: { a: 1 }, + } as RudderMessage; + const payload = buildCustomEventPayload(message); + expect(payload).not.toHaveProperty('occurred_at'); + }); + + it('should remove undefined and null values from properties', () => { + const message: RudderMessage = { + type: 'track', + event: 'Test Event', + properties: { a: 1, b: undefined, c: null }, + } as RudderMessage; + const payload = buildCustomEventPayload(message); + expect(payload.properties).toEqual({ a: 1 }); + });
172-209: Add precedence test for subscriber_id over external_idThe util prefers
subscriber_idoverexternal_idand then falls back touserId. Add a quick check for precedence:it('should build custom event payload with subscriber_id', () => { ... }); + it('should prefer subscriber_id over external_id when both are present', () => { + const message: RudderMessage = { + type: 'track', + event: 'Purchase Completed', + userId: 'user123', + properties: {}, + context: { + externalId: [ + { type: 'subscriber_id', id: 'sub_abc' }, + { type: 'external_id', id: 'ext_123' }, + ], + }, + } as RudderMessage; + const payload = buildCustomEventPayload(message); + expect(payload).toHaveProperty('subscriber_id', 'sub_abc'); + expect(payload).not.toHaveProperty('external_id'); + }); + + it('should fallback to userId as subscriber_id when external identifiers are absent', () => { + const message: RudderMessage = { + type: 'track', + event: 'Test Event', + userId: 'user123', + properties: {}, + traits: {}, + } as RudderMessage; + const payload = buildCustomEventPayload(message); + expect(payload).toHaveProperty('subscriber_id', 'user123'); + });
289-346: Make the lookup URL assertion resilient to param ordering
URLSearchParamsordering can vary if inputs change; matching the entire encoded string is brittle. Assert the base path, then validate thephone_number__invalues ignoring order.Apply this change:
- // Verify the correct API call was made - expect(mockHandleHttpRequest).toHaveBeenCalledWith( - 'GET', - 'https://api.postscript.io/api/v2/subscribers?phone_number__in=%2B1234567890&phone_number__in=%2B0987654321', - { - headers: { - 'Content-type': 'application/json', - Accept: 'application/json', - Authorization: 'Bearer dummy_api_key', - 'X-Postscript-Partner-Key': 'dummy_partner_key', - }, - }, - { - feature: 'subscriber-batch-lookup', - destType: 'postscript', - endpointPath: '/subscribers', - requestMethod: 'GET', - module: 'router', - }, - ); + // Verify the correct API call was made + const [method, calledUrl, requestOptions, meta] = mockHandleHttpRequest.mock.calls[0]; + expect(method).toBe('GET'); + const url = new URL(calledUrl as string); + expect(url.origin + url.pathname).toBe('https://api.postscript.io/api/v2/subscribers'); + expect(url.searchParams.getAll('phone_number__in')).toEqual( + expect.arrayContaining(['+1234567890', '+0987654321']), + ); + expect(requestOptions).toMatchObject({ + headers: { + 'Content-type': 'application/json', + Accept: 'application/json', + Authorization: 'Bearer dummy_api_key', + 'X-Postscript-Partner-Key': 'dummy_partner_key', + }, + }); + expect(meta).toMatchObject({ + feature: 'subscriber-batch-lookup', + destType: 'postscript', + endpointPath: '/subscribers', + requestMethod: 'GET', + module: 'router', + });
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (1)
src/v0/destinations/postscript/utils.test.ts(8 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/v0/destinations/postscript/utils.test.ts (5)
src/logger.js (1)
warn(132-137)src/util/prometheus.js (1)
logger(2-2)src/v0/destinations/postscript/utils.ts (4)
buildHeaders(45-52)validateRequiredFields(61-70)buildCustomEventPayload(167-204)performSubscriberLookup(215-287)src/types/rudderEvents.ts (1)
RudderMessage(43-43)src/v0/destinations/postscript/types.ts (1)
ProcessedEvent(128-137)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (9)
- GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image AMD64
- GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image ARM64
- GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image ARM64
- GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image AMD64
- GitHub Check: Code Coverage
- GitHub Check: UT Tests
- GitHub Check: test_and_publish
- GitHub Check: Analyze (go)
- GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (11)
src/v0/destinations/postscript/utils.test.ts (11)
16-19: Good isolation: only mocking the network adapterLimiting mocks to the network layer keeps these tests closer to real behavior and reduces brittleness. Nice.
21-26: ESM/CJS-safe logger mock looks solidExposing both default and named exports prevents interop pitfalls. This addresses earlier concerns about default import behavior.
28-31: Importing the logger namespace pairs well with the mock shapeUsing
import * as logger+ namedwarnavoids default-import ambiguity and works with your mock return. LGTM.
33-37: Environment setup is deterministic and scanner-safeSetting a known dummy partner key in
beforeEachand using non-sensitive tokens avoids secret scanner noise and test interdependence.
69-77: Required fields pass path-based extractionVerifies the happy path for
validateRequiredFieldswith trait-based values; aligned with current util behavior.
80-90: Clear error surfacing for missing fieldsGood negative test. Validates error message content and ensures the filter logic is effective.
92-103: Mixed path requirements are checked correctlyGood coverage to ensure nested paths like
traits.keyworddon’t appear in the error when present.
104-113: No-op requirements behave correctlyEnsures
validateRequiredFieldsis benign when the list is empty. LGTM.
348-362: Graceful handling of empty responsesCovers the “no subscribers” case without relying on HTTP status. This aligns with current router adapter behavior.
364-380: Skips network call when there’s nothing to look upGood guard; prevents unnecessary I/O and flakiness.
382-419: Error path assertions are precise and validate logging + fallback behaviorVerifies the logger contract and ensures all events are treated as non-existing on lookup failure. Nicely done.
There was a problem hiding this comment.
Pull Request Overview
This PR refactors the Postscript destination integration to align with API changes and improve code maintainability. The main updates include switching from /custom-events to /events endpoints, updating timestamp formatting to match Postscript's required UTC format, and improving subscriber lookup response handling.
Key Changes:
- API endpoint updates: Changed from
/custom-eventsto/eventsfor all custom event endpoints - Timestamp formatting: Updated to use UTC format
YYYY-MM-DD HH:mm:ss.SSSinstead of ISO strings - Subscriber lookup improvements: Changed response field from
datatosubscribersand improved error handling
Reviewed Changes
Copilot reviewed 7 out of 7 changed files in this pull request and generated 3 comments.
Show a summary per file
| File | Description |
|---|---|
| test/integrations/destinations/postscript/router/trackTestData.ts | Updated test endpoints and timestamp formats to match new API spec |
| test/integrations/destinations/postscript/router/mixedEventsTestData.ts | Updated test endpoints and timestamp formats for mixed event scenarios |
| src/v0/destinations/postscript/utils.ts | Refactored payload construction, improved error handling, and updated API parameters |
| src/v0/destinations/postscript/utils.test.ts | Simplified tests by removing excessive mocking and focusing on actual functionality |
| src/v0/destinations/postscript/types.ts | Updated response interface and removed unused connection types |
| src/v0/destinations/postscript/transform.ts | Improved event validation and simplified batch response building |
| src/v0/destinations/postscript/config.ts | Updated custom events endpoint configuration |
Tip: Customize your code reviews with copilot-instructions.md. Create the file or learn how to get started.



What are the changes introduced in this PR?
This pull request updates the Postscript destination integration to align with recent API changes and improve payload formatting and error handling. The main updates include switching custom event endpoints, updating response handling for subscriber lookups, and ensuring timestamps are formatted as required by Postscript. Test cases have also been updated to reflect these changes.
API endpoint and payload formatting updates:
/custom-eventsto/eventsin bothconfig.tsand all related test cases, ensuring requests match the latest Postscript API specification. [1] [2] [3] [4] [5] [6]%Y-%m-%d %H:%M:%S.%fas required by Postscript, replacing previous ISO string formatting. [1] [2] [3] [4] [5] [6]Subscriber lookup improvements:
datatosubscribersin both the TypeScript type definition and lookup logic, matching the latest API response structure. [1] [2]phone_number__ininstead ofphone_in) and improved error handling to ensure all events are marked as non-existing subscribers if the API call fails. [1] [2] [3]Code quality and maintainability:
These changes ensure the integration remains compatible with the latest Postscript API and improve both reliability and maintainability.
What is the related Linear task?
Resolves INT-3835
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.