Skip to content

Commit

Permalink
Check if browser supports keepalive for network requests (#90)
Browse files Browse the repository at this point in the history
  • Loading branch information
tore-statsig authored Sep 24, 2021
1 parent d7a93b3 commit fed041f
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 8 deletions.
7 changes: 1 addition & 6 deletions src/StatsigLogger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,6 @@ type FailedLogEventBody = {
time: number;
};

let SUPPORTS_KEEPALIVE = false;
try {
SUPPORTS_KEEPALIVE = 'keepalive' in new Request('');
} catch (_e) {}

const MS_RETRY_LOGS_CUTOFF = 5 * 24 * 60 * 60 * 1000;

export default class StatsigLogger {
Expand Down Expand Up @@ -133,7 +128,7 @@ export default class StatsigLogger {

const oldQueue = this.queue;
this.queue = [];
if (isClosing && !SUPPORTS_KEEPALIVE && navigator && navigator.sendBeacon) {
if (isClosing && !this.sdkInternal.getNetwork().supportsKeepalive() && navigator && navigator.sendBeacon) {
const beacon = this.sdkInternal.getNetwork().sendLogBeacon({
events: oldQueue,
statsigMetadata: this.sdkInternal.getStatsigMetadata(),
Expand Down
16 changes: 14 additions & 2 deletions src/StatsigNetwork.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,14 @@ export default class StatsigNetwork {

private leakyBucket: Record<string, number>;

private canUseKeepalive : boolean = false;

public constructor(sdkInternal: IHasStatsigInternal) {
this.sdkInternal = sdkInternal;
this.leakyBucket = {};
try {
this.canUseKeepalive = 'keepalive' in new Request('');
} catch (_e) {}
}

public fetchValues(
Expand Down Expand Up @@ -117,17 +122,20 @@ export default class StatsigNetwork {
this.leakyBucket[url] = counter + 1;
}

const params = {
const params : RequestInit = {
method: 'POST',
body: JSON.stringify(body),
headers: {
'Content-type': 'application/json; charset=UTF-8',
'STATSIG-API-KEY': this.sdkInternal.getSDKKey(),
'STATSIG-CLIENT-TIME': Date.now() + '',
},
keepalive: true,
};

if (this.canUseKeepalive) {
params.keepalive = true;
}

return fetch(url, params)
.then((res) => {
if (res.ok) {
Expand Down Expand Up @@ -157,4 +165,8 @@ export default class StatsigNetwork {
this.leakyBucket[url] = Math.max(this.leakyBucket[url] - 1, 0);
});
}

public supportsKeepalive(): boolean {
return this.canUseKeepalive;
}
}

0 comments on commit fed041f

Please sign in to comment.