@hot-updater/azure 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.
@@ -4339,14 +4339,14 @@ function modularInverse(value, modulus) {
4339
4339
  if (r > 1) throw new Error(`No modular inverse for ${value} mod ${modulus}`);
4340
4340
  return positiveMod(t, modulus);
4341
4341
  }
4342
- function getRolloutShuffleParameters(bundleId) {
4343
- let multiplier = positiveMod(hashString(`${bundleId}:multiplier`), 997);
4342
+ function getRolloutShuffleParameters(releaseId) {
4343
+ let multiplier = positiveMod(hashString(`${releaseId}:multiplier`), 997);
4344
4344
  if (multiplier === 0) multiplier = 1;
4345
4345
  while (gcd(multiplier, NUMERIC_COHORT_SIZE) !== 1) {
4346
4346
  multiplier = positiveMod(multiplier + 1, NUMERIC_COHORT_SIZE);
4347
4347
  if (multiplier === 0) multiplier = 1;
4348
4348
  }
4349
- const offset = positiveMod(hashString(`${bundleId}:offset`), NUMERIC_COHORT_SIZE);
4349
+ const offset = positiveMod(hashString(`${releaseId}:offset`), NUMERIC_COHORT_SIZE);
4350
4350
  return {
4351
4351
  multiplier,
4352
4352
  offset,
@@ -4379,16 +4379,16 @@ function isValidCohort(cohort) {
4379
4379
  const normalized = normalizeCohortValue(cohort);
4380
4380
  return isNumericCohort(normalized) || isCustomCohort(normalized);
4381
4381
  }
4382
- function getNumericCohortRolloutPosition(bundleId, cohortValue) {
4382
+ function getNumericCohortRolloutPosition(releaseId, cohortValue) {
4383
4383
  if (cohortValue < 1 || cohortValue > 1e3) throw new Error(`Invalid numeric cohort: ${cohortValue}`);
4384
- const { offset, inverseMultiplier } = getRolloutShuffleParameters(bundleId);
4384
+ const { offset, inverseMultiplier } = getRolloutShuffleParameters(releaseId);
4385
4385
  return positiveMod(inverseMultiplier * (cohortValue - 1 - offset), NUMERIC_COHORT_SIZE);
4386
4386
  }
4387
- function getRolledOutNumericCohorts(bundleId, rolloutCohortCount) {
4387
+ function getRolledOutNumericCohorts(releaseId, rolloutCohortCount) {
4388
4388
  const normalizedRolloutCount = normalizeRolloutCohortCount(rolloutCohortCount);
4389
4389
  if (normalizedRolloutCount <= 0) return [];
4390
4390
  if (normalizedRolloutCount >= 1e3) return Array.from({ length: NUMERIC_COHORT_SIZE }, (_, index) => index + 1);
4391
- const { multiplier, offset } = getRolloutShuffleParameters(bundleId);
4391
+ const { multiplier, offset } = getRolloutShuffleParameters(releaseId);
4392
4392
  return Array.from({ length: normalizedRolloutCount }, (_, position) => positiveMod(multiplier * position + offset, NUMERIC_COHORT_SIZE)).map((zeroBasedCohort) => zeroBasedCohort + 1).sort((left, right) => left - right);
4393
4393
  }
4394
4394
  const RELEASE_CATALOG_FALLBACK_POLICY = "BUILTIN_IF_ACTIVE_INELIGIBLE";
@@ -6743,7 +6743,7 @@ const build = (changes, current) => {
6743
6743
  return changes.map((change, at) => rewrites(change) ? rewrite(change, keys[at], current.get(rowId(change.model, keys[at])) ?? null) : increment(change, keys[at]));
6744
6744
  };
6745
6745
  const isOp = (op) => op !== void 0;
6746
- const sleep$1 = (attempt) => new Promise((resolve) => setTimeout(resolve, Math.min(250, 5 * 2 ** attempt) * Math.random()));
6746
+ const sleep$3 = (attempt) => new Promise((resolve) => setTimeout(resolve, Math.min(250, 5 * 2 ** attempt) * Math.random()));
6747
6747
  const pack = (text) => {
6748
6748
  const runs = (text.match(/(.)\1*/gsu) ?? []).flatMap((run) => [run[0], run.length]);
6749
6749
  return JSON.stringify(runs).length < JSON.stringify(text).length ? runs : text;
@@ -6862,7 +6862,7 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { windowMs
6862
6862
  const result = await adapter.write(ops);
6863
6863
  if (result.ok) return true;
6864
6864
  if (!("retry" in result)) return false;
6865
- await sleep$1(failures);
6865
+ await sleep$3(failures);
6866
6866
  }
6867
6867
  return false;
6868
6868
  };
@@ -7805,6 +7805,7 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
7805
7805
  let negative;
7806
7806
  let failures = 0;
7807
7807
  let lost;
7808
+ let busy = false;
7808
7809
  for (let round = 0;; round += 1) {
7809
7810
  const delay = round && Math.min(maxDelayMs, baseDelayMs * 2 ** (round - 1));
7810
7811
  if (delay > 0) await new Promise((resolve) => setTimeout(resolve, delay / 2 + Math.random() * (delay / 2)));
@@ -7815,6 +7816,7 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
7815
7816
  if (run === void 0) {
7816
7817
  onRetry?.("rerun", round + 1);
7817
7818
  lost = void 0;
7819
+ busy = false;
7818
7820
  if ((failures += 1) >= attempts) break;
7819
7821
  continue;
7820
7822
  }
@@ -7825,6 +7827,7 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
7825
7827
  if (!(error instanceof NegativeGaugeError)) throw error;
7826
7828
  negative = error;
7827
7829
  onRetry?.("rerun", round + 1);
7830
+ busy = false;
7828
7831
  run = void 0;
7829
7832
  lost = void 0;
7830
7833
  if ((failures += 1) >= attempts) break;
@@ -7845,6 +7848,7 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
7845
7848
  }
7846
7849
  if (outcome.ok) return run.result;
7847
7850
  const failed = "failedOp" in outcome ? outcome.failedOp : void 0;
7851
+ busy = failed === void 0;
7848
7852
  if (failed === void 0 || failed >= run.ops.length) {
7849
7853
  onRetry?.("resend", round + 1);
7850
7854
  failures += 1;
@@ -7858,7 +7862,7 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
7858
7862
  run = void 0;
7859
7863
  if ((failures += 1) >= attempts) break;
7860
7864
  }
7861
- throw negative ?? new DatabaseConflictError(`The transaction conflicted ${attempts} times.`);
7865
+ 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.`);
7862
7866
  } };
7863
7867
  };
7864
7868
  //#endregion
@@ -8484,7 +8488,7 @@ const createKvAdapter = ({ store, tablePrefix = "" }) => {
8484
8488
  };
8485
8489
  //#endregion
8486
8490
  //#region ../../packages/server/dist/version.mjs
8487
- const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.57";
8491
+ const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.59";
8488
8492
  //#endregion
8489
8493
  //#region ../../packages/server/dist/handlerVersionRoutes.mjs
8490
8494
  const createVersionRouteHandlers = (plugins = []) => {
@@ -9222,7 +9226,7 @@ const baseBundleIdsOf = (row, range, bundleId, limit) => {
9222
9226
  };
9223
9227
  //#endregion
9224
9228
  //#region ../../packages/server/dist/core/reads.mjs
9225
- const PAGE$4 = 500;
9229
+ const PAGE$5 = 500;
9226
9230
  const pick$2 = (fields) => (row) => Object.fromEntries(fields.map((field) => [field, row[field]]));
9227
9231
  const toBundleRow = pick$2([
9228
9232
  "id",
@@ -9313,7 +9317,7 @@ const createCoreReads = (db, storage) => {
9313
9317
  const page = await db.findMany("bundle_patches", {
9314
9318
  index: "byBundle",
9315
9319
  where: { bundle_id: row.id },
9316
- limit: Math.min(count - patches.length, PAGE$4),
9320
+ limit: Math.min(count - patches.length, PAGE$5),
9317
9321
  ...cursor === void 0 ? {} : { cursor }
9318
9322
  });
9319
9323
  patches.push(...page.rows.map(toPatchRow));
@@ -9517,7 +9521,7 @@ const createCoreReads = (db, storage) => {
9517
9521
  return (await drain$1((page) => db.findMany("channels", {
9518
9522
  index: "all",
9519
9523
  where: {},
9520
- limit: PAGE$4,
9524
+ limit: PAGE$5,
9521
9525
  ...page
9522
9526
  }))).map(toChannelRow);
9523
9527
  },
@@ -9873,11 +9877,15 @@ const createLabelAllocator = (tx, used, caughtUp) => {
9873
9877
  };
9874
9878
  };
9875
9879
  const FILL_BATCH = 25;
9876
- const PAGE$3 = 500;
9880
+ const PAGE$4 = 500;
9881
+ const PAUSE_MS$1 = 1e3;
9882
+ const MAX_PAUSE_MS$1 = 32e3;
9883
+ const sleep$2 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
9877
9884
  const fillLabels = async (db, { channelId, platform }, { dryRun = false } = {}) => {
9878
9885
  const id = labelSequenceId(channelId, platform);
9879
9886
  let labeled = 0;
9880
9887
  let batchSize = FILL_BATCH;
9888
+ let paused = 0;
9881
9889
  const label = async (ids) => {
9882
9890
  for (let at = 0; at < ids.length;) {
9883
9891
  const batch = ids.slice(at, at + batchSize);
@@ -9902,12 +9910,16 @@ const fillLabels = async (db, { channelId, platform }, { dryRun = false } = {})
9902
9910
  return count;
9903
9911
  });
9904
9912
  at += batch.length;
9913
+ paused = 0;
9905
9914
  } catch (error) {
9906
9915
  if (batchSize > 1 && error instanceof DatabaseConstraintError && error.reason === "too_large") {
9907
9916
  batchSize = Math.max(1, Math.floor(batchSize / 2));
9908
9917
  continue;
9909
9918
  }
9910
- throw error;
9919
+ if (!isDatabaseBusyError(error) || paused >= MAX_PAUSE_MS$1) throw error;
9920
+ batchSize = Math.max(1, Math.floor(batchSize / 2));
9921
+ paused = paused === 0 ? PAUSE_MS$1 : paused * 2;
9922
+ await sleep$2(paused);
9911
9923
  }
9912
9924
  }
9913
9925
  };
@@ -9919,7 +9931,7 @@ const fillLabels = async (db, { channelId, platform }, { dryRun = false } = {})
9919
9931
  channel_id: channelId,
9920
9932
  platform
9921
9933
  },
9922
- limit: PAGE$3,
9934
+ limit: PAGE$4,
9923
9935
  ...cursor === void 0 ? {} : { cursor }
9924
9936
  });
9925
9937
  const unlabeled = page.rows.filter((row) => typeof row.label !== "number").map((row) => row.id);
@@ -10080,7 +10092,7 @@ const pendingLabelPairs = async (db) => {
10080
10092
  };
10081
10093
  //#endregion
10082
10094
  //#region ../../packages/server/dist/core/writes.mjs
10083
- const PAGE$2 = 500;
10095
+ const PAGE$3 = 500;
10084
10096
  const countBundle = (tx, platform, delta) => {
10085
10097
  for (const key of [platform, "*"]) tx.aggregate("bundle_totals", { platform_key: key }, { bundles: delta });
10086
10098
  };
@@ -10107,7 +10119,7 @@ const replaceBundlePatches = async (tx, bundle, rows, checkNew) => {
10107
10119
  const page = await tx.findMany("bundle_patches", {
10108
10120
  index: "byBundle",
10109
10121
  where: { bundle_id: bundle.id },
10110
- limit: Math.min(count - seen, PAGE$2),
10122
+ limit: Math.min(count - seen, PAGE$3),
10111
10123
  ...cursor === void 0 ? {} : { cursor }
10112
10124
  });
10113
10125
  for (const stored of page.rows) {
@@ -10590,7 +10602,7 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
10590
10602
  });
10591
10603
  //#endregion
10592
10604
  //#region ../../packages/server/dist/core/releases.mjs
10593
- const PAGE$1 = 500;
10605
+ const PAGE$2 = 500;
10594
10606
  const fail$1 = (code, message) => {
10595
10607
  throw new ReleaseCatalogMutationError(code, message);
10596
10608
  };
@@ -10624,7 +10636,7 @@ const enabledIn = (scopeKey, cursor) => ({
10624
10636
  scope_key: scopeKey,
10625
10637
  enabled: true
10626
10638
  },
10627
- limit: PAGE$1,
10639
+ limit: PAGE$2,
10628
10640
  ...cursor === void 0 ? {} : { cursor }
10629
10641
  });
10630
10642
  const enabledReleases = (tx, scopeKey) => drainReleases((cursor) => tx.findMany("releases", enabledIn(scopeKey, cursor)));
@@ -12862,13 +12874,15 @@ const isLaunch = (row) => {
12862
12874
  const kinds = metadataOf(row).change?.kinds ?? [];
12863
12875
  return kinds.includes("bundle") && !kinds.includes("first_seen") && row.to_release_id !== null;
12864
12876
  };
12865
- const bundleRefsOf = (row) => {
12877
+ const sideRef = (key, releaseId, bundleId) => key === "release" ? releaseId ?? bundleId : bundleId;
12878
+ const bundleRefsOf = (row, key = "release") => {
12866
12879
  if (isFailedCheck(row) || isLateEvent(row)) return [];
12867
- if (row.type === "RECOVERED") return [`from:${row.from_bundle_id}`];
12868
- if (row.type === "UNCHANGED") return isLaunch(row) ? [`on:${row.to_bundle_id}`] : [];
12869
- return [`to:${row.to_bundle_id}`];
12880
+ if (row.type === "RECOVERED") return [`from:${sideRef(key, row.from_release_id, row.from_bundle_id)}`];
12881
+ if (row.type === "UNCHANGED") return isLaunch(row) ? [`on:${sideRef(key, row.to_release_id, row.to_bundle_id)}`] : [];
12882
+ return [`to:${sideRef(key, row.to_release_id, row.to_bundle_id)}`];
12870
12883
  };
12871
- const bundleRefOfFilter = (filter) => filter.type === "RECOVERED" ? `from:${filter.fromBundleId}` : filter.type === "UNCHANGED" ? `on:${filter.toBundleId}` : `to:${filter.toBundleId}`;
12884
+ 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)}`]] : []];
12885
+ const bundleRefOfFilter = (filter) => filter.type === "RECOVERED" ? `from:${filter.fromReleaseId}` : filter.type === "UNCHANGED" ? `on:${filter.toReleaseId}` : `to:${filter.toReleaseId}`;
12872
12886
  const bundleEvents = (days) => defineTable({
12873
12887
  id: {
12874
12888
  type: "string",
@@ -13298,6 +13312,83 @@ const createInsightsSchema = ({ rawDays, dailyDays } = DEFAULT_INSIGHTS_RETENTIO
13298
13312
  };
13299
13313
  createInsightsSchema();
13300
13314
  //#endregion
13315
+ //#region ../insights/dist/server/backfill.mjs
13316
+ const PAGE$1 = 500;
13317
+ const BATCH = 25;
13318
+ const PAUSE_MS = 1e3;
13319
+ const MAX_PAUSE_MS = 32e3;
13320
+ const sleep$1 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
13321
+ const sameRefs = (stored, refs) => {
13322
+ const values = Array.isArray(stored) ? stored : [];
13323
+ return values.length === refs.length && values.every((value) => refs.includes(value));
13324
+ };
13325
+ const namesArtifact = (row) => {
13326
+ const byKey = (key) => bundleRefsOf(row, key);
13327
+ return sameRefs(row.bundle_ref, byKey("artifact")) && !sameRefs(row.bundle_ref, byKey("release"));
13328
+ };
13329
+ const backfillReleaseRefs = async (db, now, { rawDays }, { dryRun = false } = {}) => {
13330
+ const today = now() - now() % DAY_MS$1;
13331
+ let events = 0;
13332
+ let size = BATCH;
13333
+ let paused = 0;
13334
+ const move = async (stale) => {
13335
+ if (dryRun) {
13336
+ events += stale.length;
13337
+ return;
13338
+ }
13339
+ for (let start = 0; start < stale.length;) {
13340
+ const candidates = stale.slice(start, start + size);
13341
+ try {
13342
+ events += await rewrite(candidates);
13343
+ start += candidates.length;
13344
+ paused = 0;
13345
+ } catch (error) {
13346
+ if (error instanceof DatabaseConstraintError && error.reason === "too_large" && candidates.length > 1) {
13347
+ size = Math.ceil(candidates.length / 2);
13348
+ continue;
13349
+ }
13350
+ if (!isDatabaseBusyError(error) || paused >= MAX_PAUSE_MS) throw error;
13351
+ size = Math.ceil(candidates.length / 2);
13352
+ paused = paused === 0 ? PAUSE_MS : paused * 2;
13353
+ await sleep$1(paused);
13354
+ }
13355
+ }
13356
+ };
13357
+ const rewrite = (candidates) => db.transaction(async (tx) => {
13358
+ const rows = await Promise.all(candidates.map(({ id }) => tx.findOne("bundle_events", { id })));
13359
+ let moved = 0;
13360
+ for (const row of rows) {
13361
+ if (row === null || !namesArtifact(row)) continue;
13362
+ tx.update("bundle_events", row, {});
13363
+ const outcome = (ref, delta) => tx.aggregate("insights_outcomes", {
13364
+ platform: row.platform,
13365
+ channel: row.channel,
13366
+ type: ref[0],
13367
+ bundle_ref: ref[1],
13368
+ bucket_start_ms: row.received_at_ms - row.received_at_ms % HOUR_MS$1
13369
+ }, { events: delta }, { shardBy: row.install_id });
13370
+ for (const ref of outcomeRefsOf(row, "artifact")) outcome(ref, -1);
13371
+ for (const ref of outcomeRefsOf(row, "release")) outcome(ref, 1);
13372
+ moved += 1;
13373
+ }
13374
+ return moved;
13375
+ });
13376
+ for (let day = today - rawDays * DAY_MS$1; day <= today; day += DAY_MS$1) {
13377
+ let cursor;
13378
+ do {
13379
+ const page = await db.findMany("bundle_events", {
13380
+ index: "byDay",
13381
+ where: { day },
13382
+ limit: PAGE$1,
13383
+ ...cursor === void 0 ? {} : { cursor }
13384
+ });
13385
+ await move(page.rows.filter(namesArtifact));
13386
+ cursor = page.next;
13387
+ } while (cursor !== void 0);
13388
+ }
13389
+ return { events };
13390
+ };
13391
+ //#endregion
13301
13392
  //#region ../insights/dist/server/eventRow.mjs
13302
13393
  const CHANGE_KINDS = /* @__PURE__ */ new Set([
13303
13394
  "first_seen",
@@ -13375,7 +13466,7 @@ const isBundleFilter = (value, withKind = false) => {
13375
13466
  "type",
13376
13467
  ...withKind ? ["kind"] : []
13377
13468
  ];
13378
- 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"]);
13469
+ 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"]);
13379
13470
  };
13380
13471
  const isEventFilter = (value) => {
13381
13472
  if (!isRecord$3(value)) return false;
@@ -13470,20 +13561,24 @@ const createValidatedInsightsModel = (model) => ({
13470
13561
  if (!isRecord$3(input) || !hasOnlyKeys(input, [
13471
13562
  "platform",
13472
13563
  "channel",
13473
- "sinceMs",
13474
- "bundle"
13475
- ]) || !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, [
13476
- "field",
13477
- "value",
13478
- "types"
13479
- ]) || 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) => ![
13480
- "UNCHANGED",
13481
- "UPDATE_DOWNLOADED",
13482
- "UPDATE_APPLIED",
13483
- "RECOVERED"
13484
- ].includes(type))))) invalidQuery();
13564
+ "sinceMs"
13565
+ ]) || !hasScope(input) || !isTimestamp(input.sinceMs)) invalidQuery();
13485
13566
  return validateCount(await model.countLatestEvents(input));
13486
13567
  },
