From 462be8278214de0354389dc6532614c2add0c980 Mon Sep 17 00:00:00 2001 From: Francis Cao Date: Fri, 22 May 2026 10:47:56 -0700 Subject: [PATCH] swap out S3 for R2 for heatmap storage --- .../(reports)/heatmaps/Heatmap.tsx | 6 +- src/lib/heatmap-r2.ts | 100 ++++++++++++++++++ src/lib/heatmap-s3.ts | 56 ---------- .../sql/heatmap/ensureHeatmapSnapshot.ts | 71 ++++++++++--- 4 files changed, 163 insertions(+), 70 deletions(-) create mode 100644 src/lib/heatmap-r2.ts delete mode 100644 src/lib/heatmap-s3.ts diff --git a/src/app/(main)/websites/[websiteId]/(reports)/heatmaps/Heatmap.tsx b/src/app/(main)/websites/[websiteId]/(reports)/heatmaps/Heatmap.tsx index b8d8d5353..01622e2a0 100644 --- a/src/app/(main)/websites/[websiteId]/(reports)/heatmaps/Heatmap.tsx +++ b/src/app/(main)/websites/[websiteId]/(reports)/heatmaps/Heatmap.tsx @@ -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; diff --git a/src/lib/heatmap-r2.ts b/src/lib/heatmap-r2.ts new file mode 100644 index 000000000..76c8b7343 --- /dev/null +++ b/src/lib/heatmap-r2.ts @@ -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()), + }; +} diff --git a/src/lib/heatmap-s3.ts b/src/lib/heatmap-s3.ts deleted file mode 100644 index ccb234d47..000000000 --- a/src/lib/heatmap-s3.ts +++ /dev/null @@ -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()), - }; -} diff --git a/src/queries/sql/heatmap/ensureHeatmapSnapshot.ts b/src/queries/sql/heatmap/ensureHeatmapSnapshot.ts index 49beb663a..62095c1a1 100644 --- a/src/queries/sql/heatmap/ensureHeatmapSnapshot.ts +++ b/src/queries/sql/heatmap/ensureHeatmapSnapshot.ts @@ -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 { 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) {