@hot-updater/plugin-insights 1.2.0-rc.6 → 1.2.0-rc.60

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.
Files changed (39) hide show
  1. package/dist/server/adminReads.cjs +5 -4
  2. package/dist/server/adminReads.mjs +5 -4
  3. package/dist/server/backfill.cjs +117 -0
  4. package/dist/server/backfill.d.cts +9 -0
  5. package/dist/server/backfill.d.mts +9 -0
  6. package/dist/server/backfill.mjs +117 -0
  7. package/dist/server/contract.cjs +18 -14
  8. package/dist/server/contract.mjs +18 -14
  9. package/dist/server/domain.d.cts +20 -2
  10. package/dist/server/domain.d.mts +20 -2
  11. package/dist/server/index.cjs +12 -1
  12. package/dist/server/index.d.cts +24 -2
  13. package/dist/server/index.d.mts +24 -2
  14. package/dist/server/index.mjs +13 -3
  15. package/dist/server/model.cjs +1 -0
  16. package/dist/server/model.mjs +1 -0
  17. package/dist/server/modelTypes.d.cts +32 -13
  18. package/dist/server/modelTypes.d.mts +32 -13
  19. package/dist/server/provider.cjs +24 -35
  20. package/dist/server/provider.mjs +24 -35
  21. package/dist/server/queryInput.cjs +4 -4
  22. package/dist/server/queryInput.mjs +4 -4
  23. package/dist/server/reads.cjs +118 -61
  24. package/dist/server/reads.d.cts +7 -0
  25. package/dist/server/reads.d.mts +7 -0
  26. package/dist/server/reads.mjs +119 -63
  27. package/dist/server/recordEvent.cjs +8 -44
  28. package/dist/server/recordEvent.mjs +10 -44
  29. package/dist/server/routes.cjs +2 -1
  30. package/dist/server/routes.mjs +2 -1
  31. package/dist/server/schema.cjs +30 -9
  32. package/dist/server/schema.mjs +30 -10
  33. package/dist/server/types.d.cts +2 -1
  34. package/dist/server/types.d.mts +2 -1
  35. package/dist/server/wire.cjs +34 -0
  36. package/dist/server/wire.d.cts +13 -0
  37. package/dist/server/wire.d.mts +13 -0
  38. package/dist/server/wire.mjs +32 -0
  39. package/package.json +4 -10
@@ -1,5 +1,6 @@
1
1
  const require_model = require("./model.cjs");
2
2
  const require_provider = require("./provider.cjs");
3
+ const require_wire = require("./wire.cjs");
3
4
  //#region src/server/adminReads.ts
4
5
  /** The reads over the `insights()` API tooling assembled on the server's database. */
