-
Notifications
You must be signed in to change notification settings - Fork 453
feat(shared): Introduce client-side caching for telemetry events #3267
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
Closed
LauraBeatris
wants to merge
8
commits into
clerk:main
from
LauraBeatris:add-client-cache-for-telemetry-events
Closed
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
46bb20b
feat(shared): Introduce client-side caching for telemetry events
LauraBeatris 6ac00de
fix(shared): Fallback to sampling rate when storage is not supported
LauraBeatris 0ee1108
perf(shared): Clear storage key on quota exceeded error
LauraBeatris 9038c88
test(shared): Add unit tests for client cache
LauraBeatris 39e5aaf
perf(shared): Move TelemetryClientCache instance to TelemetryCollector
LauraBeatris 625fd6a
fix(shared): Verify if window is defined
LauraBeatris 253e682
perf(shared): Generate cache key based on payload
LauraBeatris 43d94bc
fix(shared): Do not override previous cache state
LauraBeatris 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 hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| '@clerk/shared': patch | ||
| --- | ||
|
|
||
| Introduce client-side caching to TelemetryCollector |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,94 @@ | ||
| import type { TelemetryEventRaw } from './types'; | ||
|
|
||
| type TtlInMilliseconds = number; | ||
|
|
||
| const DEFAULT_CACHE_TTL_MS = 86400000; // 24 hours | ||
|
|
||
| /** | ||
| * Manages caching for telemetry events using the browser's localStorage to | ||
| * mitigate event flooding in frequently executed code paths. | ||
| */ | ||
| export class TelemetryClientCache { | ||
| #storageKey = 'clerk_telemetry'; | ||
| #cacheTtl = DEFAULT_CACHE_TTL_MS; | ||
|
|
||
| cacheAndRetrieve(event: TelemetryEventRaw): boolean { | ||
| const now = Date.now(); | ||
| const key = this.#generateKey(event); | ||
| const entry = this.#cache?.[key]; | ||
|
|
||
| if (!entry) { | ||
| const updatedCache = { | ||
| ...this.#cache, | ||
| [key]: now, | ||
| }; | ||
|
|
||
| localStorage.setItem(this.#storageKey, JSON.stringify(updatedCache)); | ||
| } | ||
|
|
||
| const hasExpired = entry && now - entry > this.#cacheTtl; | ||
| if (hasExpired) { | ||
| localStorage.removeItem(key); | ||
| } | ||
|
|
||
| return !!entry; | ||
| } | ||
|
|
||
| #generateKey({ event, payload }: TelemetryEventRaw): string { | ||
| const payloadUniqueKey = JSON.stringify( | ||
| Object.keys(payload) | ||
| .sort() | ||
| .map(key => payload[key]), | ||
| ); | ||
|
|
||
| return `${event}:${payloadUniqueKey}`; | ||
| } | ||
|
|
||
| get #cache(): Record<string, TtlInMilliseconds> | undefined { | ||
| const cacheString = localStorage.getItem(this.#storageKey); | ||
|
|
||
| if (!cacheString) { | ||
| return {}; | ||
| } | ||
|
|
||
| return JSON.parse(cacheString); | ||
| } | ||
|
|
||
| /** | ||
| * Checks if the browser's localStorage is supported and writable. | ||
| * | ||
| * If any of these operations fail, it indicates that localStorage is either | ||
| * not supported or not writable (e.g., in cases where the storage is full or | ||
| * the browser is in a privacy mode that restricts localStorage usage). | ||
| */ | ||
| get isStorageSupported(): boolean { | ||
| if (typeof window === 'undefined') { | ||
| return false; | ||
| } | ||
|
|
||
| const storage = window['localStorage']; | ||
|
|
||
| if (!storage) { | ||
| return false; | ||
| } | ||
|
|
||
| try { | ||
| const testKey = 'test'; | ||
| storage.setItem(testKey, testKey); | ||
| storage.removeItem(testKey); | ||
|
|
||
| return true; | ||
| } catch (err: unknown) { | ||
| const isQuotaExceededError = | ||
| err instanceof DOMException && | ||
| // Check error names for different browsers | ||
| (err.name === 'QuotaExceededError' || err.name === 'NS_ERROR_DOM_QUOTA_REACHED'); | ||
|
|
||
| if (isQuotaExceededError && storage.length > 0) { | ||
| storage.removeItem(this.#storageKey); | ||
| } | ||
|
|
||
| return false; | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.
Uh oh!
There was an error while loading. Please reload this page.
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.
Also introducing a sampling rate lower than the default for this event, to handle the server-side scenarios.
CC @brkalow let me know if that makes sense