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

Function foldLegacyUsage

telemetry-worker/src/rollup.ts:339–368  ·  view source on GitHub ↗
(
  env: Env,
  day: string,
  deadline = Number.POSITIVE_INFINITY,
)

Source from the content-addressed store, hash-verified

337 * loses nothing and the next call simply continues.
338 */
339export async function foldLegacyUsage(
340 env: Env,
341 day: string,
342 deadline = Number.POSITIVE_INFINITY,
343): Promise<FoldResult> {
344 const any = await env.DB.prepare(`SELECT 1 AS hit FROM events WHERE day = ? AND event = 'usage_rollup' LIMIT 1`)
345 .bind(day)
346 .first<{ hit: number }>();
347 if (!any) return { moved: 0, complete: true };
348
349 let moved = 0;
350 for (let chunk = 0; chunk < LEGACY_MAX_CHUNKS; chunk++) {
351 if (Date.now() >= deadline) return { moved, complete: false };
352 // Always the oldest remaining rows: everything below the next chunk's first id.
353 // Rows folded by earlier chunks are gone, so there is no cursor to carry.
354 const next = await env.DB.prepare(
355 `SELECT id FROM events WHERE day = ? AND event = 'usage_rollup' ORDER BY id LIMIT 1 OFFSET ${LEGACY_CHUNK_ROWS}`,
356 )
357 .bind(day)
358 .first<{ id: number }>();
359 const below = next?.id ?? Number.MAX_SAFE_INTEGER;
360 const [, deleted] = await env.DB.batch([
361 env.DB.prepare(LEGACY_FOLD).bind(day, below),
362 env.DB.prepare(LEGACY_DELETE).bind(day, below),
363 ]);
364 moved += deleted?.meta?.changes ?? 0;
365 if (!next) return { moved, complete: true };
366 }
367 throw new Error(`legacy usage fold for ${day} did not finish within ${LEGACY_MAX_CHUNKS} chunks`);
368}
369
370export interface PurgeResult {
371 /** Everything strictly before this day was deleted. */

Callers 1

rollupDayFunction · 0.85

Calls 3

bindMethod · 0.80
batchMethod · 0.80
prepareMethod · 0.65

Tested by

no test coverage detected