@hot-updater/vercel 1.2.0-rc.56 → 1.2.0-rc.58

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.
@@ -541,14 +541,14 @@ function modularInverse(value, modulus) {
541
541
  if (r > 1) throw new Error(`No modular inverse for ${value} mod ${modulus}`);
542
542
  return positiveMod(t, modulus);
543
543
  }
544
- function getRolloutShuffleParameters(bundleId) {
545
- let multiplier = positiveMod(hashString(`${bundleId}:multiplier`), 997);
544
+ function getRolloutShuffleParameters(releaseId) {
545
+ let multiplier = positiveMod(hashString(`${releaseId}:multiplier`), 997);
546
546
  if (multiplier === 0) multiplier = 1;
547
547
  while (gcd(multiplier, NUMERIC_COHORT_SIZE) !== 1) {
548
548
  multiplier = positiveMod(multiplier + 1, NUMERIC_COHORT_SIZE);
549
549
  if (multiplier === 0) multiplier = 1;
550
550
  }
551
- const offset = positiveMod(hashString(`${bundleId}:offset`), NUMERIC_COHORT_SIZE);
551
+ const offset = positiveMod(hashString(`${releaseId}:offset`), NUMERIC_COHORT_SIZE);
552
552
  return {
553
553
  multiplier,
554
554
  offset,
@@ -581,16 +581,16 @@ function isValidCohort(cohort) {
581
581
  const normalized = normalizeCohortValue(cohort);
582
582
  return isNumericCohort(normalized) || isCustomCohort(normalized);
583
583
  }
584
- function getNumericCohortRolloutPosition(bundleId, cohortValue) {
584
+ function getNumericCohortRolloutPosition(releaseId, cohortValue) {
585
585
  if (cohortValue < 1 || cohortValue > 1e3) throw new Error(`Invalid numeric cohort: ${cohortValue}`);
586
- const { offset, inverseMultiplier } = getRolloutShuffleParameters(bundleId);
586
+ const { offset, inverseMultiplier } = getRolloutShuffleParameters(releaseId);
587
587
  return positiveMod(inverseMultiplier * (cohortValue - 1 - offset), NUMERIC_COHORT_SIZE);
588
588
  }
589
- function getRolledOutNumericCohorts(bundleId, rolloutCohortCount) {
589
+ function getRolledOutNumericCohorts(releaseId, rolloutCohortCount) {
590
590
  const normalizedRolloutCount = normalizeRolloutCohortCount(rolloutCohortCount);
591
591
  if (normalizedRolloutCount <= 0) return [];
592
592
  if (normalizedRolloutCount >= 1e3) return Array.from({ length: NUMERIC_COHORT_SIZE }, (_, index) => index + 1);
593
- const { multiplier, offset } = getRolloutShuffleParameters(bundleId);
593
+ const { multiplier, offset } = getRolloutShuffleParameters(releaseId);
594
594
  return Array.from({ length: normalizedRolloutCount }, (_, position) => positiveMod(multiplier * position + offset, NUMERIC_COHORT_SIZE)).map((zeroBasedCohort) => zeroBasedCohort + 1).sort((left, right) => left - right);
595
595
  }
596
596
  const RELEASE_CATALOG_FALLBACK_POLICY = "BUILTIN_IF_ACTIVE_INELIGIBLE";
@@ -18083,7 +18083,7 @@ const postgres = (config) => {
18083
18083
  };
18084
18084
  //#endregion
18085
18085
  //#region ../../packages/server/dist/version.mjs
18086
- const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.56";
18086
+ const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.58";
18087
18087
  //#endregion
18088
18088
  //#region ../../packages/server/dist/handlerVersionRoutes.mjs
18089
18089
  const createVersionRouteHandlers = (plugins = []) => {
@@ -18821,7 +18821,7 @@ const baseBundleIdsOf = (row, range, bundleId, limit) => {
18821
18821
  };
18822
18822
  //#endregion
18823
18823
  //#region ../../packages/server/dist/core/reads.mjs
18824
- const PAGE$4 = 500;
18824
+ const PAGE$5 = 500;
18825
18825
  const pick$2 = (fields) => (row) => Object.fromEntries(fields.map((field) => [field, row[field]]));
18826
18826
  const toBundleRow = pick$2([
18827
18827
  "id",
@@ -18912,7 +18912,7 @@ const createCoreReads = (db, storage) => {
18912
18912
  const page = await db.findMany("bundle_patches", {
18913
18913
  index: "byBundle",
18914
18914
  where: { bundle_id: row.id },
18915
- limit: Math.min(count - patches.length, PAGE$4),
18915
+ limit: Math.min(count - patches.length, PAGE$5),
18916
18916
  ...cursor === void 0 ? {} : { cursor }
18917
18917
  });
18918
18918
  patches.push(...page.rows.map(toPatchRow));
@@ -19116,7 +19116,7 @@ const createCoreReads = (db, storage) => {
19116
19116
  return (await drain$1((page) => db.findMany("channels", {
19117
19117
  index: "all",
19118
19118
  where: {},
19119
- limit: PAGE$4,
19119
+ limit: PAGE$5,
19120
19120
  ...page
19121
19121
  }))).map(toChannelRow);
19122
19122
  },
@@ -19472,7 +19472,7 @@ const createLabelAllocator = (tx, used, caughtUp) => {
19472
19472
  };
19473
19473
  };
19474
19474
  const FILL_BATCH = 25;
19475
- const PAGE$3 = 500;
19475
+ const PAGE$4 = 500;
19476
19476
  const fillLabels = async (db, { channelId, platform }, { dryRun = false } = {}) => {
19477
19477
  const id = labelSequenceId(channelId, platform);
19478
19478
  let labeled = 0;
@@ -19518,7 +19518,7 @@ const fillLabels = async (db, { channelId, platform }, { dryRun = false } = {})
19518
19518
  channel_id: channelId,
19519
19519
  platform
19520
19520
  },
19521
- limit: PAGE$3,
19521
+ limit: PAGE$4,
19522
19522
  ...cursor === void 0 ? {} : { cursor }
19523
19523
  });
19524
19524
  const unlabeled = page.rows.filter((row) => typeof row.label !== "number").map((row) => row.id);
@@ -19679,7 +19679,7 @@ const pendingLabelPairs = async (db) => {
19679
19679
  };
19680
19680
  //#endregion
19681
19681
  //#region ../../packages/server/dist/core/writes.mjs
19682
- const PAGE$2 = 500;
19682
+ const PAGE$3 = 500;
19683
19683
  const countBundle = (tx, platform, delta) => {
19684
19684
  for (const key of [platform, "*"]) tx.aggregate("bundle_totals", { platform_key: key }, { bundles: delta });
19685
19685
  };
@@ -19706,7 +19706,7 @@ const replaceBundlePatches = async (tx, bundle, rows, checkNew) => {
19706
19706
  const page = await tx.findMany("bundle_patches", {
19707
19707
  index: "byBundle",
19708
19708
  where: { bundle_id: bundle.id },
19709
- limit: Math.min(count - seen, PAGE$2),
19709
+ limit: Math.min(count - seen, PAGE$3),
19710
19710
  ...cursor === void 0 ? {} : { cursor }
19711
19711
  });
19712
19712
  for (const stored of page.rows) {
@@ -20189,7 +20189,7 @@ const createNativeBuildApi = (db, { now = Date.now } = {}) => ({
20189
20189
  });
20190
20190
  //#endregion
20191
20191
  //#region ../../packages/server/dist/core/releases.mjs
20192
- const PAGE$1 = 500;
20192
+ const PAGE$2 = 500;
20193
20193
  const fail$1 = (code, message) => {
20194
20194
  throw new ReleaseCatalogMutationError(code, message);
20195
20195
  };
@@ -20223,7 +20223,7 @@ const enabledIn = (scopeKey, cursor) => ({
20223
20223
  scope_key: scopeKey,
20224
20224
  enabled: true
20225
20225
  },
20226
- limit: PAGE$1,
20226
+ limit: PAGE$2,
20227
20227
  ...cursor === void 0 ? {} : { cursor }
20228
20228
  });
20229
20229
  const enabledReleases = (tx, scopeKey) => drainReleases((cursor) => tx.findMany("releases", enabledIn(scopeKey, cursor)));
@@ -21959,7 +21959,8 @@ const createRequestHandler = ({ api, clientPolicy, privateResponses = false, rou
21959
21959
  let authenticated;
21960
21960
  try {
21961
21961
  authenticated = await clientPolicy.authenticate(request);
21962
- } catch {
21962
+ } catch (error) {
21963
+ console.error("Hot Updater client authentication failed:", error);
21963
21964
  return errorResponse("Service unavailable", 503);
21964
21965
  }
21965
21966
  if (!authenticated) return errorResponse("Unauthorized", 401);
@@ -22460,13 +22461,15 @@ const isLaunch = (row) => {
22460
22461
  const kinds = metadataOf(row).change?.kinds ?? [];
22461
22462
  return kinds.includes("bundle") && !kinds.includes("first_seen") && row.to_release_id !== null;
22462
22463
  };
22463
- const bundleRefsOf = (row) => {
22464
+ const sideRef = (key, releaseId, bundleId) => key === "release" ? releaseId ?? bundleId : bundleId;
22465
+ const bundleRefsOf = (row, key = "release") => {
22464
22466
  if (isFailedCheck(row) || isLateEvent(row)) return [];
22465
- if (row.type === "RECOVERED") return [`from:${row.from_bundle_id}`];
22466
- if (row.type === "UNCHANGED") return isLaunch(row) ? [`on:${row.to_bundle_id}`] : [];
22467
- return [`to:${row.to_bundle_id}`];
22467
+ if (row.type === "RECOVERED") return [`from:${sideRef(key, row.from_release_id, row.from_bundle_id)}`];
22468
+ if (row.type === "UNCHANGED") return isLaunch(row) ? [`on:${sideRef(key, row.to_release_id, row.to_bundle_id)}`] : [];
22469
+ return [`to:${sideRef(key, row.to_release_id, row.to_bundle_id)}`];
22468
22470
  };
22469
- const bundleRefOfFilter = (filter) => filter.type === "RECOVERED" ? `from:${filter.fromBundleId}` : filter.type === "UNCHANGED" ? `on:${filter.toBundleId}` : `to:${filter.toBundleId}`;
22471
+ 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)}`]] : []];
22472
+ const bundleRefOfFilter = (filter) => filter.type === "RECOVERED" ? `from:${filter.fromReleaseId}` : filter.type === "UNCHANGED" ? `on:${filter.toReleaseId}` : `to:${filter.toReleaseId}`;
22470
22473
  const bundleEvents = (days) => defineTable({
22471
22474
  id: {
22472
22475
  type: "string",
@@ -22896,6 +22899,70 @@ const createInsightsSchema = ({ rawDays, dailyDays } = DEFAULT_INSIGHTS_RETENTIO
22896
22899
  };
22897
22900
  createInsightsSchema();
22898
22901
  //#endregion
22902
+ //#region ../insights/dist/server/backfill.mjs
22903
+ const PAGE$1 = 500;
22904
+ const BATCH = 25;
22905
+ const sameRefs = (stored, refs) => {
22906
+ const values = Array.isArray(stored) ? stored : [];
22907
+ return values.length === refs.length && values.every((value) => refs.includes(value));
22908
+ };
22909
+ const namesArtifact = (row) => {
22910
+ const byKey = (key) => bundleRefsOf(row, key);
22911
+ return sameRefs(row.bundle_ref, byKey("artifact")) && !sameRefs(row.bundle_ref, byKey("release"));
22912
+ };
22913
+ const backfillReleaseRefs = async (db, now, { rawDays }, { dryRun = false } = {}) => {
22914
+ const today = now() - now() % DAY_MS$1;
22915
+ let events = 0;
22916
+ const move = async (candidates) => {
22917
+ if (dryRun) {
22918
+ events += candidates.length;
22919
+ return;
22920
+ }
22921
+ const moved = await rewrite(candidates).catch(async (error) => {
22922
+ if (!(error instanceof DatabaseConstraintError) || error.reason !== "too_large" || candidates.length === 1) throw error;
22923
+ const half = Math.ceil(candidates.length / 2);
22924
+ await move(candidates.slice(0, half));
22925
+ await move(candidates.slice(half));
22926
+ return 0;
22927
+ });
22928
+ events += moved;
22929
+ };
22930
+ const rewrite = (candidates) => db.transaction(async (tx) => {
22931
+ const rows = await Promise.all(candidates.map(({ id }) => tx.findOne("bundle_events", { id })));
22932
+ let moved = 0;
22933
+ for (const row of rows) {
22934
+ if (row === null || !namesArtifact(row)) continue;
22935
+ tx.update("bundle_events", row, {});
22936
+ const outcome = (ref, delta) => tx.aggregate("insights_outcomes", {
22937
+ platform: row.platform,
22938
+ channel: row.channel,
22939
+ type: ref[0],
22940
+ bundle_ref: ref[1],
22941
+ bucket_start_ms: row.received_at_ms - row.received_at_ms % HOUR_MS$1
22942
+ }, { events: delta }, { shardBy: row.install_id });
22943
+ for (const ref of outcomeRefsOf(row, "artifact")) outcome(ref, -1);
22944
+ for (const ref of outcomeRefsOf(row, "release")) outcome(ref, 1);
22945
+ moved += 1;
22946
+ }
22947
+ return moved;
22948
+ });
22949
+ for (let day = today - rawDays * DAY_MS$1; day <= today; day += DAY_MS$1) {
22950
+ let cursor;
22951
+ do {
22952
+ const page = await db.findMany("bundle_events", {
22953
+ index: "byDay",
22954
+ where: { day },
22955
+ limit: PAGE$1,
22956
+ ...cursor === void 0 ? {} : { cursor }
22957
+ });
22958
+ const stale = page.rows.filter(namesArtifact);
22959
+ for (let start = 0; start < stale.length; start += BATCH) await move(stale.slice(start, start + BATCH));
22960
+ cursor = page.next;
22961
+ } while (cursor !== void 0);
22962
+ }
22963
+ return { events };
22964
+ };
22965
+ //#endregion
22899
22966
  //#region ../insights/dist/server/eventRow.mjs
22900
22967
  const CHANGE_KINDS = /* @__PURE__ */ new Set([
22901
22968
  "first_seen",
@@ -22973,7 +23040,7 @@ const isBundleFilter = (value, withKind = false) => {
22973
23040
  "type",
22974
23041
  ...withKind ? ["kind"] : []
22975
23042
  ];
22976
- 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"]);
23043
+ 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"]);
22977
23044
  };
22978
23045
  const isEventFilter = (value) => {
22979
23046
  if (!isRecord$3(value)) return false;
@@ -23068,20 +23135,24 @@ const createValidatedInsightsModel = (model) => ({
23068
23135
  if (!isRecord$3(input) || !hasOnlyKeys(input, [
23069
23136
  "platform",
23070
23137
  "channel",
23071
- "sinceMs",
23072
- "bundle"
23073
- ]) || !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, [
23074
- "field",
23075
- "value",
23076
- "types"
23077
- ]) || 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) => ![
23078
- "UNCHANGED",
23079
- "UPDATE_DOWNLOADED",
23080
- "UPDATE_APPLIED",
23081
- "RECOVERED"
23082
- ].includes(type))))) invalidQuery();
23138
+ "sinceMs"
23139
+ ]) || !hasScope(input) || !isTimestamp(input.sinceMs)) invalidQuery();
23083
23140
  return validateCount(await model.countLatestEvents(input));
23084
23141
  },
23142
+ async countReleaseInstallations(input) {
23143
+ if (!isRecord$3(input) || !hasOnlyKeys(input, [
23144
+ "platform",
23145
+ "channel",
23146
+ "sinceMs",
23147
+ "releaseId"
23148
+ ]) || !hasScope(input) || !isTimestamp(input.sinceMs) || !isText$1(input.releaseId)) invalidQuery();
23149
+ const counts = await model.countReleaseInstallations(input);
23150
+ if (!isRecord$3(counts) || !hasOnlyKeys(counts, ["installations", "release"])) invalidResult();
23151
+ return {
23152
+ installations: validateCount(counts.installations),
23153
+ release: validateCount(counts.release)
23154
+ };
23155
+ },
23085
23156
  async countEvents(input) {
23086
23157
  if (!isRecord$3(input) || !hasOnlyKeys(input, [
23087
23158
  "filter",
@@ -23134,6 +23205,7 @@ const createInsightsModel = (api) => createValidatedInsightsModel({
23134
23205
  listEvents: api.listEvents,
23135
23206
  findLatestEvents: api.findLatestEvents,
23136
23207
  countLatestEvents: api.countLatestEvents,
23208
+ countReleaseInstallations: api.countReleaseInstallations,
23137
23209
  countEvents: api.countEvents,
23138
23210
  countEventSeries: api.countEventSeries,
23139
23211
  getReleaseActivity: api.getReleaseActivity,
@@ -23502,27 +23574,27 @@ const readScope$1 = (input) => {
23502
23574
  };
23503
23575
  const bundleFilter = (input) => {
23504
23576
  const scope = readScope$1(input);
23505
- const bundleId = requireString(input.bundleId, "bundle ID", MAX_EVENT_ID_LENGTH);
23577
+ const releaseId = requireString(input.releaseId, "bundle ID", MAX_EVENT_ID_LENGTH);
23506
23578
  switch (input.outcome) {
23507
23579
  case "downloaded": return {
23508
23580
  ...scope,
23509
23581
  type: "UPDATE_DOWNLOADED",
23510
- toBundleId: bundleId
23582
+ toReleaseId: releaseId
23511
23583
  };
23512
23584
  case "applied": return {
23513
23585
  ...scope,
23514
23586
  type: "UPDATE_APPLIED",
23515
- toBundleId: bundleId
23587
+ toReleaseId: releaseId
23516
23588
  };
23517
23589
  case "recovered": return {
23518
23590
  ...scope,
23519
23591
  type: "RECOVERED",
23520
- fromBundleId: bundleId
23592
+ fromReleaseId: releaseId
23521
23593
  };
23522
23594
  case "failed": return {
23523
23595
  ...scope,
23524
23596
  type: "UPDATE_FAILED",
23525
- toBundleId: bundleId
23597
+ toReleaseId: releaseId
23526
23598
  };
23527
23599
  default: throw new InsightsBadRequestError("Invalid Insights outcome.");
23528
23600
  }
@@ -23532,7 +23604,7 @@ const sameFilter = (left, right) => {
23532
23604
  switch (right.kind) {
23533
23605
  case "all": return true;
23534
23606
  case "installationMovement": return left.installId === right.installId;
23535
- 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);
23607
+ 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);
23536
23608
  }
23537
23609
  };
23538
23610
  const readEventCursor = (value, filter) => {
@@ -23569,7 +23641,7 @@ const assertEventRows = (rows, input) => {
23569
23641
  for (let index = 0; index < rows.length; index += 1) {
23570
23642
  const row = rows[index];
23571
23643
  const previous = rows[index - 1];
23572
- 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.");
23644
+ 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.");
23573
23645
  }
23574
23646
  };
23575
23647
  const toFailure = (failure) => ({
@@ -23608,6 +23680,7 @@ const eventDetails = ({ type, metadata }) => ({
23608
23680
  ...metadata.implied_download === true ? { impliedDownload: true } : {}
23609
23681
  });
23610
23682
  const toEventHistoryRow = (row) => ({
23683
+ ...row.from_release_id == null ? {} : { fromReleaseId: row.from_release_id },
23611
23684
  ...row.to_release_id == null ? {} : { toReleaseId: row.to_release_id },
23612
23685
  ...row.metadata.sdk_version == null ? {} : { sdkVersion: row.metadata.sdk_version },
23613
23686
  ...row.metadata.min_bundle_id === void 0 ? {} : { minBundleId: row.metadata.min_bundle_id },
@@ -23632,6 +23705,7 @@ const toInstallationRow = (row) => ({
23632
23705
  cohort: row.metadata.cohort,
23633
23706
  installId: row.install_id,
23634
23707
  lastKnownBundleId: row.type === "UPDATE_DOWNLOADED" ? row.from_bundle_id : row.to_bundle_id,
23708
+ lastKnownReleaseId: row.type === "UPDATE_DOWNLOADED" ? row.from_release_id : row.to_release_id,
23635
23709
  pendingBundleId: row.type === "UPDATE_DOWNLOADED" ? row.to_bundle_id : null,
23636
23710
  pendingReleaseId: row.type === "UPDATE_DOWNLOADED" ? row.to_release_id : null,
23637
23711
  latestStatus: row.type,
@@ -23754,46 +23828,33 @@ const createInsightsProvider = (model) => Object.freeze({
23754
23828
  measuredAtMs: Date.now()
23755
23829
  };
23756
23830
  };
23757
- const bundleId = input.bundleId === void 0 ? void 0 : requireString(input.bundleId, "bundle ID", MAX_EVENT_ID_LENGTH);
23758
- const reporting = measure(model.countLatestEvents({
23759
- ...scope,
23760
- sinceMs
23761
- }));
23762
- if (bundleId === void 0) return {
23831
+ const releaseId = input.releaseId === void 0 ? void 0 : requireString(input.releaseId, "bundle ID", MAX_EVENT_ID_LENGTH);
23832
+ if (releaseId === void 0) return {
23763
23833
  ...scope,
23764
23834
  window,
23765
23835
  sinceMs,
23766
23836
  beforeReceivedAtMs,
23767
- reportingInstallations: await reporting
23837
+ reportingInstallations: await measure(model.countLatestEvents({
23838
+ ...scope,
23839
+ sinceMs
23840
+ }))
23768
23841
  };
23842
+ const installations = model.countReleaseInstallations({
23843
+ ...scope,
23844
+ sinceMs,
23845
+ releaseId
23846
+ }).then(async (counts) => [await measure(Promise.resolve(counts.installations)), await measure(Promise.resolve(counts.release))]);
23769
23847
  const countOutcome = (outcome) => measure(model.countEvents({
23770
23848
  filter: bundleFilter({
23771
23849
  ...scope,
23772
- bundleId,
23850
+ releaseId,
23773
23851
  outcome
23774
23852
  }),
23775
23853
  sinceMs,
23776
23854
  beforeReceivedAtMs
23777
23855
  }));
23778
- const [reportingInstallations, bundleInstallations, downloadedReports, appliedReports, recoveredReports, failedReports] = await Promise.all([
23779
- reporting,
23780
- measure(model.countLatestEvents({
23781
- ...scope,
23782
- sinceMs,
23783
- bundle: [{
23784
- field: "from_bundle_id",
23785
- value: bundleId,
23786
- types: ["UPDATE_DOWNLOADED"]
23787
- }, {
23788
- field: "to_bundle_id",
23789
- value: bundleId,
23790
- types: [
23791
- "UNCHANGED",
23792
- "UPDATE_APPLIED",
23793
- "RECOVERED"
23794
- ]
23795
- }]
23796
- })),
23856
+ const [[reportingInstallations, bundleInstallations], downloadedReports, appliedReports, recoveredReports, failedReports] = await Promise.all([
23857
+ installations,
23797
23858
  countOutcome("downloaded"),
23798
23859
  countOutcome("applied"),
23799
23860
  countOutcome("recovered"),
@@ -23806,7 +23867,7 @@ const createInsightsProvider = (model) => Object.freeze({
23806
23867
  beforeReceivedAtMs,
23807
23868
  reportingInstallations,
23808
23869
  bundle: {
23809
- bundleId,
23870
+ releaseId,
23810
23871
  reportingInstallations: bundleInstallations,
23811
23872
  downloadedReports,
23812
23873
  appliedReports,
@@ -23931,8 +23992,6 @@ const gaugeSlot = (head) => ({
23931
23992
  releaseId: head.type === "UPDATE_DOWNLOADED" ? head.from_release_id : head.to_release_id,
23932
23993
  builtinBundleId: runningBuiltinBundleId(head)
23933
23994
  });
23934
- const PAIR_FIELD = "from_to";
23935
- const bundlePairKey = (from, to) => insightsKey(`${from.length}:${from}${to.length}:${to}`);
23936
23995
  const countHead = (tx, head, delta) => {
23937
23996
  const { bucket, releaseId, builtinBundleId } = gaugeSlot(head);
23938
23997
  const shardBy = head.install_id;
@@ -23951,26 +24010,6 @@ const countHead = (tx, head, delta) => {
23951
24010
  builtin_bundle_id: builtinBundleId,
23952
24011
  bucket_start_ms: bucket
23953
24012
  }, { latest_installations: delta }, { shardBy });
23954
- for (const field of ["from_bundle_id", "to_bundle_id"]) {
23955
- const bundleId = head[field];
23956
- if (bundleId === null) continue;
23957
- tx.aggregate("insights_latest_by_bundle", {
23958
- platform: head.platform,
23959
- channel: head.channel,
23960
- bundle_field: field,
23961
- bundle_id: bundleId,
23962
- type: head.type,
23963
- bucket_start_ms: bucket
23964
- }, { installations: delta }, { shardBy });
23965
- }
23966
- if (head.from_bundle_id !== null) tx.aggregate("insights_latest_by_bundle", {
23967
- platform: head.platform,
23968
- channel: head.channel,
23969
- bundle_field: PAIR_FIELD,
23970
- bundle_id: bundlePairKey(head.from_bundle_id, head.to_bundle_id),
23971
- type: head.type,
23972
- bucket_start_ms: bucket
23973
- }, { installations: delta }, { shardBy });
23974
24013
  };
23975
24014
  const PERIOD_MODELS = {
23976
24015
  hour: {
@@ -24020,18 +24059,13 @@ const countEvent = (tx, event) => {
24020
24059
  };
24021
24060
  const countOutcome = (tx, event) => {
24022
24061
  const shardBy = event.install_id;
24023
- const hour = (type, bundleRef) => tx.aggregate("insights_outcomes", {
24062
+ for (const [type, bundleRef] of outcomeRefsOf(event)) tx.aggregate("insights_outcomes", {
24024
24063
  platform: event.platform,
24025
24064
  channel: event.channel,
24026
24065
  type,
24027
24066
  bundle_ref: bundleRef,
24028
24067
  bucket_start_ms: hourOf(event.received_at_ms)
24029
24068
  }, { events: 1 }, { shardBy });
24030
- for (const bundleRef of bundleRefsOf(event)) hour(event.type, bundleRef);
24031
- if (event.metadata.implied_download === true) hour("UPDATE_DOWNLOADED", bundleRefOfFilter({
24032
- type: "UPDATE_DOWNLOADED",
24033
- toBundleId: event.type === "RECOVERED" ? event.from_bundle_id : event.to_bundle_id
24034
- }));
24035
24069
  tx.aggregate("insights_outcomes", {
24036
24070
  ...DAILY_EVENTS,
24037
24071
  bucket_start_ms: dayOf(event.received_at_ms)
@@ -24417,25 +24451,34 @@ const countEventSeries = async (db, input) => {
24417
24451
  events: count
24418
24452
  }));
24419
24453
  };
24420
- const latestPredicates = (bundle) => {
24421
- if (bundle === void 0) return void 0;
24422
- return [...new Map(bundle.flatMap(({ field, value, types }) => types.map((type) => [JSON.stringify([
24423
- field,
24424
- value,
24425
- type
24426
- ]), {
24427
- field,
24428
- value,
24429
- type
24430
- }]))).values()];
24431
- };
24432
- const countLatestEvents = async (db, input) => {
24433
- const { platform, channel, sinceMs: start } = input;
24454
+ const distributionRows = (db, { platform, channel, sinceMs: start }) => {
24434
24455
  if (start % 864e5 !== 0) throw new DatabaseAdapterInputError("invalid-query");
24435
- const predicates = latestPredicates(input.bundle);
24456
+ return drain((page) => db.findAggregates("insights_distribution", {
24457
+ index: "byScope",
24458
+ where: {
24459
+ channel,
24460
+ platform
24461
+ },
24462
+ range: { gte: start },
24463
+ limit: PAGE,
24464
+ ...page
24465
+ }));
24466
+ };
24467
+ const installations = (count) => Math.max(0, count);
24468
+ const countLatestEvents = async (db, input) => installations((await distributionRows(db, input)).reduce((sum, row) => sum + row.latest_installations, 0));
24469
+ const countReleaseInstallations = async (db, input) => {
24470
+ const { platform, channel, sinceMs: start, releaseId } = input;
24436
24471
  let total = 0;
24437
- if (predicates === void 0) {
24438
- const rows = await drain((page) => db.findAggregates("insights_distribution", {
24472
+ let release = 0;
24473
+ let named = false;
24474
+ for (const row of await distributionRows(db, input)) {
24475
+ total += row.latest_installations;
24476
+ if (row.release_id !== releaseId) continue;
24477
+ named = true;
24478
+ release += row.latest_installations;
24479
+ }
24480
+ if (!named) {
24481
+ const builtin = await drain((page) => db.findAggregates("insights_builtin_distribution", {
24439
24482
  index: "byScope",
24440
24483
  where: {
24441
24484
  channel,
@@ -24445,33 +24488,12 @@ const countLatestEvents = async (db, input) => {
24445
24488
  limit: PAGE,
24446
24489
  ...page
24447
24490
  }));
24448
- total += rows.reduce((sum, row) => sum + row.latest_installations, 0);
24449
- } else {
24450
- const gauge = async (bundleField, bundleId, type) => {
24451
- return (await drain((page) => db.findAggregates("insights_latest_by_bundle", {
24452
- index: "byBundle",
24453
- where: {
24454
- platform,
24455
- channel,
24456
- bundle_field: bundleField,
24457
- bundle_id: bundleId,
24458
- type
24459
- },
24460
- range: { gte: start },
24461
- limit: PAGE,
24462
- ...page
24463
- }))).reduce((sum, row) => sum + row.installations, 0);
24464
- };
24465
- for (const { field, value, type } of predicates) total += await gauge(field, value, type);
24466
- for (const from of predicates) {
24467
- if (from.field !== "from_bundle_id") continue;
24468
- for (const to of predicates) {
24469
- if (to.field !== "to_bundle_id" || to.type !== from.type) continue;
24470
- total -= await gauge(PAIR_FIELD, bundlePairKey(from.value, to.value), from.type);
24471
- }
24472
- }
24491
+ for (const row of builtin) if (row.release_id === "" && row.builtin_bundle_id === releaseId) release += row.latest_installations;
24473
24492
  }
24474
- return Math.max(0, total);
24493
+ return {
24494
+ installations: installations(total),
24495
+ release: installations(release)
24496
+ };
24475
24497
  };
24476
24498
  const retained = (now, { rawDays, dailyDays }) => ({
24477
24499
  hour: hourCeil(now - rawDays * DAY_MS$1),
@@ -24888,6 +24910,20 @@ const getUpdateFailures = async (db, input, now, retention) => {
24888
24910
  };
24889
24911
  };
24890
24912
  //#endregion
24913
+ //#region ../insights/dist/server/wire.mjs
24914
+ const RELEASE_ID_PARAM = "bundleId";
24915
+ const toWireOverview = ({ bundle, ...overview }) => {
24916
+ if (bundle === void 0) return overview;
24917
+ const { releaseId, ...counts } = bundle;
24918
+ return {
24919
+ ...overview,
24920
+ bundle: {
24921
+ ...counts,
24922
+ bundleId: releaseId
24923
+ }
24924
+ };
24925
+ };
24926
+ //#endregion
24891
24927
  //#region ../insights/dist/server/queryInput.mjs
24892
24928
  const MAX_PAGE_LIMIT = 100;
24893
24929
  const MAX_IDENTITY_LENGTH = 255;
@@ -24932,7 +24968,7 @@ const readScope = (url) => {
24932
24968
  const parseEventPageInput = (request) => {
24933
24969
  const url = new URL(request.url);
24934
24970
  const bundleFields = [
24935
- "bundleId",
24971
+ RELEASE_ID_PARAM,
24936
24972
  "outcome",
24937
24973
  "platform",
24938
24974
  "channel"
@@ -24943,7 +24979,7 @@ const parseEventPageInput = (request) => {
24943
24979
  if (outcome !== "downloaded" && outcome !== "applied" && outcome !== "recovered" && outcome !== "failed") throw new InsightsBadRequestError("Invalid 'outcome' query parameter.");
24944
24980
  bundle = {
24945
24981
  ...readScope(url),
24946
- bundleId: readId(url, "bundleId", 1024),
24982
+ releaseId: readId(url, RELEASE_ID_PARAM, 1024),
24947
24983
  outcome
24948
24984
  };
24949
24985
  }
@@ -24969,11 +25005,10 @@ const parseReportingOverviewInput = (request) => {
24969
25005
  const url = new URL(request.url);
24970
25006
  const window = readSingle(url, "window") ?? "30d";
24971
25007
  if (window !== "24h" && window !== "7d" && window !== "30d") throw new InsightsBadRequestError("Invalid 'window' query parameter.");
24972
- const bundleId = readSingle(url, "bundleId");
24973
25008
  return {
24974
25009
  ...readScope(url),
24975
25010
  window,
24976
- ...bundleId === void 0 ? {} : { bundleId: readId(url, "bundleId", 1024) }
25011
+ ...readSingle(url, "bundleId") === void 0 ? {} : { releaseId: readId(url, RELEASE_ID_PARAM, 1024) }
24977
25012
  };
24978
25013
  };
24979
25014
  //#endregion
@@ -25052,7 +25087,7 @@ const createInsightsRouteHandlers = (provider) => ({
25052
25087
  await provider.appendBundleEvent(await parseBundleEventRequest(request));
25053
25088
  return new Response(null, { status: 204 });
25054
25089
  }),
25055
- getReportingOverview: (_params, request) => query(() => provider.getReportingOverview(parseReportingOverviewInput(request))),
25090
+ getReportingOverview: (_params, request) => query(async () => toWireOverview(await provider.getReportingOverview(parseReportingOverviewInput(request)))),
25056
25091
  getInstallation: (params) => run$1(async () => {
25057
25092
  const installation = await provider.getInstallation({ installId: requireParam(params, "installId") });
25058
25093
  return installation === null ? json$1({ error: "Installation not found" }, 404) : json$1(installation, 200);
@@ -25072,11 +25107,13 @@ const createInsightsApi = (db, now, retention) => ({
25072
25107
  listEvents: (input) => listEvents(db, input),
25073
25108
  findLatestEvents: (input) => findLatestEvents(db, input),
25074
25109
  countLatestEvents: (input) => countLatestEvents(db, input),
25110
+ countReleaseInstallations: (input) => countReleaseInstallations(db, input),
25075
25111
  countEvents: (input) => countEvents(db, input),
25076
25112
  countEventSeries: (input) => countEventSeries(db, input),
25077
25113
  getReleaseActivity: (input) => getReleaseActivity(db, input, now),
25078
25114
  getAppUsage: (input) => getAppUsage(db, input, now, retention),
25079
- getUpdateFailures: (input) => getUpdateFailures(db, input, now, retention)
25115
+ getUpdateFailures: (input) => getUpdateFailures(db, input, now, retention),
25116
+ backfillReleaseRefs: (options) => backfillReleaseRefs(db, now, retention, options)
25080
25117
  });
25081
25118
  const readFailuresQuery = (url) => {
25082
25119
  const query = url.searchParams;
@@ -7136,6 +7136,7 @@ const runInit = async ({ build, envFile, secretsEnv }) => {
7136
7136
  let credential;
7137
7137
  try {
7138
7138
  await (0, _hot_updater_cli_tools.fillReleaseLabels)(server);
7139
+ await (0, _hot_updater_cli_tools.backfillInsightsReleaseRefs)(server);
7139
7140
  credential = await (0, _hot_updater_cli_tools.provisionClientCredential)(server, {
7140
7141
  env: initInputEnv,
7141
7142
  name: "Vercel init"
@@ -2,7 +2,7 @@ import { createRequire } from "node:module";
2
2
  import fs from "fs/promises";
3
3
  import os from "os";
4
4
  import path from "path";
5
- import { ConfigBuilder, InitError, LegacyInfrastructureError, assembleServer, assertInfrastructureGenerationPayload, confirmInitInputPersistence, createHotUpdaterConfigScaffoldFromBuilder, createMigrator, fillReleaseLabels, getCwd, getHotUpdaterInitInputEnv, getInitProviderEnvVars, getInitProviderTextPromptValues, link, makeEnv, p, printAppSetup, provisionClientCredential, readHotUpdaterInitEnv, resolveInitProviderInputs, shouldAutoSelectOnlyInitResource, writeHotUpdaterFiles } from "@hot-updater/cli-tools";
5
+ import { ConfigBuilder, InitError, LegacyInfrastructureError, assembleServer, assertInfrastructureGenerationPayload, backfillInsightsReleaseRefs, confirmInitInputPersistence, createHotUpdaterConfigScaffoldFromBuilder, createMigrator, fillReleaseLabels, getCwd, getHotUpdaterInitInputEnv, getInitProviderEnvVars, getInitProviderTextPromptValues, link, makeEnv, p, printAppSetup, provisionClientCredential, readHotUpdaterInitEnv, resolveInitProviderInputs, shouldAutoSelectOnlyInitResource, writeHotUpdaterFiles } from "@hot-updater/cli-tools";
6
6
  import { postgres } from "@hot-updater/postgres";
7
7
  import { apiKeys, insights, remoteConfig } from "@hot-updater/server/plugins";
8
8
  import { fileURLToPath } from "node:url";
@@ -7130,6 +7130,7 @@ const runInit = async ({ build, envFile, secretsEnv }) => {
7130
7130
  let credential;
7131
7131
  try {
7132
7132
  await fillReleaseLabels(server);
7133
+ await backfillInsightsReleaseRefs(server);
7133
7134
  credential = await provisionClientCredential(server, {
7134
7135
  env: initInputEnv,
7135
7136
  name: "Vercel init"
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@hot-updater/vercel",
3
3
  "type": "module",
4
- "version": "1.2.0-rc.56",
4
+ "version": "1.2.0-rc.58",
5
5
  "description": "React Native OTA solution for self-hosted",
6
6
  "main": "dist/index.cjs",
7
7
  "module": "dist/index.mjs",
@@ -41,11 +41,11 @@
41
41
  "@vercel/cli-auth": "0.3.10",
42
42
  "@vercel/cli-config": "0.3.1",
43
43
  "pg": "8.13.1",
44
- "@hot-updater/cli-tools": "1.2.0-rc.56",
45
- "@hot-updater/plugin-core": "1.2.0-rc.56",
46
- "@hot-updater/postgres": "1.2.0-rc.56",
47
- "@hot-updater/protocol": "1.2.0-rc.56",
48
- "@hot-updater/server": "1.2.0-rc.56"
44
+ "@hot-updater/cli-tools": "1.2.0-rc.58",
45
+ "@hot-updater/plugin-core": "1.2.0-rc.58",
46
+ "@hot-updater/postgres": "1.2.0-rc.58",
47
+ "@hot-updater/protocol": "1.2.0-rc.58",
48
+ "@hot-updater/server": "1.2.0-rc.58"
49
49
  },
50
50
  "devDependencies": {
51
51
  "@types/node": "^20",
@@ -54,7 +54,7 @@
54
54
  "execa": "9.5.2",
55
55
  "kysely": "0.28.17",
56
56
  "vitest": "4.1.4",
57
- "@hot-updater/test-utils": "1.2.0-rc.56"
57
+ "@hot-updater/test-utils": "1.2.0-rc.58"
58
58
  },
59
59
  "scripts": {
60
60
  "build": "tsdown",