返回 CodeWhale
index.ts
根目录 / telemetry-ingest / src / index.ts
1 /**
2 * Codewhale first-party telemetry ingest.
3 *
4 * ============================ THE RED LINE ============================
5 *
6 * THIS WORKER NEVER READS, LOGS, STORES, OR FORWARDS THE CLIENT IP.
7 *
8 * `docs/TELEMETRY.md` publishes "Batches are IP-stripped at ingest. No IP is
9 * stored, logged, or joined to `install_id`." This file is the whole of what
10 * makes that sentence true. There is no other component. If you add an IP read
11 * here, the published document becomes a false statement about a shipped
12 * product, and every user who opted in did so on the strength of it.
13 *
14 * Concretely, and permanently:
15 *
16 * - Do not read the connecting-address header, the proxy-chain header, or any
17 * other header that carries a network address. The names are deliberately
18 * spelled nowhere in this directory: `test/no-ip.test.ts` greps the source
19 * for them and fails the build, so an edit that adds one cannot land quietly
20 * and cannot be justified as "just for debugging".
21 * - Do not read the `cf` property of the request. Country, colo, city, region,
22 * ASN, and coordinates all live there; none of them are in the schema, and
23 * the same test greps for that access too.
24 * - Read exactly two headers, ever: `content-type` and `content-length`. The
25 * same test extracts every header name this source asks for and fails if the
26 * set grows.
27 * - Do not log the request. Structured logs in Workers are queryable, and a
28 * log line is storage. Nothing in this file logs a payload or a header.
29 * - Analytics Engine rows are built in `datapoint.ts` from the *validated
30 * batch body only*. The request object is not in scope there.
31 *
32 * Debugging without an IP is a solved problem: the schema carries `os`, `arch`,
33 * `libc`, `surface`, `app_version`, and `git_sha`, which is what a crash triage
34 * actually needs. If you find yourself wanting the IP, you want a different
35 * feature, and it needs the owner's sign-off and a doc change first.
36 *
37 * ======================================================================
38 *
39 * Shape of the service: write-only. One POST route, no GET that returns data,
40 * no response body on any path, ever. The client
41 * (`crates/telemetry/src/client.rs`) reads only the status class and drops the
42 * batch on anything that is not 2xx — no retry, no backoff, no re-queue — so a
43 * rejection here is invisible to the user by construction, and a 5xx can never
44 * become a client-visible error. That is what lets this endpoint fail closed:
45 * when in doubt, refuse the batch.
46 */
47
48 import { writeBatch, type DataPointSink } from "./datapoint";
49 import { INGEST_PATH } from "./route";
50 import { MAX_BODY_BYTES, validateBatch } from "./schema";
51
52 /**
53 * Rate-limit binding shape (`ratelimits` in `wrangler.jsonc`).
54 *
55 * Note that this module exports exactly one value — the default handler. The
56 * Workers runtime maps every *named* export of the entrypoint to an entrypoint
57 * of its own and refuses to start when one is not callable. Interfaces are
58 * erased at build time, so these cost nothing; a constant would not.
59 */
60 export interface RateLimiter {
61 limit(options: { key: string }): Promise<{ success: boolean }>;
62 }
63
64 export interface Env {
65 /** `analytics_engine_datasets` binding. */
66 TELEMETRY: DataPointSink;
67 /**
68 * Optional per-location ingest rate limiter keyed on the server-controlled
69 * route path (`INGEST_PATH`) before body reading, parsing, or downstream
70 * delivery. Caps aggregate throughput even when a caller rotates `install_id`
71 * on every request, without reading any client IP or network header.
72 */
73 INGEST_RATE_LIMITER?: RateLimiter;
74 /**
75 * Optional per-install rate limiter.
76 *
77 * Keyed on `install_id` — the identifier the batch already carries — and
78 * never on a network address. Known limitation: `install_id` is caller-
79 * supplied and can be rotated between POSTs; `INGEST_RATE_LIMITER` above and
80 * Cloudflare edge rules provide the rotation-resistant cap so this Worker
81 * never handles IPs.
82 */
83 RATE_LIMITER?: RateLimiter;
84 }
85
86 /** Every response is a bare status. No body, no echo of the payload, ever. */
87 function status(code: number, headers?: HeadersInit): Response {
88 return new Response(null, { status: code, headers });
89 }
90
91 /**
92 * Read at most `limit` bytes, aborting the stream the moment it goes over.
93 *
94 * `content-length` is checked first as a cheap reject, but it is client-supplied
95 * and may be absent or wrong, so the real bound is enforced while reading.
96 * Returns `null` when the body is missing or too large.
97 */
98 async function readBounded(
99 body: ReadableStream<Uint8Array> | null,
100 limit: number,
101 ): Promise<Uint8Array | null> {
102 if (body === null) return null;
103 const reader = body.getReader();
104 const chunks: Uint8Array[] = [];
105 let total = 0;
106 try {
107 for (;;) {
108 const { done, value } = await reader.read();
109 if (done) break;
110 if (value === undefined) continue;
111 total += value.byteLength;
112 if (total > limit) {
113 await reader.cancel();
114 return null;
115 }
116 chunks.push(value);
117 }
118 } finally {
119 reader.releaseLock();
120 }
121 const joined = new Uint8Array(total);
122 let offset = 0;
123 for (const chunk of chunks) {
124 joined.set(chunk, offset);
125 offset += chunk.byteLength;
126 }
127 return joined;
128 }
129
130 async function ingest(request: Request, env: Env): Promise<Response> {
131 // Method before path, so a probe of any path with any verb other than POST
132 // gets the same answer and learns nothing about what exists here.
133 if (request.method !== "POST") {
134 return status(405, { allow: "POST" });
135 }
136 if (new URL(request.url).pathname !== INGEST_PATH) {
137 return status(404);
138 }
139
140 // Header read #1 of 2. `client.rs` sends exactly `application/json`.
141 const contentType = request.headers.get("content-type") ?? "";
142 if (!contentType.toLowerCase().startsWith("application/json")) {
143 return status(415);
144 }
145
146 // Header read #2 of 2, and the last. See the red line above.
147 const declared = request.headers.get("content-length");
148 if (declared !== null) {
149 const length = Number(declared);
150 if (!Number.isFinite(length) || length > MAX_BODY_BYTES) {
151 return status(413);
152 }
153 }
154
155 if (env.INGEST_RATE_LIMITER !== undefined) {
156 const { success } = await env.INGEST_RATE_LIMITER.limit({
157 key: INGEST_PATH,
158 });
159 if (!success) return status(429);
160 }
161
162 const raw = await readBounded(request.body, MAX_BODY_BYTES);
163 if (raw === null) return status(413);
164
165 let text: string;
166 try {
167 text = new TextDecoder("utf-8", { fatal: true }).decode(raw);
168 } catch {
169 return status(400);
170 }
171
172 let parsed: unknown;
173 try {
174 parsed = JSON.parse(text);
175 } catch {
176 return status(400);
177 }
178
179 // The closed-field-set check. An unexpected key anywhere rejects the whole
180 // batch: a future client bug that starts attaching a path or a prompt must be
181 // refused by the server rather than quietly stored. The reason string stays
182 // here — the response carries no body, because a parse error echoed back is a
183 // way to learn what this endpoint keeps.
184 const result = validateBatch(parsed);
185 if (!result.ok) return status(400);
186
187 // Rate limiting is keyed on the install id the batch already carries. It runs
188 // after validation because that is the only way to have a non-network key.
189 if (env.RATE_LIMITER !== undefined) {
190 const { success } = await env.RATE_LIMITER.limit({
191 key: result.batch.install_id,
192 });
193 if (!success) return status(429);
194 }
195
196 // `writeDataPoint` is non-blocking and returns void; it is never awaited.
197 writeBatch(env.TELEMETRY, result.batch);
198
199 return status(204);
200 }
201
202 export default {
203 async fetch(request: Request, env: Env): Promise<Response> {
204 try {
205 return await ingest(request, env);
206 } catch {
207 // Fail closed and quiet. Nothing is written, nothing is logged, and the
208 // response has no body. The client treats any non-2xx as "dropped" and
209 // surfaces nothing to the user, so a 5xx here costs one batch and never
210 // becomes a user-visible error.
211 return status(500);
212 }
213 },
214 };
215
215 lines TYPESCRIPT