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