Skip to content

Commit

Permalink
fix(observation): warn without error on observations without sessions
Browse files Browse the repository at this point in the history
  • Loading branch information
uladkasach committed Sep 7, 2023
1 parent 54aeadc commit a4cac62
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 8 deletions.
22 changes: 21 additions & 1 deletion src/logic/capture/captureObservationEvent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,27 @@ export const captureObservationEvent = async ({
details: AppUsageEvent['details'];
}) => {
if (typeof window === 'undefined') return; // do nothing on serverside, since no installation-uuid available
await waitForApplicationOfSession();

// wait for the app session to be loaded
try {
await waitForApplicationOfSession();
} catch (error) {
if (!(error instanceof Error)) throw error;

// if the error was due to not having the app session, then just warn and exit. dont pass up the error
if (error.message.includes('application wait attempts exceeded')) {
console.warn(
'could not capture observation event, app.session was not instantiated. was the AppUsageEventProvider loaded?',
{ type, details },
);
return;
}

// otherwise, pass up the error since we dont know what to do with it
throw error;
}

// capture the event
await captureAppUsageEvent({
source: AppUsageEventSource.OBSERVATION,
type,
Expand Down
20 changes: 13 additions & 7 deletions src/logic/session/getApplicationOfSession.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import { createCache } from 'simple-in-memory-cache';
import { withSimpleCaching } from 'with-simple-caching';

import { AppUsageApplication } from '../../domain/AppUsageApplication';

// track the application in memory
Expand All @@ -13,10 +16,13 @@ export const getApplicationOfSession = (): AppUsageApplication => {

export const sleep = (ms: number) =>
new Promise((resolve) => setTimeout(resolve, ms));
export const waitForApplicationOfSession = async () => {
for (let attempt = 0; attempt < 5; attempt++) {
if (application) return application;
await sleep(300);
}
throw new Error('application wait attempts exceeded');
};
export const waitForApplicationOfSession = withSimpleCaching(
async () => {
for (let attempt = 0; attempt < 5; attempt++) {
if (application) return application;
await sleep(300);
}
throw new Error('application wait attempts exceeded');
},
{ cache: createCache() }, // cache the promise in memory, so we only ever create one promise for this no matter how many duplicate requests
);

0 comments on commit a4cac62

Please sign in to comment.