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

Function fetch

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

Source from the content-addressed store, hash-verified

429
430export default {
431 async fetch(request, env, ctx): Promise<Response> {
432 try {
433 const url = new URL(request.url);
434
435 if (request.method === 'GET' && url.pathname === '/') {
436 return new Response(infoText(retentionDays(env)), {
437 headers: { 'content-type': 'text/plain; charset=utf-8' },
438 });
439 }
440 // Backfill/repair for the nightly rollup. 404s unless ADMIN_TOKEN is configured.
441 if (url.pathname === '/admin/rollup') {
442 return await handleAdminRollup(request, env, url);
443 }
444 if (url.pathname !== '/v1/events') {
445 return new Response('not found\n', { status: 404 });
446 }
447 if (request.method !== 'POST') {
448 return new Response('method not allowed\n', { status: 405, headers: { allow: 'POST' } });
449 }
450
451 const contentLength = Number(request.headers.get('content-length'));
452 if (!Number.isFinite(contentLength) || contentLength <= 0) {
453 return new Response('length required\n', { status: 411 });
454 }
455 if (contentLength > MAX_BODY_BYTES) {
456 return new Response('payload too large\n', { status: 413 });
457 }
458
459 let body: JsonObject;
460 try {
461 const text = await request.text();
462 if (text.length > MAX_BODY_BYTES) return new Response('payload too large\n', { status: 413 });
463 const parsed: unknown = JSON.parse(text);
464 if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
465 return new Response('bad request\n', { status: 400 });
466 }
467 body = parsed as JsonObject;
468 } catch {
469 return new Response('bad request\n', { status: 400 });
470 }
471
472 const machineId = body.machine_id;
473 if (typeof machineId !== 'string' || !UUID_RE.test(machineId)) {
474 return new Response('bad request\n', { status: 400 });
475 }
476
477 // Best-effort rate limit; fails open — losing a data point beats losing availability.
478 try {
479 const { success } = await env.MACHINE_RATE_LIMITER.limit({ key: machineId });
480 if (!success) return new Response('rate limited\n', { status: 429 });
481 } catch (err) {
482 console.error(JSON.stringify({ msg: 'rate limiter unavailable', err: String(err) }));
483 }
484
485 const common: JsonObject = {};
486 for (const [key, sanitize] of Object.entries(ENVELOPE_PROPS)) {
487 const val = sanitize(body[key]);
488 if (val !== undefined) common[key] = val;

Callers 3

realFileProjectsFunction · 0.50
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