-
Notifications
You must be signed in to change notification settings - Fork 350
Implemented service worker to intercept network traces, added tracking simple page navigation #2743
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
Merged
Merged
Changes from 5 commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
6224c5e
Added sent page load metrics to backend logs
ygrik b4fab85
Added service worker, network traces and tracking simple page navigation
ygrik e4f76fc
resolved comments and moved unique user id from cookie to local storage
ygrik ae9573b
Fixed comments
ygrik a2c8fc4
Added feature flag for client telemetry
ygrik 284c9a3
code clean up
ygrik f368663
added constant changes
ygrik 6d15cf4
added utils changes
ygrik c24c4d3
extended user event logging for buttons clicks
ygrik a0d84ad
improved logging messages format
ygrik 347e629
Update mainCI.yml
ygrik b9cbaba
set console logger by default and improved user interaction logging
ygrik 14da51f
Merge branch 'igo/telemetry' of https://github.com/Azure/api-manageme…
ygrik d60bc0f
resolved comments
ygrik 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
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
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,67 @@ | ||
| import { Bag } from "@paperbits/common/bag"; | ||
| declare const clients: any; | ||
|
|
||
| const allowedList = ["state", "session_state"]; | ||
|
|
||
| function sendMessageToClients(message: Bag<string>): void { | ||
| clients.matchAll().then((items: any[]) => { | ||
| if (items.length > 0) { | ||
| items.forEach(client => client.postMessage(message)); | ||
| } | ||
| }); | ||
| } | ||
|
|
||
| addEventListener("fetch", (event: FetchEvent) => { | ||
| const request = event.request; | ||
|
|
||
| event.respondWith( | ||
| (async () => { | ||
| const response = await fetch(request); | ||
|
|
||
| if (request.url.endsWith("/trace")) { | ||
| return response; | ||
| } | ||
|
|
||
| const cleanedUrl = request.url.indexOf("#code=") > -1 ? cleanUpUrlParams(request) : request.url; | ||
|
|
||
| const telemetryData = { | ||
| url: cleanedUrl, | ||
| method: request.method.toUpperCase(), | ||
| status: response.status.toString(), | ||
| responseHeaders: "" | ||
| }; | ||
|
|
||
| const headers: { [key: string]: string } = {}; | ||
| response.headers.forEach((value, key) => { | ||
ygrik marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| if (key.toLocaleLowerCase() === "authorization") { | ||
| return; | ||
| } | ||
| headers[key] = value; | ||
| }); | ||
| telemetryData.responseHeaders = JSON.stringify(headers); | ||
|
|
||
| sendMessageToClients(telemetryData); | ||
|
|
||
| return response; | ||
| })() | ||
| ); | ||
| }); | ||
|
|
||
| console.log("Telemetry worker started."); | ||
|
|
||
| function cleanUpUrlParams(request: Request): string { | ||
| const url = new URL(request.url); | ||
| const hash = url.hash.substring(1); // Remove the leading '#' | ||
| const params = new URLSearchParams(hash); | ||
|
|
||
| // Remove all parameters except those in the allowedList | ||
| for (const key of params.keys()) { | ||
| if (!allowedList.includes(key)) { | ||
| // Replace the 'code' parameter value | ||
| params.set(key, "xxxxxxxxxx"); | ||
| } | ||
| } | ||
|
|
||
| url.hash = params.toString(); | ||
| return url.toString(); | ||
| } | ||
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,169 @@ | ||
| import { IInjector } from "@paperbits/common/injection"; | ||
| import { Logger } from "@paperbits/common/logging"; | ||
| import { Utils } from "../utils"; | ||
| import { USER_ACTION, USER_ID, USER_SESSION } from "../constants"; | ||
|
|
||
| const TrackingEventElements = ["BUTTON", "A"]; | ||
|
|
||
| export class TelemetryConfigurator { | ||
|
|
||
| constructor(private injector: IInjector) { | ||
| // required for user session init. | ||
| const userId = this.userId | ||
|
||
| const sessionId = this.sessionId; | ||
|
||
| } | ||
|
|
||
| public get userId(): string { | ||
| const uniqueUser = localStorage.getItem(USER_ID); | ||
| if (uniqueUser) { | ||
| return uniqueUser; | ||
| } else { | ||
| const newId = Utils.guid(); | ||
| localStorage.setItem(USER_ID, newId); | ||
| return newId; | ||
| } | ||
| } | ||
|
|
||
| public get sessionId(): string { | ||
| const sessionId = sessionStorage.getItem(USER_SESSION); | ||
| if (sessionId) { | ||
| return sessionId; | ||
| } else { | ||
| const newId = Utils.guid(); | ||
| sessionStorage.setItem(USER_SESSION, newId); | ||
| return newId; | ||
| } | ||
| } | ||
|
|
||
| public configure(): void { | ||
| const logger = this.injector.resolve<Logger>("logger"); | ||
| // Register service worker for network telemetry. | ||
| if ("serviceWorker" in navigator) { | ||
| navigator.serviceWorker.register("/serviceWorker.js", { scope: "/" }).then(registration => { | ||
| console.log("Service Worker registered with scope:", registration.scope); | ||
| }).catch(error => { | ||
| console.error("Service Worker registration failed:", error); | ||
ygrik marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| logger.trackError(error); | ||
| }); | ||
|
|
||
| // Listen for messages from the service worker | ||
| navigator.serviceWorker.addEventListener("message", (event) => { | ||
| console.log("Received message from Service Worker:", event.data); | ||
| if (event.data) { | ||
| logger.trackEvent("NetworkRequest", event.data); | ||
| } else { | ||
| console.error("No telemetry data received from Service Worker."); | ||
| } | ||
| }); | ||
| } | ||
|
|
||
| // Init page load telemetry. | ||
| window.onload = () => { | ||
| if (logger) { | ||
ygrik marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| const observer = new PerformanceObserver((list: PerformanceObserverEntryList) => { | ||
| const timing = list.getEntriesByType("navigation")[0] as PerformanceNavigationTiming; | ||
| if (timing) { | ||
| const location = window.location; | ||
| const screenSize = { | ||
| width: window.innerWidth.toString(), | ||
| height: window.innerHeight.toString() | ||
| }; | ||
| const pageLoadTime = timing.loadEventEnd - timing.loadEventStart; | ||
| const domRenderingTime = timing.domComplete - timing.domInteractive; | ||
| const resources = performance.getEntriesByType("resource") as PerformanceResourceTiming[]; | ||
| const jsCssResources = resources.filter(resource => { | ||
| return resource.initiatorType === "script" || resource.initiatorType === "link"; | ||
| }); | ||
| const stats = { | ||
| pageLoadTime, | ||
| domRenderingTime, | ||
| jsCssResources: jsCssResources.map(resource => ({ | ||
| name: resource.name, | ||
| duration: resource.duration | ||
| })) | ||
| }; | ||
| logger.trackEvent("PageLoad", { host: location.host, pathName: location.pathname, total: timing.loadEventEnd.toString(), pageLoadStats: JSON.stringify(stats), ...screenSize }); | ||
| } | ||
| }); | ||
| observer.observe({ type: "navigation", buffered: true }); | ||
| } else { | ||
| console.error("Logger is not available"); | ||
| } | ||
| } | ||
|
|
||
| document.addEventListener("click", (event) => { | ||
ygrik marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| this.processUserInteraction(event).then(() => { | ||
| console.log("Click processed"); | ||
| }).catch((error) => { | ||
| console.error("Error processing user interaction:", error); | ||
| }); | ||
| }); | ||
|
|
||
| document.addEventListener("keydown", (event) => { | ||
| if (event.key === "Enter") { | ||
| this.processUserInteraction(event).then(() => { | ||
| console.log("Enter key processed"); | ||
| }).catch((error) => { | ||
| console.error("Error processing user interaction:", error); | ||
| }); | ||
| } | ||
| }); | ||
| } | ||
|
|
||
| public cleanUp() { | ||
| if ('serviceWorker' in navigator) { | ||
|
||
| navigator.serviceWorker.getRegistration().then((registration) => { | ||
| if (registration) { | ||
| registration.unregister().then((boolean) => { | ||
| if (boolean) { | ||
| console.log('Service Worker unregistered successfully.'); | ||
|
||
| } else { | ||
| console.log('Service Worker unregistering failed.'); | ||
|
||
| } | ||
| }).catch((error) => { | ||
| console.error('Error unregistering Service Worker:', error); | ||
|
||
| }); | ||
| } else { | ||
| console.log('No Service Worker to unregister.'); | ||
|
||
| } | ||
| }).catch((error) => { | ||
| console.error('Error getting Service Worker registration:', error); | ||
|
||
| }); | ||
| } else { | ||
| console.log('Service Worker not registered.'); | ||
|
||
| } | ||
| } | ||
|
|
||
| private async processUserInteraction(event: Event) { | ||
| const element = event.target as HTMLElement; | ||
ygrik marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| const elementTag = element?.tagName; | ||
| const parent = element?.parentElement; | ||
| const parentTag = parent?.tagName; | ||
| if (!(elementTag && TrackingEventElements.includes(elementTag)) && !(parentTag && TrackingEventElements.includes(parentTag))) { | ||
| return; | ||
| } | ||
|
|
||
| const eventAction = element.attributes.getNamedItem(USER_ACTION)?.value; | ||
ygrik marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| const eventMessage = { | ||
| elementId: element.id | ||
| }; | ||
|
|
||
| const navigation = ((elementTag === "A" && element) || (parentTag === "A" && parent)) as HTMLAnchorElement; | ||
|
|
||
| if (navigation?.href) { | ||
| eventMessage["navigationTo"] = navigation.href; | ||
| eventMessage["navigationText"] = navigation.innerText; | ||
| } | ||
|
|
||
| if (!eventAction && !navigation) { | ||
| return; | ||
| } | ||
|
|
||
| if (eventAction) { | ||
| eventMessage["eventAction"] = eventAction; | ||
| } | ||
|
|
||
| const logger = this.injector.resolve<Logger>("logger"); | ||
| await logger.trackEvent("UserEvent", eventMessage); | ||
| } | ||
| } | ||
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.