Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 12 additions & 26 deletions apps/basket/src/utils/ip-geo.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { createHash } from "node:crypto";
import { cacheable } from "@databuddy/redis/cacheable";
import { captureError, mergeWideEvent, record } from "@lib/tracing";
import type { City } from "@maxmind/geoip2-node";
import {
Expand Down Expand Up @@ -169,30 +168,6 @@ function lookupGeoLocation(ip: string): Promise<{
});
}

function coarsenIpForCache(ip: string): string {
if (ip.includes(":")) {
const groups = ip.split(":");
const head = groups.slice(0, 4).join(":");
return `${head}::`;
}
const octets = ip.split(".");
if (octets.length === 4) {
return `${octets[0]}.${octets[1]}.${octets[2]}.0`;
}
return ip;
}

const getCachedGeoLocation = cacheable(lookupGeoLocation, {
expireInSec: 86_400 * 7,
prefix: "geoip_location",
staleWhileRevalidate: true,
staleTime: 86_400,
});

function getGeoLocation(ip: string) {
return getCachedGeoLocation(coarsenIpForCache(ip));
}

export function anonymizeIp(ip: string): string {
if (!ip) {
return "";
Expand All @@ -218,7 +193,7 @@ export function getGeo(ip: string, request?: Request) {
};
}

const geo = await getGeoLocation(ip);
const geo = await lookupGeoLocation(ip);

if (!geo.country && request?.headers) {
const cfCountry = getCloudflareCountry(request.headers);
Expand All @@ -238,6 +213,17 @@ export function getGeo(ip: string, request?: Request) {
}
}

mergeWideEvent({
geo: geo.country
? {
source: "maxmind",
country: geo.country,
region: geo.region,
city: geo.city,
}
: { source: "unresolved" },
});
Comment on lines +216 to +225

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Telemetry expands precise geo data

The new MaxMind merge sends user-derived city and region data to operational telemetry even for callers that never persist an analytics event. These fields are unnecessary for measuring resolution source and broaden the retention and audience exposure of precise location data.

Suggested change
mergeWideEvent({
geo: geo.country
? {
source: "maxmind",
country: geo.country,
region: geo.region,
city: geo.city,
}
: { source: "unresolved" },
});
mergeWideEvent({
geo: geo.country
? {
source: "maxmind",
country: geo.country,
}
: { source: "unresolved" },
});

Knowledge Base Used: Basket Ingestion Flow

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!


return {
anonymizedIP: anonymizeIp(ip),
country: geo.country,
Expand Down