-
Notifications
You must be signed in to change notification settings - Fork 141
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Increases specificity of localStorage keys to differentiate events by writeKey #861
Merged
Merged
Changes from 2 commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
--- | ||
'@segment/analytics-next': patch | ||
--- | ||
|
||
Fixes issue related to how retried events are stored in localStorage to prevent analytics.js from reading events for a different writeKey when that writeKey is used on the same domain as the current analytics.js. |
This file contains 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
9 changes: 9 additions & 0 deletions
9
packages/browser-integration-tests/src/helpers/extract-writekey.ts
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
export function extractWriteKeyFromUrl(url: string): string | undefined { | ||
const matches = url.match( | ||
/https:\/\/cdn.segment.com\/v1\/projects\/(.+)\/settings/ | ||
) | ||
|
||
if (matches) { | ||
return matches[1] | ||
} | ||
} |
42 changes: 42 additions & 0 deletions
42
packages/browser-integration-tests/src/helpers/get-persisted-items.ts
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
export interface PersistedQueueResult { | ||
key: string | ||
name: string | ||
messageIds: string[] | ||
writeKey?: string | ||
} | ||
|
||
export function getPersistedItems(): PersistedQueueResult[] { | ||
const results: PersistedQueueResult[] = [] | ||
|
||
for (let i = 0; i < window.localStorage.length; i++) { | ||
const key = window.localStorage.key(i) | ||
if ( | ||
key && | ||
key.startsWith('persisted-queue:v1:') && | ||
key.endsWith(':items') | ||
) { | ||
const value = window.localStorage.getItem(key) | ||
const messageIds = value | ||
? JSON.parse(value).map((i: any) => i.event.messageId) | ||
: [] | ||
|
||
// Key looks like either: | ||
// new keys - persisted-queue:v1:writeKey:dest-Segment.io:items | ||
// old keys - persisted-queue:v1:dest-Segment.io:items | ||
const components = key.split(':') | ||
let writeKey: string | undefined | ||
let name: string | ||
|
||
if (components.length === 5) { | ||
;[, , writeKey, name] = components | ||
} else if (components.length === 4) { | ||
;[, , name] = components | ||
} else { | ||
throw new Error('Unrecognized persisted queue key.') | ||
} | ||
results.push({ key, messageIds, name, writeKey }) | ||
} | ||
} | ||
|
||
return results | ||
} |
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,30 +1,38 @@ | ||
import { Request, test, expect } from '@playwright/test' | ||
import { SettingsBuilder } from './fixtures/settings' | ||
import { standaloneMock } from './helpers/standalone-mock' | ||
import { extractWriteKeyFromUrl } from './helpers/extract-writekey' | ||
import { | ||
PersistedQueueResult, | ||
getPersistedItems, | ||
} from './helpers/get-persisted-items' | ||
|
||
test.describe('Standalone tests', () => { | ||
test.beforeEach(standaloneMock) | ||
|
||
test.describe('Segment.io Retries', () => { | ||
test.beforeEach(async ({ context }) => { | ||
await context.route( | ||
'https://cdn.segment.com/v1/projects/*/settings', | ||
(route, request) => { | ||
if (request.method().toLowerCase() !== 'get') { | ||
return route.continue() | ||
} | ||
|
||
return route.fulfill({ | ||
status: 200, | ||
headers: { | ||
'Content-Type': 'application/json', | ||
}, | ||
body: JSON.stringify(new SettingsBuilder().build()), | ||
}) | ||
test.beforeEach(async ({ context }) => { | ||
await context.route( | ||
'https://cdn.segment.com/v1/projects/*/settings', | ||
(route, request) => { | ||
if (request.method().toLowerCase() !== 'get') { | ||
return route.continue() | ||
} | ||
) | ||
}) | ||
|
||
const writeKey = extractWriteKeyFromUrl(request.url()) || 'writeKey' | ||
return route.fulfill({ | ||
status: 200, | ||
headers: { | ||
'Content-Type': 'application/json', | ||
}, | ||
body: JSON.stringify(new SettingsBuilder(writeKey).build()), | ||
}) | ||
} | ||
) | ||
}) | ||
test.beforeEach(async ({ context }) => { | ||
await context.setOffline(false) | ||
}) | ||
|
||
test.describe('Segment.io Retries', () => { | ||
test('supports retrying failed requests on page navigation', async ({ | ||
page, | ||
}) => { | ||
|
@@ -111,5 +119,85 @@ test.describe('Standalone tests', () => { | |
expect(request.method()).toBe('POST') | ||
expect(request.postDataJSON().messageId).toBe(messageId) | ||
}) | ||
|
||
test('events persisted to localStorage do not leak across write keys', async ({ | ||
page, | ||
}) => { | ||
// Load analytics.js | ||
await page.goto('/standalone.html') | ||
await page.evaluate(() => window.analytics.load('key1')) | ||
|
||
// fail the initial track request on first 2 page loads (2 different write keys) | ||
await page.route( | ||
'https://api.segment.io/v1/t', | ||
(route) => { | ||
return route.abort('blockedbyclient') | ||
}, | ||
{ | ||
times: 2, | ||
} | ||
) | ||
let requestFailure = new Promise<Record<string, any>>((resolve) => { | ||
page.once('requestfailed', (request) => resolve(request.postDataJSON())) | ||
}) | ||
|
||
// trigger an event that wil fail | ||
await page.evaluate(() => { | ||
void window.analytics.track('test event') | ||
}) | ||
|
||
const { messageId: messageId1 } = await requestFailure | ||
await page.reload() | ||
|
||
// check localstorage for event data from previous analytics (key1) | ||
let persistedItems = await page.evaluate(getPersistedItems) | ||
|
||
expect(persistedItems).toHaveLength(1) | ||
expect(persistedItems[0].writeKey).toBe('key1') | ||
expect(persistedItems[0].messageIds).toStrictEqual([messageId1]) | ||
|
||
requestFailure = new Promise<Record<string, any>>((resolve) => { | ||
page.once('requestfailed', (request) => resolve(request.postDataJSON())) | ||
}) | ||
|
||
// Load analytics with a different write key (key2) | ||
await page.evaluate(() => window.analytics.load('key2')) | ||
|
||
// trigger an event that will fail | ||
await page.evaluate(() => { | ||
void window.analytics.track('test event') | ||
}) | ||
|
||
const { messageId: messageId2 } = await requestFailure | ||
await page.reload() | ||
|
||
// check localstorage for data from both write keys | ||
persistedItems = await page.evaluate(getPersistedItems) | ||
|
||
expect(persistedItems).toHaveLength(2) | ||
const persistedByWriteKey = persistedItems.reduce((prev, cur) => { | ||
prev[cur.writeKey || '_'] = cur | ||
return prev | ||
}, {} as { [writeKey: string]: PersistedQueueResult }) | ||
expect(persistedByWriteKey['key1'].messageIds).toStrictEqual([messageId1]) | ||
expect(persistedByWriteKey['key2'].messageIds).toStrictEqual([messageId2]) | ||
|
||
// Now load analytics with original write key (key1) to validate message is sent | ||
const [request] = await Promise.all([ | ||
page.waitForRequest('https://api.segment.io/v1/t'), | ||
page.evaluate(() => window.analytics.load('key1')), | ||
]) | ||
|
||
expect(request.method()).toBe('POST') | ||
expect(request.postDataJSON().messageId).toBe(messageId1) | ||
expect(request.postDataJSON().writeKey).toBe('key1') | ||
|
||
// Make sure localStorage only has data for the 2nd writeKey - which wasn't reloaded. | ||
persistedItems = await page.evaluate(getPersistedItems) | ||
|
||
expect(persistedItems).toHaveLength(1) | ||
expect(persistedItems[0].writeKey).toBe('key2') | ||
expect(persistedItems[0].messageIds).toStrictEqual([messageId2]) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This whole test... 🤩 |
||
}) | ||
}) | ||
}) |
This file contains 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
This file contains 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
This file contains 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
This file contains 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
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Was this meant to be the suite name, or is this copypasta?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ooph, I think it was meant to signify these tests are for the standalone (CDN) version of a.js, not the NPM version. Can probably remove this describe block though.