@hot-updater/aws 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.
@@ -8830,6 +8830,19 @@ const runInit = async ({ build, envFile, secretsEnv }) => {
8830
8830
  cwd: process.cwd(),
8831
8831
  settings: "AWS"
8832
8832
  });
8833
+ const backfillDatabase = dynamoDB({
8834
+ credentials,
8835
+ region: bucketRegion,
8836
+ tableName: resolvedDynamoDBTableName
8837
+ });
8838
+ try {
8839
+ await (0, _hot_updater_cli_tools.backfillInsightsReleaseRefs)((0, _hot_updater_cli_tools.assembleServer)({
8840
+ database: backfillDatabase,
8841
+ plugins: server.plugins
8842
+ }));
8843
+ } finally {
8844
+ await backfillDatabase.dispose?.();
8845
+ }
8833
8846
  (0, _hot_updater_cli_tools.printAppSetup)({
8834
8847
  baseURL: `https://${distributionDomain}`,
8835
8848
  ...credential === void 0 ? {} : { credential },
@@ -1,5 +1,5 @@
1
1
  import { createRequire } from "node:module";
2
- import { ConfigBuilder, InitError, MissingInitInputsError, assembleServer, assertInfrastructureGenerationAtUrl, assertInfrastructureGenerationPayload, assertInitProviderInputs, colors, confirmInitInputPersistence, copyDirToTmp, createHotUpdaterConfigScaffoldFromBuilder, createZip, ensureInstallPackages, fillReleaseLabels, getCwd, getHotUpdaterInitInputEnv, getInitProviderEnvVars, getInitProviderTextPromptValues, link, makeEnv, p, printAppSetup, provisionClientCredential, readHotUpdaterInitEnv, resolveInitProviderInput, transformEnv, writeHotUpdaterFiles } from "@hot-updater/cli-tools";
2
+ import { ConfigBuilder, InitError, MissingInitInputsError, assembleServer, assertInfrastructureGenerationAtUrl, assertInfrastructureGenerationPayload, assertInitProviderInputs, backfillInsightsReleaseRefs, colors, confirmInitInputPersistence, copyDirToTmp, createHotUpdaterConfigScaffoldFromBuilder, createZip, ensureInstallPackages, fillReleaseLabels, getCwd, getHotUpdaterInitInputEnv, getInitProviderEnvVars, getInitProviderTextPromptValues, link, makeEnv, p, printAppSetup, provisionClientCredential, readHotUpdaterInitEnv, resolveInitProviderInput, transformEnv, writeHotUpdaterFiles } from "@hot-updater/cli-tools";
3
3
  import { apiKeys, insights, remoteConfig } from "@hot-updater/server/plugins";
4
4
  import { fileURLToPath } from "node:url";
5
5
  import { ChildProcess, execFile, spawn, spawnSync } from "node:child_process";
@@ -8825,6 +8825,19 @@ const runInit = async ({ build, envFile, secretsEnv }) => {
8825
8825
  cwd: process.cwd(),
8826
8826
  settings: "AWS"
8827
8827
  });
8828
+ const backfillDatabase = dynamoDB({
8829
+ credentials,
8830
+ region: bucketRegion,
8831
+ tableName: resolvedDynamoDBTableName
8832
+ });
8833
+ try {
8834
+ await backfillInsightsReleaseRefs(assembleServer({
8835
+ database: backfillDatabase,
8836
+ plugins: server.plugins
8837
+ }));
8838
+ } finally {
8839
+ await backfillDatabase.dispose?.();
8840
+ }
8828
8841
  printAppSetup({
8829
8842
  baseURL: `https://${distributionDomain}`,
8830
8843
  ...credential === void 0 ? {} : { credential },
@@ -554,14 +554,14 @@ function modularInverse(value, modulus) {
554
554
  if (r > 1) throw new Error(`No modular inverse for ${value} mod ${modulus}`);
555
555
  return positiveMod(t, modulus);
556
556
  }
557
- function getRolloutShuffleParameters(bundleId) {
558
- let multiplier = positiveMod(hashString(`${bundleId}:multiplier`), 997);
557
+ function getRolloutShuffleParameters(releaseId) {
558
+ let multiplier = positiveMod(hashString(`${releaseId}:multiplier`), 997);
559
559
  if (multiplier === 0) multiplier = 1;
560
560
  while (gcd(multiplier, NUMERIC_COHORT_SIZE) !== 1) {
561
561
  multiplier = positiveMod(multiplier + 1, NUMERIC_COHORT_SIZE);
562
562
  if (multiplier === 0) multiplier = 1;
563
563
  }
564
- const offset = positiveMod(hashString(`${bundleId}:offset`), NUMERIC_COHORT_SIZE);
564
+ const offset = positiveMod(hashString(`${releaseId}:offset`), NUMERIC_COHORT_SIZE);
565
565
  return {
566
566
  multiplier,
567
567
  offset,
@@ -594,16 +594,16 @@ function isValidCohort(cohort) {
594
594
  const normalized = normalizeCohortValue(cohort);
595
595
  return isNumericCohort(normalized) || isCustomCohort(normalized);
596
596
  }
597
- function getNumericCohortRolloutPosition(bundleId, cohortValue) {
597
+ function getNumericCohortRolloutPosition(releaseId, cohortValue) {
598
598
  if (cohortValue < 1 || cohortValue > 1e3) throw new Error(`Invalid numeric cohort: ${cohortValue}`);
599
- const { offset, inverseMultiplier } = getRolloutShuffleParameters(bundleId);
599
+ const { offset, inverseMultiplier } = getRolloutShuffleParameters(releaseId);
600
600
  return positiveMod(inverseMultiplier * (cohortValue - 1 - offset), NUMERIC_COHORT_SIZE);
601
601
  }
602
- function getRolledOutNumericCohorts(bundleId, rolloutCohortCount) {
602
+ function getRolledOutNumericCohorts(releaseId, rolloutCohortCount) {
603
603
  const normalizedRolloutCount = normalizeRolloutCohortCount(rolloutCohortCount);
604
604
  if (normalizedRolloutCount <= 0) return [];
605
605
  if (normalizedRolloutCount >= 1e3) return Array.from({ length: NUMERIC_COHORT_SIZE }, (_, index) => index + 1);
606
- const { multiplier, offset } = getRolloutShuffleParameters(bundleId);
606
+ const { multiplier, offset } = getRolloutShuffleParameters(releaseId);
607
607
  return Array.from({ length: normalizedRolloutCount }, (_, position) => positiveMod(multiplier * position + offset, NUMERIC_COHORT_SIZE)).map((zeroBasedCohort) => zeroBasedCohort + 1).sort((left, right) => left - right);
608
608
  }
609
609
  const RELEASE_CATALOG_FALLBACK_POLICY = "BUILTIN_IF_ACTIVE_INELIGIBLE";
@@ -3313,7 +3313,7 @@ const build = (changes, current) => {
3313
3313
  return changes.map((change, at) => rewrites(change) ? rewrite(change, keys[at], current.get(rowId(change.model, keys[at])) ?? null) : increment(change, keys[at]));
3314
3314
  };
3315
3315
  const isOp = (op) => op !== void 0;
3316
- const sleep$2 = (attempt) => new Promise((resolve) => setTimeout(resolve, Math.min(250, 5 * 2 ** attempt) * Math.random()));
3316
+ const sleep$4 = (attempt) => new Promise((resolve) => setTimeout(resolve, Math.min(250, 5 * 2 ** attempt) * Math.random()));
3317
3317
  /** Runs of one character, where shorter: a sparse sketch packs into a few. */
3318
3318
  const pack = (text) => {
3319
3319
  const runs = (text.match(/(.)\1*/gsu) ?? []).flatMap((run) => [run[0], run.length]);
@@ -3462,7 +3462,7 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { windowMs
3462
3462
  const result = await adapter.write(ops);
3463
3463
  if (result.ok) return true;
3464
3464
  if (!("retry" in result)) return false;
3465
- await sleep$2(failures);
3465
+ await sleep$4(failures);
3466
3466
  }
3467
3467
  return false;
3468
3468
  };
@@ -4476,6 +4476,7 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
4476
4476
  let negative;
4477
4477
  let failures = 0;
4478
4478
  let lost;
4479
+ let busy = false;
4479
4480
  for (let round = 0;; round += 1) {
4480
4481
  const delay = round && Math.min(maxDelayMs, baseDelayMs * 2 ** (round - 1));
4481
4482
  if (delay > 0) await new Promise((resolve) => setTimeout(resolve, delay / 2 + Math.random() * (delay / 2)));
@@ -4486,6 +4487,7 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
4486
4487
  if (run === void 0) {
4487
4488
  onRetry?.("rerun", round + 1);
4488
4489
  lost = void 0;
4490
+ busy = false;
4489
4491
  if ((failures += 1) >= attempts) break;
4490
4492
  continue;
4491
4493
  }
@@ -4496,6 +4498,7 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
4496
4498
  if (!(error instanceof NegativeGaugeError)) throw error;
4497
4499
  negative = error;
4498
4500
  onRetry?.("rerun", round + 1);
4501
+ busy = false;
4499
4502
  run = void 0;
4500
4503
  lost = void 0;
4501
4504
  if ((failures += 1) >= attempts) break;
@@ -4516,6 +4519,7 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
4516
4519
  }
4517
4520
  if (outcome.ok) return run.result;
4518
4521
  const failed = "failedOp" in outcome ? outcome.failedOp : void 0;
4522
+ busy = failed === void 0;
4519
4523
  if (failed === void 0 || failed >= run.ops.length) {
4520
4524
  onRetry?.("resend", round + 1);
4521
4525
  failures += 1;
@@ -4529,7 +4533,7 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
4529
4533
  run = void 0;
4530
4534
  if ((failures += 1) >= attempts) break;
4531
4535
  }
4532
- throw negative ?? new DatabaseConflictError(`The transaction conflicted ${attempts} times.`);
4536
+ 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.`);
4533
4537
  } };
4534
4538
  };
4535
4539
  //#endregion
@@ -5226,7 +5230,7 @@ const createKvAdapter = ({ store, tablePrefix = "" }) => {
5226
5230
  };
5227
5231
  //#endregion
5228
5232
  //#region ../../packages/server/dist/version.mjs
5229
- const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.57";
5233
+ const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.59";
5230
5234
  //#endregion
5231
5235
  //#region ../../packages/server/dist/handlerVersionRoutes.mjs
5232
5236
  /**
@@ -6025,7 +6029,7 @@ const baseBundleIdsOf = (row, range, bundleId, limit) => {
6025
6029
  };
6026
6030
  //#endregion
6027
6031
  //#region ../../packages/server/dist/core/reads.mjs
6028
- const PAGE$4 = 500;
6032
+ const PAGE$5 = 500;
6029
6033
  const pick$2 = (fields) => (row) => Object.fromEntries(fields.map((field) => [field, row[field]]));
6030
6034
  const toBundleRow = pick$2([
6031
6035
  "id",
@@ -6122,7 +6126,7 @@ const createCoreReads = (db, storage) => {
6122
6126
  const page = await db.findMany("bundle_patches", {
6123
6127
  index: "byBundle",
6124
6128
  where: { bundle_id: row.id },
6125
- limit: Math.min(count - patches.length, PAGE$4),
6129
+ limit: Math.min(count - patches.length, PAGE$5),
6126
6130
  ...cursor === void 0 ? {} : { cursor }
6127
6131
  });
6128
6132
  patches.push(...page.rows.map(toPatchRow));
@@ -6348,7 +6352,7 @@ const createCoreReads = (db, storage) => {
6348
6352
  return (await drain$1((page) => db.findMany("channels", {
6349
6353
  index: "all",
6350
6354
  where: {},
6351
- limit: PAGE$4,
6355
+ limit: PAGE$5,
6352
6356
  ...page
6353
6357
  }))).map(toChannelRow);
6354
6358
  },
@@ -6743,7 +6747,10 @@ const createLabelAllocator = (tx, used, caughtUp) => {
6743
6747
  };
6744
6748
  };
6745
6749
  const FILL_BATCH = 25;
6746
- const PAGE$3 = 500;
6750
+ const PAGE$4 = 500;
6751
+ const PAUSE_MS$1 = 1e3;
6752
+ const MAX_PAUSE_MS$1 = 32e3;
6753
+ const sleep$3 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
6747
6754
  /**
6748
6755
  * Labels a channel and platform's releases that have none, in ID order,
6749
6756
  * which is the order they were created in, and marks its counter filled:
@@ -6755,6 +6762,7 @@ const fillLabels = async (db, { channelId, platform }, { dryRun = false } = {})
6755
6762
  const id = labelSequenceId(channelId, platform);
6756
6763
  let labeled = 0;
6757
6764
  let batchSize = FILL_BATCH;
6765
+ let paused = 0;
6758
6766
  const label = async (ids) => {
6759
6767
  for (let at = 0; at < ids.length;) {
6760
6768
  const batch = ids.slice(at, at + batchSize);
@@ -6779,12 +6787,16 @@ const fillLabels = async (db, { channelId, platform }, { dryRun = false } = {})
6779
6787
  return count;
6780
6788
  });
6781
6789
  at += batch.length;
6790
+ paused = 0;
6782
6791
  } catch (error) {
6783
6792
  if (batchSize > 1 && error instanceof DatabaseConstraintError && error.reason === "too_large") {
6784
6793
  batchSize = Math.max(1, Math.floor(batchSize / 2));
6785
6794
  continue;
6786
6795
  }
6787
- throw error;
6796
+ if (!isDatabaseBusyError(error) || paused >= MAX_PAUSE_MS$1) throw error;
6797
+ batchSize = Math.max(1, Math.floor(batchSize / 2));
6798
+ paused = paused === 0 ? PAUSE_MS$1 : paused * 2;
6799
+ await sleep$3(paused);
6788
6800
  }
6789
6801
  }
6790
6802
  };
@@ -6796,7 +6808,7 @@ const fillLabels = async (db, { channelId, platform }, { dryRun = false } = {})
6796
6808
  channel_id: channelId,
6797
6809
  platform
6798
6810
  },
6799
- limit: PAGE$3,
6811
+ limit: PAGE$4,
6800
6812
  ...cursor === void 0 ? {} : { cursor }
6801
6813
  });
6802
6814
  const unlabeled = page.rows.filter((row) => typeof row.label !== "number").map((row) => row.id);
@@ -6984,7 +6996,7 @@ const pendingLabelPairs = async (db) => {
6984
6996
  };
6985
6997
  //#endregion
6986
6998
  //#region ../../packages/server/dist/core/writes.mjs
6987
- const PAGE$2 = 500;
6999
+ const PAGE$3 = 500;
6988
7000
  /** Moves one bundle into or out of its platform's total and the overall total. */
6989
7001
  const countBundle = (tx, platform, delta) => {
6990
7002
  for (const key of [platform, "*"]) tx.aggregate("bundle_totals", { platform_key: key }, { bundles: delta });
@@ -7023,7 +7035,7 @@ const replaceBundlePatches = async (tx, bundle, rows, checkNew) => {
7023
7035
  const page = await tx.findMany("bundle_patches", {
7024
7036
  index: "byBundle",
7025
7037
  where: { bundle_id: bundle.id },
7026
- limit: Math.min(count - seen, PAGE$2),
7038
+ limit: Math.min(count - seen, PAGE$3),
7027
7039
  ...cursor === void 0 ? {} : { cursor }
7028
7040
  });
7029
7041
  for (const stored of page.rows) {
@@ -7587,7 +7599,7 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
7587
7599
  });
7588
7600
  //#endregion
7589
7601
  //#region ../../packages/server/dist/core/releases.mjs
7590
- const PAGE$1 = 500;
7602
+ const PAGE$2 = 500;
7591
7603
  const fail$1 = (code, message) => {
7592
7604
  throw new ReleaseCatalogMutationError(code, message);
7593
7605
  };
@@ -7622,7 +7634,7 @@ const enabledIn = (scopeKey, cursor) => ({
7622
7634
  scope_key: scopeKey,
7623
7635
  enabled: true
7624
7636
  },
7625
- limit: PAGE$1,
7637
+ limit: PAGE$2,
7626
7638
  ...cursor === void 0 ? {} : { cursor }
7627
7639
  });
7628
7640
  /** A scope's enabled releases, all of them, under the catalog's guard. */
@@ -10037,21 +10049,29 @@ const isLaunch = (row) => {
10037
10049
  const kinds = metadataOf(row).change?.kinds ?? [];
10038
10050
  return kinds.includes("bundle") && !kinds.includes("first_seen") && row.to_release_id !== null;
10039
10051
  };
10052
+ const sideRef = (key, releaseId, bundleId) => key === "release" ? releaseId ?? bundleId : bundleId;
10040
10053
  /**
10041
10054
  * The bundle a stored row's bundle filter matches: `from:<bundle>` for a
10042
10055
  * recovery; `to:<bundle>` for a download, an apply, and an update failure;
10043
10056
  * `on:<bundle>` for an UNCHANGED row that launched a bundle (`isLaunch`), a
10044
10057
  * key no other row uses. None for a failed check, which targets no bundle, a
10045
- * late row, or any other UNCHANGED row.
10058
+ * late row, or any other UNCHANGED row. Each names its bundle by `key`.
10046
10059
  */
10047
- const bundleRefsOf = (row) => {
10060
+ const bundleRefsOf = (row, key = "release") => {
10048
10061
  if (isFailedCheck(row) || isLateEvent(row)) return [];
10049
- if (row.type === "RECOVERED") return [`from:${row.from_bundle_id}`];
10050
- if (row.type === "UNCHANGED") return isLaunch(row) ? [`on:${row.to_bundle_id}`] : [];
10051
- return [`to:${row.to_bundle_id}`];
10062
+ if (row.type === "RECOVERED") return [`from:${sideRef(key, row.from_release_id, row.from_bundle_id)}`];
10063
+ if (row.type === "UNCHANGED") return isLaunch(row) ? [`on:${sideRef(key, row.to_release_id, row.to_bundle_id)}`] : [];
10064
+ return [`to:${sideRef(key, row.to_release_id, row.to_bundle_id)}`];
10052
10065
  };
10066
+ /**
10067
+ * The hourly outcome rows a stored row counts in, as `[type, bundle ref]`:
10068
+ * its bundle filter's (`bundleRefsOf`), and a download that a launch or
10069
+ * crash implied, in its bundle's download hour, so the download series
10070
+ * covers what the release's downloads count.
10071
+ */
10072
+ 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)}`]] : []];
10053
10073
  /** The key a bundle filter reads, as `bundleRefsOf` writes it. */
10054
- const bundleRefOfFilter = (filter) => filter.type === "RECOVERED" ? `from:${filter.fromBundleId}` : filter.type === "UNCHANGED" ? `on:${filter.toBundleId}` : `to:${filter.toBundleId}`;
10074
+ const bundleRefOfFilter = (filter) => filter.type === "RECOVERED" ? `from:${filter.fromReleaseId}` : filter.type === "UNCHANGED" ? `on:${filter.toReleaseId}` : `to:${filter.toReleaseId}`;
10055
10075
  /**
10056
10076
  * Downloads, applies, recoveries, update failures, and the UNCHANGED
10057
10077
  * reports that changed what their installation runs, whole. An UNCHANGED
@@ -10116,7 +10136,11 @@ const bundleEvents = (days) => defineTable({
10116
10136
  type: "string",
10117
10137
  compute: (row) => MOVEMENTS.has(row.type) ? row.install_id : null
10118
10138
  },
10119
- /** The bundle a bundle filter matches (`bundleRefsOf`). */
10139
+ /**
10140
+ * The bundle a bundle filter matches (`bundleRefsOf`), by release.
10141
+ * Rows a 1.1 server wrote name the artifact until
10142
+ * `backfillReleaseRefs` rewrites them.
10143
+ */
10120
10144
  bundle_ref: {
10121
10145
  type: "string",
10122
10146
  multi: true,
@@ -10435,7 +10459,13 @@ const insightsBuiltinDistribution = (retention) => defineAggregate({
10435
10459
  },
10436
10460
  retention
10437
10461
  });
10438
- /** Latest events by the bundle they came from or went to, bucketed like the distribution. */
10462
+ /**
10463
+ * Latest events by the artifact they came from or went to, bucketed like
10464
+ * the distribution, as 1.1 servers wrote them. Nothing writes or reads it
10465
+ * since a bundle's installations come from `insights_distribution`, which
10466
+ * names the release; it stays declared so retention still empties the rows
10467
+ * a 1.1 server wrote.
10468
+ */
10439
10469
  const insightsLatestByBundle = (retention) => defineAggregate({
10440
10470
  platform: {
10441
10471
  type: "string",
@@ -10483,7 +10513,9 @@ const insightsLatestByBundle = (retention) => defineAggregate({
10483
10513
  * Stored events by outcome and the bundle a bundle filter matches, a row an
10484
10514
  * hour, which a failed check has none of; and every stored event, a row a UTC
10485
10515
  * day (`DAILY_EVENTS`). Bundle counts sum the hourly rows, and event lists
10486
- * read either to skip days without events.
10516
+ * read either to skip days without events. `bundle_ref` names the release
10517
+ * (`outcomeRefsOf`); a 1.1 server's rows name the artifact until
10518
+ * `backfillReleaseRefs` moves their counts.
10487
10519
  */
10488
10520
  const insightsOutcomes = (retention) => defineAggregate({
10489
10521
  platform: {
@@ -10562,6 +10594,120 @@ const createInsightsSchema = ({ rawDays, dailyDays } = DEFAULT_INSIGHTS_RETENTIO
10562
10594
  };
10563
10595
  createInsightsSchema();
10564
10596
  //#endregion
10597
+ //#region ../insights/dist/server/backfill.mjs
10598
+ /**
10599
+ * Stored events read a page, and rewritten up to `BATCH` a transaction. A
10600
+ * run keeps one batch size, which only shrinks, halving whenever a store
10601
+ * refuses a batch:
10602
+ * - as too large, before writing anything: DynamoDB's 100 items hold fewer
10603
+ * than 25 rewrites with their index copies and counts;
10604
+ * - as busy through the transaction's retries: a write-capacity cap, such as
10605
+ * the 100 write units a second `hot-updater init` gives a DynamoDB table,
10606
+ * throttles a transaction that costs more than the cap admits, about 13
10607
+ * rewrites of 2 KB events there, and refuses every write for seconds once
10608
+ * the run has spent it.
10609
+ * After a busy refusal the run also waits before it writes again, `PAUSE_MS`
10610
+ * and twice as long after each further one, so the cap refills; a commit
10611
+ * starts the waits over. A batch the store still refuses after the
10612
+ * `MAX_PAUSE_MS` wait, or a one-event batch too large to write, fails the
10613
+ * run, which a rerun resumes.
10614
+ */
10615
+ const PAGE$1 = 500;
10616
+ const BATCH = 25;
10617
+ const PAUSE_MS = 1e3;
10618
+ const MAX_PAUSE_MS = 32e3;
10619
+ const sleep$2 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
10620
+ const sameRefs = (stored, refs) => {
10621
+ const values = Array.isArray(stored) ? stored : [];
10622
+ return values.length === refs.length && values.every((value) => refs.includes(value));
10623
+ };
10624
+ /**
10625
+ * Whether a stored event still names its artifact, as a 1.1 server wrote
10626
+ * it: its stored refs are the artifact's and differ from the release's. Its
10627
+ * stored refs are how its outcome rows counted it, so they are what a
10628
+ * rewrite moves, and a rewritten event reads as done.
10629
+ */
10630
+ const namesArtifact = (row) => {
10631
+ const byKey = (key) => bundleRefsOf(row, key);
10632
+ return sameRefs(row.bundle_ref, byKey("artifact")) && !sameRefs(row.bundle_ref, byKey("release"));
10633
+ };
10634
+ /**
10635
+ * Rewrites the stored events in the raw period whose refs name their
10636
+ * artifact, as 1.1 servers wrote them, to name their release, and moves
10637
+ * their hourly outcome counts with them, each event in the transaction that
10638
+ * rewrites it. Each event carries its own release IDs, so two releases of
10639
+ * one artifact in one scope come apart; an event without a release ID keeps
10640
+ * the bundle ID it reports, as new events do.
10641
+ *
10642
+ * It reads every stored event once and writes only those still to move, so
10643
+ * an interrupted run can run again. `hot-updater db migrate` and `hot-updater
10644
+ * init` run it once a database: when it completes they record the settings
10645
+ * row `insights.releaseRefs`, and later runs read no event. Installation
10646
+ * gauges need nothing: they name releases already.
10647
+ */
10648
+ const backfillReleaseRefs = async (db, now, { rawDays }, { dryRun = false } = {}) => {
10649
+ const today = now() - now() % DAY_MS$1;
10650
+ let events = 0;
10651
+ let size = BATCH;
10652
+ let paused = 0;
10653
+ const move = async (stale) => {
10654
+ if (dryRun) {
10655
+ events += stale.length;
10656
+ return;
10657
+ }
10658
+ for (let start = 0; start < stale.length;) {
10659
+ const candidates = stale.slice(start, start + size);
10660
+ try {
10661
+ events += await rewrite(candidates);
10662
+ start += candidates.length;
10663
+ paused = 0;
10664
+ } catch (error) {
10665
+ if (error instanceof DatabaseConstraintError && error.reason === "too_large" && candidates.length > 1) {
10666
+ size = Math.ceil(candidates.length / 2);
10667
+ continue;
10668
+ }
10669
+ if (!isDatabaseBusyError(error) || paused >= MAX_PAUSE_MS) throw error;
10670
+ size = Math.ceil(candidates.length / 2);
10671
+ paused = paused === 0 ? PAUSE_MS : paused * 2;
10672
+ await sleep$2(paused);
10673
+ }
10674
+ }
10675
+ };
10676
+ const rewrite = (candidates) => db.transaction(async (tx) => {
10677
+ const rows = await Promise.all(candidates.map(({ id }) => tx.findOne("bundle_events", { id })));
10678
+ let moved = 0;
10679
+ for (const row of rows) {
10680
+ if (row === null || !namesArtifact(row)) continue;
10681
+ tx.update("bundle_events", row, {});
10682
+ const outcome = (ref, delta) => tx.aggregate("insights_outcomes", {
10683
+ platform: row.platform,
10684
+ channel: row.channel,
10685
+ type: ref[0],
10686
+ bundle_ref: ref[1],
10687
+ bucket_start_ms: row.received_at_ms - row.received_at_ms % HOUR_MS$1
10688
+ }, { events: delta }, { shardBy: row.install_id });
10689
+ for (const ref of outcomeRefsOf(row, "artifact")) outcome(ref, -1);
10690
+ for (const ref of outcomeRefsOf(row, "release")) outcome(ref, 1);
10691
+ moved += 1;
10692
+ }
10693
+ return moved;
10694
+ });
10695
+ for (let day = today - rawDays * DAY_MS$1; day <= today; day += DAY_MS$1) {
10696
+ let cursor;
10697
+ do {
10698
+ const page = await db.findMany("bundle_events", {
10699
+ index: "byDay",
10700
+ where: { day },
10701
+ limit: PAGE$1,
10702
+ ...cursor === void 0 ? {} : { cursor }
10703
+ });
10704
+ await move(page.rows.filter(namesArtifact));
10705
+ cursor = page.next;
10706
+ } while (cursor !== void 0);
10707
+ }
10708
+ return { events };
10709
+ };
10710
+ //#endregion
10565
10711
  //#region ../insights/dist/server/eventRow.mjs
10566
10712
  const CHANGE_KINDS = /* @__PURE__ */ new Set([
10567
10713
  "first_seen",
@@ -10658,7 +10804,7 @@ const isBundleFilter = (value, withKind = false) => {
10658
10804
  "type",
10659
10805
  ...withKind ? ["kind"] : []
10660
10806
  ];
10661
- 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"]);
10807
+ 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"]);
10662
10808
  };
10663
10809
  const isEventFilter = (value) => {
10664
10810
  if (!isRecord$3(value)) return false;
@@ -10759,20 +10905,24 @@ const createValidatedInsightsModel = (model) => ({
10759
10905
  if (!isRecord$3(input) || !hasOnlyKeys(input, [
10760
10906
  "platform",
10761
10907
  "channel",
10762
- "sinceMs",
10763
- "bundle"
10764
- ]) || !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, [
10765
- "field",
10766
- "value",
10767
- "types"
10768
- ]) || 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) => ![
10769
- "UNCHANGED",
10770
- "UPDATE_DOWNLOADED",
10771
- "UPDATE_APPLIED",
10772
- "RECOVERED"
10773
- ].includes(type))))) invalidQuery();
10908
+ "sinceMs"
10909
+ ]) || !hasScope(input) || !isTimestamp(input.sinceMs)) invalidQuery();
10774
10910
  return validateCount(await model.countLatestEvents(input));
10775
10911
  },
10912
+ async countReleaseInstallations(input) {
10913
+ if (!isRecord$3(input) || !hasOnlyKeys(input, [
10914
+ "platform",
10915
+ "channel",
10916
+ "sinceMs",
10917
+ "releaseId"
10918
+ ]) || !hasScope(input) || !isTimestamp(input.sinceMs) || !isText$1(input.releaseId)) invalidQuery();
10919
+ const counts = await model.countReleaseInstallations(input);
10920
+ if (!isRecord$3(counts) || !hasOnlyKeys(counts, ["installations", "release"])) invalidResult();
10921
+ return {
10922
+ installations: validateCount(counts.installations),
10923
+ release: validateCount(counts.release)
10924
+ };
10925
+ },
10776
10926
  async countEvents(input) {
10777
10927
  if (!isRecord$3(input) || !hasOnlyKeys(input, [
10778
10928
  "filter",
@@ -10829,6 +10979,7 @@ const createInsightsModel = (api) => createValidatedInsightsModel({
10829
10979
  listEvents: api.listEvents,
10830
10980
  findLatestEvents: api.findLatestEvents,
10831
10981
  countLatestEvents: api.countLatestEvents,
10982
+ countReleaseInstallations: api.countReleaseInstallations,
10832
10983
  countEvents: api.countEvents,
10833
10984
  countEventSeries: api.countEventSeries,
10834
10985
  getReleaseActivity: api.getReleaseActivity,
@@ -11231,27 +11382,27 @@ const readScope$1 = (input) => {
11231
11382
  };
11232
11383
  const bundleFilter = (input) => {
11233
11384
  const scope = readScope$1(input);
11234
- const bundleId = requireString(input.bundleId, "bundle ID", MAX_EVENT_ID_LENGTH);
11385
+ const releaseId = requireString(input.releaseId, "bundle ID", MAX_EVENT_ID_LENGTH);
11235
11386
  switch (input.outcome) {
11236
11387
  case "downloaded": return {
11237
11388
  ...scope,
11238
11389
  type: "UPDATE_DOWNLOADED",
11239
- toBundleId: bundleId
11390
+ toReleaseId: releaseId
11240
11391
  };
11241
11392
  case "applied": return {
11242
11393
  ...scope,
11243
11394
  type: "UPDATE_APPLIED",
11244
- toBundleId: bundleId
11395
+ toReleaseId: releaseId
11245
11396
  };
11246
11397
  case "recovered": return {
11247
11398
  ...scope,
11248
11399
  type: "RECOVERED",
11249
- fromBundleId: bundleId
11400
+ fromReleaseId: releaseId
11250
11401
  };
11251
11402
  case "failed": return {
11252
11403
  ...scope,
11253
11404
  type: "UPDATE_FAILED",
11254
- toBundleId: bundleId
11405
+ toReleaseId: releaseId
11255
11406
  };
11256
11407
  default: throw new InsightsBadRequestError("Invalid Insights outcome.");
11257
11408
  }
@@ -11261,7 +11412,7 @@ const sameFilter = (left, right) => {
11261
11412
  switch (right.kind) {
11262
11413
  case "all": return true;
11263
11414
  case "installationMovement": return left.installId === right.installId;
11264
- 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);
11415
+ 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);
11265
11416
  }
11266
11417
  };
11267
11418
  const readEventCursor = (value, filter) => {
@@ -11298,7 +11449,7 @@ const assertEventRows = (rows, input) => {
11298
11449
  for (let index = 0; index < rows.length; index += 1) {
11299
11450
  const row = rows[index];
11300
11451
  const previous = rows[index - 1];
11301
- 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.");
11452
+ 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.");
11302
11453
  }
11303
11454
  };
11304
11455
  /** An `UPDATE_FAILED` row's failure, as the event lists show it. */
@@ -11339,6 +11490,7 @@ const eventDetails = ({ type, metadata }) => ({
11339
11490
  ...metadata.implied_download === true ? { impliedDownload: true } : {}
11340
11491
  });
11341
11492
  const toEventHistoryRow = (row) => ({
11493
+ ...row.from_release_id == null ? {} : { fromReleaseId: row.from_release_id },
11342
11494
  ...row.to_release_id == null ? {} : { toReleaseId: row.to_release_id },
11343
11495
  ...row.metadata.sdk_version == null ? {} : { sdkVersion: row.metadata.sdk_version },
11344
11496
  ...row.metadata.min_bundle_id === void 0 ? {} : { minBundleId: row.metadata.min_bundle_id },
@@ -11363,6 +11515,7 @@ const toInstallationRow = (row) => ({
11363
11515
  cohort: row.metadata.cohort,
11364
11516
  installId: row.install_id,
11365
11517
  lastKnownBundleId: row.type === "UPDATE_DOWNLOADED" ? row.from_bundle_id : row.to_bundle_id,
11518
+ lastKnownReleaseId: row.type === "UPDATE_DOWNLOADED" ? row.from_release_id : row.to_release_id,
11366
11519
  pendingBundleId: row.type === "UPDATE_DOWNLOADED" ? row.to_bundle_id : null,
11367
11520
  pendingReleaseId: row.type === "UPDATE_DOWNLOADED" ? row.to_release_id : null,
11368
11521
  latestStatus: row.type,
@@ -11491,46 +11644,33 @@ const createInsightsProvider = (model) => Object.freeze({
11491
11644
  measuredAtMs: Date.now()
11492
11645
  };
11493
11646
  };
11494
- const bundleId = input.bundleId === void 0 ? void 0 : requireString(input.bundleId, "bundle ID", MAX_EVENT_ID_LENGTH);
11495
- const reporting = measure(model.countLatestEvents({
11496
- ...scope,
11497
- sinceMs
11498
- }));
11499
- if (bundleId === void 0) return {
11647
+ const releaseId = input.releaseId === void 0 ? void 0 : requireString(input.releaseId, "bundle ID", MAX_EVENT_ID_LENGTH);
11648
+ if (releaseId === void 0) return {
11500
11649
  ...scope,
11501
11650
  window,
11502
11651
  sinceMs,
11503
11652
  beforeReceivedAtMs,
11504
- reportingInstallations: await reporting
11653
+ reportingInstallations: await measure(model.countLatestEvents({
11654
+ ...scope,
11655
+ sinceMs
11656
+ }))
11505
11657
  };
11658
+ const installations = model.countReleaseInstallations({
11659
+ ...scope,
11660
+ sinceMs,
11661
+ releaseId
11662
+ }).then(async (counts) => [await measure(Promise.resolve(counts.installations)), await measure(Promise.resolve(counts.release))]);
11506
11663
  const countOutcome = (outcome) => measure(model.countEvents({
11507
11664
  filter: bundleFilter({
11508
11665
  ...scope,
11509
- bundleId,
11666
+ releaseId,
11510
11667
  outcome
11511
11668
  }),
11512
11669
  sinceMs,
11513
11670
  beforeReceivedAtMs
11514
11671
  }));
11515
- const [reportingInstallations, bundleInstallations, downloadedReports, appliedReports, recoveredReports, failedReports] = await Promise.all([
11516
- reporting,
11517
- measure(model.countLatestEvents({
11518
- ...scope,
11519
- sinceMs,
11520
- bundle: [{
11521
- field: "from_bundle_id",
11522
- value: bundleId,
11523
- types: ["UPDATE_DOWNLOADED"]
11524
- }, {
11525
- field: "to_bundle_id",
11526
- value: bundleId,
11527
- types: [
11528
- "UNCHANGED",
11529
- "UPDATE_APPLIED",
11530
- "RECOVERED"
11531
- ]
11532
- }]
11533
- })),
11672
+ const [[reportingInstallations, bundleInstallations], downloadedReports, appliedReports, recoveredReports, failedReports] = await Promise.all([
11673
+ installations,
11534
11674
  countOutcome("downloaded"),
11535
11675
  countOutcome("applied"),
11536
11676
  countOutcome("recovered"),
@@ -11543,7 +11683,7 @@ const createInsightsProvider = (model) => Object.freeze({
11543
11683
  beforeReceivedAtMs,
11544
11684
  reportingInstallations,
11545
11685
  bundle: {
11546
- bundleId,
11686
+ releaseId,
11547
11687
  reportingInstallations: bundleInstallations,
11548
11688
  downloadedReports,
11549
11689
  appliedReports,
@@ -11678,17 +11818,10 @@ const gaugeSlot = (head) => ({
11678
11818
  builtinBundleId: runningBuiltinBundleId(head)
11679
11819
  });
11680
11820
  /**
11681
- * The `insights_latest_by_bundle` field of a head's (from, to) pair. A head
11682
- * matches a `from` and a `to` predicate of one type at once only through its
11683
- * pair, so this gauge is what a count subtracts to count it once.
11684
- */
11685
- const PAIR_FIELD = "from_to";
11686
- /** The pair gauge's `bundle_id`: a hash of the two bundle ids, which fit no single 36-character column. */
11687
- const bundlePairKey = (from, to) => insightsKey(`${from.length}:${from}${to.length}:${to}`);
11688
- /**
11689
11821
  * Moves a head's gauges: the distribution row, and the built-in one when it
11690
- * runs its build's built-in bundle, one row per bundle it references, and
11691
- * its pair; -1 takes back the head an event replaces.
11822
+ * runs its build's built-in bundle; -1 takes back the head an event
11823
+ * replaces. The distribution row names the release the head runs, so it is
11824
+ * also each release's installation gauge.
11692
11825
  */
11693
11826
  const countHead = (tx, head, delta) => {
11694
11827
  const { bucket, releaseId, builtinBundleId } = gaugeSlot(head);
@@ -11708,26 +11841,6 @@ const countHead = (tx, head, delta) => {
11708
11841
  builtin_bundle_id: builtinBundleId,
11709
11842
  bucket_start_ms: bucket
11710
11843
  }, { latest_installations: delta }, { shardBy });
11711
- for (const field of ["from_bundle_id", "to_bundle_id"]) {
11712
- const bundleId = head[field];
11713
- if (bundleId === null) continue;
11714
- tx.aggregate("insights_latest_by_bundle", {
11715
- platform: head.platform,
11716
- channel: head.channel,
11717
- bundle_field: field,
11718
- bundle_id: bundleId,
11719
- type: head.type,
11720
- bucket_start_ms: bucket
11721
- }, { installations: delta }, { shardBy });
11722
- }
11723
- if (head.from_bundle_id !== null) tx.aggregate("insights_latest_by_bundle", {
11724
- platform: head.platform,
11725
- channel: head.channel,
11726
- bundle_field: PAIR_FIELD,
11727
- bundle_id: bundlePairKey(head.from_bundle_id, head.to_bundle_id),
11728
- type: head.type,
11729
- bucket_start_ms: bucket
11730
- }, { installations: delta }, { shardBy });
11731
11844
  };
11732
11845
  /**
11733
11846
  * Where each period's rows go, each with its retention: hours for 90 days,
@@ -11788,26 +11901,19 @@ const countEvent = (tx, event) => {
11788
11901
  }
11789
11902
  };
11790
11903
  /**
11791
- * A stored event's outcome rows: its bundle filter's hour, when it has one
11792
- * (`bundleRefsOf`), and every stored event's UTC day. A download that a
11793
- * launch or crash implied counts in its bundle's download hour too, in the
11794
- * hour of that launch or crash, so the download series covers what the
11795
- * release's downloads count; the launch or crash is its row.
11904
+ * A stored event's outcome rows: its bundle filter's hour, and the download
11905
+ * hour of a download its launch or crash implied, each by release
11906
+ * (`outcomeRefsOf`); and every stored event's UTC day.
11796
11907
  */
11797
11908
  const countOutcome = (tx, event) => {
11798
11909
  const shardBy = event.install_id;
11799
- const hour = (type, bundleRef) => tx.aggregate("insights_outcomes", {
11910
+ for (const [type, bundleRef] of outcomeRefsOf(event)) tx.aggregate("insights_outcomes", {
11800
11911
  platform: event.platform,
11801
11912
  channel: event.channel,
11802
11913
  type,
11803
11914
  bundle_ref: bundleRef,
11804
11915
  bucket_start_ms: hourOf(event.received_at_ms)
11805
11916
  }, { events: 1 }, { shardBy });
11806
- for (const bundleRef of bundleRefsOf(event)) hour(event.type, bundleRef);
11807
- if (event.metadata.implied_download === true) hour("UPDATE_DOWNLOADED", bundleRefOfFilter({
11808
- type: "UPDATE_DOWNLOADED",
11809
- toBundleId: event.type === "RECOVERED" ? event.from_bundle_id : event.to_bundle_id
11810
- }));
11811
11917
  tx.aggregate("insights_outcomes", {
11812
11918
  ...DAILY_EVENTS,
11813
11919
  bucket_start_ms: dayOf(event.received_at_ms)
@@ -12287,31 +12393,48 @@ const countEventSeries = async (db, input) => {
12287
12393
  events: count
12288
12394
  }));
12289
12395
  };
12290
- /** A bundle filter's distinct (field, value, type) predicates. */
12291
- const latestPredicates = (bundle) => {
12292
- if (bundle === void 0) return void 0;
12293
- return [...new Map(bundle.flatMap(({ field, value, types }) => types.map((type) => [JSON.stringify([
12294
- field,
12295
- value,
12296
- type
12297
- ]), {
12298
- field,
12299
- value,
12300
- type
12301
- }]))).values()];
12396
+ /** The distribution rows at or after `start`, a UTC day's start. */
12397
+ const distributionRows = (db, { platform, channel, sinceMs: start }) => {
12398
+ if (start % 864e5 !== 0) throw new DatabaseAdapterInputError("invalid-query");
12399
+ return drain((page) => db.findAggregates("insights_distribution", {
12400
+ index: "byScope",
12401
+ where: {
12402
+ channel,
12403
+ platform
12404
+ },
12405
+ range: { gte: start },
12406
+ limit: PAGE,
12407
+ ...page
12408
+ }));
12302
12409
  };
12410
+ const installations = (count) => Math.max(0, count);
12303
12411
  /**
12304
12412
  * Latest events at or after `sinceMs`, a UTC day's start: the gauges count
12305
12413
  * each installation in the UTC day of its latest event, so they answer whole
12306
12414
  * days only, and a later start is rejected rather than rounded.
12307
12415
  */
12308
- const countLatestEvents = async (db, input) => {
12309
- const { platform, channel, sinceMs: start } = input;
12310
- if (start % 864e5 !== 0) throw new DatabaseAdapterInputError("invalid-query");
12311
- const predicates = latestPredicates(input.bundle);
12416
+ const countLatestEvents = async (db, input) => installations((await distributionRows(db, input)).reduce((sum, row) => sum + row.latest_installations, 0));
12417
+ /**
12418
+ * `countLatestEvents`, and of those the installations it leaves running
12419
+ * `releaseId`, from the same distribution rows in one read: each names the
12420
+ * release its installations run. An ID no row names as a release may be a
12421
+ * built-in bundle's, which a report without a release names, as event
12422
+ * counts match it: its installations outside any release are in the
12423
+ * built-in rows, read only then. Release and bundle IDs never coincide.
12424
+ */
12425
+ const countReleaseInstallations = async (db, input) => {
12426
+ const { platform, channel, sinceMs: start, releaseId } = input;
12312
12427
  let total = 0;
12313
- if (predicates === void 0) {
12314
- const rows = await drain((page) => db.findAggregates("insights_distribution", {
12428
+ let release = 0;
12429
+ let named = false;
12430
+ for (const row of await distributionRows(db, input)) {
12431
+ total += row.latest_installations;
12432
+ if (row.release_id !== releaseId) continue;
12433
+ named = true;
12434
+ release += row.latest_installations;
12435
+ }
12436
+ if (!named) {
12437
+ const builtin = await drain((page) => db.findAggregates("insights_builtin_distribution", {
12315
12438
  index: "byScope",
12316
12439
  where: {
12317
12440
  channel,
@@ -12321,33 +12444,12 @@ const countLatestEvents = async (db, input) => {
12321
12444
  limit: PAGE,
12322
12445
  ...page
12323
12446
  }));
12324
- total += rows.reduce((sum, row) => sum + row.latest_installations, 0);
12325
- } else {
12326
- const gauge = async (bundleField, bundleId, type) => {
12327
- return (await drain((page) => db.findAggregates("insights_latest_by_bundle", {
12328
- index: "byBundle",
12329
- where: {
12330
- platform,
12331
- channel,
12332
- bundle_field: bundleField,
12333
- bundle_id: bundleId,
12334
- type
12335
- },
12336
- range: { gte: start },
12337
- limit: PAGE,
12338
- ...page
12339
- }))).reduce((sum, row) => sum + row.installations, 0);
12340
- };
12341
- for (const { field, value, type } of predicates) total += await gauge(field, value, type);
12342
- for (const from of predicates) {
12343
- if (from.field !== "from_bundle_id") continue;
12344
- for (const to of predicates) {
12345
- if (to.field !== "to_bundle_id" || to.type !== from.type) continue;
12346
- total -= await gauge(PAIR_FIELD, bundlePairKey(from.value, to.value), from.type);
12347
- }
12348
- }
12447
+ for (const row of builtin) if (row.release_id === "" && row.builtin_bundle_id === releaseId) release += row.latest_installations;
12349
12448
  }
12350
- return Math.max(0, total);
12449
+ return {
12450
+ installations: installations(total),
12451
+ release: installations(release)
12452
+ };
12351
12453
  };
12352
12454
  /** The oldest whole hour and UTC day that hourly and daily rows still hold. */
12353
12455
  const retained = (now, { rawDays, dailyDays }) => ({
@@ -12817,6 +12919,26 @@ const getUpdateFailures = async (db, input, now, retention) => {
12817
12919
  };
12818
12920
  };
12819
12921
  //#endregion
12922
+ //#region ../insights/dist/server/wire.mjs
12923
+ /**
12924
+ * The HTTP API calls a release ID `bundleId`, the word users have for it, in
12925
+ * its query parameters and its overview's JSON. The code calls it
12926
+ * `releaseId`; only this module maps between the two names.
12927
+ */
12928
+ const RELEASE_ID_PARAM = "bundleId";
12929
+ /** An overview as the HTTP API and the CLI's `--json` send it. */
12930
+ const toWireOverview = ({ bundle, ...overview }) => {
12931
+ if (bundle === void 0) return overview;
12932
+ const { releaseId, ...counts } = bundle;
12933
+ return {
12934
+ ...overview,
12935
+ bundle: {
12936
+ ...counts,
12937
+ bundleId: releaseId
12938
+ }
12939
+ };
12940
+ };
12941
+ //#endregion
12820
12942
  //#region ../insights/dist/server/queryInput.mjs
12821
12943
  const MAX_PAGE_LIMIT = 100;
12822
12944
  const MAX_IDENTITY_LENGTH = 255;
@@ -12861,7 +12983,7 @@ const readScope = (url) => {
12861
12983
  const parseEventPageInput = (request) => {
12862
12984
  const url = new URL(request.url);
12863
12985
  const bundleFields = [
12864
- "bundleId",
12986
+ RELEASE_ID_PARAM,
12865
12987
  "outcome",
12866
12988
  "platform",
12867
12989
  "channel"
@@ -12872,7 +12994,7 @@ const parseEventPageInput = (request) => {
12872
12994
  if (outcome !== "downloaded" && outcome !== "applied" && outcome !== "recovered" && outcome !== "failed") throw new InsightsBadRequestError("Invalid 'outcome' query parameter.");
12873
12995
  bundle = {
12874
12996
  ...readScope(url),
12875
- bundleId: readId(url, "bundleId", 1024),
12997
+ releaseId: readId(url, RELEASE_ID_PARAM, 1024),
12876
12998
  outcome
12877
12999
  };
12878
13000
  }
@@ -12898,11 +13020,10 @@ const parseReportingOverviewInput = (request) => {
12898
13020
  const url = new URL(request.url);
12899
13021
  const window = readSingle(url, "window") ?? "30d";
12900
13022
  if (window !== "24h" && window !== "7d" && window !== "30d") throw new InsightsBadRequestError("Invalid 'window' query parameter.");
12901
- const bundleId = readSingle(url, "bundleId");
12902
13023
  return {
12903
13024
  ...readScope(url),
12904
13025
  window,
12905
- ...bundleId === void 0 ? {} : { bundleId: readId(url, "bundleId", 1024) }
13026
+ ...readSingle(url, "bundleId") === void 0 ? {} : { releaseId: readId(url, RELEASE_ID_PARAM, 1024) }
12906
13027
  };
12907
13028
  };
12908
13029
  //#endregion
@@ -12983,7 +13104,7 @@ const createInsightsRouteHandlers = (provider) => ({
12983
13104
  await provider.appendBundleEvent(await parseBundleEventRequest(request));
12984
13105
  return new Response(null, { status: 204 });
12985
13106
  }),
12986
- getReportingOverview: (_params, request) => query(() => provider.getReportingOverview(parseReportingOverviewInput(request))),
13107
+ getReportingOverview: (_params, request) => query(async () => toWireOverview(await provider.getReportingOverview(parseReportingOverviewInput(request)))),
12987
13108
  getInstallation: (params) => run$1(async () => {
12988
13109
  const installation = await provider.getInstallation({ installId: requireParam(params, "installId") });
12989
13110
  return installation === null ? json$1({ error: "Installation not found" }, 404) : json$1(installation, 200);
@@ -13005,12 +13126,20 @@ const createInsightsApi = (db, now, retention) => ({
13005
13126
  listEvents: (input) => listEvents(db, input),
13006
13127
  findLatestEvents: (input) => findLatestEvents(db, input),
13007
13128
  countLatestEvents: (input) => countLatestEvents(db, input),
13129
+ countReleaseInstallations: (input) => countReleaseInstallations(db, input),
13008
13130
  countEvents: (input) => countEvents(db, input),
13009
13131
  countEventSeries: (input) => countEventSeries(db, input),
13010
13132
  getReleaseActivity: (input) => getReleaseActivity(db, input, now),
13011
13133
  getAppUsage: (input) => getAppUsage(db, input, now, retention),
13012
13134
  /** A release's or a channel's update failures, and their breakdown over a time range. */
13013
- getUpdateFailures: (input) => getUpdateFailures(db, input, now, retention)
13135
+ getUpdateFailures: (input) => getUpdateFailures(db, input, now, retention),
13136
+ /**
13137
+ * Moves the stored events a 1.1 server keyed by artifact, and their
13138
+ * outcome counts, to their release, reading every stored event of the
13139
+ * raw period: `hot-updater db migrate` and `hot-updater init` run it once
13140
+ * a database, and an interrupted run can run again.
13141
+ */
13142
+ backfillReleaseRefs: (options) => backfillReleaseRefs(db, now, retention, options)
13014
13143
  });
13015
13144
  /** `GET /failures`'s query: a scope, an optional release, and a time range or none. */
13016
13145
  const readFailuresQuery = (url) => {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@hot-updater/aws",
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
  "module": "dist/index.mjs",
@@ -45,9 +45,9 @@
45
45
  "es-toolkit": "^1.32.0",
46
46
  "execa": "9.5.2",
47
47
  "mime": "^4.0.4",
48
- "@hot-updater/protocol": "1.2.0-rc.57",
49
- "@hot-updater/mock": "1.2.0-rc.57",
50
- "@hot-updater/test-utils": "1.2.0-rc.57"
48
+ "@hot-updater/protocol": "1.2.0-rc.59",
49
+ "@hot-updater/mock": "1.2.0-rc.59",
50
+ "@hot-updater/test-utils": "1.2.0-rc.59"
51
51
  },
52
52
  "dependencies": {
53
53
  "@aws-sdk/client-cloudfront": "3.1066.0",
@@ -64,10 +64,10 @@
64
64
  "@aws-sdk/lib-dynamodb": "3.1066.0",
65
65
  "@aws-sdk/s3-request-presigner": "3.1066.0",
66
66
  "hono": "4.12.34",
67
- "@hot-updater/plugin-core": "1.2.0-rc.57",
68
- "@hot-updater/server": "1.2.0-rc.57",
69
- "@hot-updater/cli-tools": "1.2.0-rc.57",
70
- "@hot-updater/storage-s3": "1.2.0-rc.57"
67
+ "@hot-updater/cli-tools": "1.2.0-rc.59",
68
+ "@hot-updater/plugin-core": "1.2.0-rc.59",
69
+ "@hot-updater/server": "1.2.0-rc.59",
70
+ "@hot-updater/storage-s3": "1.2.0-rc.59"
71
71
  },
72
72
  "scripts": {
73
73
  "build": "tsdown",