5
6
  const createInsightsReads = (api) => ({
@@ -41,18 +42,18 @@ const createInsightsAdminReads = (fetchAdmin, { unavailable = () => /* @__PURE__
41
42
  return value;
42
43
  };
43
44
  return {
44
- getReportingOverview: ({ platform, channel, window, bundleId }) => required(withQuery("/overview", {
45
+ getReportingOverview: async ({ platform, channel, window, releaseId }) => require_wire.fromWireOverview(await required(withQuery("/overview", {
45
46
  platform,
46
47
  channel,
47
48
  window,
48
- bundleId
49
- })),
49
+ [require_wire.RELEASE_ID_PARAM]: releaseId
50
+ }))),
50
51
  listEvents: ({ bundle, ...input }) => required(withQuery("/events", {
51
52
  ...eventQuery(input),
52
53
  ...bundle === void 0 ? {} : {
53
54
  platform: bundle.platform,
54
55
  channel: bundle.channel,
55
- bundleId: bundle.bundleId,
56
+ [require_wire.RELEASE_ID_PARAM]: bundle.releaseId,
56
57
  outcome: bundle.outcome
57
58
  }
58
59
  })),
@@ -1,5 +1,6 @@
1
1
  import { createInsightsModel } from "./model.mjs";
2
2
  import { createInsightsProvider } from "./provider.mjs";
3
+ import { RELEASE_ID_PARAM, fromWireOverview } from "./wire.mjs";
3
4
  //#region src/server/adminReads.ts
4
5
  /** The reads over the `insights()` API tooling assembled on the server's database. */
5
6
  const createInsightsReads = (api) => ({
@@ -41,18 +42,18 @@ const createInsightsAdminReads = (fetchAdmin, { unavailable = () => /* @__PURE__
41
42
  return value;
42
43
  };
43
44
  return {
44
- getReportingOverview: ({ platform, channel, window, bundleId }) => required(withQuery("/overview", {
45
+ getReportingOverview: async ({ platform, channel, window, releaseId }) => fromWireOverview(await required(withQuery("/overview", {
45
46
  platform,
46
47
  channel,
47
48
  window,
48
- bundleId
49
- })),
49
+ [RELEASE_ID_PARAM]: releaseId
50
+ }))),
50
51
  listEvents: ({ bundle, ...input }) => required(withQuery("/events", {
51
52
  ...eventQuery(input),
52
53
  ...bundle === void 0 ? {} : {
53
54
  platform: bundle.platform,
54
55
  channel: bundle.channel,
55
- bundleId: bundle.bundleId,
56
+ [RELEASE_ID_PARAM]: bundle.releaseId,
56
57
  outcome: bundle.outcome
57
58
  }
58
59
  })),
@@ -0,0 +1,117 @@
1
+ const require_schema = require("./schema.cjs");
2
+ let _hot_updater_plugin_core = require("@hot-updater/plugin-core");
3
+ //#region src/server/backfill.ts
4
+ /**
5
+ * Stored events read a page, and rewritten up to `BATCH` a transaction. A
6
+ * run keeps one batch size, which only shrinks, halving whenever a store
7
+ * refuses a batch:
8
+ * - as too large, before writing anything: DynamoDB's 100 items hold fewer
9
+ * than 25 rewrites with their index copies and counts;
10
+ * - as busy through the transaction's retries: a write-capacity cap, such as
11
+ * the 100 write units a second `hot-updater init` gives a DynamoDB table,
12
+ * throttles a transaction that costs more than the cap admits, about 13
13
+ * rewrites of 2 KB events there, and refuses every write for seconds once
14
+ * the run has spent it.
15
+ * After a busy refusal the run also waits before it writes again, `PAUSE_MS`
16
+ * and twice as long after each further one, so the cap refills; a commit
17
+ * starts the waits over. A batch the store still refuses after the
18
+ * `MAX_PAUSE_MS` wait, or a one-event batch too large to write, fails the
19
+ * run, which a rerun resumes.
20
+ */
21
+ const PAGE = 500;
22
+ const BATCH = 25;
23
+ const PAUSE_MS = 1e3;
24
+ const MAX_PAUSE_MS = 32e3;
25
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
26
+ const sameRefs = (stored, refs) => {
27
+ const values = Array.isArray(stored) ? stored : [];
28
+ return values.length === refs.length && values.every((value) => refs.includes(value));
29
+ };
30
+ /**
31
+ * Whether a stored event still names its artifact, as a 1.1 server wrote
32
+ * it: its stored refs are the artifact's and differ from the release's. Its
33
+ * stored refs are how its outcome rows counted it, so they are what a
34
+ * rewrite moves, and a rewritten event reads as done.
35
+ */
36
+ const namesArtifact = (row) => {
37
+ const byKey = (key) => require_schema.bundleRefsOf(row, key);
38
+ return sameRefs(row.bundle_ref, byKey("artifact")) && !sameRefs(row.bundle_ref, byKey("release"));
39
+ };
40
+ /**
41
+ * Rewrites the stored events in the raw period whose refs name their
42
+ * artifact, as 1.1 servers wrote them, to name their release, and moves
43
+ * their hourly outcome counts with them, each event in the transaction that
44
+ * rewrites it. Each event carries its own release IDs, so two releases of
45
+ * one artifact in one scope come apart; an event without a release ID keeps
46
+ * the bundle ID it reports, as new events do.
47
+ *
48
+ * It reads every stored event once and writes only those still to move, so
49
+ * an interrupted run can run again. `hot-updater db migrate` and `hot-updater
50
+ * init` run it once a database: when it completes they record the settings
51
+ * row `insights.releaseRefs`, and later runs read no event. Installation
52
+ * gauges need nothing: they name releases already.
53
+ */
54
+ const backfillReleaseRefs = async (db, now, { rawDays }, { dryRun = false } = {}) => {
55
+ const today = now() - now() % require_schema.DAY_MS;
56
+ let events = 0;
57
+ let size = BATCH;
58
+ let paused = 0;
59
+ const move = async (stale) => {
60
+ if (dryRun) {
61
+ events += stale.length;
62
+ return;
63
+ }
64
+ for (let start = 0; start < stale.length;) {
65
+ const candidates = stale.slice(start, start + size);
66
+ try {
67
+ events += await rewrite(candidates);
68
+ start += candidates.length;
69
+ paused = 0;
70
+ } catch (error) {
71
+ if (error instanceof _hot_updater_plugin_core.DatabaseConstraintError && error.reason === "too_large" && candidates.length > 1) {
72
+ size = Math.ceil(candidates.length / 2);
73
+ continue;
74
+ }
75
+ if (!(0, _hot_updater_plugin_core.isDatabaseBusyError)(error) || paused >= MAX_PAUSE_MS) throw error;
76
+ size = Math.ceil(candidates.length / 2);
77
+ paused = paused === 0 ? PAUSE_MS : paused * 2;
78
+ await sleep(paused);
79
+ }
80
+ }
81
+ };
82
+ const rewrite = (candidates) => db.transaction(async (tx) => {
83
+ const rows = await Promise.all(candidates.map(({ id }) => tx.findOne("bundle_events", { id })));
84
+ let moved = 0;
85
+ for (const row of rows) {
86
+ if (row === null || !namesArtifact(row)) continue;
87
+ tx.update("bundle_events", row, {});
88
+ const outcome = (ref, delta) => tx.aggregate("insights_outcomes", {
89
+ platform: row.platform,
90
+ channel: row.channel,
91
+ type: ref[0],
92
+ bundle_ref: ref[1],
93
+ bucket_start_ms: row.received_at_ms - row.received_at_ms % require_schema.HOUR_MS
94
+ }, { events: delta }, { shardBy: row.install_id });
95
+ for (const ref of require_schema.outcomeRefsOf(row, "artifact")) outcome(ref, -1);
96
+ for (const ref of require_schema.outcomeRefsOf(row, "release")) outcome(ref, 1);
97
+ moved += 1;
98
+ }
99
+ return moved;
100
+ });
101
+ for (let day = today - rawDays * require_schema.DAY_MS; day <= today; day += require_schema.DAY_MS) {
102
+ let cursor;
103
+ do {
104
+ const page = await db.findMany("bundle_events", {
105
+ index: "byDay",
106
+ where: { day },
107
+ limit: PAGE,
108
+ ...cursor === void 0 ? {} : { cursor }
109
+ });
110
+ await move(page.rows.filter(namesArtifact));
111
+ cursor = page.next;
112
+ } while (cursor !== void 0);
113
+ }
114
+ return { events };
115
+ };
116
+ //#endregion
117
+ exports.backfillReleaseRefs = backfillReleaseRefs;
@@ -0,0 +1,9 @@
1
+ import { HotUpdaterDatabase } from "@hot-updater/plugin-core";
2
+ //#region src/server/backfill.d.ts
3
+ /** What `backfillReleaseRefs` moved, or with `dryRun` would move. */
4
+ interface ReleaseRefBackfill {
5
+ /** Stored events whose refs moved from their artifact to their release. */
6
+ readonly events: number;
7
+ }
8
+ //#endregion
9
+ export { ReleaseRefBackfill };
@@ -0,0 +1,9 @@
1
+ import { HotUpdaterDatabase } from "@hot-updater/plugin-core";
2
+ //#region src/server/backfill.d.ts
3
+ /** What `backfillReleaseRefs` moved, or with `dryRun` would move. */
4
+ interface ReleaseRefBackfill {
5
+ /** Stored events whose refs moved from their artifact to their release. */
6
+ readonly events: number;
7
+ }
8
+ //#endregion
9
+ export { ReleaseRefBackfill };
@@ -0,0 +1,117 @@
1
+ import { DAY_MS, HOUR_MS, bundleRefsOf, outcomeRefsOf } from "./schema.mjs";
2
+ import { DatabaseConstraintError, isDatabaseBusyError } from "@hot-updater/plugin-core";
3
+ //#region src/server/backfill.ts
4
+ /**
5
+ * Stored events read a page, and rewritten up to `BATCH` a transaction. A
6
+ * run keeps one batch size, which only shrinks, halving whenever a store
7
+ * refuses a batch:
8
+ * - as too large, before writing anything: DynamoDB's 100 items hold fewer
9
+ * than 25 rewrites with their index copies and counts;
10
+ * - as busy through the transaction's retries: a write-capacity cap, such as
11
+ * the 100 write units a second `hot-updater init` gives a DynamoDB table,
12
+ * throttles a transaction that costs more than the cap admits, about 13
13
+ * rewrites of 2 KB events there, and refuses every write for seconds once
14
+ * the run has spent it.
15
+ * After a busy refusal the run also waits before it writes again, `PAUSE_MS`
16
+ * and twice as long after each further one, so the cap refills; a commit
17
+ * starts the waits over. A batch the store still refuses after the
18
+ * `MAX_PAUSE_MS` wait, or a one-event batch too large to write, fails the
19
+ * run, which a rerun resumes.
20
+ */
21
+ const PAGE = 500;
22
+ const BATCH = 25;
23
+ const PAUSE_MS = 1e3;
24
+ const MAX_PAUSE_MS = 32e3;
25
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
26
+ const sameRefs = (stored, refs) => {
27
+ const values = Array.isArray(stored) ? stored : [];
28
+ return values.length === refs.length && values.every((value) => refs.includes(value));
29
+ };
30
+ /**
31
+ * Whether a stored event still names its artifact, as a 1.1 server wrote
32
+ * it: its stored refs are the artifact's and differ from the release's. Its
33
+ * stored refs are how its outcome rows counted it, so they are what a
34
+ * rewrite moves, and a rewritten event reads as done.
35
+ */
36
+ const namesArtifact = (row) => {
37
+ const byKey = (key) => bundleRefsOf(row, key);
38
+ return sameRefs(row.bundle_ref, byKey("artifact")) && !sameRefs(row.bundle_ref, byKey("release"));
39
+ };
40
+ /**
41
+ * Rewrites the stored events in the raw period whose refs name their
42
+ * artifact, as 1.1 servers wrote them, to name their release, and moves
43
+ * their hourly outcome counts with them, each event in the transaction that
44
+ * rewrites it. Each event carries its own release IDs, so two releases of
45
+ * one artifact in one scope come apart; an event without a release ID keeps
46
+ * the bundle ID it reports, as new events do.
47
+ *
48
+ * It reads every stored event once and writes only those still to move, so
49
+ * an interrupted run can run again. `hot-updater db migrate` and `hot-updater
50
+ * init` run it once a database: when it completes they record the settings
51
+ * row `insights.releaseRefs`, and later runs read no event. Installation
52
+ * gauges need nothing: they name releases already.
53
+ */
54
+ const backfillReleaseRefs = async (db, now, { rawDays }, { dryRun = false } = {}) => {
55
+ const today = now() - now() % DAY_MS;
56
+ let events = 0;
57
+ let size = BATCH;
58
+ let paused = 0;
59
+ const move = async (stale) => {
60
+ if (dryRun) {
61
+ events += stale.length;
62
+ return;
63
+ }
64
+ for (let start = 0; start < stale.length;) {
65
+ const candidates = stale.slice(start, start + size);
66
+ try {
67
+ events += await rewrite(candidates);
68
+ start += candidates.length;
69
+ paused = 0;
70
+ } catch (error) {
71
+ if (error instanceof DatabaseConstraintError && error.reason === "too_large" && candidates.length > 1) {
72
+ size = Math.ceil(candidates.length / 2);
73
+ continue;
74
+ }
75
+ if (!isDatabaseBusyError(error) || paused >= MAX_PAUSE_MS) throw error;
76
+ size = Math.ceil(candidates.length / 2);
77
+ paused = paused === 0 ? PAUSE_MS : paused * 2;
78
+ await sleep(paused);
79
+ }
80
+ }
81
+ };
82
+ const rewrite = (candidates) => db.transaction(async (tx) => {
83
+ const rows = await Promise.all(candidates.map(({ id }) => tx.findOne("bundle_events", { id })));
84
+ let moved = 0;
85
+ for (const row of rows) {
86
+ if (row === null || !namesArtifact(row)) continue;
87
+ tx.update("bundle_events", row, {});
88
+ const outcome = (ref, delta) => tx.aggregate("insights_outcomes", {
89
+ platform: row.platform,
90
+ channel: row.channel,
91
+ type: ref[0],
92
+ bundle_ref: ref[1],
93
+ bucket_start_ms: row.received_at_ms - row.received_at_ms % HOUR_MS
94
+ }, { events: delta }, { shardBy: row.install_id });
95
+ for (const ref of outcomeRefsOf(row, "artifact")) outcome(ref, -1);
96
+ for (const ref of outcomeRefsOf(row, "release")) outcome(ref, 1);
97
+ moved += 1;
98
+ }
99
+ return moved;
100
+ });
101
+ for (let day = today - rawDays * DAY_MS; day <= today; day += DAY_MS) {
102
+ let cursor;
103
+ do {
104
+ const page = await db.findMany("bundle_events", {
105
+ index: "byDay",
106
+ where: { day },
107
+ limit: PAGE,
108
+ ...cursor === void 0 ? {} : { cursor }
109
+ });
110
+ await move(page.rows.filter(namesArtifact));
111
+ cursor = page.next;
112
+ } while (cursor !== void 0);
113
+ }
114
+ return { events };
115
+ };
116
+ //#endregion
117
+ export { backfillReleaseRefs };
@@ -1,5 +1,5 @@
1
- const require_eventRow = require("./eventRow.cjs");
2
1
  const require_schema = require("./schema.cjs");
2
+ const require_eventRow = require("./eventRow.cjs");
3
3
  let _hot_updater_plugin_core = require("@hot-updater/plugin-core");
4
4
  //#region src/server/contract.ts
5
5
  const encoder = new TextEncoder();
@@ -31,7 +31,7 @@ const isBundleFilter = (value, withKind = false) => {
31
31
  "type",
32
32
  ...withKind ? ["kind"] : []
33
33
  ];
34
- return value.type === "RECOVERED" ? isText(value.fromBundleId) && hasOnlyKeys(value, [...keys, "fromBundleId"]) : (value.type === "UPDATE_DOWNLOADED" || value.type === "UPDATE_APPLIED" || value.type === "UPDATE_FAILED" || value.type === "UNCHANGED") && isText(value.toBundleId) && hasOnlyKeys(value, [...keys, "toBundleId"]);
34
+ return value.type === "RECOVERED" ? isText(value.fromReleaseId) && hasOnlyKeys(value, [...keys, "fromReleaseId"]) : (value.type === "UPDATE_DOWNLOADED" || value.type === "UPDATE_APPLIED" || value.type === "UPDATE_FAILED" || value.type === "UNCHANGED") && isText(value.toReleaseId) && hasOnlyKeys(value, [...keys, "toReleaseId"]);
35
35
  };
36
36
  const isEventFilter = (value) => {
37
37
  if (!require_eventRow.isRecord(value)) return false;
@@ -132,20 +132,24 @@ const createValidatedInsightsModel = (model) => ({
132
132
  if (!require_eventRow.isRecord(input) || !hasOnlyKeys(input, [
133
133
  "platform",
134
134
  "channel",
135
- "sinceMs",
136
- "bundle"
137
- ]) || !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) => !require_eventRow.isRecord(bundle) || !hasOnlyKeys(bundle, [
138
- "field",
139
- "value",
140
- "types"
141
- ]) || bundle.field !== "from_bundle_id" && bundle.field !== "to_bundle_id" || !isText(bundle.value) || !Array.isArray(bundle.types) || bundle.types.length === 0 || bundle.types.some((type) => ![
142
- "UNCHANGED",
143
- "UPDATE_DOWNLOADED",
144
- "UPDATE_APPLIED",
145
- "RECOVERED"
146
- ].includes(type))))) invalidQuery();
135
+ "sinceMs"
136
+ ]) || !hasScope(input) || !isTimestamp(input.sinceMs)) invalidQuery();
147
137
  return validateCount(await model.countLatestEvents(input));
148
138
  },
139
+ async countReleaseInstallations(input) {
140
+ if (!require_eventRow.isRecord(input) || !hasOnlyKeys(input, [
141
+ "platform",
142
+ "channel",
143
+ "sinceMs",
144
+ "releaseId"
145
+ ]) || !hasScope(input) || !isTimestamp(input.sinceMs) || !isText(input.releaseId)) invalidQuery();
146
+ const counts = await model.countReleaseInstallations(input);
147
+ if (!require_eventRow.isRecord(counts) || !hasOnlyKeys(counts, ["installations", "release"])) invalidResult();
148
+ return {
149
+ installations: validateCount(counts.installations),
150
+ release: validateCount(counts.release)
151
+ };
152
+ },
149
153
  async countEvents(input) {
150
154
  if (!require_eventRow.isRecord(input) || !hasOnlyKeys(input, [
151
155
  "filter",
@@ -1,5 +1,5 @@
1
- import { isRecord, validateBundleEventFields } from "./eventRow.mjs";
2
1
  import { bundleRefOfFilter, bundleRefsOf } from "./schema.mjs";
2
+ import { isRecord, validateBundleEventFields } from "./eventRow.mjs";
3
3
  import { DatabaseAdapterInputError, isUUIDv7 } from "@hot-updater/plugin-core";
4
4
  //#region src/server/contract.ts
5
5
  const encoder = new TextEncoder();
@@ -31,7 +31,7 @@ const isBundleFilter = (value, withKind = false) => {
31
31
  "type",
32
32
  ...withKind ? ["kind"] : []
33
33
  ];
34
- return value.type === "RECOVERED" ? isText(value.fromBundleId) && hasOnlyKeys(value, [...keys, "fromBundleId"]) : (value.type === "UPDATE_DOWNLOADED" || value.type === "UPDATE_APPLIED" || value.type === "UPDATE_FAILED" || value.type === "UNCHANGED") && isText(value.toBundleId) && hasOnlyKeys(value, [...keys, "toBundleId"]);
34
+ return value.type === "RECOVERED" ? isText(value.fromReleaseId) && hasOnlyKeys(value, [...keys, "fromReleaseId"]) : (value.type === "UPDATE_DOWNLOADED" || value.type === "UPDATE_APPLIED" || value.type === "UPDATE_FAILED" || value.type === "UNCHANGED") && isText(value.toReleaseId) && hasOnlyKeys(value, [...keys, "toReleaseId"]);
35
35
  };
36
36
  const isEventFilter = (value) => {
37
37
  if (!isRecord(value)) return false;
@@ -132,20 +132,24 @@ const createValidatedInsightsModel = (model) => ({
132
132
  if (!isRecord(input) || !hasOnlyKeys(input, [
133
133
  "platform",
134
134
  "channel",
135
- "sinceMs",
136
- "bundle"
137
- ]) || !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(bundle) || !hasOnlyKeys(bundle, [
138
- "field",
139
- "value",
140
- "types"
141
- ]) || bundle.field !== "from_bundle_id" && bundle.field !== "to_bundle_id" || !isText(bundle.value) || !Array.isArray(bundle.types) || bundle.types.length === 0 || bundle.types.some((type) => ![
142
- "UNCHANGED",
143
- "UPDATE_DOWNLOADED",
144
- "UPDATE_APPLIED",
145
- "RECOVERED"
146
- ].includes(type))))) invalidQuery();
135
+ "sinceMs"
136
+ ]) || !hasScope(input) || !isTimestamp(input.sinceMs)) invalidQuery();
147
137
  return validateCount(await model.countLatestEvents(input));
148
138
  },
139
+ async countReleaseInstallations(input) {
140
+ if (!isRecord(input) || !hasOnlyKeys(input, [
141
+ "platform",
142
+ "channel",
143
+ "sinceMs",
144
+ "releaseId"
145
+ ]) || !hasScope(input) || !isTimestamp(input.sinceMs) || !isText(input.releaseId)) invalidQuery();
146
+ const counts = await model.countReleaseInstallations(input);
147
+ if (!isRecord(counts) || !hasOnlyKeys(counts, ["installations", "release"])) invalidResult();
148
+ return {
149
+ installations: validateCount(counts.installations),
150
+ release: validateCount(counts.release)
151
+ };
152
+ },
149
153
  async countEvents(input) {
150
154
  if (!isRecord(input) || !hasOnlyKeys(input, [
151
155
  "filter",
@@ -98,7 +98,14 @@ type EventHistoryChange = {
98
98
  readonly minBundleId?: string;
99
99
  };
100
100
  };
101
+ /**
102
+ * An event as Insights lists it. `fromBundleId` and `toBundleId` are the
103
+ * artifact IDs the report names; `fromReleaseId` and `toReleaseId` the
104
+ * releases, the bundle IDs users see, absent for a side without one, such
105
+ * as the built-in bundle.
106
+ */
101
107
  type EventHistoryRow = {
108
+ readonly fromReleaseId?: string;
102
109
  readonly toReleaseId?: string;
103
110
  readonly sdkVersion?: string;
104
111
  /** The native build's built-in bundle ID, when the SDK reported it. */
@@ -145,8 +152,13 @@ type InstallationRow = {
145
152
  readonly minBundleId?: string;
146
153
  readonly installId: string;
147
154
  readonly userId: string | null;
155
+ /** The artifact the installation runs, or the built-in bundle's ID. */
148
156
  readonly lastKnownBundleId: string;
157
+ /** The release the installation runs, the bundle ID users see; null for none. */
158
+ readonly lastKnownReleaseId: string | null;
159
+ /** The artifact downloaded and not launched yet. */
149
160
  readonly pendingBundleId: string | null;
161
+ /** The release downloaded and not launched yet. */
150
162
  readonly pendingReleaseId: string | null;
151
163
  readonly latestStatus: EventHistoryRow["type"];
152
164
  readonly platform: "ios" | "android";
@@ -163,7 +175,8 @@ type EventCursorPage<T extends EventHistoryRow> = CursorPage<T> & {
163
175
  readonly beforeReceivedAtMs: number;
164
176
  };
165
177
  type InsightsBundleSelection = InsightsScope & {
166
- readonly bundleId: string;
178
+ /** The bundle users see, by its release ID. */
179
+ readonly releaseId: string;
167
180
  /** `failed`: update failures that targeted the bundle. */
168
181
  readonly outcome: "downloaded" | "applied" | "recovered" | "failed";
169
182
  };
@@ -177,7 +190,12 @@ type ReportingOverview = InsightsScope & {
177
190
  readonly beforeReceivedAtMs: number;
178
191
  readonly reportingInstallations: InsightsCountMeasurement;
179
192
  readonly bundle?: {
180
- readonly bundleId: string;
193
+ /** The bundle users see, by its release ID. */
194
+ readonly releaseId: string;
195
+ /**
196
+ * Installations whose latest report leaves them running the release;
197
+ * for a built-in bundle's ID, those running it outside any release.
198
+ */
181
199
  readonly reportingInstallations: InsightsCountMeasurement;
182
200
  /**
183
201
  * Download reports of the bundle, and in whole hours the downloads a
@@ -98,7 +98,14 @@ type EventHistoryChange = {
98
98
  readonly minBundleId?: string;
99
99
  };
100
100
  };
101
+ /**
102
+ * An event as Insights lists it. `fromBundleId` and `toBundleId` are the
103
+ * artifact IDs the report names; `fromReleaseId` and `toReleaseId` the
104
+ * releases, the bundle IDs users see, absent for a side without one, such
105
+ * as the built-in bundle.
106
+ */
101
107
  type EventHistoryRow = {
108
+ readonly fromReleaseId?: string;
102
109
  readonly toReleaseId?: string;
103
110
  readonly sdkVersion?: string;
104
111
  /** The native build's built-in bundle ID, when the SDK reported it. */
@@ -145,8 +152,13 @@ type InstallationRow = {
145
152
  readonly minBundleId?: string;
146
153
  readonly installId: string;
147
154
  readonly userId: string | null;
155
+ /** The artifact the installation runs, or the built-in bundle's ID. */
148
156
  readonly lastKnownBundleId: string;
157
+ /** The release the installation runs, the bundle ID users see; null for none. */
158
+ readonly lastKnownReleaseId: string | null;
159
+ /** The artifact downloaded and not launched yet. */
149
160
  readonly pendingBundleId: string | null;
161
+ /** The release downloaded and not launched yet. */
150
162
  readonly pendingReleaseId: string | null;
151
163
  readonly latestStatus: EventHistoryRow["type"];
152
164
  readonly platform: "ios" | "android";
@@ -163,7 +175,8 @@ type EventCursorPage<T extends EventHistoryRow> = CursorPage<T> & {
163
175
  readonly beforeReceivedAtMs: number;
164
176
  };
165
177
  type InsightsBundleSelection = InsightsScope & {
166
- readonly bundleId: string;
178
+ /** The bundle users see, by its release ID. */
179
+ readonly releaseId: string;
167
180
  /** `failed`: update failures that targeted the bundle. */
168
181
  readonly outcome: "downloaded" | "applied" | "recovered" | "failed";
169
182
  };
@@ -177,7 +190,12 @@ type ReportingOverview = InsightsScope & {
177
190
  readonly beforeReceivedAtMs: number;
178
191
  readonly reportingInstallations: InsightsCountMeasurement;
179
192
  readonly bundle?: {
180
- readonly bundleId: string;
193
+ /** The bundle users see, by its release ID. */
194
+ readonly releaseId: string;
195
+ /**
196
+ * Installations whose latest report leaves them running the release;
197
+ * for a built-in bundle's ID, those running it outside any release.
198
+ */
181
199
  readonly reportingInstallations: InsightsCountMeasurement;
182
200
  /**
183
201
  * Download reports of the bundle, and in whole hours the downloads a
@@ -1,11 +1,13 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_schema = require("./schema.cjs");
3
+ const require_backfill = require("./backfill.cjs");
3
4
  const require_model = require("./model.cjs");
4
5
  const require_official = require("./official.cjs");
5
6
  const require_errors = require("./errors.cjs");
6
7
  const require_provider = require("./provider.cjs");
7
8
  const require_recordEvent = require("./recordEvent.cjs");
8
9
  const require_reads = require("./reads.cjs");
10
+ const require_wire = require("./wire.cjs");
9
11
  const require_routes = require("./routes.cjs");
10
12
  const require_adminReads = require("./adminReads.cjs");
11
13
  let _hot_updater_plugin_core = require("@hot-updater/plugin-core");
@@ -18,12 +20,20 @@ const createInsightsApi = (db, now, retention) => ({
18
20
  listEvents: (input) => require_reads.listEvents(db, input),
19
21
  findLatestEvents: (input) => require_reads.findLatestEvents(db, input),
20
22
  countLatestEvents: (input) => require_reads.countLatestEvents(db, input),
23
+ countReleaseInstallations: (input) => require_reads.countReleaseInstallations(db, input),
21
24
  countEvents: (input) => require_reads.countEvents(db, input),
22
25
  countEventSeries: (input) => require_reads.countEventSeries(db, input),
23
26
  getReleaseActivity: (input) => require_reads.getReleaseActivity(db, input, now),
24
27
  getAppUsage: (input) => require_reads.getAppUsage(db, input, now, retention),
25
28
  /** A release's or a channel's update failures, and their breakdown over a time range. */
26
- getUpdateFailures: (input) => require_reads.getUpdateFailures(db, input, now, retention)
29
+ getUpdateFailures: (input) => require_reads.getUpdateFailures(db, input, now, retention),
30
+ /**
31
+ * Moves the stored events a 1.1 server keyed by artifact, and their
32
+ * outcome counts, to their release, reading every stored event of the
33
+ * raw period: `hot-updater db migrate` and `hot-updater init` run it once
34
+ * a database, and an interrupted run can run again.
35
+ */
36
+ backfillReleaseRefs: (options) => require_backfill.backfillReleaseRefs(db, now, retention, options)
27
37
  });
28
38
  /** `GET /failures`'s query: a scope, an optional release, and a time range or none. */
29
39
  const readFailuresQuery = (url) => {
@@ -131,3 +141,4 @@ exports.createInsightsSchema = require_schema.createInsightsSchema;
131
141
  exports.insights = insights;
132
142
  exports.insightsIdentity = require_recordEvent.insightsIdentity;
133
143
  exports.insightsSchema = require_schema.insightsSchema;
144
+ exports.toWireOverview = require_wire.toWireOverview;
@@ -1,7 +1,8 @@
1
1
  import { BundleEventFailure, BundleEventFailureReason, BundleEventFailureStage, BundleEventRow, BundleEventRowBase, DatabaseBundleEventMetadata } from "./eventRow.cjs";
2
- import { InsightsBundleEventFilter, InsightsCountEventSeriesInput, InsightsCountEventsInput, InsightsCountLatestEventsInput, InsightsCoverage, InsightsEventCursor, InsightsEventFilter, InsightsEventSeriesPoint, InsightsFindLatestEventsInput, InsightsGetAppUsageInput, InsightsGetAppUsageResult, InsightsGetReleaseActivityInput, InsightsGetReleaseActivityResult, InsightsListEventsInput, InsightsModel, InsightsRecordEventInput, InsightsScope, InsightsTimeRange, ReleaseActivityMetrics, ReleaseReference } from "./modelTypes.cjs";
2
+ import { InsightsBundleEventFilter, InsightsCountEventSeriesInput, InsightsCountEventsInput, InsightsCountLatestEventsInput, InsightsCountReleaseInstallationsInput, InsightsCoverage, InsightsEventCursor, InsightsEventFilter, InsightsEventSeriesPoint, InsightsFindLatestEventsInput, InsightsGetAppUsageInput, InsightsGetAppUsageResult, InsightsGetReleaseActivityInput, InsightsGetReleaseActivityResult, InsightsListEventsInput, InsightsModel, InsightsRecordEventInput, InsightsReleaseInstallations, InsightsScope, InsightsTimeRange, ReleaseActivityMetrics, ReleaseReference } from "./modelTypes.cjs";
3
3
  import { DEFAULT_INSIGHTS_RETENTION, InsightsRetention, InsightsSchema, createInsightsSchema, insightsSchema } from "./schema.cjs";
4
4
  import { InsightsFailureBreakdown, InsightsUpdateFailures, InsightsUpdateFailuresInput } from "./reads.cjs";
5
+ import { ReleaseRefBackfill } from "./backfill.cjs";
5
6
  import { ActiveInstallationWindow, BundleEventFailureInput, CreateBundleEventRequest, CreateBundleEventRequestBase, CursorPage, EventCursorPage, EventHistoryChange, EventHistoryRow, InsightsBundleSelection, InsightsCountMeasurement, InsightsHttpResponse, InstallationHistoryRow, InstallationRow, ReportingOverview } from "./domain.cjs";
6
7
  import { InsightsEventPageInput, InsightsInstallationEventPageInput, InsightsProvider, InsightsUserInstallationPageInput } from "./types.cjs";
7
8
  import { InsightsAdminReadsOptions, InsightsReads, createInsightsAdminReads, createInsightsReads } from "./adminReads.cjs";
@@ -9,6 +10,7 @@ import { InsightsBadRequestError } from "./errors.cjs";
9
10
  import { createInsightsModel } from "./model.cjs";
10
11
  import { createInsightsProvider } from "./provider.cjs";
11
12
  import { InsightsIdentityParts, insightsIdentity } from "./recordEvent.cjs";
13
+ import { WireReportingOverview, toWireOverview } from "./wire.cjs";
12
14
  import { HotUpdaterDatabase, PluginEndpoint } from "@hot-updater/plugin-core";
13
15
  //#region src/server/index.d.ts
14
16
  declare const createInsightsApi: (db: HotUpdaterDatabase<InsightsSchema>, now: () => number, retention: InsightsRetention) => {
@@ -19,12 +21,22 @@ declare const createInsightsApi: (db: HotUpdaterDatabase<InsightsSchema>, now: (
19
21
  listEvents: (input: InsightsListEventsInput) => Promise<readonly BundleEventRow[]>;
20
22
  findLatestEvents: (input: InsightsFindLatestEventsInput) => Promise<readonly BundleEventRow[]>;
21
23
  countLatestEvents: (input: InsightsCountLatestEventsInput) => Promise<number>;
24
+ countReleaseInstallations: (input: InsightsCountReleaseInstallationsInput) => Promise<InsightsReleaseInstallations>;
22
25
  countEvents: (input: InsightsCountEventsInput) => Promise<number>;
23
26
  countEventSeries: (input: InsightsCountEventSeriesInput) => Promise<readonly InsightsEventSeriesPoint[]>;
24
27
  getReleaseActivity: (input: InsightsGetReleaseActivityInput) => Promise<InsightsGetReleaseActivityResult>;
25
28
  getAppUsage: (input: InsightsGetAppUsageInput) => Promise<InsightsGetAppUsageResult>;
26
29
  /** A release's or a channel's update failures, and their breakdown over a time range. */
27
30
  getUpdateFailures: (input: InsightsUpdateFailuresInput) => Promise<InsightsUpdateFailures>;
31
+ /**
32
+ * Moves the stored events a 1.1 server keyed by artifact, and their
33
+ * outcome counts, to their release, reading every stored event of the
34
+ * raw period: `hot-updater db migrate` and `hot-updater init` run it once
35
+ * a database, and an interrupted run can run again.
36
+ */
37
+ backfillReleaseRefs: (options?: {
38
+ readonly dryRun?: boolean;
39
+ }) => Promise<ReleaseRefBackfill>;
28
40
  };
29
41
  type InsightsApi = ReturnType<typeof createInsightsApi>;
30
42
  interface InsightsOptions {
@@ -413,14 +425,24 @@ declare const insights: (options?: InsightsOptions) => import("@hot-updater/plug
413
425
  listEvents: (input: InsightsListEventsInput) => Promise<readonly BundleEventRow[]>;
414
426
  findLatestEvents: (input: InsightsFindLatestEventsInput) => Promise<readonly BundleEventRow[]>;
415
427
  countLatestEvents: (input: InsightsCountLatestEventsInput) => Promise<number>;
428
+ countReleaseInstallations: (input: InsightsCountReleaseInstallationsInput) => Promise<InsightsReleaseInstallations>;
416
429
  countEvents: (input: InsightsCountEventsInput) => Promise<number>;
417
430
  countEventSeries: (input: InsightsCountEventSeriesInput) => Promise<readonly InsightsEventSeriesPoint[]>;
418
431
  getReleaseActivity: (input: InsightsGetReleaseActivityInput) => Promise<InsightsGetReleaseActivityResult>;
419
432
  getAppUsage: (input: InsightsGetAppUsageInput) => Promise<InsightsGetAppUsageResult>;
420
433
  /** A release's or a channel's update failures, and their breakdown over a time range. */
421
434
  getUpdateFailures: (input: InsightsUpdateFailuresInput) => Promise<InsightsUpdateFailures>;
435
+ /**
436
+ * Moves the stored events a 1.1 server keyed by artifact, and their
437
+ * outcome counts, to their release, reading every stored event of the
438
+ * raw period: `hot-updater db migrate` and `hot-updater init` run it once
439
+ * a database, and an interrupted run can run again.
440
+ */
441
+ backfillReleaseRefs: (options?: {
442
+ readonly dryRun?: boolean;
443
+ }) => Promise<ReleaseRefBackfill>;
422
444
  };
423
445
  endpoints: PluginEndpoint[];
424
446
  }, {}>;
425
447
  //#endregion
426
- export { type ActiveInstallationWindow, type BundleEventFailure, type BundleEventFailureInput, type BundleEventFailureReason, type BundleEventFailureStage, type BundleEventRow, type BundleEventRowBase, type CreateBundleEventRequest, type CreateBundleEventRequestBase, type CursorPage, DEFAULT_INSIGHTS_RETENTION, type DatabaseBundleEventMetadata, type EventCursorPage, type EventHistoryChange, type EventHistoryRow, type InsightsAdminReadsOptions, InsightsApi, InsightsBadRequestError, type InsightsBundleEventFilter, type InsightsBundleSelection, type InsightsCountEventSeriesInput, type InsightsCountEventsInput, type InsightsCountLatestEventsInput, type InsightsCountMeasurement, type InsightsCoverage, type InsightsEventCursor, type InsightsEventFilter, type InsightsEventPageInput, type InsightsEventSeriesPoint, type InsightsFailureBreakdown, type InsightsFindLatestEventsInput, type InsightsGetAppUsageInput, type InsightsGetAppUsageResult, type InsightsGetReleaseActivityInput, type InsightsGetReleaseActivityResult, type InsightsHttpResponse, type InsightsIdentityParts, type InsightsInstallationEventPageInput, type InsightsListEventsInput, type InsightsModel, InsightsOptions, type InsightsProvider, type InsightsReads, type InsightsRecordEventInput, type InsightsRetention, type InsightsSchema, type InsightsScope, type InsightsTimeRange, type InsightsUpdateFailures, type InsightsUpdateFailuresInput, type InsightsUserInstallationPageInput, type InstallationHistoryRow, type InstallationRow, type ReleaseActivityMetrics, type ReleaseReference, type ReportingOverview, createInsightsAdminReads, createInsightsModel, createInsightsProvider, createInsightsReads, createInsightsSchema, insights, insightsIdentity, insightsSchema };
448
+ export { type ActiveInstallationWindow, type BundleEventFailure, type BundleEventFailureInput, type BundleEventFailureReason, type BundleEventFailureStage, type BundleEventRow, type BundleEventRowBase, type CreateBundleEventRequest, type CreateBundleEventRequestBase, type CursorPage, DEFAULT_INSIGHTS_RETENTION, type DatabaseBundleEventMetadata, type EventCursorPage, type EventHistoryChange, type EventHistoryRow, type InsightsAdminReadsOptions, InsightsApi, InsightsBadRequestError, type InsightsBundleEventFilter, type InsightsBundleSelection, type InsightsCountEventSeriesInput, type InsightsCountEventsInput, type InsightsCountLatestEventsInput, type InsightsCountMeasurement, type InsightsCountReleaseInstallationsInput, type InsightsCoverage, type InsightsEventCursor, type InsightsEventFilter, type InsightsEventPageInput, type InsightsEventSeriesPoint, type InsightsFailureBreakdown, type InsightsFindLatestEventsInput, type InsightsGetAppUsageInput, type InsightsGetAppUsageResult, type InsightsGetReleaseActivityInput, type InsightsGetReleaseActivityResult, type InsightsHttpResponse, type InsightsIdentityParts, type InsightsInstallationEventPageInput, type InsightsListEventsInput, type InsightsModel, InsightsOptions, type InsightsProvider, type InsightsReads, type InsightsRecordEventInput, type InsightsReleaseInstallations, type InsightsRetention, type InsightsSchema, type InsightsScope, type InsightsTimeRange, type InsightsUpdateFailures, type InsightsUpdateFailuresInput, type InsightsUserInstallationPageInput, type InstallationHistoryRow, type InstallationRow, type ReleaseActivityMetrics, type ReleaseRefBackfill, type ReleaseReference, type ReportingOverview, type WireReportingOverview, createInsightsAdminReads, createInsightsModel, createInsightsProvider, createInsightsReads, createInsightsSchema, insights, insightsIdentity, insightsSchema, toWireOverview };