@hot-updater/firebase 1.2.0-rc.57 → 1.2.0-rc.59

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -531,14 +531,14 @@ function modularInverse(value, modulus) {
531
531
  if (r > 1) throw new Error(`No modular inverse for ${value} mod ${modulus}`);
532
532
  return positiveMod(t, modulus);
533
533
  }
534
- function getRolloutShuffleParameters(bundleId) {
535
- let multiplier = positiveMod(hashString(`${bundleId}:multiplier`), 997);
534
+ function getRolloutShuffleParameters(releaseId) {
535
+ let multiplier = positiveMod(hashString(`${releaseId}:multiplier`), 997);
536
536
  if (multiplier === 0) multiplier = 1;
537
537
  while (gcd(multiplier, NUMERIC_COHORT_SIZE) !== 1) {
538
538
  multiplier = positiveMod(multiplier + 1, NUMERIC_COHORT_SIZE);
539
539
  if (multiplier === 0) multiplier = 1;
540
540
  }
541
- const offset = positiveMod(hashString(`${bundleId}:offset`), NUMERIC_COHORT_SIZE);
541
+ const offset = positiveMod(hashString(`${releaseId}:offset`), NUMERIC_COHORT_SIZE);
542
542
  return {
543
543
  multiplier,
544
544
  offset,
@@ -571,16 +571,16 @@ function isValidCohort(cohort) {
571
571
  const normalized = normalizeCohortValue(cohort);
572
572
  return isNumericCohort(normalized) || isCustomCohort(normalized);
573
573
  }
574
- function getNumericCohortRolloutPosition(bundleId, cohortValue) {
574
+ function getNumericCohortRolloutPosition(releaseId, cohortValue) {
575
575
  if (cohortValue < 1 || cohortValue > 1e3) throw new Error(`Invalid numeric cohort: ${cohortValue}`);
576
- const { offset, inverseMultiplier } = getRolloutShuffleParameters(bundleId);
576
+ const { offset, inverseMultiplier } = getRolloutShuffleParameters(releaseId);
577
577
  return positiveMod(inverseMultiplier * (cohortValue - 1 - offset), NUMERIC_COHORT_SIZE);
578
578
  }
579
- function getRolledOutNumericCohorts(bundleId, rolloutCohortCount) {
579
+ function getRolledOutNumericCohorts(releaseId, rolloutCohortCount) {
580
580
  const normalizedRolloutCount = normalizeRolloutCohortCount(rolloutCohortCount);
581
581
  if (normalizedRolloutCount <= 0) return [];
582
582
  if (normalizedRolloutCount >= 1e3) return Array.from({ length: NUMERIC_COHORT_SIZE }, (_, index) => index + 1);
583
- const { multiplier, offset } = getRolloutShuffleParameters(bundleId);
583
+ const { multiplier, offset } = getRolloutShuffleParameters(releaseId);
584
584
  return Array.from({ length: normalizedRolloutCount }, (_, position) => positiveMod(multiplier * position + offset, NUMERIC_COHORT_SIZE)).map((zeroBasedCohort) => zeroBasedCohort + 1).sort((left, right) => left - right);
585
585
  }
586
586
  const RELEASE_CATALOG_FALLBACK_POLICY = "BUILTIN_IF_ACTIVE_INELIGIBLE";
@@ -3286,7 +3286,7 @@ const build = (changes, current) => {
3286
3286
  return changes.map((change, at) => rewrites(change) ? rewrite(change, keys[at], current.get(rowId(change.model, keys[at])) ?? null) : increment(change, keys[at]));
3287
3287
  };
3288
3288
  const isOp = (op) => op !== void 0;
3289
- const sleep = (attempt) => new Promise((resolve) => setTimeout(resolve, Math.min(250, 5 * 2 ** attempt) * Math.random()));
3289
+ const sleep$2 = (attempt) => new Promise((resolve) => setTimeout(resolve, Math.min(250, 5 * 2 ** attempt) * Math.random()));
3290
3290
  /** Runs of one character, where shorter: a sparse sketch packs into a few. */
3291
3291
  const pack = (text) => {
3292
3292
  const runs = (text.match(/(.)\1*/gsu) ?? []).flatMap((run) => [run[0], run.length]);
@@ -3435,7 +3435,7 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { windowMs
3435
3435
  const result = await adapter.write(ops);
3436
3436
  if (result.ok) return true;
3437
3437
  if (!("retry" in result)) return false;
3438
- await sleep(failures);
3438
+ await sleep$2(failures);
3439
3439
  }
3440
3440
  return false;
3441
3441
  };
@@ -4449,6 +4449,7 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
4449
4449
  let negative;
4450
4450
  let failures = 0;
4451
4451
  let lost;
4452
+ let busy = false;
4452
4453
  for (let round = 0;; round += 1) {
4453
4454
  const delay = round && Math.min(maxDelayMs, baseDelayMs * 2 ** (round - 1));
4454
4455
  if (delay > 0) await new Promise((resolve) => setTimeout(resolve, delay / 2 + Math.random() * (delay / 2)));
@@ -4459,6 +4460,7 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
4459
4460
  if (run === void 0) {
4460
4461
  onRetry?.("rerun", round + 1);
4461
4462
  lost = void 0;
4463
+ busy = false;
4462
4464
  if ((failures += 1) >= attempts) break;
4463
4465
  continue;
4464
4466
  }
@@ -4469,6 +4471,7 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
4469
4471
  if (!(error instanceof NegativeGaugeError)) throw error;
4470
4472
  negative = error;
4471
4473
  onRetry?.("rerun", round + 1);
4474
+ busy = false;
4472
4475
  run = void 0;
4473
4476
  lost = void 0;
4474
4477
  if ((failures += 1) >= attempts) break;
@@ -4489,6 +4492,7 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
4489
4492
  }
4490
4493
  if (outcome.ok) return run.result;
4491
4494
  const failed = "failedOp" in outcome ? outcome.failedOp : void 0;
4495
+ busy = failed === void 0;
4492
4496
  if (failed === void 0 || failed >= run.ops.length) {
4493
4497
  onRetry?.("resend", round + 1);
4494
4498
  failures += 1;
@@ -4502,7 +4506,7 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
4502
4506
  run = void 0;
4503
4507
  if ((failures += 1) >= attempts) break;
4504
4508
  }
4505
- throw negative ?? new DatabaseConflictError(`The transaction conflicted ${attempts} times.`);
4509
+ throw negative ?? new DatabaseConflictError(busy ? `The database stayed busy through ${attempts} attempts of the transaction, as a store does at its throughput limit.` : `The transaction conflicted ${attempts} times.`);
4506
4510
  } };
4507
4511
  };
4508
4512
  //#endregion
@@ -5199,7 +5203,7 @@ const createKvAdapter = ({ store, tablePrefix = "" }) => {
5199
5203
  };
5200
5204
  //#endregion
5201
5205
  //#region ../../packages/server/dist/version.mjs
5202
- const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.57";
5206
+ const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.59";
5203
5207
  //#endregion
5204
5208
  //#region ../../packages/server/dist/handlerVersionRoutes.mjs
5205
5209
  /**
@@ -5998,7 +6002,7 @@ const baseBundleIdsOf = (row, range, bundleId, limit) => {
5998
6002
  };
5999
6003
  //#endregion
6000
6004
  //#region ../../packages/server/dist/core/reads.mjs
6001
- const PAGE$4 = 500;
6005
+ const PAGE$5 = 500;
6002
6006
  const pick$2 = (fields) => (row) => Object.fromEntries(fields.map((field) => [field, row[field]]));
6003
6007
  const toBundleRow = pick$2([
6004
6008
  "id",
@@ -6095,7 +6099,7 @@ const createCoreReads = (db, storage) => {
6095
6099
  const page = await db.findMany("bundle_patches", {
6096
6100
  index: "byBundle",
6097
6101
  where: { bundle_id: row.id },
6098
- limit: Math.min(count - patches.length, PAGE$4),
6102
+ limit: Math.min(count - patches.length, PAGE$5),
6099
6103
  ...cursor === void 0 ? {} : { cursor }
6100
6104
  });
6101
6105
  patches.push(...page.rows.map(toPatchRow));
@@ -6321,7 +6325,7 @@ const createCoreReads = (db, storage) => {
6321
6325
  return (await drain$1((page) => db.findMany("channels", {
6322
6326
  index: "all",
6323
6327
  where: {},
6324
- limit: PAGE$4,
6328
+ limit: PAGE$5,
6325
6329
  ...page
6326
6330
  }))).map(toChannelRow);
6327
6331
  },
@@ -6716,7 +6720,10 @@ const createLabelAllocator = (tx, used, caughtUp) => {
6716
6720
  };
6717
6721
  };
6718
6722
  const FILL_BATCH = 25;
6719
- const PAGE$3 = 500;
6723
+ const PAGE$4 = 500;
6724
+ const PAUSE_MS$1 = 1e3;
6725
+ const MAX_PAUSE_MS$1 = 32e3;
6726
+ const sleep$1 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
6720
6727
  /**
6721
6728
  * Labels a channel and platform's releases that have none, in ID order,
6722
6729
  * which is the order they were created in, and marks its counter filled:
@@ -6728,6 +6735,7 @@ const fillLabels = async (db, { channelId, platform }, { dryRun = false } = {})
6728
6735
  const id = labelSequenceId(channelId, platform);
6729
6736
  let labeled = 0;
6730
6737
  let batchSize = FILL_BATCH;
6738
+ let paused = 0;
6731
6739
  const label = async (ids) => {
6732
6740
  for (let at = 0; at < ids.length;) {
6733
6741
  const batch = ids.slice(at, at + batchSize);
@@ -6752,12 +6760,16 @@ const fillLabels = async (db, { channelId, platform }, { dryRun = false } = {})
6752
6760
  return count;
6753
6761
  });
6754
6762
  at += batch.length;
6763
+ paused = 0;
6755
6764
  } catch (error) {
6756
6765
  if (batchSize > 1 && error instanceof DatabaseConstraintError && error.reason === "too_large") {
6757
6766
  batchSize = Math.max(1, Math.floor(batchSize / 2));
6758
6767
  continue;
6759
6768
  }
6760
- throw error;
6769
+ if (!isDatabaseBusyError(error) || paused >= MAX_PAUSE_MS$1) throw error;
6770
+ batchSize = Math.max(1, Math.floor(batchSize / 2));
6771
+ paused = paused === 0 ? PAUSE_MS$1 : paused * 2;
6772
+ await sleep$1(paused);
6761
6773
  }
6762
6774
  }
6763
6775
  };
@@ -6769,7 +6781,7 @@ const fillLabels = async (db, { channelId, platform }, { dryRun = false } = {})
6769
6781
  channel_id: channelId,
6770
6782
  platform
6771
6783
  },
6772
- limit: PAGE$3,
6784
+ limit: PAGE$4,
6773
6785
  ...cursor === void 0 ? {} : { cursor }
6774
6786
  });
6775
6787
  const unlabeled = page.rows.filter((row) => typeof row.label !== "number").map((row) => row.id);
@@ -6957,7 +6969,7 @@ const pendingLabelPairs = async (db) => {
6957
6969
  };
6958
6970
  //#endregion
6959
6971
  //#region ../../packages/server/dist/core/writes.mjs
6960
- const PAGE$2 = 500;
6972
+ const PAGE$3 = 500;
6961
6973
  /** Moves one bundle into or out of its platform's total and the overall total. */
6962
6974
  const countBundle = (tx, platform, delta) => {
6963
6975
  for (const key of [platform, "*"]) tx.aggregate("bundle_totals", { platform_key: key }, { bundles: delta });
@@ -6996,7 +7008,7 @@ const replaceBundlePatches = async (tx, bundle, rows, checkNew) => {
6996
7008
  const page = await tx.findMany("bundle_patches", {
6997
7009
  index: "byBundle",
6998
7010
  where: { bundle_id: bundle.id },
6999
- limit: Math.min(count - seen, PAGE$2),
7011
+ limit: Math.min(count - seen, PAGE$3),
7000
7012
  ...cursor === void 0 ? {} : { cursor }
7001
7013
  });
7002
7014
  for (const stored of page.rows) {
@@ -7560,7 +7572,7 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
7560
7572
  });
7561
7573
  //#endregion
7562
7574
  //#region ../../packages/server/dist/core/releases.mjs
7563
- const PAGE$1 = 500;
7575
+ const PAGE$2 = 500;
7564
7576
  const fail$1 = (code, message) => {
7565
7577
  throw new ReleaseCatalogMutationError(code, message);
7566
7578
  };
@@ -7595,7 +7607,7 @@ const enabledIn = (scopeKey, cursor) => ({
7595
7607
  scope_key: scopeKey,
7596
7608
  enabled: true
7597
7609
  },
7598
- limit: PAGE$1,
7610
+ limit: PAGE$2,
7599
7611
  ...cursor === void 0 ? {} : { cursor }
7600
7612
  });
7601
7613
  /** A scope's enabled releases, all of them, under the catalog's guard. */
@@ -10010,21 +10022,29 @@ const isLaunch = (row) => {
10010
10022
  const kinds = metadataOf(row).change?.kinds ?? [];
10011
10023
  return kinds.includes("bundle") && !kinds.includes("first_seen") && row.to_release_id !== null;
10012
10024
  };
10025
+ const sideRef = (key, releaseId, bundleId) => key === "release" ? releaseId ?? bundleId : bundleId;
10013
10026
  /**
10014
10027
  * The bundle a stored row's bundle filter matches: `from:<bundle>` for a
10015
10028
  * recovery; `to:<bundle>` for a download, an apply, and an update failure;
10016
10029
  * `on:<bundle>` for an UNCHANGED row that launched a bundle (`isLaunch`), a
10017
10030
  * key no other row uses. None for a failed check, which targets no bundle, a
10018
- * late row, or any other UNCHANGED row.
10031
+ * late row, or any other UNCHANGED row. Each names its bundle by `key`.
10019
10032
  */
10020
- const bundleRefsOf = (row) => {
10033
+ const bundleRefsOf = (row, key = "release") => {
10021
10034
  if (isFailedCheck(row) || isLateEvent(row)) return [];
10022
- if (row.type === "RECOVERED") return [`from:${row.from_bundle_id}`];
10023
- if (row.type === "UNCHANGED") return isLaunch(row) ? [`on:${row.to_bundle_id}`] : [];
10024
- return [`to:${row.to_bundle_id}`];
10035
+ if (row.type === "RECOVERED") return [`from:${sideRef(key, row.from_release_id, row.from_bundle_id)}`];
10036
+ if (row.type === "UNCHANGED") return isLaunch(row) ? [`on:${sideRef(key, row.to_release_id, row.to_bundle_id)}`] : [];
10037
+ return [`to:${sideRef(key, row.to_release_id, row.to_bundle_id)}`];
10025
10038
  };
10039
+ /**
10040
+ * The hourly outcome rows a stored row counts in, as `[type, bundle ref]`:
10041
+ * its bundle filter's (`bundleRefsOf`), and a download that a launch or
10042
+ * crash implied, in its bundle's download hour, so the download series
10043
+ * covers what the release's downloads count.
10044
+ */
10045
+ const outcomeRefsOf = (row, key = "release") => [...bundleRefsOf(row, key).map((ref) => [row.type, ref]), ...metadataOf(row).implied_download === true ? [["UPDATE_DOWNLOADED", row.type === "RECOVERED" ? `to:${sideRef(key, row.from_release_id, row.from_bundle_id)}` : `to:${sideRef(key, row.to_release_id, row.to_bundle_id)}`]] : []];
10026
10046
  /** The key a bundle filter reads, as `bundleRefsOf` writes it. */
10027
- const bundleRefOfFilter = (filter) => filter.type === "RECOVERED" ? `from:${filter.fromBundleId}` : filter.type === "UNCHANGED" ? `on:${filter.toBundleId}` : `to:${filter.toBundleId}`;
10047
+ const bundleRefOfFilter = (filter) => filter.type === "RECOVERED" ? `from:${filter.fromReleaseId}` : filter.type === "UNCHANGED" ? `on:${filter.toReleaseId}` : `to:${filter.toReleaseId}`;
10028
10048
  /**
10029
10049
  * Downloads, applies, recoveries, update failures, and the UNCHANGED
10030
10050
  * reports that changed what their installation runs, whole. An UNCHANGED
@@ -10089,7 +10109,11 @@ const bundleEvents = (days) => defineTable({
10089
10109
  type: "string",
10090
10110
  compute: (row) => MOVEMENTS.has(row.type) ? row.install_id : null
10091
10111
  },
10092
- /** The bundle a bundle filter matches (`bundleRefsOf`). */
10112
+ /**
10113
+ * The bundle a bundle filter matches (`bundleRefsOf`), by release.
10114
+ * Rows a 1.1 server wrote name the artifact until
10115
+ * `backfillReleaseRefs` rewrites them.
10116
+ */
10093
10117
  bundle_ref: {
10094
10118
  type: "string",
10095
10119
  multi: true,
@@ -10408,7 +10432,13 @@ const insightsBuiltinDistribution = (retention) => defineAggregate({
10408
10432
  },
10409
10433
  retention
10410
10434
  });
10411
- /** Latest events by the bundle they came from or went to, bucketed like the distribution. */
10435
+ /**
10436
+ * Latest events by the artifact they came from or went to, bucketed like
10437
+ * the distribution, as 1.1 servers wrote them. Nothing writes or reads it
10438
+ * since a bundle's installations come from `insights_distribution`, which
10439
+ * names the release; it stays declared so retention still empties the rows
10440
+ * a 1.1 server wrote.
10441
+ */
10412
10442
  const insightsLatestByBundle = (retention) => defineAggregate({
10413
10443
  platform: {
10414
10444
  type: "string",
@@ -10456,7 +10486,9 @@ const insightsLatestByBundle = (retention) => defineAggregate({
10456
10486
  * Stored events by outcome and the bundle a bundle filter matches, a row an
10457
10487
  * hour, which a failed check has none of; and every stored event, a row a UTC
10458
10488
  * day (`DAILY_EVENTS`). Bundle counts sum the hourly rows, and event lists
10459
- * read either to skip days without events.
10489
+ * read either to skip days without events. `bundle_ref` names the release
10490
+ * (`outcomeRefsOf`); a 1.1 server's rows name the artifact until
10491
+ * `backfillReleaseRefs` moves their counts.
10460
10492
  */
10461
10493
  const insightsOutcomes = (retention) => defineAggregate({
10462
10494
  platform: {
@@ -10535,6 +10567,120 @@ const createInsightsSchema = ({ rawDays, dailyDays } = DEFAULT_INSIGHTS_RETENTIO
10535
10567
  };
10536
10568
  createInsightsSchema();
10537
10569
  //#endregion
10570
+ //#region ../insights/dist/server/backfill.mjs
10571
+ /**
10572
+ * Stored events read a page, and rewritten up to `BATCH` a transaction. A
10573
+ * run keeps one batch size, which only shrinks, halving whenever a store
10574
+ * refuses a batch:
10575
+ * - as too large, before writing anything: DynamoDB's 100 items hold fewer
10576
+ * than 25 rewrites with their index copies and counts;
10577
+ * - as busy through the transaction's retries: a write-capacity cap, such as
10578
+ * the 100 write units a second `hot-updater init` gives a DynamoDB table,
10579
+ * throttles a transaction that costs more than the cap admits, about 13
10580
+ * rewrites of 2 KB events there, and refuses every write for seconds once
10581
+ * the run has spent it.
10582
+ * After a busy refusal the run also waits before it writes again, `PAUSE_MS`
10583
+ * and twice as long after each further one, so the cap refills; a commit
10584
+ * starts the waits over. A batch the store still refuses after the
10585
+ * `MAX_PAUSE_MS` wait, or a one-event batch too large to write, fails the
10586
+ * run, which a rerun resumes.
10587
+ */
10588
+ const PAGE$1 = 500;
10589
+ const BATCH = 25;
10590
+ const PAUSE_MS = 1e3;
10591
+ const MAX_PAUSE_MS = 32e3;
10592
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
10593
+ const sameRefs = (stored, refs) => {
10594
+ const values = Array.isArray(stored) ? stored : [];
10595
+ return values.length === refs.length && values.every((value) => refs.includes(value));
10596
+ };
10597
+ /**
10598
+ * Whether a stored event still names its artifact, as a 1.1 server wrote
10599
+ * it: its stored refs are the artifact's and differ from the release's. Its
10600
+ * stored refs are how its outcome rows counted it, so they are what a
10601
+ * rewrite moves, and a rewritten event reads as done.
10602
+ */
10603
+ const namesArtifact = (row) => {
10604
+ const byKey = (key) => bundleRefsOf(row, key);
10605
+ return sameRefs(row.bundle_ref, byKey("artifact")) && !sameRefs(row.bundle_ref, byKey("release"));
10606
+ };
10607
+ /**
10608
+ * Rewrites the stored events in the raw period whose refs name their
10609
+ * artifact, as 1.1 servers wrote them, to name their release, and moves
10610
+ * their hourly outcome counts with them, each event in the transaction that
10611
+ * rewrites it. Each event carries its own release IDs, so two releases of
10612
+ * one artifact in one scope come apart; an event without a release ID keeps
10613
+ * the bundle ID it reports, as new events do.
10614
+ *
10615
+ * It reads every stored event once and writes only those still to move, so
10616
+ * an interrupted run can run again. `hot-updater db migrate` and `hot-updater
10617
+ * init` run it once a database: when it completes they record the settings
10618
+ * row `insights.releaseRefs`, and later runs read no event. Installation
10619
+ * gauges need nothing: they name releases already.
10620
+ */
10621
+ const backfillReleaseRefs = async (db, now, { rawDays }, { dryRun = false } = {}) => {
10622
+ const today = now() - now() % DAY_MS$1;
10623
+ let events = 0;
10624
+ let size = BATCH;
10625
+ let paused = 0;
10626
+ const move = async (stale) => {
10627
+ if (dryRun) {
10628
+ events += stale.length;
10629
+ return;
10630
+ }
10631
+ for (let start = 0; start < stale.length;) {
10632
+ const candidates = stale.slice(start, start + size);
10633
+ try {
10634
+ events += await rewrite(candidates);
10635
+ start += candidates.length;
10636
+ paused = 0;
10637
+ } catch (error) {
10638
+ if (error instanceof DatabaseConstraintError && error.reason === "too_large" && candidates.length > 1) {
10639
+ size = Math.ceil(candidates.length / 2);
10640
+ continue;
10641
+ }
10642
+ if (!isDatabaseBusyError(error) || paused >= MAX_PAUSE_MS) throw error;
10643
+ size = Math.ceil(candidates.length / 2);
10644
+ paused = paused === 0 ? PAUSE_MS : paused * 2;
10645
+ await sleep(paused);
10646
+ }
10647
+ }
10648
+ };
10649
+ const rewrite = (candidates) => db.transaction(async (tx) => {
10650
+ const rows = await Promise.all(candidates.map(({ id }) => tx.findOne("bundle_events", { id })));
10651
+ let moved = 0;
10652
+ for (const row of rows) {
10653
+ if (row === null || !namesArtifact(row)) continue;
10654
+ tx.update("bundle_events", row, {});
10655
+ const outcome = (ref, delta) => tx.aggregate("insights_outcomes", {
10656
+ platform: row.platform,
10657
+ channel: row.channel,
10658
+ type: ref[0],
10659
+ bundle_ref: ref[1],
10660
+ bucket_start_ms: row.received_at_ms - row.received_at_ms % HOUR_MS$1
10661
+ }, { events: delta }, { shardBy: row.install_id });
10662
+ for (const ref of outcomeRefsOf(row, "artifact")) outcome(ref, -1);
10663
+ for (const ref of outcomeRefsOf(row, "release")) outcome(ref, 1);
10664
+ moved += 1;
10665
+ }
10666
+ return moved;
10667
+ });
10668
+ for (let day = today - rawDays * DAY_MS$1; day <= today; day += DAY_MS$1) {
10669
+ let cursor;
10670
+ do {
10671
+ const page = await db.findMany("bundle_events", {
10672
+ index: "byDay",
10673
+ where: { day },
10674
+ limit: PAGE$1,
10675
+ ...cursor === void 0 ? {} : { cursor }
10676
+ });
10677
+ await move(page.rows.filter(namesArtifact));
10678
+ cursor = page.next;
10679
+ } while (cursor !== void 0);
10680
+ }
10681
+ return { events };
10682
+ };
10683
+ //#endregion
10538
10684
  //#region ../insights/dist/server/eventRow.mjs
10539
10685
  const CHANGE_KINDS = /* @__PURE__ */ new Set([
10540
10686
  "first_seen",
@@ -10631,7 +10777,7 @@ const isBundleFilter = (value, withKind = false) => {
10631
10777
  "type",
10632
10778
  ...withKind ? ["kind"] : []
10633
10779
  ];
10634
- return value.type === "RECOVERED" ? isText$1(value.fromBundleId) && hasOnlyKeys(value, [...keys, "fromBundleId"]) : (value.type === "UPDATE_DOWNLOADED" || value.type === "UPDATE_APPLIED" || value.type === "UPDATE_FAILED" || value.type === "UNCHANGED") && isText$1(value.toBundleId) && hasOnlyKeys(value, [...keys, "toBundleId"]);
10780
+ return value.type === "RECOVERED" ? isText$1(value.fromReleaseId) && hasOnlyKeys(value, [...keys, "fromReleaseId"]) : (value.type === "UPDATE_DOWNLOADED" || value.type === "UPDATE_APPLIED" || value.type === "UPDATE_FAILED" || value.type === "UNCHANGED") && isText$1(value.toReleaseId) && hasOnlyKeys(value, [...keys, "toReleaseId"]);
10635
10781
  };
10636
10782
  const isEventFilter = (value) => {
10637
10783
  if (!isRecord$3(value)) return false;
@@ -10732,20 +10878,24 @@ const createValidatedInsightsModel = (model) => ({
10732
10878
  if (!isRecord$3(input) || !hasOnlyKeys(input, [
10733
10879
  "platform",
10734
10880
  "channel",
10735
- "sinceMs",
10736
- "bundle"
10737
- ]) || !hasScope(input) || !isTimestamp(input.sinceMs) || input.bundle !== void 0 && (!Array.isArray(input.bundle) || input.bundle.length < 1 || input.bundle.length > 2 || input.bundle.some((bundle) => !isRecord$3(bundle) || !hasOnlyKeys(bundle, [
10738
- "field",
10739
- "value",
10740
- "types"
10741
- ]) || bundle.field !== "from_bundle_id" && bundle.field !== "to_bundle_id" || !isText$1(bundle.value) || !Array.isArray(bundle.types) || bundle.types.length === 0 || bundle.types.some((type) => ![
10742
- "UNCHANGED",
10743
- "UPDATE_DOWNLOADED",
10744
- "UPDATE_APPLIED",
10745
- "RECOVERED"
10746
- ].includes(type))))) invalidQuery();
10881
+ "sinceMs"
10882
+ ]) || !hasScope(input) || !isTimestamp(input.sinceMs)) invalidQuery();
10747
10883
  return validateCount(await model.countLatestEvents(input));
10748
10884
  },
10885
+ async countReleaseInstallations(input) {
10886
+ if (!isRecord$3(input) || !hasOnlyKeys(input, [
10887
+ "platform",
10888
+ "channel",
10889
+ "sinceMs",
10890
+ "releaseId"
10891
+ ]) || !hasScope(input) || !isTimestamp(input.sinceMs) || !isText$1(input.releaseId)) invalidQuery();
10892
+ const counts = await model.countReleaseInstallations(input);
10893
+ if (!isRecord$3(counts) || !hasOnlyKeys(counts, ["installations", "release"])) invalidResult();
10894
+ return {
10895
+ installations: validateCount(counts.installations),
10896
+ release: validateCount(counts.release)
10897
+ };
10898
+ },
10749
10899
  async countEvents(input) {
10750
10900
  if (!isRecord$3(input) || !hasOnlyKeys(input, [
10751
10901
  "filter",
@@ -10802,6 +10952,7 @@ const createInsightsModel = (api) => createValidatedInsightsModel({
10802
10952
  listEvents: api.listEvents,
10803
10953
  findLatestEvents: api.findLatestEvents,
10804
10954
  countLatestEvents: api.countLatestEvents,
10955
+ countReleaseInstallations: api.countReleaseInstallations,
10805
10956
  countEvents: api.countEvents,
10806
10957
  countEventSeries: api.countEventSeries,
10807
10958
  getReleaseActivity: api.getReleaseActivity,
@@ -11204,27 +11355,27 @@ const readScope$1 = (input) => {
11204
11355
  };
11205
11356
  const bundleFilter = (input) => {
11206
11357
  const scope = readScope$1(input);
11207
- const bundleId = requireString(input.bundleId, "bundle ID", MAX_EVENT_ID_LENGTH);
11358
+ const releaseId = requireString(input.releaseId, "bundle ID", MAX_EVENT_ID_LENGTH);
11208
11359
  switch (input.outcome) {
11209
11360
  case "downloaded": return {
11210
11361
  ...scope,
11211
11362
  type: "UPDATE_DOWNLOADED",
11212
- toBundleId: bundleId
11363
+ toReleaseId: releaseId
11213
11364
  };
11214
11365
  case "applied": return {
11215
11366
  ...scope,
11216
11367
  type: "UPDATE_APPLIED",
11217
- toBundleId: bundleId
11368
+ toReleaseId: releaseId
11218
11369
  };
11219
11370
  case "recovered": return {
11220
11371
  ...scope,
11221
11372
  type: "RECOVERED",
11222
- fromBundleId: bundleId
11373
+ fromReleaseId: releaseId
11223
11374
  };
11224
11375
  case "failed": return {
11225
11376
  ...scope,
11226
11377
  type: "UPDATE_FAILED",
11227
- toBundleId: bundleId
11378
+ toReleaseId: releaseId
11228
11379
  };
11229
11380
  default: throw new InsightsBadRequestError("Invalid Insights outcome.");
11230
11381
  }
@@ -11234,7 +11385,7 @@ const sameFilter = (left, right) => {
11234
11385
  switch (right.kind) {
11235
11386
  case "all": return true;
11236
11387
  case "installationMovement": return left.installId === right.installId;
11237
- case "bundle": return left.platform === right.platform && left.channel === right.channel && left.type === right.type && (right.type === "RECOVERED" ? left.fromBundleId === right.fromBundleId : left.toBundleId === right.toBundleId);
11388
+ case "bundle": return left.platform === right.platform && left.channel === right.channel && left.type === right.type && (right.type === "RECOVERED" ? left.fromReleaseId === right.fromReleaseId : left.toReleaseId === right.toReleaseId);
11238
11389
  }
11239
11390
  };
11240
11391
  const readEventCursor = (value, filter) => {
@@ -11271,7 +11422,7 @@ const assertEventRows = (rows, input) => {
11271
11422
  for (let index = 0; index < rows.length; index += 1) {
11272
11423
  const row = rows[index];
11273
11424
  const previous = rows[index - 1];
11274
- if (!row || typeof row.id !== "string" || !isUUIDv7(row.id) || !Number.isSafeInteger(row.received_at_ms) || row.received_at_ms >= input.beforeReceivedAtMs || row.received_at_ms < input.sinceMs || previous !== void 0 && compareEventNewest(previous, row) >= 0 || input.after !== void 0 && !isAfterEventCursor(row, input.after) || input.filter.kind === "installationMovement" && (row.install_id !== input.filter.installId || !isInsightsMovementEvent(row)) || input.filter.kind === "bundle" && (row.platform !== input.filter.platform || row.channel !== input.filter.channel || row.type !== input.filter.type || (input.filter.type === "RECOVERED" ? row.from_bundle_id !== input.filter.fromBundleId : row.to_bundle_id !== input.filter.toBundleId))) throw new Error("Insights database returned invalid event rows.");
11425
+ if (!row || typeof row.id !== "string" || !isUUIDv7(row.id) || !Number.isSafeInteger(row.received_at_ms) || row.received_at_ms >= input.beforeReceivedAtMs || row.received_at_ms < input.sinceMs || previous !== void 0 && compareEventNewest(previous, row) >= 0 || input.after !== void 0 && !isAfterEventCursor(row, input.after) || input.filter.kind === "installationMovement" && (row.install_id !== input.filter.installId || !isInsightsMovementEvent(row)) || input.filter.kind === "bundle" && (row.platform !== input.filter.platform || row.channel !== input.filter.channel || row.type !== input.filter.type || (input.filter.type === "RECOVERED" ? (row.from_release_id ?? row.from_bundle_id) !== input.filter.fromReleaseId : (row.to_release_id ?? row.to_bundle_id) !== input.filter.toReleaseId))) throw new Error("Insights database returned invalid event rows.");
11275
11426
  }
11276
11427
  };
11277
11428
  /** An `UPDATE_FAILED` row's failure, as the event lists show it. */
@@ -11312,6 +11463,7 @@ const eventDetails = ({ type, metadata }) => ({
11312
11463
  ...metadata.implied_download === true ? { impliedDownload: true } : {}
11313
11464
  });
11314
11465
  const toEventHistoryRow = (row) => ({
11466
+ ...row.from_release_id == null ? {} : { fromReleaseId: row.from_release_id },
11315
11467
  ...row.to_release_id == null ? {} : { toReleaseId: row.to_release_id },
11316
11468
  ...row.metadata.sdk_version == null ? {} : { sdkVersion: row.metadata.sdk_version },
11317
11469
  ...row.metadata.min_bundle_id === void 0 ? {} : { minBundleId: row.metadata.min_bundle_id },
@@ -11336,6 +11488,7 @@ const toInstallationRow = (row) => ({
11336
11488
  cohort: row.metadata.cohort,
11337
11489
  installId: row.install_id,
11338
11490
  lastKnownBundleId: row.type === "UPDATE_DOWNLOADED" ? row.from_bundle_id : row.to_bundle_id,
11491
+ lastKnownReleaseId: row.type === "UPDATE_DOWNLOADED" ? row.from_release_id : row.to_release_id,
11339
11492
  pendingBundleId: row.type === "UPDATE_DOWNLOADED" ? row.to_bundle_id : null,
11340
11493
  pendingReleaseId: row.type === "UPDATE_DOWNLOADED" ? row.to_release_id : null,
11341
11494
  latestStatus: row.type,
@@ -11464,46 +11617,33 @@ const createInsightsProvider = (model) => Object.freeze({
11464
11617
  measuredAtMs: Date.now()
11465
11618
  };
11466
11619
  };
11467
- const bundleId = input.bundleId === void 0 ? void 0 : requireString(input.bundleId, "bundle ID", MAX_EVENT_ID_LENGTH);
11468
- const reporting = measure(model.countLatestEvents({
11469
- ...scope,
11470
- sinceMs
11471
- }));
11472
- if (bundleId === void 0) return {
11620
+ const releaseId = input.releaseId === void 0 ? void 0 : requireString(input.releaseId, "bundle ID", MAX_EVENT_ID_LENGTH);
11621
+ if (releaseId === void 0) return {
11473
11622
  ...scope,
11474
11623
  window,
11475
11624
  sinceMs,
11476
11625
  beforeReceivedAtMs,
11477
- reportingInstallations: await reporting
11626
+ reportingInstallations: await measure(model.countLatestEvents({
11627
+ ...scope,
11628
+ sinceMs
11629
+ }))
11478
11630
  };
11631
+ const installations = model.countReleaseInstallations({
11632
+ ...scope,
11633
+ sinceMs,
11634
+ releaseId
11635
+ }).then(async (counts) => [await measure(Promise.resolve(counts.installations)), await measure(Promise.resolve(counts.release))]);
11479
11636
  const countOutcome = (outcome) => measure(model.countEvents({
11480
11637
  filter: bundleFilter({
11481
11638
  ...scope,
11482
- bundleId,
11639
+ releaseId,
11483
11640
  outcome
11484
11641
  }),
11485
11642
  sinceMs,
11486
11643
  beforeReceivedAtMs
11487
11644
  }));
11488
- const [reportingInstallations, bundleInstallations, downloadedReports, appliedReports, recoveredReports, failedReports] = await Promise.all([
11489
- reporting,
11490
- measure(model.countLatestEvents({
11491
- ...scope,
11492
- sinceMs,
11493
- bundle: [{
11494
- field: "from_bundle_id",
11495
- value: bundleId,
11496
- types: ["UPDATE_DOWNLOADED"]
11497
- }, {
11498
- field: "to_bundle_id",
11499
- value: bundleId,
11500
- types: [
11501
- "UNCHANGED",
11502
- "UPDATE_APPLIED",
11503
- "RECOVERED"
11504
- ]
11505
- }]
11506
- })),
11645
+ const [[reportingInstallations, bundleInstallations], downloadedReports, appliedReports, recoveredReports, failedReports] = await Promise.all([
11646
+ installations,
11507
11647
  countOutcome("downloaded"),
11508
11648
  countOutcome("applied"),
11509
11649
  countOutcome("recovered"),
@@ -11516,7 +11656,7 @@ const createInsightsProvider = (model) => Object.freeze({
11516
11656
  beforeReceivedAtMs,
11517
11657
  reportingInstallations,
11518
11658
  bundle: {
11519
- bundleId,
11659
+ releaseId,
11520
11660
  reportingInstallations: bundleInstallations,
11521
11661
  downloadedReports,
11522
11662
  appliedReports,
@@ -11651,17 +11791,10 @@ const gaugeSlot = (head) => ({
11651
11791
  builtinBundleId: runningBuiltinBundleId(head)
11652
11792
  });
11653
11793
  /**
11654
- * The `insights_latest_by_bundle` field of a head's (from, to) pair. A head
11655
- * matches a `from` and a `to` predicate of one type at once only through its
11656
- * pair, so this gauge is what a count subtracts to count it once.
11657
- */
11658
- const PAIR_FIELD = "from_to";
11659
- /** The pair gauge's `bundle_id`: a hash of the two bundle ids, which fit no single 36-character column. */
11660
- const bundlePairKey = (from, to) => insightsKey(`${from.length}:${from}${to.length}:${to}`);
11661
- /**
11662
11794
  * Moves a head's gauges: the distribution row, and the built-in one when it
11663
- * runs its build's built-in bundle, one row per bundle it references, and
11664
- * its pair; -1 takes back the head an event replaces.
11795
+ * runs its build's built-in bundle; -1 takes back the head an event
11796
+ * replaces. The distribution row names the release the head runs, so it is
11797
+ * also each release's installation gauge.
11665
11798
  */
11666
11799
  const countHead = (tx, head, delta) => {
11667
11800
  const { bucket, releaseId, builtinBundleId } = gaugeSlot(head);
@@ -11681,26 +11814,6 @@ const countHead = (tx, head, delta) => {
11681
11814
  builtin_bundle_id: builtinBundleId,
11682
11815
  bucket_start_ms: bucket
11683
11816
  }, { latest_installations: delta }, { shardBy });
11684
- for (const field of ["from_bundle_id", "to_bundle_id"]) {
11685
- const bundleId = head[field];
11686
- if (bundleId === null) continue;
11687
- tx.aggregate("insights_latest_by_bundle", {
11688
- platform: head.platform,
11689
- channel: head.channel,
11690
- bundle_field: field,
11691
- bundle_id: bundleId,
11692
- type: head.type,
11693
- bucket_start_ms: bucket
11694
- }, { installations: delta }, { shardBy });
11695
- }
11696
- if (head.from_bundle_id !== null) tx.aggregate("insights_latest_by_bundle", {
11697
- platform: head.platform,
11698
- channel: head.channel,
11699
- bundle_field: PAIR_FIELD,
11700
- bundle_id: bundlePairKey(head.from_bundle_id, head.to_bundle_id),
11701
- type: head.type,
11702
- bucket_start_ms: bucket
11703
- }, { installations: delta }, { shardBy });
11704
11817
  };
11705
11818
  /**
11706
11819
  * Where each period's rows go, each with its retention: hours for 90 days,
@@ -11761,26 +11874,19 @@ const countEvent = (tx, event) => {
11761
11874
  }
11762
11875
  };
11763
11876
  /**
11764
- * A stored event's outcome rows: its bundle filter's hour, when it has one
11765
- * (`bundleRefsOf`), and every stored event's UTC day. A download that a
11766
- * launch or crash implied counts in its bundle's download hour too, in the
11767
- * hour of that launch or crash, so the download series covers what the
11768
- * release's downloads count; the launch or crash is its row.
11877
+ * A stored event's outcome rows: its bundle filter's hour, and the download
11878
+ * hour of a download its launch or crash implied, each by release
11879
+ * (`outcomeRefsOf`); and every stored event's UTC day.
11769
11880
  */
11770
11881
  const countOutcome = (tx, event) => {
11771
11882
  const shardBy = event.install_id;
11772
- const hour = (type, bundleRef) => tx.aggregate("insights_outcomes", {
11883
+ for (const [type, bundleRef] of outcomeRefsOf(event)) tx.aggregate("insights_outcomes", {
11773
11884
  platform: event.platform,
11774
11885
  channel: event.channel,
11775
11886
  type,
11776
11887
  bundle_ref: bundleRef,
11777
11888
  bucket_start_ms: hourOf(event.received_at_ms)
11778
11889
  }, { events: 1 }, { shardBy });
11779
- for (const bundleRef of bundleRefsOf(event)) hour(event.type, bundleRef);
11780
- if (event.metadata.implied_download === true) hour("UPDATE_DOWNLOADED", bundleRefOfFilter({
11781
- type: "UPDATE_DOWNLOADED",
11782
- toBundleId: event.type === "RECOVERED" ? event.from_bundle_id : event.to_bundle_id
11783
- }));
11784
11890
  tx.aggregate("insights_outcomes", {
11785
11891
  ...DAILY_EVENTS,
11786
11892
  bucket_start_ms: dayOf(event.received_at_ms)
@@ -12260,31 +12366,48 @@ const countEventSeries = async (db, input) => {
12260
12366
  events: count
12261
12367
  }));
12262
12368
  };
12263
- /** A bundle filter's distinct (field, value, type) predicates. */
12264
- const latestPredicates = (bundle) => {
12265
- if (bundle === void 0) return void 0;
12266
- return [...new Map(bundle.flatMap(({ field, value, types }) => types.map((type) => [JSON.stringify([
12267
- field,
12268
- value,
12269
- type
12270
- ]), {
12271
- field,
12272
- value,
12273
- type
12274
- }]))).values()];
12369
+ /** The distribution rows at or after `start`, a UTC day's start. */
12370
+ const distributionRows = (db, { platform, channel, sinceMs: start }) => {
12371
+ if (start % 864e5 !== 0) throw new DatabaseAdapterInputError("invalid-query");
12372
+ return drain((page) => db.findAggregates("insights_distribution", {
12373
+ index: "byScope",
12374
+ where: {
12375
+ channel,
12376
+ platform
12377
+ },
12378
+ range: { gte: start },
12379
+ limit: PAGE,
12380
+ ...page
12381
+ }));
12275
12382
  };
12383
+ const installations = (count) => Math.max(0, count);
12276
12384
  /**
12277
12385
  * Latest events at or after `sinceMs`, a UTC day's start: the gauges count
12278
12386
  * each installation in the UTC day of its latest event, so they answer whole
12279
12387
  * days only, and a later start is rejected rather than rounded.
12280
12388
  */
12281
- const countLatestEvents = async (db, input) => {
12282
- const { platform, channel, sinceMs: start } = input;
12283
- if (start % 864e5 !== 0) throw new DatabaseAdapterInputError("invalid-query");
12284
- const predicates = latestPredicates(input.bundle);
12389
+ const countLatestEvents = async (db, input) => installations((await distributionRows(db, input)).reduce((sum, row) => sum + row.latest_installations, 0));
12390
+ /**
12391
+ * `countLatestEvents`, and of those the installations it leaves running
12392
+ * `releaseId`, from the same distribution rows in one read: each names the
12393
+ * release its installations run. An ID no row names as a release may be a
12394
+ * built-in bundle's, which a report without a release names, as event
12395
+ * counts match it: its installations outside any release are in the
12396
+ * built-in rows, read only then. Release and bundle IDs never coincide.
12397
+ */
12398
+ const countReleaseInstallations = async (db, input) => {
12399
+ const { platform, channel, sinceMs: start, releaseId } = input;
12285
12400
  let total = 0;
12286
- if (predicates === void 0) {
12287
- const rows = await drain((page) => db.findAggregates("insights_distribution", {
12401
+ let release = 0;
12402
+ let named = false;
12403
+ for (const row of await distributionRows(db, input)) {
12404
+ total += row.latest_installations;
12405
+ if (row.release_id !== releaseId) continue;
12406
+ named = true;
12407
+ release += row.latest_installations;
12408
+ }
12409
+ if (!named) {
12410
+ const builtin = await drain((page) => db.findAggregates("insights_builtin_distribution", {
12288
12411
  index: "byScope",
12289
12412
  where: {
12290
12413
  channel,
@@ -12294,33 +12417,12 @@ const countLatestEvents = async (db, input) => {
12294
12417
  limit: PAGE,
12295
12418
  ...page
12296
12419
  }));
12297
- total += rows.reduce((sum, row) => sum + row.latest_installations, 0);
12298
- } else {
12299
- const gauge = async (bundleField, bundleId, type) => {
12300
- return (await drain((page) => db.findAggregates("insights_latest_by_bundle", {
12301
- index: "byBundle",
12302
- where: {
12303
- platform,
12304
- channel,
12305
- bundle_field: bundleField,
12306
- bundle_id: bundleId,
12307
- type
12308
- },
12309
- range: { gte: start },
12310
- limit: PAGE,
12311
- ...page
12312
- }))).reduce((sum, row) => sum + row.installations, 0);
12313
- };
12314
- for (const { field, value, type } of predicates) total += await gauge(field, value, type);
12315
- for (const from of predicates) {
12316
- if (from.field !== "from_bundle_id") continue;
12317
- for (const to of predicates) {
12318
- if (to.field !== "to_bundle_id" || to.type !== from.type) continue;
12319
- total -= await gauge(PAIR_FIELD, bundlePairKey(from.value, to.value), from.type);
12320
- }
12321
- }
12420
+ for (const row of builtin) if (row.release_id === "" && row.builtin_bundle_id === releaseId) release += row.latest_installations;
12322
12421
  }
12323
- return Math.max(0, total);
12422
+ return {
12423
+ installations: installations(total),
12424
+ release: installations(release)
12425
+ };
12324
12426
  };
12325
12427
  /** The oldest whole hour and UTC day that hourly and daily rows still hold. */
12326
12428
  const retained = (now, { rawDays, dailyDays }) => ({
@@ -12790,6 +12892,26 @@ const getUpdateFailures = async (db, input, now, retention) => {
12790
12892
  };
12791
12893
  };
12792
12894
  //#endregion
12895
+ //#region ../insights/dist/server/wire.mjs
12896
+ /**
12897
+ * The HTTP API calls a release ID `bundleId`, the word users have for it, in
12898
+ * its query parameters and its overview's JSON. The code calls it
12899
+ * `releaseId`; only this module maps between the two names.
12900
+ */
12901
+ const RELEASE_ID_PARAM = "bundleId";
12902
+ /** An overview as the HTTP API and the CLI's `--json` send it. */
12903
+ const toWireOverview = ({ bundle, ...overview }) => {
12904
+ if (bundle === void 0) return overview;
12905
+ const { releaseId, ...counts } = bundle;
12906
+ return {
12907
+ ...overview,
12908
+ bundle: {
12909
+ ...counts,
12910
+ bundleId: releaseId
12911
+ }
12912
+ };
12913
+ };
12914
+ //#endregion
12793
12915
  //#region ../insights/dist/server/queryInput.mjs
12794
12916
  const MAX_PAGE_LIMIT = 100;
12795
12917
  const MAX_IDENTITY_LENGTH = 255;
@@ -12834,7 +12956,7 @@ const readScope = (url) => {
12834
12956
  const parseEventPageInput = (request) => {
12835
12957
  const url = new URL(request.url);
12836
12958
  const bundleFields = [
12837
- "bundleId",
12959
+ RELEASE_ID_PARAM,
12838
12960
  "outcome",
12839
12961
  "platform",
12840
12962
  "channel"
@@ -12845,7 +12967,7 @@ const parseEventPageInput = (request) => {
12845
12967
  if (outcome !== "downloaded" && outcome !== "applied" && outcome !== "recovered" && outcome !== "failed") throw new InsightsBadRequestError("Invalid 'outcome' query parameter.");
12846
12968
  bundle = {
12847
12969
  ...readScope(url),
12848
- bundleId: readId(url, "bundleId", 1024),
12970
+ releaseId: readId(url, RELEASE_ID_PARAM, 1024),
12849
12971
  outcome
12850
12972
  };
12851
12973
  }
@@ -12871,11 +12993,10 @@ const parseReportingOverviewInput = (request) => {
12871
12993
  const url = new URL(request.url);
12872
12994
  const window = readSingle(url, "window") ?? "30d";
12873
12995
  if (window !== "24h" && window !== "7d" && window !== "30d") throw new InsightsBadRequestError("Invalid 'window' query parameter.");
12874
- const bundleId = readSingle(url, "bundleId");
12875
12996
  return {
12876
12997
  ...readScope(url),
12877
12998
  window,
12878
- ...bundleId === void 0 ? {} : { bundleId: readId(url, "bundleId", 1024) }
12999
+ ...readSingle(url, "bundleId") === void 0 ? {} : { releaseId: readId(url, RELEASE_ID_PARAM, 1024) }
12879
13000
  };
12880
13001
  };
12881
13002
  //#endregion
@@ -12956,7 +13077,7 @@ const createInsightsRouteHandlers = (provider) => ({
12956
13077
  await provider.appendBundleEvent(await parseBundleEventRequest(request));
12957
13078
  return new Response(null, { status: 204 });
12958
13079
  }),
12959
- getReportingOverview: (_params, request) => query(() => provider.getReportingOverview(parseReportingOverviewInput(request))),
13080
+ getReportingOverview: (_params, request) => query(async () => toWireOverview(await provider.getReportingOverview(parseReportingOverviewInput(request)))),
12960
13081
  getInstallation: (params) => run$1(async () => {
12961
13082
  const installation = await provider.getInstallation({ installId: requireParam(params, "installId") });
12962
13083
  return installation === null ? json$1({ error: "Installation not found" }, 404) : json$1(installation, 200);
@@ -12978,12 +13099,20 @@ const createInsightsApi = (db, now, retention) => ({
12978
13099
  listEvents: (input) => listEvents(db, input),
12979
13100
  findLatestEvents: (input) => findLatestEvents(db, input),
12980
13101
  countLatestEvents: (input) => countLatestEvents(db, input),
13102
+ countReleaseInstallations: (input) => countReleaseInstallations(db, input),
12981
13103
  countEvents: (input) => countEvents(db, input),
12982
13104
  countEventSeries: (input) => countEventSeries(db, input),
12983
13105
  getReleaseActivity: (input) => getReleaseActivity(db, input, now),
12984
13106
  getAppUsage: (input) => getAppUsage(db, input, now, retention),
12985
13107
  /** A release's or a channel's update failures, and their breakdown over a time range. */
12986
- getUpdateFailures: (input) => getUpdateFailures(db, input, now, retention)
13108
+ getUpdateFailures: (input) => getUpdateFailures(db, input, now, retention),
13109
+ /**
13110
+ * Moves the stored events a 1.1 server keyed by artifact, and their
13111
+ * outcome counts, to their release, reading every stored event of the
13112
+ * raw period: `hot-updater db migrate` and `hot-updater init` run it once
13113
+ * a database, and an interrupted run can run again.
13114
+ */
13115
+ backfillReleaseRefs: (options) => backfillReleaseRefs(db, now, retention, options)
12987
13116
  });
12988
13117
  /** `GET /failures`'s query: a scope, an optional release, and a time range or none. */
12989
13118
  const readFailuresQuery = (url) => {
@@ -8002,6 +8002,16 @@ const runInit = async ({ build, envFile, secretsEnv }) => {
8002
8002
  await removeTmpDir();
8003
8003
  process.exit(1);
8004
8004
  }
8005
+ const backfillDatabase = firebaseDatabase(databaseConfig);
8006
+ try {
8007
+ await (0, _hot_updater_cli_tools.backfillInsightsReleaseRefs)((0, _hot_updater_cli_tools.assembleServer)({
8008
+ database: backfillDatabase,
8009
+ plugins: server.plugins
8010
+ }));
8011
+ } finally {
8012
+ await backfillDatabase.dispose?.();
8013
+ await Promise.all((0, firebase_admin_app.getApps)().map((app) => (0, firebase_admin_app.deleteApp)(app)));
8014
+ }
8005
8015
  await printTemplate(clientCredential, initializeVariable.projectId, currentRegion, server.clientPlugins, cliEnv);
8006
8016
  await removeTmpDir();
8007
8017
  return { nextSteps: [(0, _hot_updater_cli_tools.link)("https://hot-updater.dev/docs/managed/firebase#step-3-add-hotupdater-to-your-project"), ...applicationCredentials ? [] : ["Change GOOGLE_APPLICATION_CREDENTIALS=your-credentials.json in .env.hotupdater"]] };
@@ -1,7 +1,7 @@
1
1
  import { createRequire } from "node:module";
2
2
  import fs from "fs";
3
3
  import path from "path";
4
- import { ConfigBuilder, HOT_UPDATER_SERVER_PACKAGE_VERSION_ENV, InitError, LegacyInfrastructureError, MissingInitInputsError, assembleServer, assertInfrastructureGenerationAtUrl, assertInitProviderInputs, confirmInitInputPersistence, copyDirToTmp, createHotUpdaterConfigScaffoldFromBuilder, fillReleaseLabels, getHotUpdaterInitInputEnv, getInitProviderEnvVars, getInitProviderTextPromptValues, link, makeEnv, p, printAppSetup, provisionClientCredential, readHotUpdaterInitEnv, resolveHotUpdaterServerVersion, resolveInitProviderInput, resolvePackageVersion, transformEnv, writeHotUpdaterFiles } from "@hot-updater/cli-tools";
4
+ import { ConfigBuilder, HOT_UPDATER_SERVER_PACKAGE_VERSION_ENV, InitError, LegacyInfrastructureError, MissingInitInputsError, assembleServer, assertInfrastructureGenerationAtUrl, assertInitProviderInputs, backfillInsightsReleaseRefs, confirmInitInputPersistence, copyDirToTmp, createHotUpdaterConfigScaffoldFromBuilder, fillReleaseLabels, getHotUpdaterInitInputEnv, getInitProviderEnvVars, getInitProviderTextPromptValues, link, makeEnv, p, printAppSetup, provisionClientCredential, readHotUpdaterInitEnv, resolveHotUpdaterServerVersion, resolveInitProviderInput, resolvePackageVersion, transformEnv, writeHotUpdaterFiles } from "@hot-updater/cli-tools";
5
5
  import { apiKeys, insights, remoteConfig } from "@hot-updater/server/plugins";
6
6
  import { fileURLToPath } from "node:url";
7
7
  import { ChildProcess, execFile, spawn, spawnSync } from "node:child_process";
@@ -7995,6 +7995,16 @@ const runInit = async ({ build, envFile, secretsEnv }) => {
7995
7995
  await removeTmpDir();
7996
7996
  process.exit(1);
7997
7997
  }
7998
+ const backfillDatabase = firebaseDatabase(databaseConfig);
7999
+ try {
8000
+ await backfillInsightsReleaseRefs(assembleServer({
8001
+ database: backfillDatabase,
8002
+ plugins: server.plugins
8003
+ }));
8004
+ } finally {
8005
+ await backfillDatabase.dispose?.();
8006
+ await Promise.all(getApps().map((app) => deleteApp(app)));
8007
+ }
7998
8008
  await printTemplate(clientCredential, initializeVariable.projectId, currentRegion, server.clientPlugins, cliEnv);
7999
8009
  await removeTmpDir();
8000
8010
  return { nextSteps: [link("https://hot-updater.dev/docs/managed/firebase#step-3-add-hotupdater-to-your-project"), ...applicationCredentials ? [] : ["Change GOOGLE_APPLICATION_CREDENTIALS=your-credentials.json in .env.hotupdater"]] };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@hot-updater/firebase",
3
3
  "type": "module",
4
- "version": "1.2.0-rc.57",
4
+ "version": "1.2.0-rc.59",
5
5
  "description": "React Native OTA solution for self-hosted",
6
6
  "main": "dist/index.cjs",
7
7
  "types": "dist/index.d.cts",
@@ -38,10 +38,10 @@
38
38
  "dependencies": {
39
39
  "hono": "4.12.34",
40
40
  "google-auth-library": "10.7.0",
41
- "@hot-updater/cli-tools": "1.2.0-rc.57",
42
- "@hot-updater/protocol": "1.2.0-rc.57",
43
- "@hot-updater/server": "1.2.0-rc.57",
44
- "@hot-updater/plugin-core": "1.2.0-rc.57"
41
+ "@hot-updater/cli-tools": "1.2.0-rc.59",
42
+ "@hot-updater/plugin-core": "1.2.0-rc.59",
43
+ "@hot-updater/protocol": "1.2.0-rc.59",
44
+ "@hot-updater/server": "1.2.0-rc.59"
45
45
  },
46
46
  "publishConfig": {
47
47
  "access": "public"
@@ -56,8 +56,8 @@
56
56
  "firebase-tools": "15.29.0",
57
57
  "fkill": "^9.0.0",
58
58
  "mime": "^4.0.4",
59
- "@hot-updater/mock": "1.2.0-rc.57",
60
- "@hot-updater/test-utils": "1.2.0-rc.57"
59
+ "@hot-updater/mock": "1.2.0-rc.59",
60
+ "@hot-updater/test-utils": "1.2.0-rc.59"
61
61
  },
62
62
  "peerDependencies": {
63
63
  "firebase-admin": ">=11.10.0",