@hot-updater/test-utils 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.
package/dist/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
2
+ import { DATABASE_VERSION_COLUMN, DatabaseAdapterContractError, DatabaseConstraintError, SETTINGS_TABLE, addDistinct, aggregateBatchingTables, assertStorageOperations, bundleToPatchRows, bundleToRow, compareUtf8, coreSchema, countDistinct, createBundleStorageKey, createEngine, createMemoryAdapter, createStorageKeyBuilder, createStorageRootUriWithPath, createStorageUri, createStorageUriWithRelativePath, defineAggregate, definePlugin, defineTable, findPhysicalIndex, getBundleArchiveStorageUri, getContentAddressedAssetStoragePath, indexOrderColumns, meterReads, parseStorageUri, targetBaseCandidateKey, toolingTargetOf, verifyAdapter } from "@hot-updater/plugin-core";
2
3
  import { NIL_UUID, createReleaseCatalogScopeKey, encodeChannelKey, selectDesiredRelease } from "@hot-updater/protocol";
3
- import { DATABASE_VERSION_COLUMN, DatabaseAdapterContractError, SETTINGS_TABLE, addDistinct, aggregateBatchingTables, assertStorageOperations, bundleToPatchRows, bundleToRow, compareUtf8, coreSchema, countDistinct, createBundleStorageKey, createEngine, createMemoryAdapter, createStorageKeyBuilder, createStorageRootUriWithPath, createStorageUri, createStorageUriWithRelativePath, findPhysicalIndex, getBundleArchiveStorageUri, getContentAddressedAssetStoragePath, indexOrderColumns, meterReads, parseStorageUri, targetBaseCandidateKey, toolingTargetOf, verifyAdapter } from "@hot-updater/plugin-core";
4
4
  import { createServer } from "node:http";
5
5
  //#region src/adminApiTestClient.ts
6
6
  const jsonRequest = (method, body) => ({
@@ -79,6 +79,43 @@ const createAdminApiTestClient = (getClient) => {
79
79
  };
80
80
  };
81
81
  //#endregion
82
+ //#region src/catalogFromLaterRelease.ts
83
+ /** A field no release of Hot Updater compiles, as a later release may add one. */
84
+ const LATER_RELEASE_CATALOG_FIELD = "laterReleaseField";
85
+ const sha256 = async (value) => {
86
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(value));
87
+ return `sha256:${[...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("")}`;
88
+ };
89
+ const canonical = (value) => {
90
+ if (value === null || typeof value !== "object") return JSON.stringify(value);
91
+ if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
92
+ const record = value;
93
+ return `{${Object.keys(record).sort().map((key) => `${JSON.stringify(key)}:${canonical(record[key])}`).join(",")}}`;
94
+ };
95
+ /**
96
+ * Rewrites a scope's stored catalog as a later release would compile it: a
97
+ * field this release does not know on each release descriptor, with the
98
+ * payload's hash and size to match. Returns the payload it wrote.
99
+ */
100
+ const writeCatalogFromLaterRelease = async (core, scopeKey) => core.transaction(async (tx) => {
101
+ const row = await tx.findOne("release_catalogs", { scope_key: scopeKey });
102
+ if (row === null) throw new Error(`No catalog for ${scopeKey}.`);
103
+ const parsed = JSON.parse(row.payload);
104
+ const payload = canonical({
105
+ ...parsed,
106
+ releaseDescriptors: parsed.releaseDescriptors.map((descriptor) => ({
107
+ ...descriptor,
108
+ [LATER_RELEASE_CATALOG_FIELD]: `for ${String(descriptor.releaseId)}`
109
+ }))
110
+ });
111
+ tx.update("release_catalogs", row, {
112
+ payload,
113
+ catalog_hash: await sha256(payload),
114
+ byte_size: new TextEncoder().encode(payload).byteLength
115
+ });
116
+ return payload;
117
+ });
118
+ //#endregion
82
119
  //#region src/databaseTestFixtures.ts
83
120
  const fixtureId$1 = (suffix) => `00000000-0000-7000-8000-${suffix.padStart(12, "0")}`;
