Skip to content
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

Adds serverside collection support for v2 #111

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
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
23 changes: 23 additions & 0 deletions app/analytics/__tests__/collect.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { Mock, describe, expect, test, vi, beforeEach } from "vitest";
import httpMocks from "node-mocks-http";

import { collectRequestHandler } from "../collect";
import { AnalyticsEngineDataset } from "@cloudflare/workers-types";

const defaultRequestParams = generateRequestParams({
"user-agent":
Expand Down Expand Up @@ -216,4 +217,26 @@ describe("collectRequestHandler", () => {
],
);
});

test("a PATCH request should return 405", () => {
const env = {
WEB_COUNTER_AE: {
writeDataPoint: vi.fn(),
} as AnalyticsEngineDataset,
} as Env;

const request = httpMocks.createRequest({
method: "PATCH",
url: "https://example.com",
// Cloudflare-specific request properties
cf: {
country: "US",
},
});

const response = collectRequestHandler(request as any, env);

expect(response.status).toBe(405);
expect(response.statusText).toBe("Method not allowed");
});
});
161 changes: 109 additions & 52 deletions app/analytics/collect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,60 +52,117 @@ function extractParamsFromQueryString(requestUrl: string): {
}

export function collectRequestHandler(request: Request, env: Env) {
const params = extractParamsFromQueryString(request.url);

const userAgent = request.headers.get("user-agent") || undefined;
const parsedUserAgent = new UAParser(userAgent);

parsedUserAgent.getBrowser().name;

const { newVisitor, newSession } = checkVisitorSession(
request.headers.get("if-modified-since"),
);

const data: DataPoint = {
siteId: params.sid,
host: params.h,
path: params.p,
referrer: params.r,
newVisitor: newVisitor ? 1 : 0,
newSession: newSession ? 1 : 0,
// user agent stuff
userAgent: userAgent,
browserName: parsedUserAgent.getBrowser().name,
deviceModel: parsedUserAgent.getDevice().model,
};

// NOTE: location is derived from Cloudflare-specific request properties
// see: https://developers.cloudflare.com/workers/runtime-apis/request/#incomingrequestcfproperties
const country = (request as RequestInit).cf?.country;
if (typeof country === "string") {
data.country = country;
}

writeDataPoint(env.WEB_COUNTER_AE, data);

// encode 1x1 transparent gif
const gif = "R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
const gifData = atob(gif);
const gifLength = gifData.length;
const arrayBuffer = new ArrayBuffer(gifLength);
const uintArray = new Uint8Array(arrayBuffer);
for (let i = 0; i < gifLength; i++) {
uintArray[i] = gifData.charCodeAt(i);
switch (request.method) {
case "GET": {
const params = extractParamsFromQueryString(request.url);

const userAgent = request.headers.get("user-agent") || undefined;
const parsedUserAgent = new UAParser(userAgent);

parsedUserAgent.getBrowser().name;

const { newVisitor, newSession } = checkVisitorSession(
request.headers.get("if-modified-since"),
);

const data: DataPoint = {
siteId: params.sid,
host: params.h,
path: params.p,
referrer: params.r,
newVisitor: newVisitor ? 1 : 0,
newSession: newSession ? 1 : 0,
// user agent stuff
userAgent: userAgent,
browserName: parsedUserAgent.getBrowser().name,
deviceModel: parsedUserAgent.getDevice().model,
};

// NOTE: location is derived from Cloudflare-specific request properties
// see: https://developers.cloudflare.com/workers/runtime-apis/request/#incomingrequestcfproperties
const country = (request as RequestInit).cf?.country;
if (typeof country === "string") {
data.country = country;
}

writeDataPoint(env.WEB_COUNTER_AE, data);

// encode 1x1 transparent gif
const gif =
"R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
const gifData = atob(gif);
const gifLength = gifData.length;
const arrayBuffer = new ArrayBuffer(gifLength);
const uintArray = new Uint8Array(arrayBuffer);
for (let i = 0; i < gifLength; i++) {
uintArray[i] = gifData.charCodeAt(i);
}

return new Response(arrayBuffer, {
headers: {
"Content-Type": "image/gif",
Expires: "Mon, 01 Jan 1990 00:00:00 GMT",
"Cache-Control": "no-cache",
Pragma: "no-cache",
"Last-Modified": new Date().toUTCString(),
Tk: "N", // not tracking
},
status: 200,
});
}
case "POST": {
const body: PostRequestBody =
request.json() as unknown as PostRequestBody;
if (!body) {
return new Response("Invalid request", { status: 400 });
}

const userAgent =
body.ua || request.headers.get("user-agent") || undefined;
const parsedUserAgent = new UAParser(userAgent);
parsedUserAgent.getBrowser().name;

const ifModifiedSince =
body.ims || request.headers.get("if-modified-since");
const { newVisitor, newSession } =
checkVisitorSession(ifModifiedSince);

const data: DataPoint = {
siteId: body.sid,
host: body.h,
userAgent: body.ua,
path: body.p,
country: body.c,
referrer: body.r,
browserName: body.bn || parsedUserAgent.getBrowser().name,
deviceModel: body.dm || parsedUserAgent.getDevice().model,
newVisitor: newVisitor ? 1 : 0,
newSession: newSession ? 1 : 0,
};

writeDataPoint(env.WEB_COUNTER_AE, data);

return new Response("OK", { status: 200 });
}
default: {
return new Response("Method not allowed", {
status: 405,
statusText: "Method not allowed",
});
}
}
}

return new Response(arrayBuffer, {
headers: {
"Content-Type": "image/gif",
Expires: "Mon, 01 Jan 1990 00:00:00 GMT",
"Cache-Control": "no-cache",
Pragma: "no-cache",
"Last-Modified": new Date().toUTCString(),
Tk: "N", // not tracking
},
status: 200,
});
interface PostRequestBody {
sid?: string; // site id
h?: string; // host
ua?: string; // user agent
p?: string; // path
c?: string; // country
r?: string; // referrer
bn?: string; // browser name
dm?: string; // device model
ims?: string; // if modified since
}

interface DataPoint {
Expand Down