Repository navigation
feat(analytics): count CV and resume.json downloads server-side #145
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
cbc6a51
feat(analytics): count CV and resume.json downloads server-side
roschaefer 40b6183
feat(analytics): count CV and resume.json downloads server-side
roschaefer e37b24e
perf(analytics): keep conditional requests for counted downloads
roschaefer 7844fd7
fix(analytics): count downloads only on the production hostname
roschaefer 91e8ec9
docs(privacy): say GoatCounter measures content, not just pages
roschaefer File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,61 @@ | ||
| import { siteUrl } from "../../src/lib/config/site.ts"; | ||
| import { primaryLanguage, send } from "./goatcounter.ts"; | ||
|
|
||
| declare const Netlify: { env: { get: (name: string) => string | undefined } }; | ||
|
|
||
| type Context = { | ||
| ip: string; | ||
| next: (options?: { sendConditionalRequest?: boolean }) => Promise<Response>; | ||
| waitUntil: (promise: Promise<unknown>) => void; | ||
| }; | ||
|
|
||
| const productionHostname = new URL(siteUrl).hostname; | ||
|
|
||
| const isPrefetch = (request: Request): boolean => | ||
| /prefetch|prerender/i.test( | ||
| `${request.headers.get("sec-purpose") ?? ""} ${request.headers.get("purpose") ?? ""}`, | ||
| ); | ||
|
|
||
| // PDF viewers fetch large files in byte ranges after the first request; only | ||
| // the range that starts at the beginning counts as a download. | ||
| const isFollowUpRange = (request: Request): boolean => { | ||
| const range = request.headers.get("range"); | ||
| return range !== null && !/^bytes=0-/.test(range.trim()); | ||
| }; | ||
|
|
||
| const shouldCount = (request: Request): boolean => | ||
| new URL(request.url).hostname === productionHostname && | ||
| request.method === "GET" && | ||
| !isPrefetch(request) && | ||
| !isFollowUpRange(request); | ||
|
|
||
| export default async (request: Request, context: Context) => { | ||
| const response = await context.next({ sendConditionalRequest: true }); | ||
|
|
||
| if (!shouldCount(request) || response.status >= 400) { | ||
| return response; | ||
| } | ||
|
|
||
| const token = Netlify.env.get("GOATCOUNTER_API_TOKEN"); | ||
| if (!token) { | ||
| console.error("GOATCOUNTER_API_TOKEN is not set, not counting"); | ||
| return response; | ||
| } | ||
|
|
||
| const url = new URL(request.url); | ||
| const hit = { | ||
| path: url.pathname, | ||
| title: "", | ||
| ref: request.headers.get("referer") ?? "", | ||
| event: false, | ||
| size: "", | ||
| query: url.search, | ||
| bot: 0, | ||
| user_agent: request.headers.get("user-agent") ?? "", | ||
| language: primaryLanguage(request.headers.get("accept-language")), | ||
| ip: context.ip, | ||
| }; | ||
| context.waitUntil(send(hit, token).catch((error) => console.error(error))); | ||
|
roschaefer marked this conversation as resolved.
|
||
|
|
||
| return response; | ||
| }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,164 @@ | ||
| import { readFileSync } from "node:fs"; | ||
| import { resolve } from "node:path"; | ||
| import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; | ||
|
|
||
| import { resumePdfPath } from "$lib/data/resume-pdf"; | ||
| import countDownload from "../../../netlify/edge-functions/count-download.ts"; | ||
| import { goatcounterApiUrl } from "../../../netlify/edge-functions/goatcounter.ts"; | ||
|
|
||
| const visitorIp = "203.0.113.7"; | ||
| const firefox = "Mozilla/5.0 (X11; Linux x86_64; rv:130.0) Gecko/20100101 Firefox/130.0"; | ||
| const pdfUrl = "https://roschaefer.de/en/robert-schaefer-resume.en.pdf"; | ||
|
|
||
| const download = (url: string, headers: Record<string, string> = {}, method = "GET") => | ||
| new Request(url, { | ||
| method, | ||
| headers: { "user-agent": firefox, "accept-language": "en-US,en;q=0.9", ...headers }, | ||
| }); | ||
|
|
||
| let fileResponse: Response; | ||
|
|
||
| const run = async (request: Request) => { | ||
| const pending: Promise<unknown>[] = []; | ||
| const response = await countDownload(request, { | ||
| ip: visitorIp, | ||
| next: nextMock, | ||
| waitUntil: (promise) => pending.push(promise), | ||
| }); | ||
| await Promise.all(pending); | ||
| return response; | ||
| }; | ||
|
|
||
| const nextMock = vi.fn(async (_options?: { sendConditionalRequest?: boolean }) => fileResponse); | ||
|
|
||
| let token: string | undefined; | ||
| const fetchMock = vi.fn(async () => new Response(null, { status: 202 })); | ||
|
|
||
| beforeEach(() => { | ||
| token = "secret-token"; | ||
| fileResponse = new Response("%PDF-1.7", { headers: { "content-type": "application/pdf" } }); | ||
| vi.stubGlobal("Netlify", { env: { get: () => token } }); | ||
| vi.stubGlobal("fetch", fetchMock); | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| vi.unstubAllGlobals(); | ||
| vi.restoreAllMocks(); | ||
| fetchMock.mockClear(); | ||
| nextMock.mockClear(); | ||
| }); | ||
|
|
||
| describe("count-download edge function", () => { | ||
| it("counts a direct download that the JS beacon never sees, e.g. a CV link opened from a printout or email", async () => { | ||
| const response = await run(download(pdfUrl, { referer: "https://mail.example.com/" })); | ||
|
|
||
| expect(response).toBe(fileResponse); | ||
| expect(fetchMock).toHaveBeenCalledOnce(); | ||
| const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit]; | ||
| expect(url).toBe(goatcounterApiUrl); | ||
| expect(init.headers).toMatchObject({ authorization: "Bearer secret-token" }); | ||
| expect(JSON.parse(init.body as string)).toEqual({ | ||
| hits: [ | ||
| { | ||
| path: "/en/robert-schaefer-resume.en.pdf", | ||
| title: "", | ||
| ref: "https://mail.example.com/", | ||
| event: false, | ||
| size: "", | ||
| query: "", | ||
| bot: 0, | ||
| user_agent: firefox, | ||
| language: "en-US", | ||
| ip: visitorIp, | ||
| }, | ||
| ], | ||
| }); | ||
| }); | ||
|
|
||
| it("leaves bot detection to GoatCounter, whose API flags hits by the forwarded user agent", async () => { | ||
| const googlebot = "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"; | ||
|
|
||
| await run(download(pdfUrl, { "user-agent": googlebot })); | ||
|
|
||
| const [, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit]; | ||
| expect(JSON.parse(init.body as string).hits[0]).toMatchObject({ | ||
| user_agent: googlebot, | ||
| bot: 0, | ||
| }); | ||
| }); | ||
|
|
||
| it("lets the CDN answer revalidations with 304 instead of resending the whole file, and counts them as views", async () => { | ||
| fileResponse = new Response(null, { status: 304 }); | ||
|
|
||
| const response = await run(download(pdfUrl, { "if-none-match": '"abc"' })); | ||
|
|
||
| expect(nextMock).toHaveBeenCalledWith({ sendConditionalRequest: true }); | ||
| expect(response.status).toBe(304); | ||
| expect(fetchMock).toHaveBeenCalledOnce(); | ||
| }); | ||
|
|
||
| it("does not count downloads from deploy previews, so reviewing a PR does not pollute the production stats", async () => { | ||
| await run( | ||
| download( | ||
| "https://deploy-preview-145--roschaefer.netlify.app/en/robert-schaefer-resume.en.pdf", | ||
| ), | ||
| ); | ||
|
|
||
| expect(fetchMock).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it("does not count speculative prefetches", async () => { | ||
| await run(download(pdfUrl, { "sec-purpose": "prefetch;prerender" })); | ||
|
|
||
| expect(fetchMock).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it("counts a PDF viewer's first byte range but not the follow-up ranges of the same download", async () => { | ||
| await run(download(pdfUrl, { range: "bytes=0-65535" })); | ||
| await run(download(pdfUrl, { range: "bytes=65536-131071" })); | ||
|
|
||
| expect(fetchMock).toHaveBeenCalledOnce(); | ||
| }); | ||
|
|
||
| it("does not count HEAD requests", async () => { | ||
| await run(download(pdfUrl, {}, "HEAD")); | ||
|
|
||
| expect(fetchMock).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it("does not count failed responses", async () => { | ||
| fileResponse = new Response("Not found", { status: 404 }); | ||
|
|
||
| await run(download(pdfUrl)); | ||
|
|
||
| expect(fetchMock).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it("still serves the file when the API token is not configured", async () => { | ||
| token = undefined; | ||
| vi.spyOn(console, "error").mockImplementation(() => {}); | ||
|
|
||
| const response = await run(download(pdfUrl)); | ||
|
|
||
| expect(response).toBe(fileResponse); | ||
| expect(fetchMock).not.toHaveBeenCalled(); | ||
| }); | ||
| }); | ||
|
|
||
| describe("count-download routes in netlify.toml", () => { | ||
| const countedPaths = readFileSync(resolve(process.cwd(), "netlify.toml"), "utf8") | ||
| .split("[[edge_functions]]") | ||
| .slice(1) | ||
| .filter((block) => block.includes('function = "count-download"')) | ||
| .map((block) => block.match(/path = "([^"]+)"/)?.[1]); | ||
|
|
||
| it.each( | ||
| (["de", "en"] as const).flatMap((locale) => [ | ||
| resumePdfPath(locale), | ||
| resumePdfPath(locale, "ats"), | ||
| `/${locale}/resume.json`, | ||
| ]), | ||
| )("counts %s", (path) => { | ||
| expect(countedPaths).toContain(path); | ||
| }); | ||
| }); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.