(request, env, ctx)
| 429 | |
| 430 | export 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; |
no test coverage detected