* 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[], )
| 267 | * logged (Workers Logs) with counts only — never the payload. |
| 268 | */ |
| 269 | async function writeToD1( |
| 270 | env: Env, |
| 271 | machineId: string, |
| 272 | common: JsonObject, |
| 273 | batch: StoredEvent[], |
| 274 | ): Promise<void> { |
| 275 | try { |
| 276 | const receivedAt = new Date().toISOString(); |
| 277 | const insertEvent = env.DB.prepare(INSERT_EVENT); |
| 278 | const stmts: D1PreparedStatement[] = []; |
| 279 | // Envelope columns are identical for every row in the batch. |
| 280 | const envelopeCols = [ |
| 281 | asText(common.codegraph_version), |
| 282 | asText(common.os), |
| 283 | asText(common.arch), |
| 284 | asInt(common.node_major), |
| 285 | asFlag(common.ci), |
| 286 | asInt(common.schema_version), |
| 287 | ] as const; |
| 288 | // A batch can span days (offline buffers hold completed-day rollups), so |
| 289 | // machine_days gets one row per distinct day rather than one per batch. |
| 290 | const days = new Set<string>(); |
| 291 | |
| 292 | const usage = batch.filter((e) => e.event === 'usage_rollup'); |
| 293 | if (usage.length > 0) { |
| 294 | const upsertUsage = env.DB.prepare(UPSERT_USAGE); |
| 295 | const [version, os, arch, nodeMajor] = envelopeCols; |
| 296 | for (const u of foldUsage(usage, receivedAt)) { |
| 297 | days.add(u.day); |
| 298 | stmts.push( |
| 299 | upsertUsage.bind( |
| 300 | u.day, |
| 301 | machineId, |
| 302 | u.kind, |
| 303 | u.name, |
| 304 | u.clientName, |
| 305 | u.clientVersion, |
| 306 | version ?? '', |
| 307 | os ?? '', |
| 308 | arch ?? '', |
| 309 | nodeMajor === null ? '' : String(nodeMajor), |
| 310 | u.count, |
| 311 | u.errors, |
| 312 | ), |
| 313 | ); |
| 314 | } |
| 315 | } |
| 316 | |
| 317 | // The earliest day this batch indexed on, if it did — see UPSERT_FIRST_SEEN. |
| 318 | let firstIndexDay: string | null = null; |
| 319 | for (const e of batch) { |
| 320 | if (e.event === 'usage_rollup') continue; |
| 321 | const day = (e.ts ?? receivedAt).slice(0, 10); |
| 322 | days.add(day); |
| 323 | if (e.event === 'index' && (firstIndexDay === null || day < firstIndexDay)) firstIndexDay = day; |
| 324 | stmts.push( |
| 325 | insertEvent.bind( |
| 326 | receivedAt, |