* Persist a sanitized batch: one `events` row per lifecycle event, usage counters * added into `usage_daily`, plus the machine×day and first-seen bookkeeping the * dashboard's retention/activation panels need. One D1 `batch()` = one implicit * transaction = one round trip. * * Fail-silent by de
( env: Env, machineId: string, common: JsonObject, batch: StoredEvent[], )
| 315 | * logged (Workers Logs) with counts only — never the payload. |
| 316 | */ |
| 317 | async function writeToD1( |
| 318 | env: Env, |
| 319 | machineId: string, |
| 320 | common: JsonObject, |
| 321 | batch: StoredEvent[], |
| 322 | ): Promise<void> { |
| 323 | try { |
| 324 | const receivedAt = new Date().toISOString(); |
| 325 | const insertEvent = env.DB.prepare(INSERT_EVENT); |
| 326 | const stmts: D1PreparedStatement[] = []; |
| 327 | // Envelope columns are identical for every row in the batch. |
| 328 | const envelopeCols = [ |
| 329 | asText(common.codegraph_version), |
| 330 | asText(common.os), |
| 331 | asText(common.arch), |
| 332 | asInt(common.node_major), |
| 333 | asFlag(common.ci), |
| 334 | asInt(common.schema_version), |
| 335 | ] as const; |
| 336 | // A batch can span days (offline buffers hold completed-day rollups), so |
| 337 | // machine_days gets one row per distinct day rather than one per batch. |
| 338 | const days = new Set<string>(); |
| 339 | |
| 340 | // The proof of install this batch carries, each kind by its earliest day. |
| 341 | const proof: { fresh: string | null; agent: string | null; upgrade: string | null } = { |
| 342 | fresh: null, |
| 343 | agent: null, |
| 344 | upgrade: null, |
| 345 | }; |
| 346 | const shows = (kind: keyof typeof proof, day: string): void => { |
| 347 | const known = proof[kind]; |
| 348 | if (known === null || day < known) proof[kind] = day; |
| 349 | }; |
| 350 | |
| 351 | const usage = batch.filter((e) => e.event === 'usage_rollup'); |
| 352 | if (usage.length > 0) { |
| 353 | const upsertUsage = env.DB.prepare(UPSERT_USAGE); |
| 354 | const [version, os, arch, nodeMajor] = envelopeCols; |
| 355 | for (const u of foldUsage(usage, receivedAt)) { |
| 356 | days.add(u.day); |
| 357 | if (isAgentRun(u.kind, u.name)) shows('agent', u.day); |
| 358 | if (isUpgradeRun(u.kind, u.name)) shows('upgrade', u.day); |
| 359 | stmts.push( |
| 360 | upsertUsage.bind( |
| 361 | u.day, |
| 362 | machineId, |
| 363 | u.kind, |
| 364 | u.name, |
| 365 | u.clientName, |
| 366 | u.clientVersion, |
| 367 | version ?? '', |
| 368 | os ?? '', |
| 369 | arch ?? '', |
| 370 | nodeMajor === null ? '' : String(nodeMajor), |
| 371 | u.count, |
| 372 | u.errors, |
| 373 | ), |
| 374 | ); |
no test coverage detected