MCPcopy Create free account
hub / github.com/colbymchenry/codegraph / fetch

Function fetch

telemetry-worker/src/index.ts:353–432  ·  view source on GitHub ↗
(request, env, ctx)

Source from the content-addressed store, hash-verified

351
352export default {
353 async fetch(request, env, ctx): Promise<Response> {
354 try {
355 const url = new URL(request.url);
356
357 if (request.method === 'GET' && url.pathname === '/') {
358 return new Response(infoText(retentionDays(env)), {
359 headers: { 'content-type': 'text/plain; charset=utf-8' },
360 });
361 }
362 // Backfill/repair for the nightly rollup. 404s unless ADMIN_TOKEN is configured.
363 if (url.pathname === '/admin/rollup') {
364 return await handleAdminRollup(request, env, url);
365 }
366 if (url.pathname !== '/v1/events') {
367 return new Response('not found\n', { status: 404 });
368 }
369 if (request.method !== 'POST') {
370 return new Response('method not allowed\n', { status: 405, headers: { allow: 'POST' } });
371 }
372
373 const contentLength = Number(request.headers.get('content-length'));
374 if (!Number.isFinite(contentLength) || contentLength <= 0) {
375 return new Response('length required\n', { status: 411 });
376 }
377 if (contentLength > MAX_BODY_BYTES) {
378 return new Response('payload too large\n', { status: 413 });
379 }
380
381 let body: JsonObject;
382 try {
383 const text = await request.text();
384 if (text.length > MAX_BODY_BYTES) return new Response('payload too large\n', { status: 413 });
385 const parsed: unknown = JSON.parse(text);
386 if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
387 return new Response('bad request\n', { status: 400 });
388 }
389 body = parsed as JsonObject;
390 } catch {
391 return new Response('bad request\n', { status: 400 });
392 }
393
394 const machineId = body.machine_id;
395 if (typeof machineId !== 'string' || !UUID_RE.test(machineId)) {
396 return new Response('bad request\n', { status: 400 });
397 }
398
399 // Best-effort rate limit; fails open — losing a data point beats losing availability.
400 try {
401 const { success } = await env.MACHINE_RATE_LIMITER.limit({ key: machineId });
402 if (!success) return new Response('rate limited\n', { status: 429 });
403 } catch (err) {
404 console.error(JSON.stringify({ msg: 'rate limiter unavailable', err: String(err) }));
405 }
406
407 const common: JsonObject = {};
408 for (const [key, sanitize] of Object.entries(ENVELOPE_PROPS)) {
409 const val = sanitize(body[key]);
410 if (val !== undefined) common[key] = val;

Callers 2

fetchStarsFunction · 0.50
runMethod · 0.50

Calls 11

retentionDaysFunction · 0.90
handleAdminRollupFunction · 0.90
infoTextFunction · 0.85
NumberInterface · 0.85
sanitizeEventFunction · 0.85
writeToD1Function · 0.85
parseMethod · 0.80
pushMethod · 0.80
getMethod · 0.65
textMethod · 0.65
errorMethod · 0.65

Tested by

no test coverage detected