13568
+ async countReleaseInstallations(input) {
13569
+ if (!isRecord$3(input) || !hasOnlyKeys(input, [
13570
+ "platform",
13571
+ "channel",
13572
+ "sinceMs",
13573
+ "releaseId"
13574
+ ]) || !hasScope(input) || !isTimestamp(input.sinceMs) || !isText$1(input.releaseId)) invalidQuery();
13575
+ const counts = await model.countReleaseInstallations(input);
13576
+ if (!isRecord$3(counts) || !hasOnlyKeys(counts, ["installations", "release"])) invalidResult();
13577
+ return {
13578
+ installations: validateCount(counts.installations),
13579
+ release: validateCount(counts.release)
13580
+ };
13581
+ },
13487
13582
  async countEvents(input) {
13488
13583
  if (!isRecord$3(input) || !hasOnlyKeys(input, [
13489
13584
  "filter",
@@ -13536,6 +13631,7 @@ const createInsightsModel = (api) => createValidatedInsightsModel({
13536
13631
  listEvents: api.listEvents,
13537
13632
  findLatestEvents: api.findLatestEvents,
13538
13633
  countLatestEvents: api.countLatestEvents,
13634
+ countReleaseInstallations: api.countReleaseInstallations,
13539
13635
  countEvents: api.countEvents,
13540
13636
  countEventSeries: api.countEventSeries,
13541
13637
  getReleaseActivity: api.getReleaseActivity,
@@ -13904,27 +14000,27 @@ const readScope$1 = (input) => {
13904
14000
  };
13905
14001
  const bundleFilter = (input) => {
13906
14002
  const scope = readScope$1(input);
13907
- const bundleId = requireString(input.bundleId, "bundle ID", MAX_EVENT_ID_LENGTH);
14003
+ const releaseId = requireString(input.releaseId, "bundle ID", MAX_EVENT_ID_LENGTH);
13908
14004
  switch (input.outcome) {
13909
14005
  case "downloaded": return {
13910
14006
  ...scope,
13911
14007
  type: "UPDATE_DOWNLOADED",
13912
- toBundleId: bundleId
14008
+ toReleaseId: releaseId
13913
14009
  };
13914
14010
  case "applied": return {
13915
14011
  ...scope,
13916
14012
  type: "UPDATE_APPLIED",
13917
- toBundleId: bundleId
14013
+ toReleaseId: releaseId
13918
14014
  };
13919
14015
  case "recovered": return {
13920
14016
  ...scope,
13921
14017
  type: "RECOVERED",
13922
- fromBundleId: bundleId
14018
+ fromReleaseId: releaseId
13923
14019
  };
13924
14020
  case "failed": return {
13925
14021
  ...scope,
13926
14022
  type: "UPDATE_FAILED",
13927
- toBundleId: bundleId
14023
+ toReleaseId: releaseId
13928
14024
  };
13929
14025
  default: throw new InsightsBadRequestError("Invalid Insights outcome.");
13930
14026
  }
@@ -13934,7 +14030,7 @@ const sameFilter = (left, right) => {
13934
14030
  switch (right.kind) {
13935
14031
  case "all": return true;
13936
14032
  case "installationMovement": return left.installId === right.installId;
13937
- 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);
14033
+ 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);
13938
14034
  }
13939
14035
  };
13940
14036
  const readEventCursor = (value, filter) => {
@@ -13971,7 +14067,7 @@ const assertEventRows = (rows, input) => {
13971
14067
  for (let index = 0; index < rows.length; index += 1) {
13972
14068
  const row = rows[index];
13973
14069
  const previous = rows[index - 1];
13974
- 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.");
14070
+ 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.");
13975
14071
  }
13976
14072
  };
13977
14073
  const toFailure = (failure) => ({
@@ -14010,6 +14106,7 @@ const eventDetails = ({ type, metadata }) => ({
14010
14106
  ...metadata.implied_download === true ? { impliedDownload: true } : {}
14011
14107
  });
14012
14108
  const toEventHistoryRow = (row) => ({
14109
+ ...row.from_release_id == null ? {} : { fromReleaseId: row.from_release_id },
14013
14110
  ...row.to_release_id == null ? {} : { toReleaseId: row.to_release_id },
14014
14111
  ...row.metadata.sdk_version == null ? {} : { sdkVersion: row.metadata.sdk_version },
14015
14112
  ...row.metadata.min_bundle_id === void 0 ? {} : { minBundleId: row.metadata.min_bundle_id },
@@ -14034,6 +14131,7 @@ const toInstallationRow = (row) => ({
14034
14131
  cohort: row.metadata.cohort,
14035
14132
  installId: row.install_id,
14036
14133
  lastKnownBundleId: row.type === "UPDATE_DOWNLOADED" ? row.from_bundle_id : row.to_bundle_id,
14134
+ lastKnownReleaseId: row.type === "UPDATE_DOWNLOADED" ? row.from_release_id : row.to_release_id,
14037
14135
  pendingBundleId: row.type === "UPDATE_DOWNLOADED" ? row.to_bundle_id : null,
14038
14136
  pendingReleaseId: row.type === "UPDATE_DOWNLOADED" ? row.to_release_id : null,
14039
14137
  latestStatus: row.type,
@@ -14156,46 +14254,33 @@ const createInsightsProvider = (model) => Object.freeze({
14156
14254
  measuredAtMs: Date.now()
14157
14255
  };
14158
14256
  };
14159
- const bundleId = input.bundleId === void 0 ? void 0 : requireString(input.bundleId, "bundle ID", MAX_EVENT_ID_LENGTH);
14160
- const reporting = measure(model.countLatestEvents({
14161
- ...scope,
14162
- sinceMs
14163
- }));
14164
- if (bundleId === void 0) return {
14257
+ const releaseId = input.releaseId === void 0 ? void 0 : requireString(input.releaseId, "bundle ID", MAX_EVENT_ID_LENGTH);
14258
+ if (releaseId === void 0) return {
14165
14259
  ...scope,
14166
14260
  window,
14167
14261
  sinceMs,
14168
14262
  beforeReceivedAtMs,
14169
- reportingInstallations: await reporting
14263
+ reportingInstallations: await measure(model.countLatestEvents({
14264
+ ...scope,
14265
+ sinceMs
14266
+ }))
14170
14267
  };
14268
+ const installations = model.countReleaseInstallations({
14269
+ ...scope,
14270
+ sinceMs,
14271
+ releaseId
14272
+ }).then(async (counts) => [await measure(Promise.resolve(counts.installations)), await measure(Promise.resolve(counts.release))]);
14171
14273
  const countOutcome = (outcome) => measure(model.countEvents({
14172
14274
  filter: bundleFilter({
14173
14275
  ...scope,
14174
- bundleId,
14276
+ releaseId,
14175
14277
  outcome
14176
14278
  }),
14177
14279
  sinceMs,
14178
14280
  beforeReceivedAtMs
14179
14281
  }));
14180
- const [reportingInstallations, bundleInstallations, downloadedReports, appliedReports, recoveredReports, failedReports] = await Promise.all([
14181
- reporting,
14182
- measure(model.countLatestEvents({
14183
- ...scope,
14184
- sinceMs,
14185
- bundle: [{
14186
- field: "from_bundle_id",
14187
- value: bundleId,
14188
- types: ["UPDATE_DOWNLOADED"]
14189
- }, {
14190
- field: "to_bundle_id",
14191
- value: bundleId,
14192
- types: [
14193
- "UNCHANGED",
14194
- "UPDATE_APPLIED",
14195
- "RECOVERED"
14196
- ]
14197
- }]
14198
- })),
14282
+ const [[reportingInstallations, bundleInstallations], downloadedReports, appliedReports, recoveredReports, failedReports] = await Promise.all([
14283
+ installations,
14199
14284
  countOutcome("downloaded"),
14200
14285
  countOutcome("applied"),
14201
14286
  countOutcome("recovered"),
@@ -14208,7 +14293,7 @@ const createInsightsProvider = (model) => Object.freeze({
14208
14293
  beforeReceivedAtMs,
14209
14294
  reportingInstallations,
14210
14295
  bundle: {
14211
- bundleId,
14296
+ releaseId,
14212
14297
  reportingInstallations: bundleInstallations,
14213
14298
  downloadedReports,
14214
14299
  appliedReports,
@@ -14333,8 +14418,6 @@ const gaugeSlot = (head) => ({
14333
14418
  releaseId: head.type === "UPDATE_DOWNLOADED" ? head.from_release_id : head.to_release_id,
14334
14419
  builtinBundleId: runningBuiltinBundleId(head)
14335
14420
  });
14336
- const PAIR_FIELD = "from_to";
14337
- const bundlePairKey = (from, to) => insightsKey(`${from.length}:${from}${to.length}:${to}`);
14338
14421
  const countHead = (tx, head, delta) => {
14339
14422
  const { bucket, releaseId, builtinBundleId } = gaugeSlot(head);
14340
14423
  const shardBy = head.install_id;
@@ -14353,26 +14436,6 @@ const countHead = (tx, head, delta) => {
14353
14436
  builtin_bundle_id: builtinBundleId,
14354
14437
  bucket_start_ms: bucket
14355
14438
  }, { latest_installations: delta }, { shardBy });
14356
- for (const field of ["from_bundle_id", "to_bundle_id"]) {
14357
- const bundleId = head[field];
14358
- if (bundleId === null) continue;
14359
- tx.aggregate("insights_latest_by_bundle", {
14360
- platform: head.platform,
14361
- channel: head.channel,
14362
- bundle_field: field,
14363
- bundle_id: bundleId,
14364
- type: head.type,
14365
- bucket_start_ms: bucket
14366
- }, { installations: delta }, { shardBy });
14367
- }
14368
- if (head.from_bundle_id !== null) tx.aggregate("insights_latest_by_bundle", {
14369
- platform: head.platform,
14370
- channel: head.channel,
14371
- bundle_field: PAIR_FIELD,
14372
- bundle_id: bundlePairKey(head.from_bundle_id, head.to_bundle_id),
14373
- type: head.type,
14374
- bucket_start_ms: bucket
14375
- }, { installations: delta }, { shardBy });
14376
14439
  };
14377
14440
  const PERIOD_MODELS = {
14378
14441
  hour: {
@@ -14422,18 +14485,13 @@ const countEvent = (tx, event) => {
14422
14485
  };
14423
14486
  const countOutcome = (tx, event) => {
14424
14487
  const shardBy = event.install_id;
14425
- const hour = (type, bundleRef) => tx.aggregate("insights_outcomes", {
14488
+ for (const [type, bundleRef] of outcomeRefsOf(event)) tx.aggregate("insights_outcomes", {
14426
14489
  platform: event.platform,
14427
14490
  channel: event.channel,
14428
14491
  type,
14429
14492
  bundle_ref: bundleRef,
14430
14493
  bucket_start_ms: hourOf(event.received_at_ms)
14431
14494
  }, { events: 1 }, { shardBy });
14432
- for (const bundleRef of bundleRefsOf(event)) hour(event.type, bundleRef);
14433
- if (event.metadata.implied_download === true) hour("UPDATE_DOWNLOADED", bundleRefOfFilter({
14434
- type: "UPDATE_DOWNLOADED",
14435
- toBundleId: event.type === "RECOVERED" ? event.from_bundle_id : event.to_bundle_id
14436
- }));
14437
14495
  tx.aggregate("insights_outcomes", {
14438
14496
  ...DAILY_EVENTS,
14439
14497
  bucket_start_ms: dayOf(event.received_at_ms)
@@ -14819,25 +14877,34 @@ const countEventSeries = async (db, input) => {
14819
14877
  events: count
14820
14878
  }));
14821
14879
  };
14822
- const latestPredicates = (bundle) => {
14823
- if (bundle === void 0) return void 0;
14824
- return [...new Map(bundle.flatMap(({ field, value, types }) => types.map((type) => [JSON.stringify([
14825
- field,
14826
- value,
14827
- type
14828
- ]), {
14829
- field,
14830
- value,
14831
- type
14832
- }]))).values()];
14833
- };
14834
- const countLatestEvents = async (db, input) => {
14835
- const { platform, channel, sinceMs: start } = input;
14880
+ const distributionRows = (db, { platform, channel, sinceMs: start }) => {
14836
14881
  if (start % 864e5 !== 0) throw new DatabaseAdapterInputError("invalid-query");
14837
- const predicates = latestPredicates(input.bundle);
14882
+ return drain((page) => db.findAggregates("insights_distribution", {
14883
+ index: "byScope",
14884
+ where: {
14885
+ channel,
14886
+ platform
14887
+ },
14888
+ range: { gte: start },
14889
+ limit: PAGE,
14890
+ ...page
14891
+ }));
14892
+ };
14893
+ const installations = (count) => Math.max(0, count);
14894
+ const countLatestEvents = async (db, input) => installations((await distributionRows(db, input)).reduce((sum, row) => sum + row.latest_installations, 0));
14895
+ const countReleaseInstallations = async (db, input) => {
14896
+ const { platform, channel, sinceMs: start, releaseId } = input;
14838
14897
  let total = 0;
14839
- if (predicates === void 0) {
14840
- const rows = await drain((page) => db.findAggregates("insights_distribution", {
14898
+ let release = 0;
14899
+ let named = false;
14900
+ for (const row of await distributionRows(db, input)) {
14901
+ total += row.latest_installations;
14902
+ if (row.release_id !== releaseId) continue;
14903
+ named = true;
14904
+ release += row.latest_installations;
14905
+ }
14906
+ if (!named) {
14907
+ const builtin = await drain((page) => db.findAggregates("insights_builtin_distribution", {
14841
14908
  index: "byScope",
14842
14909
  where: {
14843
14910
  channel,
@@ -14847,33 +14914,12 @@ const countLatestEvents = async (db, input) => {
14847
14914
  limit: PAGE,
14848
14915
  ...page
14849
14916
  }));
14850
- total += rows.reduce((sum, row) => sum + row.latest_installations, 0);
14851
- } else {
14852
- const gauge = async (bundleField, bundleId, type) => {
14853
- return (await drain((page) => db.findAggregates("insights_latest_by_bundle", {
14854
- index: "byBundle",
14855
- where: {
14856
- platform,
14857
- channel,
14858
- bundle_field: bundleField,
14859
- bundle_id: bundleId,
14860
- type
14861
- },
14862
- range: { gte: start },
14863
- limit: PAGE,
14864
- ...page
14865
- }))).reduce((sum, row) => sum + row.installations, 0);
14866
- };
14867
- for (const { field, value, type } of predicates) total += await gauge(field, value, type);
14868
- for (const from of predicates) {
14869
- if (from.field !== "from_bundle_id") continue;
14870
- for (const to of predicates) {
14871
- if (to.field !== "to_bundle_id" || to.type !== from.type) continue;
14872
- total -= await gauge(PAIR_FIELD, bundlePairKey(from.value, to.value), from.type);
14873
- }
14874
- }
14917
+ for (const row of builtin) if (row.release_id === "" && row.builtin_bundle_id === releaseId) release += row.latest_installations;
14875
14918
  }
14876
- return Math.max(0, total);
14919
+ return {
14920
+ installations: installations(total),
14921
+ release: installations(release)
14922
+ };
14877
14923
  };
14878
14924
  const retained = (now, { rawDays, dailyDays }) => ({
14879
14925
  hour: hourCeil(now - rawDays * DAY_MS$1),
@@ -15290,6 +15336,20 @@ const getUpdateFailures = async (db, input, now, retention) => {
15290
15336
  };
15291
15337
  };
15292
15338
  //#endregion
15339
+ //#region ../insights/dist/server/wire.mjs
15340
+ const RELEASE_ID_PARAM = "bundleId";
15341
+ const toWireOverview = ({ bundle, ...overview }) => {
15342
+ if (bundle === void 0) return overview;
15343
+ const { releaseId, ...counts } = bundle;
15344
+ return {
15345
+ ...overview,
15346
+ bundle: {
15347
+ ...counts,
15348
+ bundleId: releaseId
15349
+ }
15350
+ };
15351
+ };
15352
+ //#endregion
15293
15353
  //#region ../insights/dist/server/queryInput.mjs
15294
15354
  const MAX_PAGE_LIMIT = 100;
15295
15355
  const MAX_IDENTITY_LENGTH = 255;
@@ -15334,7 +15394,7 @@ const readScope = (url) => {
15334
15394
  const parseEventPageInput = (request) => {
15335
15395
  const url = new URL(request.url);
15336
15396
  const bundleFields = [
15337
- "bundleId",
15397
+ RELEASE_ID_PARAM,
15338
15398
  "outcome",
15339
15399
  "platform",
15340
15400
  "channel"
@@ -15345,7 +15405,7 @@ const parseEventPageInput = (request) => {
15345
15405
  if (outcome !== "downloaded" && outcome !== "applied" && outcome !== "recovered" && outcome !== "failed") throw new InsightsBadRequestError("Invalid 'outcome' query parameter.");
15346
15406
  bundle = {
15347
15407
  ...readScope(url),
15348
- bundleId: readId(url, "bundleId", 1024),
15408
+ releaseId: readId(url, RELEASE_ID_PARAM, 1024),
15349
15409
  outcome
15350
15410
  };
15351
15411
  }
@@ -15371,11 +15431,10 @@ const parseReportingOverviewInput = (request) => {
15371
15431
  const url = new URL(request.url);
15372
15432
  const window = readSingle(url, "window") ?? "30d";
15373
15433
  if (window !== "24h" && window !== "7d" && window !== "30d") throw new InsightsBadRequestError("Invalid 'window' query parameter.");
15374
- const bundleId = readSingle(url, "bundleId");
15375
15434
  return {
15376
15435
  ...readScope(url),
15377
15436
  window,
15378
- ...bundleId === void 0 ? {} : { bundleId: readId(url, "bundleId", 1024) }
15437
+ ...readSingle(url, "bundleId") === void 0 ? {} : { releaseId: readId(url, RELEASE_ID_PARAM, 1024) }
15379
15438
  };
15380
15439
  };
15381
15440
  //#endregion
@@ -15454,7 +15513,7 @@ const createInsightsRouteHandlers = (provider) => ({
15454
15513
  await provider.appendBundleEvent(await parseBundleEventRequest(request));
15455
15514
  return new Response(null, { status: 204 });
15456
15515
  }),
15457
- getReportingOverview: (_params, request) => query(() => provider.getReportingOverview(parseReportingOverviewInput(request))),
15516
+ getReportingOverview: (_params, request) => query(async () => toWireOverview(await provider.getReportingOverview(parseReportingOverviewInput(request)))),
15458
15517
  getInstallation: (params) => run$1(async () => {
15459
15518
  const installation = await provider.getInstallation({ installId: requireParam(params, "installId") });
15460
15519
  return installation === null ? json$1({ error: "Installation not found" }, 404) : json$1(installation, 200);
@@ -15474,11 +15533,13 @@ const createInsightsApi = (db, now, retention) => ({
15474
15533
  listEvents: (input) => listEvents(db, input),
15475
15534
  findLatestEvents: (input) => findLatestEvents(db, input),
15476
15535
  countLatestEvents: (input) => countLatestEvents(db, input),
15536
+ countReleaseInstallations: (input) => countReleaseInstallations(db, input),
15477
15537
  countEvents: (input) => countEvents(db, input),
15478
15538
  countEventSeries: (input) => countEventSeries(db, input),
15479
15539
  getReleaseActivity: (input) => getReleaseActivity(db, input, now),
15480
15540
  getAppUsage: (input) => getAppUsage(db, input, now, retention),
15481
- getUpdateFailures: (input) => getUpdateFailures(db, input, now, retention)
15541
+ getUpdateFailures: (input) => getUpdateFailures(db, input, now, retention),
15542
+ backfillReleaseRefs: (options) => backfillReleaseRefs(db, now, retention, options)
15482
15543
  });
15483
15544
  const readFailuresQuery = (url) => {
15484
15545
  const query = url.searchParams;
@@ -7884,6 +7884,7 @@ const runInit = async ({ build, envFile, secretsEnv }) => {
7884
7884
  let credential;
7885
7885
  try {
7886
7886
  await (0, _hot_updater_cli_tools.fillReleaseLabels)(server);
7887
+ await (0, _hot_updater_cli_tools.backfillInsightsReleaseRefs)(server);
7887
7888
  credential = await (0, _hot_updater_cli_tools.provisionClientCredential)(server, {
7888
7889
  env: initInputEnv,
7889
7890
  name: "Azure init"
@@ -1,7 +1,7 @@
1
1
  import { createRequire } from "node:module";
2
2
  import { createHash } from "crypto";
3
3
  import path from "path";
4
- import { ConfigBuilder, InitError, assembleServer, createHotUpdaterConfigScaffoldFromBuilder, createZip, fillReleaseLabels, getCwd, getHotUpdaterInitInputEnv, getInitProviderEnvVars, getInitProviderTextPromptValues, link, makeEnv, p, printAppSetup, provisionClientCredential, readHotUpdaterInitEnv, resolveInitProviderInputs, shouldAutoSelectOnlyInitResource, writeHotUpdaterFiles } from "@hot-updater/cli-tools";
4
+ import { ConfigBuilder, InitError, assembleServer, backfillInsightsReleaseRefs, createHotUpdaterConfigScaffoldFromBuilder, createZip, fillReleaseLabels, getCwd, getHotUpdaterInitInputEnv, getInitProviderEnvVars, getInitProviderTextPromptValues, link, makeEnv, p, printAppSetup, provisionClientCredential, readHotUpdaterInitEnv, resolveInitProviderInputs, shouldAutoSelectOnlyInitResource, writeHotUpdaterFiles } from "@hot-updater/cli-tools";
5
5
  import { apiKeys, insights, remoteConfig } from "@hot-updater/server/plugins";
6
6
  import { CosmosClient } from "@azure/cosmos";
7
7
  import { SETTINGS_TABLE, createEngineDatabase, createKvAdapter, encodeKvKey, migrateCoreSchema, toolingTargetOf } from "@hot-updater/plugin-core";
@@ -7879,6 +7879,7 @@ const runInit = async ({ build, envFile, secretsEnv }) => {
7879
7879
  let credential;
7880
7880
  try {
7881
7881
  await fillReleaseLabels(server);
7882
+ await backfillInsightsReleaseRefs(server);
7882
7883
  credential = await provisionClientCredential(server, {
7883
7884
  env: initInputEnv,
7884
7885
  name: "Azure init"
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@hot-updater/azure",
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
  "engines": {
7
7
  "node": "^22.23.4 || ^24.22.1 || >=26.12.1"
@@ -44,10 +44,10 @@
44
44
  "@azure/identity": "4.14.0",
45
45
  "@azure/keyvault-secrets": "4.11.2",
46
46
  "@azure/storage-blob": "12.34.0",
47
- "@hot-updater/cli-tools": "1.2.0-rc.57",
48
- "@hot-updater/protocol": "1.2.0-rc.57",
49
- "@hot-updater/server": "1.2.0-rc.57",
50
- "@hot-updater/plugin-core": "1.2.0-rc.57"
47
+ "@hot-updater/cli-tools": "1.2.0-rc.59",
48
+ "@hot-updater/plugin-core": "1.2.0-rc.59",
49
+ "@hot-updater/protocol": "1.2.0-rc.59",
50
+ "@hot-updater/server": "1.2.0-rc.59"
51
51
  },
52
52
  "devDependencies": {
53
53
  "@azure/functions": "4.16.5",
@@ -55,7 +55,7 @@
55
55
  "execa": "9.5.2",
56
56
  "jszip": "^3.10.1",
57
57
  "vitest": "4.1.4",
58
- "@hot-updater/test-utils": "1.2.0-rc.57"
58
+ "@hot-updater/test-utils": "1.2.0-rc.59"
59
59
  },
60
60
  "scripts": {
61
61
  "build": "tsdown",