Skip to content

Commit 9cbefa8

Browse files
authored
Filter invalid events sent to the API (#3792)
1 parent c8bba7b commit 9cbefa8

File tree

2 files changed

+30
-4
lines changed

2 files changed

+30
-4
lines changed

packages/gitbook/src/components/Insights/InsightsProvider.tsx

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -127,9 +127,16 @@ export function InsightsProvider(props: InsightsProviderProps) {
127127
}
128128
});
129129

130-
const flushBatchedEvents = useDebounceCallback(() => {
131-
flushEventsSync();
132-
}, 1500);
130+
const flushBatchedEvents = useDebounceCallback(
131+
() => {
132+
flushEventsSync();
133+
},
134+
1500,
135+
{
136+
// We don't want to debounce indefinitely, after 1 minute we want to flush anyway
137+
maxWait: 60000,
138+
}
139+
);
133140

134141
// Flush pending events once the visitor session has been fetched
135142
React.useEffect(() => {

packages/gitbook/src/lib/tracking.ts

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import type * as api from '@gitbook/api';
12
import type { headers as nextHeaders } from 'next/headers';
23
import { GITBOOK_API_PUBLIC_URL, GITBOOK_DISABLE_TRACKING } from './env';
34

@@ -48,6 +49,22 @@ export async function serveProxyAnalyticsEvent(req: Request) {
4849
});
4950
}
5051

52+
const body = (await req.json()) as { events: api.SiteInsightsEvent[] };
53+
// Here we should filter every event that is older than 5 minutes as the API will reject them anyway, we might as well do it here
54+
const filteredEvents = body.events.filter((event) => {
55+
const eventDate = event.timestamp ? new Date(event.timestamp) : Date.now();
56+
const now = new Date();
57+
const fiveMinutesAgo = new Date(now.getTime() - 5 * 60 * 1000);
58+
return eventDate > fiveMinutesAgo;
59+
});
60+
61+
if (filteredEvents.length === 0) {
62+
return new Response('No valid events to process', {
63+
status: 400,
64+
headers: { 'content-type': 'text/plain' },
65+
});
66+
}
67+
5168
// We make the request to the public API URL to ensure the request is properly enriched by the router..
5269
const url = new URL(`${GITBOOK_API_PUBLIC_URL}/v1/orgs/${org}/sites/${site}/insights/events`);
5370
return await fetch(url.toString(), {
@@ -59,6 +76,8 @@ export async function serveProxyAnalyticsEvent(req: Request) {
5976
...(longitude ? { 'x-location-longitude': longitude } : {}),
6077
...(continent ? { 'x-location-continent': continent } : {}),
6178
},
62-
body: req.body,
79+
body: JSON.stringify({
80+
events: filteredEvents,
81+
}),
6382
});
6483
}

0 commit comments

Comments
 (0)