84
121
  const channelFixtureSuffix = (name) => {
@@ -128,7 +165,8 @@ const createReleaseRowFixture = (suffix, bundle, channel) => ({
128
165
  source_release_id: null,
129
166
  revision: 1,
130
167
  created_at_ms: Number(suffix),
131
- updated_at_ms: Number(suffix)
168
+ updated_at_ms: Number(suffix),
169
+ label: null
132
170
  });
133
171
  const createBundleFixture = (suffix, _channel = "production") => ({
134
172
  id: fixtureId$1(suffix),
@@ -238,9 +276,9 @@ const setupBundleMethodsTestSuite = (options) => {
238
276
  /**
239
277
  * Core's operations through admin API protocol 2 that the bundle and catalog
240
278
  * suites leave out: channels, deploy refusals, promotion, preflights, a
241
- * bundle's patch children, and the native build registry. Each test deletes
242
- * what it wrote, except a native build, which the registry keeps: its IDs
243
- * and channel are the test's own.
279
+ * bundle's patch children, the native build registry, and the iOS device
280
+ * registry. Each test deletes what it wrote, except a native build, which the
281
+ * registry keeps: its IDs and channel are the test's own.
244
282
  */
245
283
  const setupCoreAdminTestSuite = (options) => {
246
284
  describe("Core admin API", () => {
@@ -290,6 +328,72 @@ const setupCoreAdminTestSuite = (options) => {
290
328
  expect(missing.status).toBe(404);
291
329
  await missing.text();
292
330
  });
331
+ it("reads channels by ID and pages them by name", async () => {
332
+ const [a, b, c] = await Promise.all([
333
+ "a",
334
+ "b",
335
+ "c"
336
+ ].map((suffix) => api.ensureChannel(`page-${namespace}-${suffix}`)));
337
+ expect((await adminJson(`/channels?ids=${c.id},${a.id},${namespace}`)).data).toEqual([c, a]);
338
+ const first = await adminJson(`/channels?limit=2&cursor=${encodeURIComponent(`page-${namespace}-`)}`);
339
+ expect(first).toEqual({
340
+ data: [a, b],
341
+ next: b.name
342
+ });
343
+ const second = await adminJson(`/channels?limit=2&cursor=${encodeURIComponent(first.next)}`);
344
+ expect(second.data[0]).toEqual(c);
345
+ for (const channel of [
346
+ a,
347
+ b,
348
+ c
349
+ ]) {
350
+ const deleted = await admin(`/channels/${channel.id}`, jsonRequest("DELETE"));
351
+ expect(deleted.status).toBe(204);
352
+ await deleted.text();
353
+ }
354
+ });
355
+ it("lists every scope that has releases by keyset pages", async () => {
356
+ const deployed = [
357
+ await api.deploy({
358
+ bundle: toDeployBundle(bundleRow("21")),
359
+ release: policy("scopes-a")
360
+ }),
361
+ await api.deploy({
362
+ bundle: toDeployBundle(bundleRow("22")),
363
+ release: policy("scopes-a")
364
+ }),
365
+ await api.deploy({
366
+ bundle: toDeployBundle(bundleRow("23")),
367
+ release: policy("scopes-b")
368
+ })
369
+ ];
370
+ const scopeKeys = [];
371
+ for (let cursor;;) {
372
+ const page = await adminJson(`/release-scopes?limit=2${cursor === void 0 ? "" : `&cursor=${encodeURIComponent(cursor)}`}`);
373
+ scopeKeys.push(...page.data);
374
+ if (page.next === void 0) break;
375
+ expect(page.next).toBe(page.data.at(-1));
376
+ cursor = page.next;
377
+ }
378
+ expect(scopeKeys).toEqual([...new Set(scopeKeys)].sort());
379
+ expect(scopeKeys).toEqual(expect.arrayContaining([...new Set(deployed.map(({ scope_key }) => scope_key))]));
380
+ const refusals = await Promise.all(["/release-scopes?limit=101", "/release-scopes?order=desc"].map(async (path) => (await admin(path)).status));
381
+ expect(refusals).toEqual([400, 400]);
382
+ });
383
+ it("takes at most 100 IDs a request", async () => {
384
+ const ids = Array.from({ length: 101 }, () => crypto.randomUUID());
385
+ const refusals = [[await admin(`/channels?ids=${ids.join(",")}`), "Channels by ID take ids=<channel id>,... with 1 to 100 ids."], [await admin("/ios-devices/in-build", jsonRequest("POST", {
386
+ buildId: crypto.randomUUID(),
387
+ ids
388
+ })), "Marking iOS devices in a build takes at most 100 ids a request."]];
389
+ expect(await Promise.all(refusals.map(async ([response]) => ({
390
+ status: response.status,
391
+ body: await response.json().catch(() => null)
392
+ })))).toEqual(refusals.map(([, error]) => ({
393
+ status: 400,
394
+ body: expect.objectContaining({ error })
395
+ })));
396
+ });
293
397
  it("keeps a release's channel when a delete races the deploy into it", async () => {
294
398
  const channel = await api.ensureChannel(`race-${namespace}`);
295
399
  const [deleted, release] = await Promise.all([admin(`/channels/${channel.id}`, jsonRequest("DELETE")), api.deploy({
@@ -434,6 +538,36 @@ const setupCoreAdminTestSuite = (options) => {
434
538
  destination: "testflight",
435
539
  version: "1.0.0 (7)"
436
540
  }))).data).toBeNull();
541
+ const androidBuiltIn = bundleRow("64");
542
+ const androidResponse = await admin("/native-builds", jsonRequest("POST", {
543
+ id: bundleRow("864").id,
544
+ platform: "android",
545
+ channel,
546
+ fingerprintHash: "android-fingerprint",
547
+ appVersion: null,
548
+ minBundleId: androidBuiltIn.id,
549
+ gitCommitHash: null,
550
+ buildKey: null,
551
+ buildNumber: "64",
552
+ artifact: {
553
+ kind: "aab",
554
+ storageUri: "storage://native-builds/android/64/app.aab",
555
+ byteSize: 1e3
556
+ },
557
+ embeddedBundle: {
558
+ manifestStorageUri: androidBuiltIn.manifest_storage_uri,
559
+ manifestFileHash: androidBuiltIn.manifest_file_hash,
560
+ assetBaseStorageUri: androidBuiltIn.asset_base_storage_uri
561
+ }
562
+ }));
563
+ expect(androidResponse.status).toBe(201);
564
+ await androidResponse.text();
565
+ const production = await admin(`/native-builds/${bundleRow("864").id}/submission`, jsonRequest("POST", {
566
+ destination: "play-production",
567
+ version: "1.0.0 (64)"
568
+ }));
569
+ expect(production.status).toBe(200);
570
+ expect((await production.json()).data.submitted_to).toBe("play-production");
437
571
  const wrongStore = await admin(`/native-builds/${newest.id}/submission`, jsonRequest("POST", {
438
572
  destination: "play-internal",
439
573
  version: "1.0.0 (7)"
@@ -455,6 +589,393 @@ const setupCoreAdminTestSuite = (options) => {
455
589
  const after = await adminJson("/bundles?limit=1&total=true");
456
590
  expect(after.total).toBe(before.total);
457
591
  });
592
+ it("marks one store build per native build scope, replacing and clearing it", async () => {
593
+ const channel = `store-build-${namespace}`;
594
+ const register = async (suffix, fingerprintHash) => {
595
+ const builtIn = bundleRow(suffix);
596
+ const response = await admin("/native-builds", jsonRequest("POST", {
597
+ id: bundleRow(`8${suffix}`).id,
598
+ platform: "ios",
599
+ channel,
600
+ fingerprintHash,
601
+ appVersion: null,
602
+ minBundleId: builtIn.id,
603
+ gitCommitHash: null,
604
+ buildKey: null,
605
+ buildNumber: suffix,
606
+ artifact: {
607
+ kind: "ipa",
608
+ storageUri: `storage://native-builds/ios/${suffix}/App.ipa`,
609
+ byteSize: 1e3
610
+ },
611
+ embeddedBundle: {
612
+ manifestStorageUri: builtIn.manifest_storage_uri,
613
+ manifestFileHash: builtIn.manifest_file_hash,
614
+ assetBaseStorageUri: builtIn.asset_base_storage_uri
615
+ }
616
+ }));
617
+ expect(response.status).toBe(201);
618
+ return (await response.json()).data;
619
+ };
620
+ const mark = (id, storeBuild) => admin(`/native-builds/${id}/store-build`, jsonRequest("POST", { storeBuild }));
621
+ const markRead = (fingerprintHash) => `/native-builds/latest?platform=ios&channel=${encodeURIComponent(channel)}&fingerprintHash=${fingerprintHash}&storeBuild=true`;
622
+ const older = await register("64", "store-fingerprint");
623
+ const newer = await register("65", "store-fingerprint");
624
+ const otherScope = await register("66", "store-fingerprint-b");
625
+ expect(older.is_store_build).toBe(false);
626
+ expect((await adminJson(markRead("store-fingerprint"))).data).toBeNull();
627
+ const marked = await mark(older.id, true);
628
+ expect(marked.status).toBe(200);
629
+ expect(await marked.json()).toMatchObject({ data: {
630
+ nativeBuild: {
631
+ id: older.id,
632
+ is_store_build: true
633
+ },
634
+ previous: null
635
+ } });
636
+ expect((await adminJson(markRead("store-fingerprint"))).data).toEqual({
637
+ ...older,
638
+ is_store_build: true
639
+ });
640
+ expect((await adminJson(`/native-builds/latest?platform=ios&channel=${encodeURIComponent(channel)}&fingerprintHash=store-fingerprint`)).data).toEqual(newer);
641
+ expect((await adminJson(markRead("store-fingerprint-b"))).data).toBeNull();
642
+ const replaced = await mark(newer.id, true);
643
+ expect(await replaced.json()).toMatchObject({ data: {
644
+ nativeBuild: {
645
+ id: newer.id,
646
+ is_store_build: true
647
+ },
648
+ previous: {
649
+ id: older.id,
650
+ is_store_build: false
651
+ }
652
+ } });
653
+ expect((await adminJson(`/native-builds/${older.id}`)).data).toEqual(older);
654
+ expect((await adminJson(markRead("store-fingerprint"))).data).toEqual({
655
+ ...newer,
656
+ is_store_build: true
657
+ });
658
+ const race = async (ids) => {
659
+ const responses = await Promise.all(ids.map((id) => mark(id, true)));
660
+ expect(responses.map(({ status }) => status)).toEqual(ids.map(() => 200));
661
+ const results = await Promise.all(responses.map((response) => response.json()));
662
+ expect(results.map(({ data }) => data.nativeBuild.is_store_build)).toEqual(ids.map(() => true));
663
+ const holders = (await Promise.all([older, newer].map(async ({ id }) => (await adminJson(`/native-builds/${id}`)).data))).filter(({ is_store_build }) => is_store_build);
664
+ expect(holders).toHaveLength(1);
665
+ expect(ids).toContain(holders[0].id);
666
+ };
667
+ await race([
668
+ older.id,
669
+ newer.id,
670
+ older.id
671
+ ]);
672
+ await mark(older.id, false).then((response) => response.text());
673
+ await mark(newer.id, false).then((response) => response.text());
674
+ expect((await adminJson(markRead("store-fingerprint"))).data).toBeNull();
675
+ await race([older.id, newer.id]);
676
+ await (await mark(newer.id, false)).text();
677
+ await mark(older.id, false).then((response) => response.text());
678
+ expect((await adminJson(markRead("store-fingerprint"))).data).toBeNull();
679
+ expect(await (await mark(bundleRow("869").id, true)).json()).toMatchObject({ data: null });
680
+ const refused = await admin(`/native-builds/${older.id}/store-build`, jsonRequest("POST", {}));
681
+ expect(refused.status).toBe(400);
682
+ await refused.text();
683
+ await mark(otherScope.id, true).then((response) => response.text());
684
+ await adminJson(`/native-builds/${otherScope.id}`, jsonRequest("DELETE"));
685
+ expect((await adminJson(markRead("store-fingerprint-b"))).data).toBeNull();
686
+ });
687
+ it("records a sandbox build on any channel, finds it through its sandbox scope, and refuses one its artifact doesn't describe", async () => {
688
+ const sandboxChannel = `pr-${namespace}`;
689
+ const channel = `plain-${namespace}`;
690
+ const sandboxFields = {
691
+ isSandbox: true,
692
+ sandboxUrlScheme: "acme-preview",
693
+ sandboxAppId: "com.example.app",
694
+ exportMethod: "ad-hoc"
695
+ };
696
+ const post = (suffix, body) => {
697
+ const builtIn = bundleRow(suffix);
698
+ return admin("/native-builds", jsonRequest("POST", {
699
+ id: bundleRow(`8${suffix}`).id,
700
+ platform: "ios",
701
+ fingerprintHash: "sandbox-fingerprint",
702
+ appVersion: null,
703
+ minBundleId: builtIn.id,
704
+ gitCommitHash: null,
705
+ buildKey: null,
706
+ artifact: {
707
+ kind: "ipa",
708
+ storageUri: `storage://native-builds/ios/${suffix}/App.ipa`,
709
+ byteSize: 1e3
710
+ },
711
+ embeddedBundle: {
712
+ manifestStorageUri: builtIn.manifest_storage_uri,
713
+ manifestFileHash: builtIn.manifest_file_hash,
714
+ assetBaseStorageUri: builtIn.asset_base_storage_uri
715
+ },
716
+ ...body
717
+ }));
718
+ };
719
+ const refusal = async (suffix, body) => {
720
+ const response = await post(suffix, body);
721
+ await response.text();
722
+ return response.status;
723
+ };
724
+ expect(await refusal("74", {
725
+ channel,
726
+ isSandbox: true
727
+ })).toBe(400);
728
+ expect(await refusal("74", {
729
+ channel,
730
+ ...sandboxFields,
731
+ sandboxAppId: void 0
732
+ })).toBe(400);
733
+ expect(await refusal("74", {
734
+ channel,
735
+ sandboxAppId: "com.example.app"
736
+ })).toBe(400);
737
+ expect(await refusal("74", {
738
+ channel: sandboxChannel,
739
+ isSandbox: null
740
+ })).toBe(400);
741
+ expect(await refusal("74", {
742
+ channel: sandboxChannel,
743
+ isSandbox: "yes"
744
+ })).toBe(400);
745
+ expect(await refusal("74", {
746
+ channel,
747
+ sandboxUrlScheme: "acme-preview"
748
+ })).toBe(400);
749
+ expect(await refusal("74", {
750
+ channel: sandboxChannel,
751
+ ...sandboxFields,
752
+ sandboxUrlScheme: "Acme"
753
+ })).toBe(400);
754
+ expect(await refusal("74", {
755
+ channel: sandboxChannel,
756
+ ...sandboxFields,
757
+ sandboxUrlScheme: 42
758
+ })).toBe(400);
759
+ expect(await refusal("74", {
760
+ channel,
761
+ nativeAppVersion: 42
762
+ })).toBe(400);
763
+ expect(await refusal("74", {
764
+ channel,
765
+ nativeAppVersion: " "
766
+ })).toBe(400);
767
+ const tagged = await post("72", {
768
+ channel: sandboxChannel,
769
+ ...sandboxFields,
770
+ nativeAppVersion: "1.6.0"
771
+ });
772
+ expect(tagged.status).toBe(201);
773
+ const sandboxBuild = (await tagged.json()).data;
774
+ const plain = await post("73", {
775
+ channel: sandboxChannel,
776
+ isSandbox: false
777
+ });
778
+ expect(plain.status).toBe(201);
779
+ const plainBuild = (await plain.json()).data;
780
+ expect(sandboxBuild).toMatchObject({
781
+ is_sandbox: true,
782
+ is_store_build: false,
783
+ sandbox_url_scheme: "acme-preview",
784
+ native_app_version: "1.6.0"
785
+ });
786
+ expect(plainBuild).toMatchObject({
787
+ is_sandbox: false,
788
+ is_store_build: false,
789
+ sandbox_url_scheme: null,
790
+ export_method: null,
791
+ native_app_version: null
792
+ });
793
+ const sandboxLookup = "sandboxAppId=com.example.app&sandboxUrlScheme=acme-preview&artifactKind=ipa&distribution=direct";
794
+ expect((await adminJson(`/native-builds/${sandboxBuild.id}`)).data).toEqual(sandboxBuild);
795
+ expect((await adminJson(`/native-builds/${plainBuild.id}`)).data).toEqual(plainBuild);
796
+ expect((await adminJson(`/native-builds/latest?platform=ios&channel=other-${namespace}&fingerprintHash=sandbox-fingerprint&${sandboxLookup}`)).data).toEqual(sandboxBuild);
797
+ expect((await adminJson(`/native-builds/latest?platform=ios&channel=${encodeURIComponent(sandboxChannel)}&fingerprintHash=sandbox-fingerprint`)).data).toEqual(plainBuild);
798
+ const partial = await admin(`/native-builds/latest?platform=ios&channel=${encodeURIComponent(sandboxChannel)}&fingerprintHash=sandbox-fingerprint&sandboxAppId=com.example.app`);
799
+ expect(partial.status).toBe(400);
800
+ await partial.text();
801
+ const invalid = await admin(`/native-builds/latest?platform=ios&channel=${encodeURIComponent(sandboxChannel)}&fingerprintHash=sandbox-fingerprint&${sandboxLookup.replace("artifactKind=ipa", "artifactKind=apk")}`);
802
+ expect(invalid.status).toBe(400);
803
+ await invalid.text();
804
+ expect((await adminJson(`/native-builds/latest?platform=ios&channel=${encodeURIComponent(sandboxChannel)}&fingerprintHash=sandbox-fingerprint&${sandboxLookup}&builtInOlderThan=ffffffff-ffff-7fff-bfff-ffffffffffff`)).data).toBeNull();
805
+ const patched = await admin(`/bundles/${plainBuild.min_bundle_id}`, jsonRequest("PATCH", { patches: [{
806
+ baseBundleId: sandboxBuild.min_bundle_id,
807
+ baseFileHash: "base-hash",
808
+ byteSize: 42,
809
+ patchFileHash: "patch-hash",
810
+ patchStorageUri: "storage://patches/sandbox.patch"
811
+ }] }));
812
+ expect(patched.status).toBe(400);
813
+ expect(await patched.text()).toContain("A sandbox build's built-in bundle is no patch base.");
814
+ const deployed = await admin("/releases", jsonRequest("POST", { deployments: [{
815
+ bundle: {
816
+ ...toDeployBundle(bundleRow("76")),
817
+ patches: [{
818
+ baseBundleId: sandboxBuild.min_bundle_id,
819
+ baseFileHash: "base-hash",
820
+ byteSize: 42,
821
+ patchFileHash: "patch-hash",
822
+ patchStorageUri: "storage://patches/sandbox-deploy.patch"
823
+ }]
824
+ },
825
+ release: policy("sandbox-patch")
826
+ }] }));
827
+ expect(deployed.status).toBe(400);
828
+ expect(await deployed.text()).toContain("A sandbox build's built-in bundle is no patch base.");
829
+ const notDeployed = await admin(`/bundles/${bundleRow("76").id}`);
830
+ expect(notDeployed.status).toBe(404);
831
+ await notDeployed.text();
832
+ const marked = await admin(`/native-builds/${sandboxBuild.id}/store-build`, jsonRequest("POST", { storeBuild: true }));
833
+ expect(marked.status).toBe(400);
834
+ await marked.text();
835
+ });
836
+ it("finds a scope's build of one kind, and a sandbox build's other install target", async () => {
837
+ const channel = `kinds-${namespace}`;
838
+ const register = async (suffix, kind, body = {}) => {
839
+ const builtIn = bundleRow(suffix);
840
+ const response = await admin("/native-builds", jsonRequest("POST", {
841
+ id: bundleRow(`8${suffix}`).id,
842
+ platform: "ios",
843
+ channel,
844
+ fingerprintHash: "kind-fingerprint",
845
+ appVersion: null,
846
+ minBundleId: builtIn.id,
847
+ gitCommitHash: null,
848
+ buildKey: null,
849
+ artifact: {
850
+ kind,
851
+ storageUri: `storage://native-builds/ios/${suffix}/App.${kind === "ipa" ? "ipa" : "app.zip"}`,
852
+ byteSize: 1e3
853
+ },
854
+ embeddedBundle: {
855
+ manifestStorageUri: builtIn.manifest_storage_uri,
856
+ manifestFileHash: builtIn.manifest_file_hash,
857
+ assetBaseStorageUri: builtIn.asset_base_storage_uri
858
+ },
859
+ ...body
860
+ }));
861
+ expect(response.status).toBe(201);
862
+ return (await response.json()).data;
863
+ };
864
+ const sandbox = (exportMethod) => ({
865
+ isSandbox: true,
866
+ sandboxUrlScheme: "acme-preview",
867
+ sandboxAppId: "com.example.app",
868
+ exportMethod
869
+ });
870
+ const ipa = await register("81", "ipa");
871
+ const app = await register("82", "app");
872
+ const latest = `/native-builds/latest?platform=ios&channel=${encodeURIComponent(channel)}&fingerprintHash=kind-fingerprint`;
873
+ expect((await adminJson(latest)).data).toEqual(app);
874
+ expect((await adminJson(`${latest}&kind=ipa`)).data).toEqual(ipa);
875
+ const refused = await admin(`${latest}&kind=apk`);
876
+ expect(refused.status).toBe(400);
877
+ await refused.text();
878
+ const sandboxIpa = await register("83", "ipa", sandbox("ad-hoc"));
879
+ const sandboxApp = await register("84", "app", sandbox(null));
880
+ expect((await adminJson(`/native-builds/${sandboxIpa.id}/sibling`)).data).toEqual(sandboxApp);
881
+ expect((await adminJson(`/native-builds/${sandboxApp.id}/sibling`)).data).toEqual(sandboxIpa);
882
+ expect((await adminJson(`/native-builds/${ipa.id}/sibling`)).data).toBeNull();
883
+ expect((await adminJson(`/native-builds/${bundleRow("899").id}/sibling`)).data).toBeNull();
884
+ expect((await adminJson(`/native-builds/built-in/${ipa.min_bundle_id}`)).data).toEqual(ipa);
885
+ expect((await adminJson(`/native-builds/built-in/${bundleRow("899").id}`)).data).toBeNull();
886
+ });
887
+ it("requests, approves, renames, records, and removes iOS devices", async () => {
888
+ const udid = namespace.replaceAll("-", "").padEnd(40, "0");
889
+ const device = async (path, init) => (await adminJson(path, init)).data;
890
+ const requested = await adminJson("/ios-devices", jsonRequest("POST", {
891
+ udid: udid.toUpperCase(),
892
+ name: "Kim's iPhone",
893
+ requestedBy: "kim@team.dev"
894
+ }));
895
+ expect(requested.data.created).toBe(true);
896
+ const { id } = requested.data.device;
897
+ expect(requested.data.device).toMatchObject({
898
+ udid,
899
+ status: "pending",
900
+ requested_by: "kim@team.dev"
901
+ });
902
+ try {
903
+ const again = await adminJson("/ios-devices", jsonRequest("POST", {
904
+ udid,
905
+ name: "Other",
906
+ requestedBy: null
907
+ }));
908
+ expect(again.data).toEqual({
909
+ device: requested.data.device,
910
+ created: false
911
+ });
912
+ const raced = `${udid.slice(0, 39)}f`;
913
+ const racing = await Promise.all(["Other", "Another"].map((name) => adminJson("/ios-devices", jsonRequest("POST", {
914
+ udid: raced,
915
+ name,
916
+ requestedBy: null
917
+ }))));
918
+ expect(racing.map(({ data }) => data.created).sort()).toEqual([false, true]);
919
+ expect(racing[0].data.device.id).toBe(racing[1].data.device.id);
920
+ await adminJson(`/ios-devices/${racing[0].data.device.id}`, jsonRequest("DELETE"));
921
+ expect(await device(`/ios-devices/udid/${udid}`)).toEqual(requested.data.device);
922
+ const pending = await adminJson("/ios-devices?status=pending&limit=500");
923
+ expect(pending.data.map((row) => row.id)).toContain(id);
924
+ const approval = await device(`/ios-devices/${id}/approval`, jsonRequest("POST", { approvedBy: "lead@team.dev" }));
925
+ expect(approval).toMatchObject({
926
+ status: "approved",
927
+ approved_by: "lead@team.dev"
928
+ });
929
+ expect(await device(`/ios-devices/${id}`, jsonRequest("PATCH", { name: "Kim's work iPhone" }))).toMatchObject({
930
+ name: "Kim's work iPhone",
931
+ status: "approved"
932
+ });
933
+ const registered = await device(`/ios-devices/${id}/outcome`, jsonRequest("POST", {
934
+ seen: {
935
+ status: "approved",
936
+ approvedAtMs: approval.approved_at_ms
937
+ },
938
+ issuerId: "issuer-a",
939
+ outcome: "registered"
940
+ }));
941
+ expect(registered).toMatchObject({
942
+ status: "registered",
943
+ apple_issuer_id: "issuer-a"
944
+ });
945
+ expect(await device(`/ios-devices/${id}/outcome`, jsonRequest("POST", {
946
+ seen: {
947
+ status: "approved",
948
+ approvedAtMs: 1
949
+ },
950
+ issuerId: "issuer-a",
951
+ outcome: "missing"
952
+ }))).toBeNull();
953
+ const claims = await Promise.all(["issuer-a", "issuer-b"].map((issuerId) => adminJson("/ios-devices/account", jsonRequest("POST", { issuerId }))));
954
+ const owner = claims.find(({ data }) => data.claimed)?.data.issuerId;
955
+ expect(claims.filter(({ data }) => data.claimed)).toHaveLength(1);
956
+ expect(claims.map(({ data }) => data.issuerId)).toEqual([owner, owner]);
957
+ expect(await adminJson("/ios-devices/account")).toEqual({ data: { issuerId: owner } });
958
+ const buildId = bundleRow("90").id;
959
+ const marked = await admin("/ios-devices/in-build", jsonRequest("POST", {
960
+ buildId,
961
+ ids: [id]
962
+ }));
963
+ expect(marked.status).toBe(204);
964
+ expect((await device(`/ios-devices/udid/${udid}`))?.build_id).toBe(buildId);
965
+ const refused = await admin("/ios-devices", jsonRequest("POST", {
966
+ udid: "1234",
967
+ name: "x",
968
+ requestedBy: null
969
+ }));
970
+ expect(refused.status).toBe(400);
971
+ await refused.text();
972
+ } finally {
973
+ await adminJson(`/ios-devices/${id}`, jsonRequest("DELETE"));
974
+ }
975
+ expect(await device(`/ios-devices/udid/${udid}`)).toBeNull();
976
+ expect(await device(`/ios-devices/${id}`, jsonRequest("DELETE"))).toBeNull();
977
+ expect((await adminJson("/ios-devices/account")).data).toMatchObject({ issuerId: expect.any(String) });
978
+ });
458
979
  it("lists the patches that start from a bundle", async () => {
459
980
  const base = bundleRow("50");
460
981
  const target = bundleRow("51");
@@ -486,6 +1007,384 @@ const setupCoreAdminTestSuite = (options) => {
486
1007
  });
487
1008
  };
488
1009
  //#endregion
1010
+ //#region src/createMeasuredDatabase.ts
1011
+ const storageOf = (storage) => ({
1012
+ name: "measuredStorage",
1013
+ protocol: "storage",
1014
+ get: async ({ storageUri }) => {
1015
+ const text = await storage.readStorageText?.(storageUri) ?? null;
1016
+ return { response: text === null ? null : new Response(text) };
1017
+ },
1018
+ getDownloadUrl: async ({ storageUri }) => ({ url: await storage.resolveFileUrl(storageUri) })
1019
+ });
1020
+ /**
1021
+ * Core and the plugins over `adapter` as `createHotUpdater` runs them: what
1022
+ * read-budget suites measure. The database is `meterReads` over
1023
+ * `verifyAdapter(adapter)`, so every adapter call is checked against the
1024
+ * contract and `measureReads` reports each call's reads; the adapter runs
1025
+ * as given, without the schema fence. It loads `@hot-updater/server`, an
1026
+ * optional peer, when called.
1027
+ */
1028
+ const createMeasuredDatabase = async (adapter, plugins, options = {}) => {
1029
+ const { createHotUpdater } = await import("@hot-updater/server");
1030
+ let clientAuth;
1031
+ const observed = plugins.map((plugin) => Object.defineProperties({}, {
1032
+ ...Object.getOwnPropertyDescriptors(plugin),
1033
+ init: {
1034
+ configurable: true,
1035
+ enumerable: true,
1036
+ writable: true,
1037
+ value: (context) => {
1038
+ const instance = plugin.init(options.now === void 0 ? context : {
1039
+ ...context,
1040
+ now: options.now
1041
+ });
1042
+ if (instance.clientAuth !== void 0) clientAuth = instance.clientAuth;
1043
+ return instance;
1044
+ }
1045
+ }
1046
+ }));
1047
+ const database = meterReads({
1048
+ name: "measured",
1049
+ adapter: verifyAdapter(adapter)
1050
+ });
1051
+ const hotUpdater = createHotUpdater({
1052
+ database,
1053
+ storage: options.storage === void 0 ? {
1054
+ name: "measuredStorage",
1055
+ protocol: "none"
1056
+ } : storageOf(options.storage),
1057
+ plugins: observed,
1058
+ ...plugins.some((plugin) => plugin.provides?.clientAuth === true) ? {} : { clientAccess: "public" }
1059
+ });
1060
+ return {
1061
+ core: hotUpdater.core,
1062
+ api: hotUpdater.api,
1063
+ ...clientAuth === void 0 ? {} : { clientAuth },
1064
+ measureReads: database.measureReads
1065
+ };
1066
+ };
1067
+ //#endregion
1068
+ //#region src/setupReleaseLabelEngineTestSuite.ts
1069
+ const NATIVE_PAGE_SIZE$1 = 2;
1070
+ /**
1071
+ * Release labels on a backend's own rows, which no HTTP API writes: the
1072
+ * releases a server of an earlier release left without labels and without
1073
+ * counters, which the fill labels per channel and platform in ID order,
1074
+ * concurrent fills and a deploy included, rebuilding the catalogs compiled
1075
+ * without them; and the label index, which refuses a second row with a label
1076
+ * and holds any number without one. Rows are written as an earlier server
1077
+ * wrote them through a second engine on the same adapter. It also writes a
1078
+ * catalog as a later release compiles it, with a field this one does not
1079
+ * know, which core verifies, never rewrites, and refuses to change. Register
1080
+ * it beside `setupReadBudgetTestSuite`, with the same options.
1081
+ */
1082
+ const setupReleaseLabelEngineTestSuite = (options) => {
1083
+ describe(`${options.name} release labels`, () => {
1084
+ let created;
1085
+ let core;
1086
+ let raw;
1087
+ beforeAll(async () => {
1088
+ created = await options.createAdapter({
1089
+ tables: [...toolingTargetOf([]).schema.tables, SETTINGS_TABLE],
1090
+ nativePageSize: NATIVE_PAGE_SIZE$1
1091
+ });
1092
+ ({core} = await createMeasuredDatabase(created.adapter, []));
1093
+ raw = createEngine({
1094
+ name: "raw",
1095
+ adapter: created.adapter
1096
+ }).core;
1097
+ }, 18e4);
1098
+ afterAll(async () => {
1099
+ await created?.cleanup?.();
1100
+ }, 6e4);
1101
+ let suffix = 0;
1102
+ let namespace = 0;
1103
+ const channel = (name) => `${name}-${namespace}`;
1104
+ const deploy = async (name, { platform = "ios", fingerprintHash = null } = {}) => {
1105
+ suffix += 1;
1106
+ const deployment = {
1107
+ bundle: {
1108
+ ...createBundleFixture(String(9e3 + suffix)),
1109
+ platform
1110
+ },
1111
+ release: {
1112
+ channel: channel(name),
1113
+ enabled: true,
1114
+ fingerprintHash,
1115
+ message: null,
1116
+ shouldForceUpdate: false,
1117
+ targetAppVersion: fingerprintHash === null ? "1.0.x" : null
1118
+ }
1119
+ };
1120
+ const [result] = await core.deploy([deployment]);
1121
+ return result.release;
1122
+ };
1123
+ /** Takes the labels off `releases` and drops their pairs' counters, as an earlier server left them. */
1124
+ const asBeforeLabels = async (releases) => {
1125
+ await raw.transaction(async (tx) => {
1126
+ const counters = /* @__PURE__ */ new Set();
1127
+ for (const { id } of releases) {
1128
+ const row = await tx.findOne("releases", { id });
1129
+ tx.update("releases", row, { label: null });
1130
+ counters.add(`releases/${row.platform}/${row.channel_id}`);
1131
+ }
1132
+ for (const id of counters) {
1133
+ const counter = await tx.findOne("label_sequences", { id });
1134
+ if (counter !== null) await tx.delete("label_sequences", counter);
1135
+ }
1136
+ });
1137
+ };
1138
+ const labelOf = async (id) => (await core.getRelease(id))?.label;
1139
+ it("labels releases an earlier server wrote in ID order per channel and platform, rebuilds their catalogs, and a deploy then takes the next", async () => {
1140
+ namespace += 1;
1141
+ const releases = [
1142
+ await deploy("fill"),
1143
+ await deploy("fill", { fingerprintHash: "fp-a" }),
1144
+ await deploy("fill"),
1145
+ await deploy("fill", { platform: "android" }),
1146
+ await deploy("fill", { fingerprintHash: "fp-b" })
1147
+ ];
1148
+ await asBeforeLabels(releases);
1149
+ for (const scope of new Set(releases.map((row) => row.scope_key))) await core.rebuildReleaseCatalog(scope);
1150
+ await expect(core.fillReleaseLabels({ dryRun: true })).resolves.toEqual({
1151
+ releases: 5,
1152
+ catalogs: 0
1153
+ });
1154
+ await expect(core.fillReleaseLabels()).resolves.toEqual({
1155
+ releases: 5,
1156
+ catalogs: 4
1157
+ });
1158
+ const inIdOrder = (rows) => rows.map(({ id }) => id).sort();
1159
+ const ios = inIdOrder(releases.filter(({ platform }) => platform === "ios"));
1160
+ const labels = {};
1161
+ for (const { id } of releases) labels[id] = await labelOf(id);
1162
+ expect(labels).toEqual({
1163
+ ...Object.fromEntries(ios.map((id, index) => [id, index + 1])),
1164
+ [releases[3].id]: 1
1165
+ });
1166
+ const served = JSON.parse((await core.getReleaseCatalogRow(releases[0].scope_key)).payload).releaseDescriptors;
1167
+ expect(Object.fromEntries(served.map(({ releaseId, label }) => [releaseId, label]))).toEqual({
1168
+ [releases[0].id]: labels[releases[0].id],
1169
+ [releases[2].id]: labels[releases[2].id]
1170
+ });
1171
+ await expect(core.fillReleaseLabels({ dryRun: true })).resolves.toEqual({
1172
+ releases: 0,
1173
+ catalogs: 0
1174
+ });
1175
+ await expect(deploy("fill")).resolves.toMatchObject({ label: 5 });
1176
+ });
1177
+ it("verifies a catalog a later release compiled with a field this one doesn't know, and refuses to rewrite it without that field", async () => {
1178
+ namespace += 1;
1179
+ const first = await deploy("later");
1180
+ await deploy("later");
1181
+ const scopeKey = first.scope_key;
1182
+ const payload = await writeCatalogFromLaterRelease(raw, scopeKey);
1183
+ const counter = async () => (await raw.findOne("label_sequences", { id: `releases/ios/${first.channel_id}` })).last_label;
1184
+ const before = await counter();
1185
+ const stored = async () => await core.getReleaseCatalogRow(scopeKey);
1186
+ const generation = (await stored()).generation;
1187
+ await expect(core.preflightReleaseCatalogRebuild(scopeKey)).resolves.toMatchObject({
1188
+ changed: false,
1189
+ labelsOnly: false
1190
+ });
1191
+ await expect(core.rebuildReleaseCatalog(scopeKey)).resolves.toMatchObject({ changed: false });
1192
+ await expect(core.fillReleaseLabels()).resolves.toMatchObject({ catalogs: 0 });
1193
+ const refusal = {
1194
+ code: "CATALOG_FROM_LATER_RELEASE",
1195
+ message: "The ios release catalog of channel \"later-" + String(namespace) + "\" was written by a later Hot Updater.\nUpgrade hot-updater, then try again."
1196
+ };
1197
+ await expect(deploy("later")).rejects.toMatchObject(refusal);
1198
+ await expect(core.updateReleasePolicy({
1199
+ releaseId: first.id,
1200
+ patch: { message: "changed" }
1201
+ })).rejects.toMatchObject(refusal);
1202
+ await expect(core.preflightReleasePolicy({
1203
+ releaseId: first.id,
1204
+ patch: { message: "changed" }
1205
+ })).rejects.toMatchObject(refusal);
1206
+ expect(await stored()).toMatchObject({
1207
+ generation,
1208
+ payload
1209
+ });
1210
+ expect(payload).toContain(LATER_RELEASE_CATALOG_FIELD);
1211
+ expect(await counter()).toBe(before);
1212
+ await expect(core.listReleases({
1213
+ filter: {
1214
+ kind: "scope",
1215
+ scopeKey
1216
+ },
1217
+ limit: 10
1218
+ })).resolves.toHaveLength(2);
1219
+ expect((await core.getRelease(first.id))?.message).toBeNull();
1220
+ });
1221
+ it("labels each release once when fills run beside a deploy that needs one", async () => {
1222
+ namespace += 1;
1223
+ const releases = [];
1224
+ for (let index = 0; index < 5; index += 1) releases.push(await deploy("race"));
1225
+ await asBeforeLabels(releases);
1226
+ const [, , deployed] = await Promise.all([
1227
+ core.fillReleaseLabels(),
1228
+ core.fillReleaseLabels(),
1229
+ deploy("race")
1230
+ ]);
1231
+ const labels = {};
1232
+ for (const { id } of releases) labels[id] = await labelOf(id);
1233
+ expect(labels).toEqual(Object.fromEntries(releases.map(({ id }) => id).sort().map((id, index) => [id, index + 1])));
1234
+ expect(deployed.label).toBe(6);
1235
+ });
1236
+ it("refuses a second release with a label in its channel and platform, and holds any number without one", async () => {
1237
+ namespace += 1;
1238
+ const releases = [
1239
+ await deploy("unique"),
1240
+ await deploy("unique"),
1241
+ await deploy("unique")
1242
+ ];
1243
+ const set = (id, label) => raw.transaction(async (tx) => {
1244
+ const row = await tx.findOne("releases", { id });
1245
+ tx.update("releases", row, { label });
1246
+ });
1247
+ await set(releases[0].id, null);
1248
+ await set(releases[1].id, null);
1249
+ await expect(set(releases[2].id, 2)).resolves.toBeUndefined();
1250
+ await expect(set(releases[0].id, 2)).rejects.toBeInstanceOf(DatabaseConstraintError);
1251
+ const other = await deploy("unique-other");
1252
+ expect(other.label).toBe(1);
1253
+ await expect(set(other.id, 2)).resolves.toBeUndefined();
1254
+ await set(other.id, 1);
1255
+ await set(releases[2].id, 3);
1256
+ await set(releases[1].id, 2);
1257
+ await set(releases[0].id, 1);
1258
+ await expect(core.getReleaseByLabel({
1259
+ channel: channel("unique"),
1260
+ platform: "ios",
1261
+ label: 3
1262
+ })).resolves.toMatchObject({ id: releases[2].id });
1263
+ });
1264
+ });
1265
+ };
1266
+ //#endregion
1267
+ //#region src/setupReleaseLabelTestSuite.ts
1268
+ /**
1269
+ * Release labels through a provider's admin and client HTTP APIs: deploys
1270
+ * take each channel and platform's next label, concurrent ones never the
1271
+ * same, a promotion takes the target's next, a delete leaves a gap, the
1272
+ * list, detail and label lookup answer it, and the scope's catalog serves
1273
+ * it. The backfill and the label index's uniqueness, which need rows an
1274
+ * earlier server wrote, are `setupReleaseLabelEngineTestSuite`'s.
1275
+ */
1276
+ const setupReleaseLabelTestSuite = (options) => {
1277
+ describe("Release labels", () => {
1278
+ const api = createAdminApiTestClient(options.getClient);
1279
+ const { adminJson } = api;
1280
+ let namespace;
1281
+ beforeEach(() => {
1282
+ namespace = crypto.randomUUID();
1283
+ });
1284
+ afterEach(async () => {
1285
+ await api.cleanup();
1286
+ });
1287
+ const bundleRow = (suffix) => ({
1288
+ ...createBundleRowFixture(suffix),
1289
+ id: `${namespace.slice(0, 8)}-0000-7000-8000-${suffix.padStart(12, "0")}`
1290
+ });
1291
+ const channel = (name = "labels") => `${name}-${namespace}`;
1292
+ const deploy = (suffix, { fingerprintHash = null, platform = "ios", channelName = channel() } = {}) => api.deploy({
1293
+ bundle: {
1294
+ ...toDeployBundle(bundleRow(suffix)),
1295
+ platform
1296
+ },
1297
+ release: {
1298
+ channel: channelName,
1299
+ enabled: true,
1300
+ fingerprintHash,
1301
+ message: null,
1302
+ shouldForceUpdate: false,
1303
+ targetAppVersion: fingerprintHash === null ? "1.0.x" : null
1304
+ }
1305
+ });
1306
+ const byLabel = async (label, { platform = "ios", channelName = channel() } = {}) => (await adminJson(`/release-labels?channel=${encodeURIComponent(channelName)}&platform=${platform}&label=${label}`)).data;
1307
+ const detail = async (id) => (await adminJson(`/releases/${encodeURIComponent(id)}`)).data;
1308
+ it("labels each channel and platform's deploys in order, and answers the label in the list, the detail and the lookup", async () => {
1309
+ const first = await deploy("1");
1310
+ const second = await deploy("2");
1311
+ const android = await deploy("3", { platform: "android" });
1312
+ expect([
1313
+ first.label,
1314
+ second.label,
1315
+ android.label
1316
+ ]).toEqual([
1317
+ 1,
1318
+ 2,
1319
+ 1
1320
+ ]);
1321
+ const { data: listed } = await adminJson(`/releases?channelId=${encodeURIComponent(first.channel_id)}&platform=ios&limit=10`);
1322
+ expect(Object.fromEntries(listed.map(({ id, label }) => [id, label]))).toEqual({
1323
+ [first.id]: 1,
1324
+ [second.id]: 2
1325
+ });
1326
+ await expect(detail(second.id)).resolves.toMatchObject({ label: 2 });
1327
+ await expect(byLabel(2)).resolves.toMatchObject({
1328
+ id: second.id,
1329
+ label: 2
1330
+ });
1331
+ await expect(byLabel(1, { platform: "android" })).resolves.toMatchObject({ id: android.id });
1332
+ await expect(byLabel(3)).resolves.toBeNull();
1333
+ });
1334
+ it("never gives concurrent deploys one label", async () => {
1335
+ await deploy("10");
1336
+ const releases = await Promise.all([
1337
+ "11",
1338
+ "12",
1339
+ "13",
1340
+ "14"
1341
+ ].map((suffix) => deploy(suffix, { fingerprintHash: `fingerprint-${suffix}` })));
1342
+ expect(releases.map(({ label }) => label).sort()).toEqual([
1343
+ 2,
1344
+ 3,
1345
+ 4,
1346
+ 5
1347
+ ]);
1348
+ });
1349
+ it("keeps a label through disable and enable, leaves a gap on delete, and gives a promotion the target's next label", async () => {
1350
+ const first = await deploy("21");
1351
+ const second = await deploy("22");
1352
+ await adminJson(`/releases/${encodeURIComponent(first.id)}`, jsonRequest("PATCH", { patch: { enabled: false } }));
1353
+ await adminJson(`/releases/${encodeURIComponent(first.id)}`, jsonRequest("PATCH", { patch: { enabled: true } }));
1354
+ await expect(detail(first.id)).resolves.toMatchObject({ label: 1 });
1355
+ await api.removeRelease(second.id);
1356
+ api.forget(second.id);
1357
+ await expect(deploy("23")).resolves.toMatchObject({ label: 3 });
1358
+ await deploy("24", { channelName: channel("target") });
1359
+ const { data: promoted } = await adminJson(`/releases/${encodeURIComponent(first.id)}/promote`, jsonRequest("POST", {
1360
+ targetChannel: channel("target"),
1361
+ action: "copy"
1362
+ }));
1363
+ api.track(promoted.target.release.id);
1364
+ expect(promoted.target.release).toMatchObject({ label: 2 });
1365
+ await expect(detail(first.id)).resolves.toMatchObject({ label: 1 });
1366
+ });
1367
+ it("serves each release's label in its scope's catalog", async () => {
1368
+ const first = await deploy("31");
1369
+ const second = await deploy("32");
1370
+ const response = await options.getClient().client(`/release-catalogs/app-version/ios/${encodeChannelKey(channel())}/1.0.0`);
1371
+ expect(response.status).toBe(200);
1372
+ const catalog = await response.json();
1373
+ expect(Object.fromEntries(catalog.releases.map(({ releaseId, label }) => [releaseId, label]))).toEqual({
1374
+ [first.id]: 1,
1375
+ [second.id]: 2
1376
+ });
1377
+ });
1378
+ it("has nothing to fill on a database whose releases all have labels", async () => {
1379
+ await deploy("41");
1380
+ await expect(adminJson("/release-labels/fill", jsonRequest("POST", { dryRun: true }))).resolves.toEqual({ data: {
1381
+ releases: 0,
1382
+ catalogs: 0
1383
+ } });
1384
+ });
1385
+ });
1386
+ };
1387
+ //#endregion
489
1388
  //#region src/setupSemverSatisfiesTestSuite.ts
490
1389
  /**
491
1390
  *
@@ -781,11 +1680,11 @@ const createReleaseCatalogTestStorage = () => ({
781
1680
  //#endregion
782
1681
  //#region src/releaseCatalogLifecycleTests.ts
783
1682
  function setupReleaseCatalogLifecycleTests(options) {
784
- const device = (minimumReleaseId = NIL_UUID) => ({
785
- builtInBundleId: minimumReleaseId,
786
- currentBundleId: minimumReleaseId,
1683
+ const device = (minBundleId = NIL_UUID) => ({
1684
+ builtInBundleId: minBundleId,
1685
+ currentBundleId: minBundleId,
787
1686
  activeReleaseId: null,
788
- minimumReleaseId,
1687
+ minBundleId,
789
1688
  cohort: "1",
790
1689
  crashedBundleIds: []
791
1690
  });
@@ -1152,7 +2051,7 @@ const setupReleaseCatalogTestSuite = (options) => {
1152
2051
  expect((await request(otherPath)).status).toBe(404);
1153
2052
  });
1154
2053
  it("caches an unknown scope's 404 like a catalog", async () => {
1155
- const response = await request(catalogPath());
2054
+ const response = await request(catalogPath(scope("unknown")));
1156
2055
  expect(response.status).toBe(404);
1157
2056
  expect(response.headers.get("cache-control")).toBe("public, max-age=0, s-maxage=5");
1158
2057
  expect(response.headers.get("cdn-cache-control")).toBe("public, max-age=5, stale-while-revalidate=5, stale-if-error=0");
@@ -1491,6 +2390,7 @@ const setupDatabaseTestSuite = (options) => {
1491
2390
  setupCoreAdminTestSuite({ getClient });
1492
2391
  setupBundleMethodsTestSuite({ getClient });
1493
2392
  setupReleaseCatalogTestSuite({ getClient });
2393
+ setupReleaseLabelTestSuite({ getClient });
1494
2394
  for (const suite of options.plugins ?? []) describe(suite.name, () => {
1495
2395
  suite.register({
1496
2396
  getClient,
@@ -1554,6 +2454,15 @@ const conformanceItems = {
1554
2454
  type: "string",
1555
2455
  nullable: true
1556
2456
  },
2457
+ (
2458
+ /** A unique slot only some rows hold, as long as a scope key. */
2459
+ {
2460
+ name: "slot",
2461
+ type: "string",
2462
+ nullable: true,
2463
+ maxLength: 2048,
2464
+ ascii: true
2465
+ }),
1557
2466
  {
1558
2467
  name: "_v",
1559
2468
  type: "integer",
@@ -1587,6 +2496,12 @@ const conformanceItems = {
1587
2496
  name: "byTag",
1588
2497
  eq: ["tags"],
1589
2498
  sort: ["score"]
2499
+ },
2500
+ {
2501
+ name: "bySlot",
2502
+ eq: ["slot"],
2503
+ sort: [],
2504
+ unique: true
1590
2505
  }
1591
2506
  ]
1592
2507
  };
@@ -1697,6 +2612,7 @@ const item = (id, values = {}) => ({
1697
2612
  tags: null,
1698
2613
  payload: null,
1699
2614
  note: null,
2615
+ slot: null,
1700
2616
  _v: 0,
1701
2617
  ...values
1702
2618
  });
@@ -2007,6 +2923,37 @@ const setupDatabaseAdapterConformanceSuite = (options) => {
2007
2923
  eq: ["L"]
2008
2924
  }))).toEqual(["f"]);
2009
2925
  });
2926
+ it("moves a unique slot between rows in one write, and holds a long ASCII value", async () => {
2927
+ const adapter = await setup();
2928
+ const slot = `s:${"a".repeat(998)}`;
2929
+ await ok(adapter, [
2930
+ insert(item("a", { slot })),
2931
+ insert(item("b")),
2932
+ insert(item("c"))
2933
+ ]);
2934
+ expect(await adapter.write([insert(item("d", { slot }))])).toEqual({
2935
+ ok: false,
2936
+ failedOp: 0
2937
+ });
2938
+ const patch = (id, from, to) => ({
2939
+ type: "patch",
2940
+ table: conformanceItems,
2941
+ key: [id],
2942
+ set: { slot: to },
2943
+ guard: { v: 0 },
2944
+ previous: item(id, { slot: from })
2945
+ });
2946
+ expect(await adapter.write([patch("b", null, slot)])).toEqual({
2947
+ ok: false,
2948
+ failedOp: 0
2949
+ });
2950
+ await ok(adapter, [patch("a", slot, null), patch("b", null, slot)]);
2951
+ expect(ids(await query(adapter, {
2952
+ index: "bySlot",
2953
+ eq: [slot]
2954
+ }))).toEqual(["b"]);
2955
+ expect(await one(adapter, "a")).toMatchObject({ slot: null });
2956
+ });
2010
2957
  it("orders strings by UTF-8 bytes and numbers numerically", async () => {
2011
2958
  const adapter = await setup();
2012
2959
  const names = [
@@ -2202,6 +3149,60 @@ const setupDatabaseAdapterConformanceSuite = (options) => {
2202
3149
  "r8"
2203
3150
  ]);
2204
3151
  });
3152
+ it("reads every write committed before the read starts", async () => {
3153
+ const adapter = await setup();
3154
+ await ok(adapter, [insert(item("s", { score: 1 }))]);
3155
+ for (let score = 2; score <= 5; score += 1) {
3156
+ const previous = await one(adapter, "s");
3157
+ await ok(adapter, [{
3158
+ type: "patch",
3159
+ table: conformanceItems,
3160
+ key: ["s"],
3161
+ set: { score },
3162
+ guard: { v: previous._v },
3163
+ previous
3164
+ }]);
3165
+ expect((await one(adapter, "s"))?.score).toBe(score);
3166
+ expect((await query(adapter, {
3167
+ index: "byGroup",
3168
+ eq: ["g"]
3169
+ })).map((row) => row.score)).toEqual([score]);
3170
+ }
3171
+ });
3172
+ it("writes the index items of rows written without the index (migrations.fillIndex)", async () => {
3173
+ const adapter = await setup();
3174
+ const fillIndex = adapter.migrations?.fillIndex;
3175
+ if (fillIndex === void 0) return;
3176
+ const earlier = {
3177
+ ...conformanceItems,
3178
+ indexes: conformanceItems.indexes.filter(({ name }) => name !== "byGroup")
3179
+ };
3180
+ await ok(adapter, [
3181
+ "r0",
3182
+ "r1",
3183
+ "r2"
3184
+ ].map((id) => ({
3185
+ type: "insert",
3186
+ table: earlier,
3187
+ row: item(id, { score: Number(id.slice(1)) })
3188
+ })));
3189
+ await ok(adapter, [insert(item("r3", { score: 3 }))]);
3190
+ const byGroup = () => query(adapter, {
3191
+ index: "byGroup",
3192
+ eq: ["g"]
3193
+ }).then(ids);
3194
+ await expect(byGroup()).resolves.toEqual(["r3"]);
3195
+ await expect(fillIndex(conformanceItems, "byGroup", { dryRun: true })).resolves.toBe(3);
3196
+ await expect(byGroup()).resolves.toEqual(["r3"]);
3197
+ await expect(fillIndex(conformanceItems, "byGroup")).resolves.toBe(3);
3198
+ await expect(byGroup()).resolves.toEqual([
3199
+ "r0",
3200
+ "r1",
3201
+ "r2",
3202
+ "r3"
3203
+ ]);
3204
+ await expect(fillIndex(conformanceItems, "byGroup", { dryRun: true })).resolves.toBe(0);
3205
+ });
2205
3206
  it(`lets exactly one of ${writers} concurrent writers win a contested key`, async () => {
2206
3207
  const adapter = await setup();
2207
3208
  const row = item("a");
@@ -2859,64 +3860,6 @@ const setupStorageAdapterTestSuite = (options) => {
2859
3860
  });
2860
3861
  };
2861
3862
  //#endregion
2862
- //#region src/createMeasuredDatabase.ts
2863
- const storageOf = (storage) => ({
2864
- name: "measuredStorage",
2865
- protocol: "storage",
2866
- get: async ({ storageUri }) => {
2867
- const text = await storage.readStorageText?.(storageUri) ?? null;
2868
- return { response: text === null ? null : new Response(text) };
2869
- },
2870
- getDownloadUrl: async ({ storageUri }) => ({ url: await storage.resolveFileUrl(storageUri) })
2871
- });
2872
- /**
2873
- * Core and the plugins over `adapter` as `createHotUpdater` runs them: what
2874
- * read-budget suites measure. The database is `meterReads` over
2875
- * `verifyAdapter(adapter)`, so every adapter call is checked against the
2876
- * contract and `measureReads` reports each call's reads; the adapter runs
2877
- * as given, without the schema fence. It loads `@hot-updater/server`, an
2878
- * optional peer, when called.
2879
- */
2880
- const createMeasuredDatabase = async (adapter, plugins, options = {}) => {
2881
- const { createHotUpdater } = await import("@hot-updater/server");
2882
- let clientAuth;
2883
- const observed = plugins.map((plugin) => Object.defineProperties({}, {
2884
- ...Object.getOwnPropertyDescriptors(plugin),
2885
- init: {
2886
- configurable: true,
2887
- enumerable: true,
2888
- writable: true,
2889
- value: (context) => {
2890
- const instance = plugin.init(options.now === void 0 ? context : {
2891
- ...context,
2892
- now: options.now
2893
- });
2894
- if (instance.clientAuth !== void 0) clientAuth = instance.clientAuth;
2895
- return instance;
2896
- }
2897
- }
2898
- }));
2899
- const database = meterReads({
2900
- name: "measured",
2901
- adapter: verifyAdapter(adapter)
2902
- });
2903
- const hotUpdater = createHotUpdater({
2904
- database,
2905
- storage: options.storage === void 0 ? {
2906
- name: "measuredStorage",
2907
- protocol: "none"
2908
- } : storageOf(options.storage),
2909
- plugins: observed,
2910
- ...plugins.some((plugin) => plugin.provides?.clientAuth === true) ? {} : { clientAccess: "public" }
2911
- });
2912
- return {
2913
- core: hotUpdater.core,
2914
- api: hotUpdater.api,
2915
- ...clientAuth === void 0 ? {} : { clientAuth },
2916
- measureReads: database.measureReads
2917
- };
2918
- };
2919
- //#endregion
2920
3863
  //#region src/setupReadBudgetTestSuite.ts
2921
3864
  /** A published template: a greeting that beta devices get another value of. */
2922
3865
  const remoteConfigTemplate = (greeting) => ({
@@ -2933,8 +3876,8 @@ const remoteConfigTemplate = (greeting) => ({
2933
3876
  conditionalValues: { Beta: { value: `${greeting}, tester` } }
2934
3877
  } }
2935
3878
  });
2936
- const DAY = 864e5;
2937
- const HOUR = 36e5;
3879
+ const DAY$2 = 864e5;
3880
+ const HOUR$2 = 36e5;
2938
3881
  /** The UTC midnight Insights events start at. */
2939
3882
  const T0 = Date.UTC(2026, 8, 20);
2940
3883
  const NATIVE_PAGE_SIZE = 2;
@@ -2995,8 +3938,51 @@ const failureOf = (n, install, check = false) => eventOf(200 + n, {
2995
3938
  http_status: 403
2996
3939
  }
2997
3940
  },
2998
- received_at_ms: T0 + 3 * DAY + n * 10 * 6e4
3941
+ received_at_ms: T0 + 3 * DAY$2 + n * 10 * 6e4
2999
3942
  });
3943
+ /** Where a client floods update failures: Android `flood`, day 5. */
3944
+ const FLOOD = {
3945
+ platform: "android",
3946
+ channel: "flood",
3947
+ start: T0 + 5 * DAY$2
3948
+ };
3949
+ /** The flood's failed checks: more breakdown rows than a read takes from an hour. */
3950
+ const FLOOD_CHECKS = 24;
3951
+ /**
3952
+ * Installations whose IDs fall on all 8 counter shards: each flood row is
3953
+ * reported by all of them, so it is stored on every shard.
3954
+ */
3955
+ const FLOOD_INSTALLS = Array.from({ length: 8 }, (_, n) => `flood-${n}`);
3956
+ /**
3957
+ * Flood failure `n`: below {@link FLOOD_CHECKS} × 8, a failed check of HTTP
3958
+ * status 100 + n / 8 by installation n % 8, all in day 5's first hour; at
3959
+ * it, a real failure, a failed download in the hour after.
3960
+ */
3961
+ const floodFailureOf = (n) => {
3962
+ const real = n === FLOOD_CHECKS * FLOOD_INSTALLS.length;
3963
+ return eventOf(1e3 + n, {
3964
+ type: "UPDATE_FAILED",
3965
+ install_id: real ? "flood-real" : FLOOD_INSTALLS[n % 8],
3966
+ user_id: null,
3967
+ to_release_id: real ? "release-b" : null,
3968
+ to_bundle_id: real ? "bundle-b" : "bundle-a",
3969
+ platform: FLOOD.platform,
3970
+ channel: FLOOD.channel,
3971
+ metadata: {
3972
+ ...eventOf(0).metadata,
3973
+ failure: real ? {
3974
+ stage: "download",
3975
+ reason: "http",
3976
+ http_status: 403
3977
+ } : {
3978
+ stage: "check",
3979
+ reason: "http",
3980
+ http_status: 100 + Math.floor(n / 8)
3981
+ }
3982
+ },
3983
+ received_at_ms: FLOOD.start + (real ? HOUR$2 : n * 1e3)
3984
+ });
3985
+ };
3000
3986
  /**
3001
3987
  * History event `n` of the day before T0, three an hour, on its own release
3002
3988
  * and bundles: every windowed read, which starts at T0 or later, skips it.
@@ -3007,7 +3993,7 @@ const historyOf = (n) => eventOf(100 + n, {
3007
3993
  from_bundle_id: "bundle-history-a",
3008
3994
  to_release_id: "release-history",
3009
3995
  to_bundle_id: "bundle-history-b",
3010
- received_at_ms: T0 - DAY + Math.floor((n - 1) / 3) * HOUR + (n - 1) % 3 * 6e5
3996
+ received_at_ms: T0 - DAY$2 + Math.floor((n - 1) / 3) * HOUR$2 + (n - 1) % 3 * 6e5
3011
3997
  });
3012
3998
  const production = {
3013
3999
  channel: "production",
@@ -3028,6 +4014,41 @@ const nativeBuildScope = {
3028
4014
  fingerprintHash: "native-fingerprint",
3029
4015
  appVersion: null
3030
4016
  };
4017
+ /** A sandbox scope of `nativeBuildScope`'s fingerprint, which no build has. */
4018
+ const nativeBuildSandboxScope = {
4019
+ appId: "com.example.app",
4020
+ urlScheme: "acme-preview",
4021
+ artifactKind: "ipa",
4022
+ distribution: "direct"
4023
+ };
4024
+ /**
4025
+ * A sandbox ad hoc .ipa of `nativeBuildScope`'s fingerprint, as a build page
4026
+ * holds its row: the source of a sibling read.
4027
+ */
4028
+ const sandboxIpaRow = {
4029
+ id: "01ffffff-ffff-7fff-bfff-ffffffffffff",
4030
+ scope_key: `v1:sandbox:ios:${nativeBuildSandboxScope.appId}:${nativeBuildSandboxScope.urlScheme}:ipa:direct:fingerprint:${nativeBuildScope.fingerprintHash}`,
4031
+ platform: "ios",
4032
+ channel_id: "channel:pr-140",
4033
+ fingerprint_hash: nativeBuildScope.fingerprintHash,
4034
+ app_version: null,
4035
+ min_bundle_id: "01ffffff-ffff-7fff-bfff-fffffffffffe",
4036
+ artifact_kind: "ipa",
4037
+ artifact_storage_uri: "storage://read-budgets/native-builds/ipa/App.ipa",
4038
+ byte_size: 1e3,
4039
+ git_commit_hash: null,
4040
+ created_at_ms: 0,
4041
+ build_key: null,
4042
+ build_number: null,
4043
+ submitted_to: null,
4044
+ submitted_at_ms: null,
4045
+ submitted_version: null,
4046
+ is_store_build: false,
4047
+ is_sandbox: true,
4048
+ sandbox_url_scheme: nativeBuildSandboxScope.urlScheme,
4049
+ export_method: "ad-hoc",
4050
+ native_app_version: null
4051
+ };
3031
4052
  /** The native build key the older of the two native builds is registered with. */
3032
4053
  const nativeBuildKey = `nbk1:${"0".repeat(64)}`;
3033
4054
  const bundleEvents = {
@@ -3035,7 +4056,7 @@ const bundleEvents = {
3035
4056
  platform: "ios",
3036
4057
  channel: "production",
3037
4058
  type: "UPDATE_APPLIED",
3038
- toBundleId: "bundle-b"
4059
+ toReleaseId: "release-b"
3039
4060
  };
3040
4061
  /** The target bundle's manifest, which artifact resolution reads from storage. */
3041
4062
  const storage = {
@@ -3109,6 +4130,39 @@ const seed = async (database) => {
3109
4130
  assetBaseStorageUri: "storage://read-budgets/assets"
3110
4131
  }
3111
4132
  });
4133
+ await core.markNativeBuild(createBundleFixture("8011").id, { storeBuild: true });
4134
+ await core.registerNativeBuild({
4135
+ ...nativeBuildScope,
4136
+ channel: "beta",
4137
+ id: createBundleFixture("8005").id,
4138
+ minBundleId: createBundleFixture("005").id,
4139
+ gitCommitHash: null,
4140
+ buildKey: null,
4141
+ isSandbox: true,
4142
+ sandboxAppId: nativeBuildSandboxScope.appId,
4143
+ sandboxUrlScheme: nativeBuildSandboxScope.urlScheme,
4144
+ artifact: {
4145
+ kind: "app",
4146
+ storageUri: "storage://read-budgets/native-builds/005/App.app.zip",
4147
+ byteSize: 1e3
4148
+ },
4149
+ embeddedBundle: {
4150
+ manifestStorageUri: "storage://bundles/005/manifest.json",
4151
+ manifestFileHash: "manifest-hash-005",
4152
+ assetBaseStorageUri: "storage://read-budgets/assets"
4153
+ }
4154
+ });
4155
+ const pendingDevice = (await core.requestIosDevice({
4156
+ udid: BUDGET_PENDING_UDID,
4157
+ name: "Pending iPhone",
4158
+ requestedBy: "kim@team.dev"
4159
+ })).device;
4160
+ const { device: requestedDevice } = await core.requestIosDevice({
4161
+ udid: BUDGET_APPROVED_UDID,
4162
+ name: "Approved iPhone",
4163
+ requestedBy: "kim@team.dev"
4164
+ });
4165
+ const approvedDevice = await core.approveIosDevice(requestedDevice.id, { approvedBy: "lead@team.dev" });
3112
4166
  const { apiKey } = await api.apiKeys.create({ name: "Read budgets" });
3113
4167
  for (let n = 1; n <= 24; n += 1) await api.insights.recordEvent(eventOf(n));
3114
4168
  await api.insights.recordEvent(eventOf(25, {
@@ -3117,17 +4171,18 @@ const seed = async (database) => {
3117
4171
  from_bundle_id: "bundle-b",
3118
4172
  to_release_id: "release-a",
3119
4173
  to_bundle_id: "bundle-a",
3120
- received_at_ms: T0 + 2 * DAY
4174
+ received_at_ms: T0 + 2 * DAY$2
3121
4175
  }));
3122
4176
  await api.insights.recordEvent(eventOf(26, {
3123
4177
  install_id: "install-1",
3124
4178
  user_id: "user-odd",
3125
- received_at_ms: T0 + 2 * DAY + 6e5
4179
+ received_at_ms: T0 + 2 * DAY$2 + 6e5
3126
4180
  }));
3127
4181
  for (let n = 1; n <= 72; n += 1) await api.insights.recordEvent(historyOf(n));
3128
4182
  await api.insights.recordEvent(failureOf(1, 3));
3129
4183
  await api.insights.recordEvent(failureOf(2, 5));
3130
4184
  await api.insights.recordEvent(failureOf(3, 7, true));
4185
+ for (let n = 0; n <= FLOOD_CHECKS * FLOOD_INSTALLS.length; n += 1) await api.insights.recordEvent(floodFailureOf(n));
3131
4186
  for (const [baseVersion, greeting] of [
3132
4187
  "Hi",
3133
4188
  "Hello",
@@ -3146,6 +4201,8 @@ const seed = async (database) => {
3146
4201
  apiKey,
3147
4202
  productionId,
3148
4203
  nightlyId: (await channel("nightly")).id,
4204
+ pendingDevice,
4205
+ approvedDevice,
3149
4206
  /** The auto-patch base key of a new production iOS 1.0.0 bundle. */
3150
4207
  candidateKey: targetBaseCandidateKey({
3151
4208
  channel: "production",
@@ -3156,6 +4213,8 @@ const seed = async (database) => {
3156
4213
  };
3157
4214
  };
3158
4215
  const budget = (entry) => entry;
4216
+ const BUDGET_PENDING_UDID = "00008030-000000000000000a";
4217
+ const BUDGET_APPROVED_UDID = "00008030-000000000000000b";
3159
4218
  const reads = (gets, keys, queries, rows) => ({
3160
4219
  gets,
3161
4220
  keys,
@@ -3336,6 +4395,46 @@ const READ_BUDGETS = [
3336
4395
  rows: 1
3337
4396
  }
3338
4397
  }),
4398
+ budget({
4399
+ api: "catalog preflight: 1 catalog point read and the scope's enabled releases",
4400
+ read: ({ core }) => core.preflightReleaseCatalogRebuild(scopeKey),
4401
+ adapter: reads(1, 1, 1, 4),
4402
+ engine: {
4403
+ calls: 2,
4404
+ rows: 5
4405
+ },
4406
+ check: (preflight) => expect(preflight.changed).toBe(false)
4407
+ }),
4408
+ budget({
4409
+ api: "release scopes: one limit-1 seek per scope, past each scope's releases",
4410
+ read: ({ core }) => core.listReleaseScopeKeys({ limit: 4 }),
4411
+ adapter: reads(0, 0, 4, 4),
4412
+ engine: {
4413
+ calls: 4,
4414
+ rows: 4
4415
+ },
4416
+ returned: (scopeKeys) => scopeKeys.length,
4417
+ check: (scopeKeys) => expect(scopeKeys).toEqual([
4418
+ "v1:app-version:android:cHJvZHVjdGlvbg",
4419
+ "v1:app-version:ios:YmV0YQ",
4420
+ "v1:app-version:ios:c3RhZ2luZw",
4421
+ scopeKey
4422
+ ])
4423
+ }),
4424
+ budget({
4425
+ api: "release scopes past the last: 1 empty query",
4426
+ read: ({ core }) => core.listReleaseScopeKeys({
4427
+ after: scopeKey,
4428
+ limit: 4
4429
+ }),
4430
+ adapter: reads(0, 0, 1, 0),
4431
+ engine: {
4432
+ calls: 1,
4433
+ rows: 0
4434
+ },
4435
+ returned: (scopeKeys) => scopeKeys.length,
4436
+ check: (scopeKeys) => expect(scopeKeys).toEqual([])
4437
+ }),
3339
4438
  budget({
3340
4439
  api: "native build by ID: 1 point read",
3341
4440
  read: ({ core }) => core.getNativeBuild(createBundleFixture("8012").id),
@@ -3346,6 +4445,16 @@ const READ_BUDGETS = [
3346
4445
  },
3347
4446
  check: (build) => expect(build).toMatchObject({ min_bundle_id: createBundleFixture("012").id })
3348
4447
  }),
4448
+ budget({
4449
+ api: "native build by its built-in bundle: 1 unique read",
4450
+ read: ({ core }) => core.findNativeBuildByBuiltInBundle(createBundleFixture("011").id),
4451
+ adapter: reads(0, 0, 1, 1),
4452
+ engine: {
4453
+ calls: 1,
4454
+ rows: 1
4455
+ },
4456
+ check: (build) => expect(build).toMatchObject({ id: createBundleFixture("8011").id })
4457
+ }),
3349
4458
  budget({
3350
4459
  api: "native build by scope: byScope descending, limit 1",
3351
4460
  read: ({ core }) => core.findNativeBuild(nativeBuildScope),
@@ -3356,6 +4465,79 @@ const READ_BUDGETS = [
3356
4465
  },
3357
4466
  check: (build) => expect(build).toMatchObject({ min_bundle_id: createBundleFixture("012").id })
3358
4467
  }),
4468
+ budget({
4469
+ api: "native build store mark: byStoreBuild, 1 row",
4470
+ read: ({ core }) => core.findNativeBuild(nativeBuildScope, { storeBuild: true }),
4471
+ adapter: reads(0, 0, 1, 1),
4472
+ engine: {
4473
+ calls: 1,
4474
+ rows: 1
4475
+ },
4476
+ check: (build) => expect(build).toMatchObject({
4477
+ min_bundle_id: createBundleFixture("011").id,
4478
+ is_store_build: true
4479
+ })
4480
+ }),
4481
+ budget({
4482
+ api: "native build store mark of a scope with none: byStoreBuild, no row",
4483
+ read: ({ core }) => core.findNativeBuild({
4484
+ ...nativeBuildScope,
4485
+ channel: "no-such-channel"
4486
+ }, { storeBuild: true }),
4487
+ adapter: reads(0, 0, 1, 0),
4488
+ engine: {
4489
+ calls: 1,
4490
+ rows: 0
4491
+ },
4492
+ check: (build) => expect(build).toBeNull()
4493
+ }),
4494
+ budget({
4495
+ api: "native build older than a bundle, the newest is: byScope, limit 1",
4496
+ read: ({ core }) => core.findNativeBuild(nativeBuildScope, { builtInOlderThan: "ffffffff-ffff-7fff-bfff-ffffffffffff" }),
4497
+ adapter: reads(0, 0, 1, 1),
4498
+ engine: {
4499
+ calls: 1,
4500
+ rows: 1
4501
+ },
4502
+ check: (build) => expect(build).toMatchObject({ min_bundle_id: createBundleFixture("012").id })
4503
+ }),
4504
+ budget({
4505
+ api: "native build older than a bundle, past the newest: byScope twice",
4506
+ read: ({ core }) => core.findNativeBuild(nativeBuildScope, { builtInOlderThan: createBundleFixture("012").id }),
4507
+ adapter: reads(0, 0, 2, 2),
4508
+ engine: {
4509
+ calls: 2,
4510
+ rows: 2
4511
+ },
4512
+ check: (build) => expect(build).toMatchObject({ min_bundle_id: createBundleFixture("011").id })
4513
+ }),
4514
+ budget({
4515
+ api: "native build older than a bundle in a sandbox scope: no read",
4516
+ read: ({ core }) => core.findNativeBuild({
4517
+ ...nativeBuildScope,
4518
+ sandbox: nativeBuildSandboxScope
4519
+ }, { builtInOlderThan: "ffffffff-ffff-7fff-bfff-ffffffffffff" }),
4520
+ adapter: reads(0, 0, 0, 0),
4521
+ engine: {
4522
+ calls: 0,
4523
+ rows: 0
4524
+ },
4525
+ check: (build) => expect(build).toBeNull()
4526
+ }),
4527
+ budget({
4528
+ api: "sandbox build on any channel: byScope descending, limit 1",
4529
+ read: ({ core }) => core.findNativeBuild({
4530
+ ...nativeBuildScope,
4531
+ channel: "pr-140",
4532
+ sandbox: nativeBuildSandboxScope
4533
+ }),
4534
+ adapter: reads(0, 0, 1, 0),
4535
+ engine: {
4536
+ calls: 1,
4537
+ rows: 0
4538
+ },
4539
+ check: (build) => expect(build).toBeNull()
4540
+ }),
3359
4541
  budget({
3360
4542
  api: "native build by key: byBuildKey descending, limit 1",
3361
4543
  read: ({ core }) => core.findNativeBuild(nativeBuildScope, { buildKey: nativeBuildKey }),
@@ -3369,6 +4551,53 @@ const READ_BUDGETS = [
3369
4551
  build_key: nativeBuildKey
3370
4552
  })
3371
4553
  }),
4554
+ budget({
4555
+ api: "native build of a kind: byScopeKind descending, limit 1",
4556
+ read: ({ core }) => core.findNativeBuild(nativeBuildScope, { artifactKind: "ipa" }),
4557
+ adapter: reads(0, 0, 1, 1),
4558
+ engine: {
4559
+ calls: 1,
4560
+ rows: 1
4561
+ },
4562
+ check: (build) => expect(build).toMatchObject({ min_bundle_id: createBundleFixture("012").id })
4563
+ }),
4564
+ budget({
4565
+ api: "native build of a kind with none: byScopeKind, then byScope, limit 1",
4566
+ read: ({ core }) => core.findNativeBuild(nativeBuildScope, { artifactKind: "app" }),
4567
+ adapter: reads(0, 0, 2, 1),
4568
+ engine: {
4569
+ calls: 2,
4570
+ rows: 1
4571
+ },
4572
+ check: (build) => expect(build).toBeNull()
4573
+ }),
4574
+ budget({
4575
+ api: "sandbox build's other install target: byScope descending, limit 1",
4576
+ read: ({ core }) => core.findNativeBuildSibling(sandboxIpaRow),
4577
+ adapter: reads(0, 0, 1, 1),
4578
+ engine: {
4579
+ calls: 1,
4580
+ rows: 1
4581
+ },
4582
+ check: (build) => expect(build).toMatchObject({
4583
+ id: createBundleFixture("8005").id,
4584
+ artifact_kind: "app"
4585
+ })
4586
+ }),
4587
+ budget({
4588
+ api: "normal build's other install target: no read",
4589
+ read: ({ core }) => core.findNativeBuildSibling({
4590
+ ...sandboxIpaRow,
4591
+ is_sandbox: false,
4592
+ scope_key: "normal"
4593
+ }),
4594
+ adapter: reads(0, 0, 0, 0),
4595
+ engine: {
4596
+ calls: 0,
4597
+ rows: 0
4598
+ },
4599
+ check: (build) => expect(build).toBeNull()
4600
+ }),
3372
4601
  budget({
3373
4602
  api: "native build list: all descending, limit rows",
3374
4603
  read: ({ core }) => core.listNativeBuilds({
@@ -3406,11 +4635,40 @@ const READ_BUDGETS = [
3406
4635
  },
3407
4636
  returned: (channel) => channel === null ? 0 : 1
3408
4637
  }),
4638
+ budget({
4639
+ api: "channels by ID: 1 batch get of their keys",
4640
+ read: ({ core, productionId, nightlyId }) => core.getChannels([
4641
+ nightlyId,
4642
+ productionId,
4643
+ nightlyId
4644
+ ]),
4645
+ adapter: reads(1, 2, 0, 0),
4646
+ engine: {
4647
+ calls: 1,
4648
+ rows: 2
4649
+ },
4650
+ returned: (channels) => channels.length,
4651
+ check: (channels) => expect(channels.map(({ name }) => name)).toEqual(["nightly", "production"])
4652
+ }),
4653
+ budget({
4654
+ api: "channel page by name: limit rows from one query",
4655
+ read: ({ core }) => core.listChannels({
4656
+ limit: 2,
4657
+ after: "beta"
4658
+ }),
4659
+ adapter: reads(0, 0, 1, 2),
4660
+ engine: {
4661
+ calls: 1,
4662
+ rows: 2
4663
+ },
4664
+ returned: (channels) => channels.length,
4665
+ check: (channels) => expect(channels.map(({ name }) => name)).toEqual(["canary", "nightly"])
4666
+ }),
3409
4667
  budget({
3410
4668
  api: "list events of a dense day: limit rows from one query",
3411
4669
  read: ({ insights }) => insights.listEvents({
3412
4670
  filter: { kind: "all" },
3413
- sinceMs: T0 - DAY,
4671
+ sinceMs: T0 - DAY$2,
3414
4672
  beforeReceivedAtMs: T0,
3415
4673
  limit: 5
3416
4674
  }),
@@ -3426,7 +4684,7 @@ const READ_BUDGETS = [
3426
4684
  read: ({ insights }) => insights.listEvents({
3427
4685
  filter: bundleEvents,
3428
4686
  sinceMs: T0,
3429
- beforeReceivedAtMs: T0 + 3 * DAY,
4687
+ beforeReceivedAtMs: T0 + 3 * DAY$2,
3430
4688
  limit: 5
3431
4689
  }),
3432
4690
  adapter: reads(1, 7, 4, 6),
@@ -3440,8 +4698,8 @@ const READ_BUDGETS = [
3440
4698
  api: "list events over an empty range: its top day and one outcome read, both empty",
3441
4699
  read: ({ insights }) => insights.listEvents({
3442
4700
  filter: { kind: "all" },
3443
- sinceMs: T0 - 91 * DAY,
3444
- beforeReceivedAtMs: T0 - DAY,
4701
+ sinceMs: T0 - 91 * DAY$2,
4702
+ beforeReceivedAtMs: T0 - DAY$2,
3445
4703
  limit: 5
3446
4704
  }),
3447
4705
  adapter: reads(0, 0, 2, 0),
@@ -3479,7 +4737,7 @@ const READ_BUDGETS = [
3479
4737
  read: ({ insights }) => insights.countEvents({
3480
4738
  filter: bundleEvents,
3481
4739
  sinceMs: T0,
3482
- beforeReceivedAtMs: T0 + 2 * HOUR
4740
+ beforeReceivedAtMs: T0 + 2 * HOUR$2
3483
4741
  }),
3484
4742
  adapter: reads(0, 0, 1, 11),
3485
4743
  engine: {
@@ -3494,9 +4752,9 @@ const READ_BUDGETS = [
3494
4752
  filter: bundleEvents,
3495
4753
  timeRange: {
3496
4754
  start: T0,
3497
- end: T0 + 3 * DAY
4755
+ end: T0 + 3 * DAY$2
3498
4756
  },
3499
- intervalMs: DAY
4757
+ intervalMs: DAY$2
3500
4758
  }),
3501
4759
  adapter: reads(0, 0, 1, 25),
3502
4760
  engine: {
@@ -3524,23 +4782,22 @@ const READ_BUDGETS = [
3524
4782
  check: (count) => expect(count).toBe(24)
3525
4783
  }),
3526
4784
  budget({
3527
- api: "countLatestEvents by bundle: buckets in the window × shards, all used",
3528
- read: ({ insights }) => insights.countLatestEvents({
4785
+ api: "countReleaseInstallations: the scope's rows, read once for both counts",
4786
+ read: ({ insights }) => insights.countReleaseInstallations({
3529
4787
  platform: "ios",
3530
4788
  channel: "production",
3531
4789
  sinceMs: T0,
3532
- bundle: [{
3533
- field: "to_bundle_id",
3534
- value: "bundle-b",
3535
- types: ["UPDATE_APPLIED"]
3536
- }]
4790
+ releaseId: "release-b"
3537
4791
  }),
3538
4792
  adapter: reads(0, 0, 1, 15),
3539
4793
  engine: {
3540
4794
  calls: 1,
3541
4795
  rows: 2
3542
4796
  },
3543
- check: (count) => expect(count).toBe(24)
4797
+ check: (counts) => expect(counts).toEqual({
4798
+ installations: 24,
4799
+ release: 24
4800
+ })
3544
4801
  }),
3545
4802
  budget({
3546
4803
  api: "release activity: buckets × shards, all used",
@@ -3563,9 +4820,9 @@ const READ_BUDGETS = [
3563
4820
  platform: "all",
3564
4821
  timeRange: {
3565
4822
  start: T0,
3566
- end: T0 + 3 * DAY
4823
+ end: T0 + 3 * DAY$2
3567
4824
  },
3568
- intervalMs: DAY
4825
+ intervalMs: DAY$2
3569
4826
  }),
3570
4827
  adapter: reads(0, 0, 6, 30),
3571
4828
  engine: {
@@ -3584,8 +4841,8 @@ const READ_BUDGETS = [
3584
4841
  channel: "production",
3585
4842
  releaseId: "release-b",
3586
4843
  timeRange: {
3587
- start: T0 + 3 * DAY,
3588
- end: T0 + 4 * DAY
4844
+ start: T0 + 3 * DAY$2,
4845
+ end: T0 + 4 * DAY$2
3589
4846
  }
3590
4847
  }),
3591
4848
  adapter: reads(0, 0, 3, 5),
@@ -3609,8 +4866,8 @@ const READ_BUDGETS = [
3609
4866
  platform: "ios",
3610
4867
  channel: "production",
3611
4868
  timeRange: {
3612
- start: T0 + 3 * DAY,
3613
- end: T0 + 4 * DAY
4869
+ start: T0 + 3 * DAY$2,
4870
+ end: T0 + 4 * DAY$2
3614
4871
  }
3615
4872
  }),
3616
4873
  adapter: reads(0, 0, 5, 6),
@@ -3623,6 +4880,32 @@ const READ_BUDGETS = [
3623
4880
  checks: { failures: 1 }
3624
4881
  })
3625
4882
  }),
4883
+ budget({
4884
+ api: "update failures of a flooded channel: 20 breakdown rows of the flooded hour, every other hour whole",
4885
+ read: ({ insights }) => insights.getUpdateFailures({
4886
+ platform: FLOOD.platform,
4887
+ channel: FLOOD.channel,
4888
+ timeRange: {
4889
+ start: FLOOD.start,
4890
+ end: FLOOD.start + 2 * HOUR$2
4891
+ }
4892
+ }),
4893
+ adapter: reads(1, 1, 5, 177),
4894
+ engine: {
4895
+ calls: 5,
4896
+ rows: 24
4897
+ },
4898
+ check: (failures) => expect(failures).toMatchObject({
4899
+ coverage: { kind: "partial" },
4900
+ cappedHours: [FLOOD.start],
4901
+ failedUpdates: 1,
4902
+ failedInstallations: 1,
4903
+ checks: {
4904
+ failures: 160,
4905
+ failedInstallations: 8
4906
+ }
4907
+ })
4908
+ }),
3626
4909
  budget({
3627
4910
  api: "update failures of a release since its first: two kept rows × shards, all used",
3628
4911
  read: ({ insights }) => insights.getUpdateFailures({
@@ -3630,80 +4913,251 @@ const READ_BUDGETS = [
3630
4913
  channel: "production",
3631
4914
  releaseId: "release-b"
3632
4915
  }),
3633
- adapter: reads(0, 0, 2, 10),
4916
+ adapter: reads(0, 0, 2, 10),
4917
+ engine: {
4918
+ calls: 2,
4919
+ rows: 2
4920
+ },
4921
+ check: (failures) => expect(failures).toMatchObject({
4922
+ failedUpdates: 2,
4923
+ failedInstallations: 2
4924
+ })
4925
+ }),
4926
+ budget({
4927
+ api: "catalog compile: the scope's enabled releases, all used",
4928
+ read: ({ core }) => core.deploy([{
4929
+ bundle: bundleOf("107"),
4930
+ release: production
4931
+ }]),
4932
+ adapter: (copies) => reads(copies ? 6 : 4, copies ? 9 : 4, 3, 6),
4933
+ engine: {
4934
+ calls: 7,
4935
+ rows: 10
4936
+ },
4937
+ writes: 1
4938
+ }),
4939
+ budget({
4940
+ api: "release by label: its unique index, then the release",
4941
+ read: ({ core }) => core.getReleaseByLabel({
4942
+ channel: "production",
4943
+ platform: "ios",
4944
+ label: 2
4945
+ }),
4946
+ adapter: reads(1, 1, 1, 1),
4947
+ engine: {
4948
+ calls: 2,
4949
+ rows: 2
4950
+ },
4951
+ check: (release) => expect(release).toMatchObject({ label: 2 })
4952
+ }),
4953
+ budget({
4954
+ api: "channel insert: 1 write, after the name's read finds nothing",
4955
+ read: ({ core }) => core.ensureChannel("read-budgets"),
4956
+ adapter: reads(0, 0, 1, 0),
4957
+ engine: {
4958
+ calls: 1,
4959
+ rows: 0
4960
+ },
4961
+ writes: 1
4962
+ }),
4963
+ budget({
4964
+ api: "channel delete: the channel, its native builds under it, its label counters, and 1 write",
4965
+ read: ({ core, nightlyId }) => core.deleteChannel(nightlyId),
4966
+ adapter: reads(4, 4, 1, 0),
4967
+ engine: {
4968
+ calls: 5,
4969
+ rows: 2
4970
+ },
4971
+ writes: 1,
4972
+ check: (result) => expect(result).toEqual({ deleted: true })
4973
+ }),
4974
+ budget({
4975
+ api: "native build submission: the build and 1 write",
4976
+ read: ({ core }) => core.recordNativeBuildSubmission(createBundleFixture("8012").id, {
4977
+ destination: "testflight",
4978
+ version: "1.0.0 (12)"
4979
+ }),
4980
+ adapter: reads(1, 1, 0, 0),
4981
+ engine: {
4982
+ calls: 1,
4983
+ rows: 1
4984
+ },
4985
+ writes: 1,
4986
+ check: (build) => expect(build).toMatchObject({
4987
+ min_bundle_id: createBundleFixture("012").id,
4988
+ submitted_to: "testflight",
4989
+ submitted_version: "1.0.0 (12)"
4990
+ })
4991
+ }),
4992
+ budget({
4993
+ api: "native build store mark write: the build, the holder, and 1 write",
4994
+ read: ({ core }) => core.markNativeBuild(createBundleFixture("8012").id, { storeBuild: true }),
4995
+ adapter: (indexCopies) => indexCopies ? reads(2, 2, 1, 1) : reads(1, 1, 1, 1),
4996
+ engine: {
4997
+ calls: 2,
4998
+ rows: 2
4999
+ },
5000
+ writes: 1,
5001
+ check: (result) => expect(result).toMatchObject({
5002
+ nativeBuild: {
5003
+ min_bundle_id: createBundleFixture("012").id,
5004
+ is_store_build: true
5005
+ },
5006
+ previous: { min_bundle_id: createBundleFixture("011").id }
5007
+ })
5008
+ }),
5009
+ budget({
5010
+ api: "native build delete: the build, its built-in bundle, and 1 write",
5011
+ read: ({ core }) => core.deleteNativeBuild(createBundleFixture("8011").id),
5012
+ adapter: reads(2, 2, 0, 0),
5013
+ engine: {
5014
+ calls: 2,
5015
+ rows: 2
5016
+ },
5017
+ writes: 1,
5018
+ check: (result) => expect(result).toMatchObject({
5019
+ deleted: true,
5020
+ nativeBuild: { min_bundle_id: createBundleFixture("011").id }
5021
+ })
5022
+ }),
5023
+ budget({
5024
+ api: "iOS devices by status: 1 query, the rows used",
5025
+ read: ({ core }) => core.listIosDevices({
5026
+ status: "approved",
5027
+ limit: 50
5028
+ }),
5029
+ adapter: reads(0, 0, 1, 1),
5030
+ engine: {
5031
+ calls: 1,
5032
+ rows: 1
5033
+ },
5034
+ returned: (rows) => rows.length,
5035
+ check: (rows) => expect(rows.map((row) => row.udid)).toEqual([BUDGET_APPROVED_UDID])
5036
+ }),
5037
+ budget({
5038
+ api: "iOS device by UDID: 1 unique read",
5039
+ read: ({ core }) => core.findIosDevice(BUDGET_PENDING_UDID.toUpperCase()),
5040
+ adapter: reads(0, 0, 1, 1),
5041
+ engine: {
5042
+ calls: 1,
5043
+ rows: 1
5044
+ },
5045
+ check: (device) => expect(device?.status).toBe("pending")
5046
+ }),
5047
+ budget({
5048
+ api: "iOS device request: the UDID's read and 1 write",
5049
+ read: ({ core }) => core.requestIosDevice({
5050
+ udid: "00008030-000000000000000c",
5051
+ name: "New iPhone",
5052
+ requestedBy: null
5053
+ }),
5054
+ adapter: reads(0, 0, 1, 0),
5055
+ engine: {
5056
+ calls: 1,
5057
+ rows: 0
5058
+ },
5059
+ writes: 1,
5060
+ check: (result) => expect(result.created).toBe(true)
5061
+ }),
5062
+ budget({
5063
+ api: "iOS device approval: the row and 1 write",
5064
+ read: ({ core, pendingDevice }) => core.approveIosDevice(pendingDevice.id, { approvedBy: null }),
5065
+ adapter: reads(1, 1, 0, 0),
5066
+ engine: {
5067
+ calls: 1,
5068
+ rows: 1
5069
+ },
5070
+ writes: 1,
5071
+ check: (device) => expect(device?.status).toBe("approved")
5072
+ }),
5073
+ budget({
5074
+ api: "iOS device outcome: the row and 1 write",
5075
+ read: ({ core, approvedDevice }) => core.recordIosDeviceOutcome({
5076
+ id: approvedDevice.id,
5077
+ seen: {
5078
+ status: "approved",
5079
+ approvedAtMs: approvedDevice.approved_at_ms
5080
+ },
5081
+ issuerId: "issuer-a",
5082
+ outcome: "registered"
5083
+ }),
5084
+ adapter: reads(1, 1, 0, 0),
3634
5085
  engine: {
3635
- calls: 2,
3636
- rows: 2
5086
+ calls: 1,
5087
+ rows: 1
3637
5088
  },
3638
- check: (failures) => expect(failures).toMatchObject({
3639
- failedUpdates: 2,
3640
- failedInstallations: 2
3641
- })
5089
+ writes: 1,
5090
+ check: (device) => expect(device?.status).toBe("registered")
3642
5091
  }),
3643
5092
  budget({
3644
- api: "catalog compile: the scope's enabled releases, all used",
3645
- read: ({ core }) => core.deploy([{
3646
- bundle: bundleOf("107"),
3647
- release: production
3648
- }]),
3649
- adapter: (copies) => reads(copies ? 5 : 3, copies ? 8 : 3, 3, 6),
5093
+ api: "iOS devices in a build: the row and 1 write each",
5094
+ read: ({ core, approvedDevice }) => core.markIosDevicesInBuild({
5095
+ buildId: createBundleFixture("8012").id,
5096
+ ids: [approvedDevice.id]
5097
+ }),
5098
+ adapter: reads(1, 1, 0, 0),
3650
5099
  engine: {
3651
- calls: 6,
3652
- rows: 9
5100
+ calls: 1,
5101
+ rows: 1
3653
5102
  },
3654
5103
  writes: 1
3655
5104
  }),
3656
5105
  budget({
3657
- api: "channel insert: 1 write, after the name's read finds nothing",
3658
- read: ({ core }) => core.ensureChannel("read-budgets"),
3659
- adapter: reads(0, 0, 1, 0),
5106
+ api: "iOS device delete: the row and 1 write",
5107
+ read: ({ core, pendingDevice }) => core.deleteIosDevice(pendingDevice.id),
5108
+ adapter: reads(1, 1, 0, 0),
3660
5109
  engine: {
3661
5110
  calls: 1,
3662
- rows: 0
5111
+ rows: 1
3663
5112
  },
3664
- writes: 1
5113
+ writes: 1,
5114
+ check: (device) => expect(device?.udid).toBe(BUDGET_PENDING_UDID)
3665
5115
  }),
3666
5116
  budget({
3667
- api: "channel delete: the channel, its native builds under it, and 1 write",
3668
- read: ({ core, nightlyId }) => core.deleteChannel(nightlyId),
3669
- adapter: reads(2, 2, 1, 0),
5117
+ api: "iOS device account read, no claim yet: its row, then the earliest registration",
5118
+ read: ({ core }) => core.findIosDeviceAccount(),
5119
+ adapter: reads(1, 1, 1, 1),
3670
5120
  engine: {
3671
- calls: 3,
3672
- rows: 2
5121
+ calls: 2,
5122
+ rows: 1
5123
+ },
5124
+ check: (account) => expect(account).toEqual({ issuerId: "issuer-a" })
5125
+ }),
5126
+ budget({
5127
+ api: "iOS device account, first claim: its one row's read, the earliest registration, and 1 write",
5128
+ read: ({ core }) => core.claimIosDeviceAccount("issuer-a"),
5129
+ adapter: reads(1, 1, 1, 1),
5130
+ engine: {
5131
+ calls: 2,
5132
+ rows: 1
3673
5133
  },
3674
5134
  writes: 1,
3675
- check: (result) => expect(result).toEqual({ deleted: true })
5135
+ check: (claim) => expect(claim).toEqual({
5136
+ issuerId: "issuer-a",
5137
+ claimed: true
5138
+ })
3676
5139
  }),
3677
5140
  budget({
3678
- api: "native build submission: the build and 1 write",
3679
- read: ({ core }) => core.recordNativeBuildSubmission(createBundleFixture("8012").id, {
3680
- destination: "testflight",
3681
- version: "1.0.0 (12)"
3682
- }),
5141
+ api: "iOS device account read, claimed: its one row's read",
5142
+ read: ({ core }) => core.findIosDeviceAccount(),
3683
5143
  adapter: reads(1, 1, 0, 0),
3684
5144
  engine: {
3685
5145
  calls: 1,
3686
5146
  rows: 1
3687
5147
  },
3688
- writes: 1,
3689
- check: (build) => expect(build).toMatchObject({
3690
- min_bundle_id: createBundleFixture("012").id,
3691
- submitted_to: "testflight",
3692
- submitted_version: "1.0.0 (12)"
3693
- })
5148
+ check: (account) => expect(account).toEqual({ issuerId: "issuer-a" })
3694
5149
  }),
3695
5150
  budget({
3696
- api: "native build delete: the build, its built-in bundle, and 1 write",
3697
- read: ({ core }) => core.deleteNativeBuild(createBundleFixture("8011").id),
3698
- adapter: reads(2, 2, 0, 0),
5151
+ api: "iOS device account, claimed: its one row's read",
5152
+ read: ({ core }) => core.claimIosDeviceAccount("issuer-b"),
5153
+ adapter: reads(1, 1, 0, 0),
3699
5154
  engine: {
3700
- calls: 2,
3701
- rows: 2
5155
+ calls: 1,
5156
+ rows: 1
3702
5157
  },
3703
- writes: 1,
3704
- check: (result) => expect(result).toMatchObject({
3705
- deleted: true,
3706
- nativeBuild: { min_bundle_id: createBundleFixture("011").id }
5158
+ check: (claim) => expect(claim).toEqual({
5159
+ issuerId: "issuer-a",
5160
+ claimed: false
3707
5161
  })
3708
5162
  }),
3709
5163
  budget({
@@ -3715,9 +5169,9 @@ const READ_BUDGETS = [
3715
5169
  from_bundle_id: "bundle-b",
3716
5170
  to_release_id: "release-c",
3717
5171
  to_bundle_id: "bundle-c",
3718
- received_at_ms: T0 + 3 * HOUR
5172
+ received_at_ms: T0 + 3 * HOUR$2
3719
5173
  })),
3720
- adapter: reads(6, 14, 0, 0),
5174
+ adapter: reads(5, 8, 0, 0),
3721
5175
  engine: {
3722
5176
  calls: 2,
3723
5177
  rows: 1
@@ -3736,6 +5190,7 @@ const READ_BUDGETS = [
3736
5190
  const setupReadBudgetTestSuite = (options) => {
3737
5191
  describe(`${options.name} read budgets`, () => {
3738
5192
  let created;
5193
+ let tables;
3739
5194
  let database;
3740
5195
  let seeded;
3741
5196
  let writes = 0;
@@ -3746,8 +5201,9 @@ const setupReadBudgetTestSuite = (options) => {
3746
5201
  apiKeys(),
3747
5202
  remoteConfig()
3748
5203
  ];
5204
+ tables = [...toolingTargetOf(plugins).schema.tables, SETTINGS_TABLE];
3749
5205
  created = await options.createAdapter({
3750
- tables: [...toolingTargetOf(plugins).schema.tables, SETTINGS_TABLE],
5206
+ tables,
3751
5207
  nativePageSize: NATIVE_PAGE_SIZE
3752
5208
  });
3753
5209
  const { adapter } = created;
@@ -3758,7 +5214,7 @@ const setupReadBudgetTestSuite = (options) => {
3758
5214
  return adapter.write(ops);
3759
5215
  }
3760
5216
  }, plugins, {
3761
- now: () => T0 + 10 * DAY,
5217
+ now: () => T0 + 10 * DAY$2,
3762
5218
  storage
3763
5219
  });
3764
5220
  seeded = await seed(database);
@@ -3787,6 +5243,42 @@ const setupReadBudgetTestSuite = (options) => {
3787
5243
  expect(await examined.total(), "rows examined").toBeLessThanOrEqual((examined.perRow ?? 1) * (keys + rows) + (examined.perRead ?? 0) * (gets + queries));
3788
5244
  }
3789
5245
  });
5246
+ /** Install `n`'s first event, all in one hour of day 4: the same rows each. */
5247
+ const newInstall = (n) => eventOf(400 + n, {
5248
+ install_id: `new-install-${n}`,
5249
+ user_id: null,
5250
+ received_at_ms: T0 + 4 * DAY$2 + n * 1e3
5251
+ });
5252
+ /** Events of later days, which no prune below reaches. */
5253
+ const store = async (from, count) => {
5254
+ for (let n = from; n < from + count; n += 1) await seeded.insights.recordEvent(newInstall(n));
5255
+ };
5256
+ it("record an insights event: no statement reads more than its row and the write's guard row, with 60 or 120 events stored", async (context) => {
5257
+ const { written } = created;
5258
+ if (written === void 0) return context.skip();
5259
+ const most = async (n) => {
5260
+ written.reset();
5261
+ await seeded.insights.recordEvent(newInstall(n));
5262
+ return Math.max(...await written.rows());
5263
+ };
5264
+ await store(1, 60);
5265
+ expect(await most(61)).toBeLessThanOrEqual(2);
5266
+ await store(62, 60);
5267
+ expect(await most(122)).toBeLessThanOrEqual(2);
5268
+ });
5269
+ it("prune: deletes 5 expired events reading no more rows with 60 more events stored", async (context) => {
5270
+ const { adapter, written } = created;
5271
+ if (written === void 0) return context.skip();
5272
+ const events = tables.find(({ name }) => name === "bundle_events");
5273
+ const prune = async () => {
5274
+ written.reset();
5275
+ expect(await adapter.prune(events, T0 - DAY$2, 5)).toBe(5);
5276
+ return (await written.rows()).reduce((sum, rows) => sum + rows, 0);
5277
+ };
5278
+ const before = await prune();
5279
+ await store(200, 60);
5280
+ expect(await prune()).toBeLessThanOrEqual(before);
5281
+ });
3790
5282
  });
3791
5283
  };
3792
5284
  //#endregion
@@ -3970,8 +5462,8 @@ const snapshot = async (db) => {
3970
5462
  };
3971
5463
  /**
3972
5464
  * Aggregates declared `batched` on a key-value store: log rows the store
3973
- * writes with each transaction and a compaction merges once, and a memory
3974
- * buffer, read back exactly as transactional writes read.
5465
+ * writes with each transaction and a compaction merges once, read back
5466
+ * exactly as transactional writes read.
3975
5467
  */
3976
5468
  const setupAggregateBatchingTestSuite = ({ name, createAdapter, oversizedRows }) => {
3977
5469
  const tables = [...toolingTargetOf([plugin]).schema.tables, ...aggregateBatchingTables];
@@ -4007,21 +5499,15 @@ const setupAggregateBatchingTestSuite = ({ name, createAdapter, oversizedRows })
4007
5499
  afterEach(async () => {
4008
5500
  for (const cleanup of cleanups.splice(0)) await cleanup();
4009
5501
  });
4010
- for (const mode of ["log", "memory"]) it(`reads what transactional writes read, in ${mode} mode`, async () => {
4011
- const { db } = server(await store(), { mode });
5502
+ it("reads what transactional writes read", async () => {
5503
+ const { db } = server(await store(), {});
4012
5504
  for (let step = 0; step < 36; step += 1) await open(db, step);
4013
5505
  expect(await snapshot(db)).toEqual(await expected(36));
4014
5506
  }, 12e4);
4015
5507
  it("applies each log row once when two servers compact while 16 writers commit", async () => {
4016
5508
  const adapter = await store();
4017
- const first = server(adapter, {
4018
- mode: "log",
4019
- windowMs: 0
4020
- });
4021
- const second = server(adapter, {
4022
- mode: "log",
4023
- windowMs: 0
4024
- });
5509
+ const first = server(adapter, { windowMs: 0 });
5510
+ const second = server(adapter, { windowMs: 0 });
4025
5511
  const report = await runContentionHarness({
4026
5512
  transactions: 12,
4027
5513
  ratePerSecond: 1e3,
@@ -4039,7 +5525,7 @@ const setupAggregateBatchingTestSuite = ({ name, createAdapter, oversizedRows })
4039
5525
  expect(await snapshot(second.db)).toEqual(await expected(48));
4040
5526
  }, 3e5);
4041
5527
  it("applies a log row larger than one write in parts, each change once", async () => {
4042
- const { db, flush } = server(await store(), { mode: "log" });
5528
+ const { db, flush } = server(await store(), {});
4043
5529
  await db.transaction(async (tx) => {
4044
5530
  for (let day = 1; day <= oversizedRows; day += 1) tx.aggregate("opens", { day }, { opens: day }, { shardBy: "i" });
4045
5531
  });
@@ -4231,18 +5717,13 @@ const createPluginTestHarness = async (plugin, options = {}) => {
4231
5717
  * bundles through the engine. A patch's base comes before it in `bundles`.
4232
5718
  */
4233
5719
  const storeBundles = async (database, bundles) => {
4234
- const engine = createEngine(database);
4235
- try {
4236
- await engine.core.transaction(async (tx) => {
4237
- for (const bundle of bundles) {
4238
- tx.create("bundles", bundleToRow(bundle));
4239
- for (const platformKey of [bundle.platform, "*"]) tx.aggregate("bundle_totals", { platform_key: platformKey }, { bundles: 1 });
4240
- for (const row of bundleToPatchRows(bundle)) tx.create("bundle_patches", row);
4241
- }
4242
- });
4243
- } finally {
4244
- await engine.dispose();
4245
- }
5720
+ await createEngine(database).core.transaction(async (tx) => {
5721
+ for (const bundle of bundles) {
5722
+ tx.create("bundles", bundleToRow(bundle));
5723
+ for (const platformKey of [bundle.platform, "*"]) tx.aggregate("bundle_totals", { platform_key: platformKey }, { bundles: 1 });
5724
+ for (const row of bundleToPatchRows(bundle)) tx.create("bundle_patches", row);
5725
+ }
5726
+ });
4246
5727
  };
4247
5728
  //#endregion
4248
5729
  //#region src/insights/expectInsightsIndex.ts
@@ -4285,6 +5766,336 @@ const createBundleEventRowFixture = (suffix, receivedAtMs) => ({
4285
5766
  received_at_ms: receivedAtMs
4286
5767
  });
4287
5768
  //#endregion
5769
+ //#region src/insights/insights11.ts
5770
+ const HOUR$1 = 36e5;
5771
+ const DAY$1 = 864e5;
5772
+ /**
5773
+ * The refs a 1.1 server wrote: each names the artifact. A frozen copy of
5774
+ * 1.1's `bundleRefsOf`, so the fixture writes rows as 1.1 did.
5775
+ */
5776
+ const artifactRefsOf = (row) => {
5777
+ const metadata = row.metadata;
5778
+ if (metadata.late === true) return [];
5779
+ if (row.type === "UPDATE_FAILED" && metadata.failure?.stage === "check") return [];
5780
+ if (row.type === "RECOVERED") return [`from:${row.from_bundle_id}`];
5781
+ if (row.type === "UNCHANGED") {
5782
+ const kinds = metadata.change?.kinds ?? [];
5783
+ return kinds.includes("bundle") && !kinds.includes("first_seen") && row.to_release_id !== null ? [`on:${row.to_bundle_id}`] : [];
5784
+ }
5785
+ return [`to:${row.to_bundle_id}`];
5786
+ };
5787
+ /**
5788
+ * Insights' raw events and outcome counters as 1.1 declared them, which a
5789
+ * 1.1 server writes: the same tables, columns, and indexes, with refs that
5790
+ * name the artifact.
5791
+ */
5792
+ const insights11Schema = {
5793
+ bundle_events: defineTable({
5794
+ id: {
5795
+ type: "string",
5796
+ maxLength: 36
5797
+ },
5798
+ type: {
5799
+ type: "string",
5800
+ maxLength: 32
5801
+ },
5802
+ install_id: {
5803
+ type: "string",
5804
+ maxLength: 255
5805
+ },
5806
+ user_id: {
5807
+ type: "string",
5808
+ maxLength: 255,
5809
+ required: false
5810
+ },
5811
+ from_release_id: {
5812
+ type: "string",
5813
+ maxLength: 36,
5814
+ required: false
5815
+ },
5816
+ from_bundle_id: {
5817
+ type: "string",
5818
+ maxLength: 36,
5819
+ required: false
5820
+ },
5821
+ to_release_id: {
5822
+ type: "string",
5823
+ maxLength: 36,
5824
+ required: false
5825
+ },
5826
+ to_bundle_id: {
5827
+ type: "string",
5828
+ maxLength: 36
5829
+ },
5830
+ platform: {
5831
+ type: "string",
5832
+ maxLength: 16
5833
+ },
5834
+ app_version: { type: "string" },
5835
+ channel: { type: "string" },
5836
+ metadata: { type: "json" },
5837
+ received_at_ms: { type: "integer" }
5838
+ }, {
5839
+ key: ["id"],
5840
+ derived: {
5841
+ day: {
5842
+ type: "integer",
5843
+ compute: (row) => row.received_at_ms - row.received_at_ms % DAY$1
5844
+ },
5845
+ movement_install_id: {
5846
+ type: "string",
5847
+ compute: (row) => row.install_id
5848
+ },
5849
+ bundle_ref: {
5850
+ type: "string",
5851
+ multi: true,
5852
+ compute: (row) => artifactRefsOf(row)
5853
+ }
5854
+ },
5855
+ indexes: {
5856
+ movementsByInstall: {
5857
+ eq: ["movement_install_id"],
5858
+ sort: ["received_at_ms"]
5859
+ },
5860
+ byBundle: {
5861
+ eq: [
5862
+ "platform",
5863
+ "channel",
5864
+ "type",
5865
+ "bundle_ref",
5866
+ "day"
5867
+ ],
5868
+ sort: ["received_at_ms"]
5869
+ },
5870
+ byDay: {
5871
+ eq: ["day"],
5872
+ sort: ["received_at_ms"]
5873
+ }
5874
+ },
5875
+ retention: {
5876
+ field: "day",
5877
+ days: 90
5878
+ }
5879
+ }),
5880
+ insights_outcomes: defineAggregate({
5881
+ platform: {
5882
+ type: "string",
5883
+ maxLength: 16
5884
+ },
5885
+ channel: { type: "string" },
5886
+ type: {
5887
+ type: "string",
5888
+ maxLength: 32
5889
+ },
5890
+ bundle_ref: {
5891
+ type: "string",
5892
+ maxLength: 41
5893
+ },
5894
+ bucket_start_ms: { type: "integer" }
5895
+ }, {
5896
+ key: [
5897
+ "platform",
5898
+ "channel",
5899
+ "type",
5900
+ "bundle_ref",
5901
+ "bucket_start_ms"
5902
+ ],
5903
+ counters: ["events"],
5904
+ shards: 8,
5905
+ batched: true,
5906
+ indexes: { byRef: {
5907
+ eq: [
5908
+ "platform",
5909
+ "channel",
5910
+ "type",
5911
+ "bundle_ref"
5912
+ ],
5913
+ sort: ["bucket_start_ms"]
5914
+ } },
5915
+ retention: {
5916
+ field: "bucket_start_ms",
5917
+ days: 90
5918
+ }
5919
+ })
5920
+ };
5921
+ /**
5922
+ * A 1.1 server's `insights()` as far as the release-ref backfill reads it:
5923
+ * its API's `record(row)` stores an event and counts its outcome hours by
5924
+ * artifact, as 1.1's `countOutcome` did, to test the backfill and `db
5925
+ * migrate` on rows a 1.1 server wrote. It stands in for the official
5926
+ * plugin, so it takes its id and brand; serve it over a database whose
5927
+ * Insights tables `insights()` created.
5928
+ */
5929
+ const insights11TestPlugin = () => Object.defineProperty(definePlugin({
5930
+ id: "insights",
5931
+ namespace: false,
5932
+ schemaVersion: "1.0.0",
5933
+ schema: insights11Schema,
5934
+ init: ({ db }) => ({ api: { record: (event) => db.transaction(async (tx) => {
5935
+ tx.create("bundle_events", event);
5936
+ const hour = (type, ref) => tx.aggregate("insights_outcomes", {
5937
+ platform: event.platform,
5938
+ channel: event.channel,
5939
+ type,
5940
+ bundle_ref: ref,
5941
+ bucket_start_ms: event.received_at_ms - event.received_at_ms % HOUR$1
5942
+ }, { events: 1 }, { shardBy: event.install_id });
5943
+ for (const ref of artifactRefsOf(event)) hour(event.type, ref);
5944
+ if (event.metadata.implied_download === true) hour("UPDATE_DOWNLOADED", `to:${event.type === "RECOVERED" ? event.from_bundle_id : event.to_bundle_id}`);
5945
+ tx.aggregate("insights_outcomes", {
5946
+ platform: "*",
5947
+ channel: "",
5948
+ type: "",
5949
+ bundle_ref: "",
5950
+ bucket_start_ms: event.received_at_ms - event.received_at_ms % DAY$1
5951
+ }, { events: 1 }, { shardBy: event.install_id });
5952
+ }) } })
5953
+ }), Symbol.for("@hot-updater/server/official-plugin"), { value: true });
5954
+ //#endregion
5955
+ //#region src/insights/insightsBackfillTests.ts
5956
+ const HOUR = 36e5;
5957
+ const DAY = 864e5;
5958
+ /**
5959
+ * The backfill of a 1.1 server's rows, on one database: `createApi(database,
5960
+ * plugin)` serves `plugin`, `insights()` when omitted, over it, and returns
5961
+ * its API.
5962
+ */
5963
+ const registerInsightsBackfillTests = (context) => {
5964
+ describe("Insights release-ref backfill", () => {
5965
+ it("moves a 1.1 server's artifact-keyed events and counts to their releases, once, and again after a 1.1 server writes more", async () => {
5966
+ const database = context.getDatabase();
5967
+ const legacy = context.createApi(database, insights11TestPlugin());
5968
+ const api = context.createApi(database);
5969
+ const base = Date.now() - Date.now() % HOUR - 6 * HOUR;
5970
+ const artifactA = createBundleEventRowFixture("9850", 0).to_bundle_id;
5971
+ const artifactB = createBundleEventRowFixture("9851", 0).to_bundle_id;
5972
+ const builtin = createBundleEventRowFixture("9852", 0).to_bundle_id;
5973
+ const v3 = "00000000-0000-7000-8000-000000009853";
5974
+ const v4 = "00000000-0000-7000-8000-000000009854";
5975
+ const v5 = "00000000-0000-7000-8000-000000009855";
5976
+ const event = (suffix, at, installId, fields) => ({
5977
+ ...createBundleEventRowFixture(suffix, base + at),
5978
+ install_id: installId,
5979
+ ...fields
5980
+ });
5981
+ const crash = (suffix, at, installId) => event(suffix, at, installId, {
5982
+ type: "RECOVERED",
5983
+ from_bundle_id: artifactA,
5984
+ from_release_id: v3,
5985
+ to_bundle_id: artifactB,
5986
+ to_release_id: v4
5987
+ });
5988
+ const onV3 = {
5989
+ to_bundle_id: artifactA,
5990
+ to_release_id: v3
5991
+ };
5992
+ const onV5 = {
5993
+ to_bundle_id: artifactA,
5994
+ to_release_id: v5
5995
+ };
5996
+ const events = [
5997
+ event("9860", 0, "backfill-1", onV3),
5998
+ event("9861", 1, "backfill-2", onV3),
5999
+ crash("9862", HOUR, "backfill-1"),
6000
+ {
6001
+ ...crash("9863", 3600001, "backfill-2"),
6002
+ metadata: {
6003
+ ...createBundleEventRowFixture("9863", 0).metadata,
6004
+ implied_download: true
6005
+ }
6006
+ },
6007
+ event("9864", 2 * HOUR, "backfill-3", onV5),
6008
+ event("9865", 7200001, "backfill-4", onV5),
6009
+ event("9866", 7200002, "backfill-5", onV5),
6010
+ event("9867", 3 * HOUR, "backfill-6", { to_bundle_id: builtin })
6011
+ ];
6012
+ for (const row of events) await legacy.record(row);
6013
+ const scope = {
6014
+ platform: "ios",
6015
+ channel: "production"
6016
+ };
6017
+ const count = (filter) => api.countEvents({
6018
+ filter,
6019
+ sinceMs: base - DAY,
6020
+ beforeReceivedAtMs: base + DAY
6021
+ });
6022
+ const launched = (id) => ({
6023
+ ...scope,
6024
+ type: "UPDATE_APPLIED",
6025
+ toReleaseId: id
6026
+ });
6027
+ const crashed = (id) => ({
6028
+ ...scope,
6029
+ type: "RECOVERED",
6030
+ fromReleaseId: id
6031
+ });
6032
+ const downloaded = (id) => ({
6033
+ ...scope,
6034
+ type: "UPDATE_DOWNLOADED",
6035
+ toReleaseId: id
6036
+ });
6037
+ await expectInsightsIndex(() => count(launched(artifactA)), 5);
6038
+ await expect(count(launched(v3))).resolves.toBe(0);
6039
+ await expectInsightsIndex(() => api.backfillReleaseRefs({ dryRun: true }), { events: 7 });
6040
+ await expect(api.backfillReleaseRefs()).resolves.toEqual({ events: 7 });
6041
+ await expectInsightsIndex(() => count(launched(v3)), 2);
6042
+ await expectInsightsIndex(() => count(launched(v5)), 3);
6043
+ await expectInsightsIndex(() => count(crashed(v3)), 2);
6044
+ await expectInsightsIndex(() => count(crashed(v5)), 0);
6045
+ await expectInsightsIndex(() => count(downloaded(v3)), 1);
6046
+ await expectInsightsIndex(() => count(launched(builtin)), 1);
6047
+ await expectInsightsIndex(() => count(launched(artifactA)), 0);
6048
+ await expectInsightsIndex(() => count(crashed(artifactA)), 0);
6049
+ await expectInsightsIndex(() => count(downloaded(artifactA)), 0);
6050
+ await expectInsightsIndex(() => api.listEvents({
6051
+ filter: {
6052
+ kind: "bundle",
6053
+ ...crashed(v3)
6054
+ },
6055
+ sinceMs: base - DAY,
6056
+ beforeReceivedAtMs: base + DAY,
6057
+ limit: 10
6058
+ }).then((rows) => rows.map(({ install_id }) => install_id)), ["backfill-2", "backfill-1"]);
6059
+ await expectInsightsIndex(() => api.backfillReleaseRefs({ dryRun: true }), { events: 0 });
6060
+ await expect(api.backfillReleaseRefs()).resolves.toEqual({ events: 0 });
6061
+ await legacy.record(event("9868", 4 * HOUR, "backfill-7", onV5));
6062
+ await expectInsightsIndex(() => count(launched(artifactA)), 1);
6063
+ await expect(count(launched(v5))).resolves.toBe(3);
6064
+ await expectInsightsIndex(() => api.backfillReleaseRefs({ dryRun: true }), { events: 1 });
6065
+ await expect(api.backfillReleaseRefs()).resolves.toEqual({ events: 1 });
6066
+ await expectInsightsIndex(() => count(launched(v5)), 4);
6067
+ await expectInsightsIndex(() => count(launched(artifactA)), 0);
6068
+ });
6069
+ it("moves a day of more stale events than one transaction of the store holds", async () => {
6070
+ const database = context.getDatabase();
6071
+ const legacy = context.createApi(database, insights11TestPlugin());
6072
+ const api = context.createApi(database);
6073
+ const base = Date.now() - Date.now() % HOUR - 2 * HOUR;
6074
+ const release = "00000000-0000-7000-8000-000000009880";
6075
+ const artifact = createBundleEventRowFixture("9881", 0).to_bundle_id;
6076
+ const count = 40;
6077
+ for (let n = 0; n < count; n += 1) await legacy.record({
6078
+ ...createBundleEventRowFixture(String(9900 + n), base + n),
6079
+ install_id: `backfill-day-${n}`,
6080
+ to_bundle_id: artifact,
6081
+ to_release_id: release
6082
+ });
6083
+ await expect(api.backfillReleaseRefs()).resolves.toEqual({ events: count });
6084
+ await expectInsightsIndex(() => api.countEvents({
6085
+ filter: {
6086
+ platform: "ios",
6087
+ channel: "production",
6088
+ type: "UPDATE_APPLIED",
6089
+ toReleaseId: release
6090
+ },
6091
+ sinceMs: base - DAY,
6092
+ beforeReceivedAtMs: base + DAY
6093
+ }), count);
6094
+ await expect(api.backfillReleaseRefs({ dryRun: true })).resolves.toEqual({ events: 0 });
6095
+ });
6096
+ });
6097
+ };
6098
+ //#endregion
4288
6099
  //#region src/insights/insightsModelTests.ts
4289
6100
  const record = (model, event) => model.recordEvent({ event });
4290
6101
  const createMovementEvent = (suffix, receivedAtMs, type, installId) => {
@@ -4352,7 +6163,7 @@ const registerInsightsModelTests = (state) => {
4352
6163
  filter: {
4353
6164
  kind: "bundle",
4354
6165
  type: "UPDATE_DOWNLOADED",
4355
- toBundleId: download.to_bundle_id,
6166
+ toReleaseId: download.to_release_id,
4356
6167
  platform: "ios",
4357
6168
  channel: "production"
4358
6169
  },
@@ -4569,12 +6380,12 @@ const registerInsightsModelTests = (state) => {
4569
6380
  platform: "ios",
4570
6381
  channel: "production",
4571
6382
  type: "UPDATE_APPLIED",
4572
- toBundleId: bundleB
6383
+ toReleaseId: bundleB
4573
6384
  }, applied], [{
4574
6385
  platform: "ios",
4575
6386
  channel: "production",
4576
6387
  type: "RECOVERED",
4577
- fromBundleId: bundleB
6388
+ fromReleaseId: bundleB
4578
6389
  }, recovered]];
4579
6390
  for (const [filter, expected] of cases) {
4580
6391
  await expectInsightsIndex(() => model.countEvents({
@@ -4621,25 +6432,11 @@ const registerInsightsModelTests = (state) => {
4621
6432
  platform: "ios",
4622
6433
  channel: "production",
4623
6434
  type: "UNCHANGED",
4624
- toBundleId: bundleB
6435
+ toReleaseId: bundleB
4625
6436
  },
4626
6437
  sinceMs: 100,
4627
6438
  beforeReceivedAtMs: 200
4628
6439
  }), 0);
4629
- await expectInsightsIndex(() => model.countLatestEvents({
4630
- platform: "ios",
4631
- channel: "production",
4632
- sinceMs: 0,
4633
- bundle: [{
4634
- field: "to_bundle_id",
4635
- value: bundleA,
4636
- types: [
4637
- "UNCHANGED",
4638
- "UPDATE_APPLIED",
4639
- "RECOVERED"
4640
- ]
4641
- }]
4642
- }), 1);
4643
6440
  await expectInsightsIndex(() => model.countLatestEvents({
4644
6441
  platform: "ios",
4645
6442
  channel: "production",
@@ -4704,40 +6501,127 @@ const registerInsightsModelTests = (state) => {
4704
6501
  await expect(model.findLatestEvents({ installId: "install-a " })).resolves.toEqual([events[3]]);
4705
6502
  await expect(model.findLatestEvents({ installId: "install-a" })).resolves.toEqual([events[2]]);
4706
6503
  });
4707
- it("counts overlapping bundle predicates once per latest installation", async () => {
6504
+ it("counts one release's latest installations: a download's source, and the target of anything else", async () => {
4708
6505
  const model = state.getDatabase();
4709
- const event = createBundleEventRowFixture("9700", 100);
4710
- await record(model, event);
4711
- const predicate = {
4712
- field: "to_bundle_id",
4713
- value: event.to_bundle_id,
4714
- types: [event.type]
6506
+ const releaseA = "00000000-0000-7000-8000-000000009702";
6507
+ const releaseB = "00000000-0000-7000-8000-000000009703";
6508
+ const applied = {
6509
+ ...createBundleEventRowFixture("9700", 100),
6510
+ to_release_id: releaseA
4715
6511
  };
4716
- await expectInsightsIndex(() => model.countLatestEvents({
4717
- platform: event.platform,
4718
- channel: event.channel,
4719
- sinceMs: 0,
4720
- bundle: [predicate, predicate]
4721
- }), 1);
6512
+ const downloaded = {
6513
+ ...createBundleEventRowFixture("9701", 100),
6514
+ type: "UPDATE_DOWNLOADED",
6515
+ from_release_id: releaseA,
6516
+ to_release_id: releaseB
6517
+ };
6518
+ await record(model, applied);
6519
+ await record(model, downloaded);
6520
+ const scope = {
6521
+ platform: "ios",
6522
+ channel: "production",
6523
+ sinceMs: 0
6524
+ };
6525
+ const count = (releaseId) => releaseId === void 0 ? model.countLatestEvents(scope) : model.countReleaseInstallations({
6526
+ ...scope,
6527
+ releaseId
6528
+ }).then(({ release }) => release);
6529
+ await expectInsightsIndex(() => count(releaseA), 2);
6530
+ await expectInsightsIndex(() => count(releaseB), 0);
6531
+ await expectInsightsIndex(() => count(), 2);
4722
6532
  });
4723
- it("counts a latest installation once when a from and a to predicate both match it", async () => {
6533
+ it("keeps two releases of one artifact in one scope apart, as a promote back into the channel makes them", async () => {
4724
6534
  const model = state.getDatabase();
4725
- const moved = createBundleEventRowFixture("9701", 100);
4726
- await record(model, moved);
4727
- await expectInsightsIndex(() => model.countLatestEvents({
4728
- platform: moved.platform,
4729
- channel: moved.channel,
6535
+ const artifactA = createBundleEventRowFixture("9750", 0).to_bundle_id;
6536
+ const artifactB = createBundleEventRowFixture("9751", 0).to_bundle_id;
6537
+ const v3 = "00000000-0000-7000-8000-000000009753";
6538
+ const v4 = "00000000-0000-7000-8000-000000009754";
6539
+ const v5 = "00000000-0000-7000-8000-000000009755";
6540
+ const event = (suffix, receivedAtMs, installId, fields) => ({
6541
+ ...createBundleEventRowFixture(suffix, receivedAtMs),
6542
+ install_id: installId,
6543
+ ...fields
6544
+ });
6545
+ const onV3 = {
6546
+ to_bundle_id: artifactA,
6547
+ to_release_id: v3
6548
+ };
6549
+ const onV5 = {
6550
+ to_bundle_id: artifactA,
6551
+ to_release_id: v5
6552
+ };
6553
+ const events = [
6554
+ event("9760", 100, "abba-1", onV3),
6555
+ event("9761", 110, "abba-2", onV3),
6556
+ event("9762", 120, "abba-1", {
6557
+ type: "RECOVERED",
6558
+ from_bundle_id: artifactA,
6559
+ from_release_id: v3,
6560
+ to_bundle_id: artifactB,
6561
+ to_release_id: v4
6562
+ }),
6563
+ event("9763", 130, "abba-2", {
6564
+ type: "RECOVERED",
6565
+ from_bundle_id: artifactA,
6566
+ from_release_id: v3,
6567
+ to_bundle_id: artifactB,
6568
+ to_release_id: v4
6569
+ }),
6570
+ event("9764", 200, "abba-3", onV5),
6571
+ event("9765", 210, "abba-4", onV5),
6572
+ event("9766", 220, "abba-5", onV5)
6573
+ ];
6574
+ for (const row of events) await record(model, row);
6575
+ const scope = {
6576
+ platform: "ios",
6577
+ channel: "production"
6578
+ };
6579
+ const count = (filter) => model.countEvents({
6580
+ filter,
4730
6581
  sinceMs: 0,
4731
- bundle: [{
4732
- field: "from_bundle_id",
4733
- value: moved.from_bundle_id,
4734
- types: [moved.type]
4735
- }, {
4736
- field: "to_bundle_id",
4737
- value: moved.to_bundle_id,
4738
- types: [moved.type]
4739
- }]
4740
- }), 1);
6582
+ beforeReceivedAtMs: 1e3
6583
+ });
6584
+ const series = (filter) => model.countEventSeries({
6585
+ filter,
6586
+ timeRange: {
6587
+ start: 0,
6588
+ end: 36e5
6589
+ },
6590
+ intervalMs: 36e5
6591
+ }).then((points) => points.map(({ events }) => events));
6592
+ const launched = (release) => ({
6593
+ ...scope,
6594
+ type: "UPDATE_APPLIED",
6595
+ toReleaseId: release
6596
+ });
6597
+ const crashed = (release) => ({
6598
+ ...scope,
6599
+ type: "RECOVERED",
6600
+ fromReleaseId: release
6601
+ });
6602
+ await expectInsightsIndex(() => count(launched(v3)), 2);
6603
+ await expectInsightsIndex(() => count(launched(v5)), 3);
6604
+ await expectInsightsIndex(() => count(crashed(v3)), 2);
6605
+ await expectInsightsIndex(() => count(crashed(v5)), 0);
6606
+ await expectInsightsIndex(() => series(launched(v5)), [3]);
6607
+ await expectInsightsIndex(() => series(crashed(v5)), [0]);
6608
+ await expectInsightsIndex(() => series(crashed(v3)), [2]);
6609
+ const installations = (releaseId) => model.countReleaseInstallations({
6610
+ ...scope,
6611
+ sinceMs: 0,
6612
+ releaseId
6613
+ }).then(({ release }) => release);
6614
+ await expectInsightsIndex(() => installations(v5), 3);
6615
+ await expectInsightsIndex(() => installations(v4), 2);
6616
+ await expectInsightsIndex(() => installations(v3), 0);
6617
+ await expectInsightsIndex(() => model.listEvents({
6618
+ filter: {
6619
+ kind: "bundle",
6620
+ ...crashed(v3)
6621
+ },
6622
+ beforeReceivedAtMs: 1e3,
6623
+ limit: 10
6624
+ }).then((rows) => rows.map(({ install_id }) => install_id)), ["abba-2", "abba-1"]);
4741
6625
  });
4742
6626
  it("returns zero for successful empty scalar queries", async () => {
4743
6627
  const model = state.getDatabase();
@@ -4751,7 +6635,7 @@ const registerInsightsModelTests = (state) => {
4751
6635
  platform: "ios",
4752
6636
  channel: "production",
4753
6637
  type: "RECOVERED",
4754
- fromBundleId: createBundleEventRowFixture("1", 0).to_bundle_id
6638
+ fromReleaseId: "00000000-0000-7000-8000-000000003001"
4755
6639
  },
4756
6640
  sinceMs: 0,
4757
6641
  beforeReceivedAtMs: 100
@@ -4836,12 +6720,12 @@ const registerInsightsModelTests = (state) => {
4836
6720
  await expectInsightsIndex(() => hourly({
4837
6721
  ...scope,
4838
6722
  type: "UPDATE_APPLIED",
4839
- toBundleId: base.to_bundle_id
6723
+ toReleaseId: releaseB
4840
6724
  }), points(2, 0, 0));
4841
6725
  await expectInsightsIndex(() => hourly({
4842
6726
  ...scope,
4843
6727
  type: "RECOVERED",
4844
- fromBundleId: base.to_bundle_id
6728
+ fromReleaseId: releaseB
4845
6729
  }), points(1, 0, 0));
4846
6730
  const usage = await model.getAppUsage({
4847
6731
  channel: "production",
@@ -4916,6 +6800,14 @@ const registerInsightsModelTests = (state) => {
4916
6800
  installations: 1
4917
6801
  }]));
4918
6802
  expect(usage.bundleDistribution).toHaveLength(2);
6803
+ const installations = (releaseId) => model.countReleaseInstallations({
6804
+ channel,
6805
+ platform: "ios",
6806
+ sinceMs: 0,
6807
+ releaseId
6808
+ }).then(({ release }) => release);
6809
+ await expectInsightsIndex(() => installations(builtin), 2);
6810
+ await expect(installations(createBundleEventRowFixture("9905", 0).id)).resolves.toBe(0);
4919
6811
  });
4920
6812
  it("pages insights events newest first with a stable cursor", async () => {
4921
6813
  const model = state.getDatabase();
@@ -5059,7 +6951,7 @@ const registerInsightsModelTests = (state) => {
5059
6951
  platform: "ios",
5060
6952
  channel: "production",
5061
6953
  type: "UNCHANGED",
5062
- toBundleId: base.to_bundle_id
6954
+ toReleaseId: releaseB
5063
6955
  },
5064
6956
  sinceMs: 0,
5065
6957
  beforeReceivedAtMs: 2 * day
@@ -5168,11 +7060,11 @@ const registerInsightsModelTests = (state) => {
5168
7060
  await expectInsightsIndex(async () => await count({
5169
7061
  ...scope,
5170
7062
  type: "UPDATE_APPLIED",
5171
- toBundleId: bundleB
7063
+ toReleaseId: releaseB
5172
7064
  }) + await count({
5173
7065
  ...scope,
5174
7066
  type: "UNCHANGED",
5175
- toBundleId: bundleB
7067
+ toReleaseId: releaseB
5176
7068
  }), metrics.applies);
5177
7069
  const implied = (await model.listEvents({
5178
7070
  filter: { kind: "all" },
@@ -5182,7 +7074,7 @@ const registerInsightsModelTests = (state) => {
5182
7074
  await expectInsightsIndex(() => count({
5183
7075
  ...scope,
5184
7076
  type: "UPDATE_DOWNLOADED",
5185
- toBundleId: bundleB
7077
+ toReleaseId: releaseB
5186
7078
  }), metrics.downloads);
5187
7079
  expect(implied).toBe(2);
5188
7080
  expect(metrics.downloads).toBeGreaterThanOrEqual(metrics.applies + metrics.failedLaunches);
@@ -5243,11 +7135,11 @@ const registerInsightsModelTests = (state) => {
5243
7135
  platform: "ios",
5244
7136
  channel: "production"
5245
7137
  };
5246
- for (const [toBundleId, listed] of [[download.to_bundle_id, [download]], [check.to_bundle_id, []]]) {
7138
+ for (const [toReleaseId, listed] of [[download.to_bundle_id, [download]], [check.to_bundle_id, []]]) {
5247
7139
  const filter = {
5248
7140
  ...scope,
5249
7141
  type: "UPDATE_FAILED",
5250
- toBundleId
7142
+ toReleaseId
5251
7143
  };
5252
7144
  await expectInsightsIndex(() => model.listEvents({
5253
7145
  filter: {
@@ -5309,6 +7201,7 @@ const setupInsightsHttpTestSuite = (options) => {
5309
7201
  installId,
5310
7202
  latestStatus: "UNCHANGED",
5311
7203
  lastKnownBundleId: event.toBundleId,
7204
+ lastKnownReleaseId: null,
5312
7205
  channel
5313
7206
  });
5314
7207
  await expectInsightsIndex(async () => {
@@ -5490,19 +7383,26 @@ const setupInsightsModelTestSuite = (lifecycle) => {
5490
7383
  //#region src/insights/index.ts
5491
7384
  /**
5492
7385
  * The Insights plugin's tests, for `setupDatabaseTestSuite`'s `plugins`: its
5493
- * HTTP routes on the provider's server, which must run `insights()`, and
5494
- * with `createModel` its report contract on the provider's database, such as
7386
+ * HTTP routes on the provider's server, which must run `insights()`; with
7387
+ * `createModel` its report contract on the provider's database, such as
5495
7388
  * `(database) => createInsightsModel(createHotUpdater({ database, storage,
5496
- * plugins: [insights()], clientAccess: "public" }).api.insights)`.
7389
+ * plugins: [insights()], clientAccess: "public" }).api.insights)`; and with
7390
+ * `createApi` the backfill of a 1.1 server's rows, such as `(database,
7391
+ * plugin = insights()) => createHotUpdater({ database, storage, plugins:
7392
+ * [plugin], clientAccess: "public" }).api.insights`.
5497
7393
  */
5498
7394
  const insightsTestSuite = (options = {}) => ({
5499
7395
  name: "Insights plugin",
5500
7396
  register: (context) => {
5501
7397
  setupInsightsHttpTestSuite({ getClient: context.getClient });
5502
- const { createModel } = options;
7398
+ const { createModel, createApi } = options;
5503
7399
  if (createModel !== void 0) describe("Insights model", () => {
5504
7400
  registerInsightsModelTests({ getDatabase: () => createModel(context.getDatabase()) });
5505
7401
  });
7402
+ if (createApi !== void 0) registerInsightsBackfillTests({
7403
+ getDatabase: context.getDatabase,
7404
+ createApi: (database, plugin) => createApi(database, plugin)
7405
+ });
5506
7406
  }
5507
7407
  });
5508
7408
  //#endregion
@@ -5662,4 +7562,61 @@ async function startHttpTestServer(handlers) {
5662
7562
  };
5663
7563
  }
5664
7564
  //#endregion
5665
- export { RELEASE_CATALOG_DOWNLOAD_HASH, RELEASE_CATALOG_MANIFEST_URIS, RELEASE_CATALOG_STORAGE_FIXTURES, conformanceCounters, conformanceExpiring, conformanceItems, createAdminApiTestClient, createBundleEventRowFixture, createBundleFixture, createBundlePatchRowFixture, createBundleRowFixture, createChannelRowFixture, createHandlerHttpTestClient, createHttpTestClient, createMeasuredDatabase, createMemoryKeyValueStore, createPluginTestHarness, createReleaseCatalogTestStorage, createReleaseRowFixture, expectInsightsIndex, insightsTestSuite, jsonRequest, mysqlRowsExamined, postgresRowsExamined, releaseCatalogArtifact, releaseCatalogArtifactFiles, releaseCatalogDownloadUrl, runContentionHarness, setupAggregateBatchingTestSuite, setupBundleMethodsTestSuite, setupCoreAdminTestSuite, setupDatabaseAdapterConformanceSuite, setupDatabaseTestSuite, setupInsightsHttpTestSuite, setupInsightsModelTestSuite, setupReadBudgetTestSuite, setupReleaseCatalogTestSuite, setupSemverSatisfiesTestSuite, setupStorageAdapterTestSuite, startHttpTestServer, storeBundles, toDeployBundle, withAdapterLatency };
7565
+ //#region src/capacityCappedStore.ts
7566
+ /**
7567
+ * DynamoDB's price of one op in `TransactWriteItems`: 2 write units per
7568
+ * started KB of the item.
7569
+ */
7570
+ const unitsOf = (op) => {
7571
+ const item = op.type === "put" ? op.value : op.type === "add" ? {
7572
+ ...op.init,
7573
+ ...op.by
7574
+ } : {};
7575
+ const bytes = new TextEncoder().encode(JSON.stringify([
7576
+ op.key.pk,
7577
+ op.key.sk,
7578
+ item
7579
+ ])).length;
7580
+ return 2 * Math.max(1, Math.ceil(bytes / 1024));
7581
+ };
7582
+ /**
7583
+ * `store` behind a strict write-capacity cap: a token bucket refilled at
7584
+ * `unitsPerSecond` on a virtual clock, holding one second of units, with
7585
+ * writes priced as DynamoDB prices transactional ones. A write that costs
7586
+ * more than the bucket holds is refused as DynamoDB's store reports a
7587
+ * throttle, `{ ok: false, retry: true }`, so one costing more than a second
7588
+ * of capacity is never admitted. DynamoDB with
7589
+ * `OnDemandThroughput.MaxWriteRequestUnits` is looser, since it admits such a
7590
+ * write from burst capacity when it has some and refuses by time window
7591
+ * otherwise; the strict cap makes a transaction too large for the cap fail
7592
+ * every time instead of by chance. Reads and `deleteConsumed` are not capped.
7593
+ */
7594
+ const createCapacityCappedStore = (store, { unitsPerSecond, writeMs = 300, throttledMs = 3e3 }) => {
7595
+ let clock = 0;
7596
+ let filledAt = 0;
7597
+ let units = unitsPerSecond;
7598
+ let throttles = 0;
7599
+ return {
7600
+ ...store,
7601
+ throttles: () => throttles,
7602
+ async write(ops) {
7603
+ units = Math.min(unitsPerSecond, units + (clock - filledAt) / 1e3 * unitsPerSecond);
7604
+ filledAt = clock;
7605
+ const cost = ops.reduce((sum, op) => sum + unitsOf(op), 0);
7606
+ if (cost > units) {
7607
+ throttles += 1;
7608
+ clock += throttledMs;
7609
+ return {
7610
+ ok: false,
7611
+ retry: true
7612
+ };
7613
+ }
7614
+ const result = await store.write(ops);
7615
+ units -= cost;
7616
+ clock += writeMs;
7617
+ return result;
7618
+ }
7619
+ };
7620
+ };
7621
+ //#endregion
7622
+ export { LATER_RELEASE_CATALOG_FIELD, RELEASE_CATALOG_DOWNLOAD_HASH, RELEASE_CATALOG_MANIFEST_URIS, RELEASE_CATALOG_STORAGE_FIXTURES, conformanceCounters, conformanceExpiring, conformanceItems, createAdminApiTestClient, createBundleEventRowFixture, createBundleFixture, createBundlePatchRowFixture, createBundleRowFixture, createCapacityCappedStore, createChannelRowFixture, createHandlerHttpTestClient, createHttpTestClient, createMeasuredDatabase, createMemoryKeyValueStore, createPluginTestHarness, createReleaseCatalogTestStorage, createReleaseRowFixture, expectInsightsIndex, insights11TestPlugin, insightsTestSuite, jsonRequest, mysqlRowsExamined, postgresRowsExamined, releaseCatalogArtifact, releaseCatalogArtifactFiles, releaseCatalogDownloadUrl, runContentionHarness, setupAggregateBatchingTestSuite, setupBundleMethodsTestSuite, setupCoreAdminTestSuite, setupDatabaseAdapterConformanceSuite, setupDatabaseTestSuite, setupInsightsHttpTestSuite, setupInsightsModelTestSuite, setupReadBudgetTestSuite, setupReleaseCatalogTestSuite, setupReleaseLabelEngineTestSuite, setupReleaseLabelTestSuite, setupSemverSatisfiesTestSuite, setupStorageAdapterTestSuite, startHttpTestServer, storeBundles, toDeployBundle, withAdapterLatency, writeCatalogFromLaterRelease };