swap out S3 for R2 for heatmap storage

This commit is contained in:
Francis Cao committed 2026-05-22 10:47:56 -07:00
1 parent 07e40db5f4
commit 462be82782
4 files changed
+163 -70

No files matched your search

@@ -265,6 +265,8 @@ function ClickHeatmapView({
const maxPointY = visible.reduce((max, point) => Math.max(max, point.pageY), 0);
const baseWidth = Math.max(snapshot?.pageW ?? 0, viewport?.pageW ?? 0, maxPointX + overlayGutter, 1200);
const baseHeight = Math.max(snapshot?.pageH ?? 0, viewport?.pageH ?? 0, maxPointY + overlayGutter, 640);
const overlayPageW = snapshot?.pageW ?? viewport?.pageW ?? baseWidth;
const overlayPageH = snapshot?.pageH ?? viewport?.pageH ?? baseHeight;
const showSnapshot = baseWidth > 0 && showPage && hasSnapshotImage;
const showOverlay = !showSnapshot || snapshotReady;
const totalClicks = visible.reduce((sum, point) => sum + point.count, 0);
@@ -325,8 +327,8 @@ function ClickHeatmapView({
{visible.map((point, index) => {
const intensity = Math.min(1, point.count / maxCount);
const desiredSize = 24 + intensity * 36;
const pointWidth = Math.max(baseWidth, point.pageW || 0, point.pageX);
const pointHeight = Math.max(baseHeight, point.pageH || 0, point.pageY);
const pointWidth = Math.max(overlayPageW, point.pageX);
const pointHeight = Math.max(overlayPageH, point.pageY);
const rawCenterX = (point.pageX / Math.max(1, pointWidth)) * 100;
const rawCenterY = (point.pageY / Math.max(1, pointHeight)) * 100;
const size = desiredSize;
+100
View File
@@ -0,0 +1,100 @@
import { GetObjectCommand, PutObjectCommand, S3Client } from '@aws-sdk/client-s3';
let client: S3Client | null = null;
function getBucket() {
const bucket = process.env.R2_BUCKET;
if (!bucket) {
throw new Error('R2_BUCKET is not set.');
}
return bucket;
}
function getAccountId() {
const accountId = process.env.R2_ACCOUNT_ID;
if (!accountId) {
throw new Error('R2_ACCOUNT_ID is not set.');
}
return accountId;
}
function getCredentials() {
const accessKeyId = process.env.R2_ACCESS_KEY_ID;
const secretAccessKey = process.env.R2_SECRET_ACCESS_KEY;
if (!accessKeyId) {
throw new Error('R2_ACCESS_KEY_ID is not set.');
}
if (!secretAccessKey) {
throw new Error('R2_SECRET_ACCESS_KEY is not set.');
}
return {
accessKeyId,
secretAccessKey,
};
}
function getClient() {
if (!client) {
client = new S3Client({
region: 'auto',
endpoint: `https://${getAccountId()}.r2.cloudflarestorage.com`,
credentials: getCredentials(),
});
}
return client;
}
export async function putHeatmapSnapshot(
objectKey: string,
imageData: Buffer,
mimeType: string,
) {
await getClient().send(
new PutObjectCommand({
Bucket: getBucket(),
Key: objectKey,
Body: imageData,
ContentType: mimeType,
}),
);
}
export async function getHeatmapSnapshot(objectKey: string) {
let response;
try {
response = await getClient().send(
new GetObjectCommand({
Bucket: getBucket(),
Key: objectKey,
}),
);
} catch (error: any) {
if (
error?.name === 'NoSuchKey' ||
error?.Code === 'NoSuchKey' ||
error?.$metadata?.httpStatusCode === 404
) {
return null;
}
throw error;
}
if (!response.Body) {
return null;
}
return {
mimeType: response.ContentType || 'application/octet-stream',
imageData: Buffer.from(await response.Body.transformToByteArray()),
};
}
-56
View File
@@ -1,56 +0,0 @@
import { GetObjectCommand, PutObjectCommand, S3Client } from '@aws-sdk/client-s3';
let client: S3Client | null = null;
function getBucket() {
const bucket = process.env.S3_HEATMAP_BUCKET;
if (!bucket) {
throw new Error('S3_HEATMAP_BUCKET is not set.');
}
return bucket;
}
function getClient() {
if (!client) {
client = new S3Client({
region: process.env.AWS_REGION,
});
}
return client;
}
export async function putHeatmapSnapshot(
objectKey: string,
imageData: Buffer,
mimeType: string,
) {
await getClient().send(
new PutObjectCommand({
Bucket: getBucket(),
Key: objectKey,
Body: imageData,
ContentType: mimeType,
}),
);
}
export async function getHeatmapSnapshot(objectKey: string) {
const response = await getClient().send(
new GetObjectCommand({
Bucket: getBucket(),
Key: objectKey,
}),
);
if (!response.Body) {
return null;
}
return {
mimeType: response.ContentType || 'application/octet-stream',
imageData: Buffer.from(await response.Body.transformToByteArray()),
};
}
@@ -1,7 +1,7 @@
import clickhouse from '@/lib/clickhouse';
import prisma from '@/lib/prisma';
import { uuid } from '@/lib/crypto';
import { getHeatmapSnapshot, putHeatmapSnapshot } from '@/lib/heatmap-s3';
import { getHeatmapSnapshot, putHeatmapSnapshot } from '@/lib/heatmap-r2';
import { getWebsite } from '@/queries/prisma';
const SNAPSHOT_STATUS = {
@@ -12,6 +12,7 @@ const SNAPSHOT_STATUS = {
const SNAPSHOT_RETRY_DELAY_MS = 15 * 60 * 1000;
const SNAPSHOT_PENDING_WINDOW_MS = 30 * 1000;
const SNAPSHOT_DEVICE_SCALE_FACTOR = 1;
export type HeatmapSnapshotStatus = (typeof SNAPSHOT_STATUS)[keyof typeof SNAPSHOT_STATUS];
export interface HeatmapSnapshotImage {
@@ -70,6 +71,19 @@ async function measurePage(page: any) {
const doc = document.documentElement;
const body = document.body;
const root = document.scrollingElement || doc || body;
const rootClientWidth = root?.clientWidth || 0;
const docClientWidth = doc?.clientWidth || 0;
const bodyClientWidth = body?.clientWidth || 0;
const visibleWidth = Math.max(window.innerWidth, rootClientWidth, docClientWidth, bodyClientWidth);
const rootScrollWidth = root?.scrollWidth || 0;
const docScrollWidth = doc?.scrollWidth || 0;
const bodyScrollWidth = body?.scrollWidth || 0;
const horizontalOverflow = Math.max(
rootScrollWidth - rootClientWidth,
docScrollWidth - docClientWidth,
bodyScrollWidth - bodyClientWidth,
0,
);
let maxRight = 0;
let maxBottom = 0;
@@ -89,13 +103,10 @@ async function measurePage(page: any) {
}
}
const pageW = Math.max(
window.innerWidth,
root?.scrollWidth || 0,
doc?.scrollWidth || 0,
body?.scrollWidth || 0,
Math.ceil(maxRight),
);
const pageW =
horizontalOverflow > 24
? Math.max(visibleWidth, rootScrollWidth, docScrollWidth, bodyScrollWidth)
: visibleWidth;
const pageH = Math.max(
window.innerHeight,
root?.scrollHeight || 0,
@@ -111,6 +122,38 @@ async function measurePage(page: any) {
});
}
async function warmLazyContent(page: any) {
await page.evaluate(async () => {
const root = document.scrollingElement || document.documentElement;
if (!root) {
return;
}
const maxScrollTop = Math.max(0, root.scrollHeight - window.innerHeight);
if (maxScrollTop <= 0) {
return;
}
const targets = [
Math.min(window.innerHeight, maxScrollTop),
Math.min(Math.round(maxScrollTop * 0.25), maxScrollTop),
Math.min(Math.round(maxScrollTop * 0.5), maxScrollTop),
Math.min(Math.round(maxScrollTop * 0.75), maxScrollTop),
maxScrollTop,
].filter((value, index, values) => value > 0 && values.indexOf(value) === index);
for (const top of targets) {
window.scrollTo(0, top);
await new Promise(resolve => window.setTimeout(resolve, 350));
}
window.scrollTo(0, 0);
await new Promise(resolve => window.setTimeout(resolve, 250));
});
}
function getSchema() {
const databaseUrl = process.env.DATABASE_URL;
@@ -517,7 +560,7 @@ async function insertClickhouseSnapshotRecord({
}
function getSnapshotObjectKey(websiteId: string, snapshotId: string, viewportW: number, viewportH: number) {
return `heatmaps/${websiteId}/${viewportW}x${viewportH}/${snapshotId}.png`;
return `${websiteId}/${viewportW}x${viewportH}/${snapshotId}.png`;
}
async function captureSnapshot(
@@ -528,13 +571,13 @@ async function captureSnapshot(
): Promise<CaptureResult> {
const { chromium } = await import('@playwright/test');
const browser = await chromium.launch({ headless: true });
const initialViewportW = Math.max(viewportW, pageW || 0);
const initialViewportW = viewportW;
try {
const context = await browser.newContext({
viewport: { width: initialViewportW, height: viewportH },
screen: { width: initialViewportW, height: viewportH },
deviceScaleFactor: 1,
deviceScaleFactor: SNAPSHOT_DEVICE_SCALE_FACTOR,
ignoreHTTPSErrors: true,
});
@@ -542,10 +585,14 @@ async function captureSnapshot(
await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 15000 });
await page.waitForLoadState('networkidle', { timeout: 5000 }).catch(() => undefined);
await page.waitForTimeout(500);
await warmLazyContent(page);
await page.waitForLoadState('networkidle', { timeout: 3000 }).catch(() => undefined);
await page.waitForTimeout(300);
let dimensions = await measurePage(page);
let currentWidth = initialViewportW;
let captureWidth = Math.max(initialViewportW, dimensions.pageW);
let captureWidth =
dimensions.pageW > initialViewportW + 24 ? Math.max(initialViewportW, dimensions.pageW) : initialViewportW;
for (let i = 0; i < 3; i++) {
if (captureWidth <= currentWidth) {