(env: Env, url: URL, range: Range)
| 445 | }; |
| 446 | |
| 447 | async function timeseries(env: Env, url: URL, range: Range): Promise<ApiResult> { |
| 448 | const metric = url.searchParams.get('metric') ?? 'installs_uninstalls'; |
| 449 | |
| 450 | // The one metric whose series are data-driven rather than fixed: one line per |
| 451 | // duration bucket, in bucket order (an ordered scale, so the order is meaning). |
| 452 | if (metric === 'duration_buckets') return durationBucketSeries(env, range); |
| 453 | |
| 454 | const spec = SERIES[metric]; |
| 455 | if (!spec) { |
| 456 | return fail(`unknown metric — one of: ${[...Object.keys(SERIES), 'duration_buckets'].join(', ')}`); |
| 457 | } |
| 458 | |
| 459 | const batch = await env.DB.batch([ |
| 460 | env.DB.prepare(spec.sql).bind(...spec.binds(range)), |
| 461 | env.DB.prepare(COVERAGE_SQL), |
| 462 | ]); |
| 463 | const results = rowsOf<DayValueRow>(batch[0]); |
| 464 | const coveredThrough = spec.live ? null : (firstOf<{ day: string | null }>(batch[1])?.day ?? null); |
| 465 | |
| 466 | const labels = dayList(range); |
| 467 | const a = new Map<string, number>(); |
| 468 | const b = new Map<string, number>(); |
| 469 | for (const row of results) { |
| 470 | a.set(row.day, row.a ?? 0); |
| 471 | b.set(row.day, row.b ?? 0); |
| 472 | } |
| 473 | |
| 474 | const fill = (byDay: Map<string, number>): (number | null)[] => |
| 475 | spec.live ? densify(labels, byDay) : densifyCovered(labels, byDay, coveredThrough); |
| 476 | const datasets = [{ label: spec.labels[0], data: fill(a) }]; |
| 477 | if (spec.labels.length === 2) datasets.push({ label: spec.labels[1], data: fill(b) }); |
| 478 | |
| 479 | return { |
| 480 | body: { |
| 481 | range, |
| 482 | metric, |
| 483 | title: spec.title, |
| 484 | /** Last day with real numbers; null for a live series, which runs through today. */ |
| 485 | covered_through: spec.live ? null : coveredThrough, |
| 486 | labels, |
| 487 | datasets, |
| 488 | rows: labels.map((day, i) => ({ |
| 489 | day, |
| 490 | ...Object.fromEntries(datasets.map((d) => [d.label, d.data[i] ?? null])), |
| 491 | })), |
| 492 | }, |
| 493 | cacheControl: CACHE_CONTROL, |
| 494 | }; |
| 495 | } |
| 496 | |
| 497 | /** "Session run length over time": one series per duration bucket, bucket-ordered. */ |
| 498 | async function durationBucketSeries(env: Env, range: Range): Promise<ApiResult> { |
no test coverage detected