@hot-updater/test-utils 1.2.0-rc.5 → 1.2.0-rc.50

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
@@ -238,9 +238,9 @@ const setupBundleMethodsTestSuite = (options) => {
238
238
  /**
239
239
  * Core's operations through admin API protocol 2 that the bundle and catalog
240
240
  * 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.
241
+ * bundle's patch children, the native build registry, and the iOS device
242
+ * registry. Each test deletes what it wrote, except a native build, which the
243
+ * registry keeps: its IDs and channel are the test's own.
244
244
  */
245
245
  const setupCoreAdminTestSuite = (options) => {
246
246
  describe("Core admin API", () => {
@@ -290,6 +290,72 @@ const setupCoreAdminTestSuite = (options) => {
290
290
  expect(missing.status).toBe(404);
291
291
  await missing.text();
292
292
  });
293
+ it("reads channels by ID and pages them by name", async () => {
294
+ const [a, b, c] = await Promise.all([
295
+ "a",
296
+ "b",
297
+ "c"
298
+ ].map((suffix) => api.ensureChannel(`page-${namespace}-${suffix}`)));
299
+ expect((await adminJson(`/channels?ids=${c.id},${a.id},${namespace}`)).data).toEqual([c, a]);
300
+ const first = await adminJson(`/channels?limit=2&cursor=${encodeURIComponent(`page-${namespace}-`)}`);
301
+ expect(first).toEqual({
302
+ data: [a, b],
303
+ next: b.name
304
+ });
305
+ const second = await adminJson(`/channels?limit=2&cursor=${encodeURIComponent(first.next)}`);
306
+ expect(second.data[0]).toEqual(c);
307
+ for (const channel of [
308
+ a,
309
+ b,
310
+ c
311
+ ]) {
312
+ const deleted = await admin(`/channels/${channel.id}`, jsonRequest("DELETE"));
313
+ expect(deleted.status).toBe(204);
314
+ await deleted.text();
315
+ }
316
+ });
317
+ it("lists every scope that has releases by keyset pages", async () => {
318
+ const deployed = [
319
+ await api.deploy({
320
+ bundle: toDeployBundle(bundleRow("21")),
321
+ release: policy("scopes-a")
322
+ }),
323
+ await api.deploy({
324
+ bundle: toDeployBundle(bundleRow("22")),
325
+ release: policy("scopes-a")
326
+ }),
327
+ await api.deploy({
328
+ bundle: toDeployBundle(bundleRow("23")),
329
+ release: policy("scopes-b")
330
+ })
331
+ ];
332
+ const scopeKeys = [];
333
+ for (let cursor;;) {
334
+ const page = await adminJson(`/release-scopes?limit=2${cursor === void 0 ? "" : `&cursor=${encodeURIComponent(cursor)}`}`);
335
+ scopeKeys.push(...page.data);
336
+ if (page.next === void 0) break;
337
+ expect(page.next).toBe(page.data.at(-1));
338
+ cursor = page.next;
339
+ }
340
+ expect(scopeKeys).toEqual([...new Set(scopeKeys)].sort());
341
+ expect(scopeKeys).toEqual(expect.arrayContaining([...new Set(deployed.map(({ scope_key }) => scope_key))]));
342
+ const refusals = await Promise.all(["/release-scopes?limit=101", "/release-scopes?order=desc"].map(async (path) => (await admin(path)).status));
343
+ expect(refusals).toEqual([400, 400]);
344
+ });
345
+ it("takes at most 100 IDs a request", async () => {
346
+ const ids = Array.from({ length: 101 }, () => crypto.randomUUID());
347
+ 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", {
348
+ buildId: crypto.randomUUID(),
349
+ ids
350
+ })), "Marking iOS devices in a build takes at most 100 ids a request."]];
351
+ expect(await Promise.all(refusals.map(async ([response]) => ({
352
+ status: response.status,
353
+ body: await response.json().catch(() => null)
354
+ })))).toEqual(refusals.map(([, error]) => ({
355
+ status: 400,
356
+ body: expect.objectContaining({ error })
357
+ })));
358
+ });
293
359
  it("keeps a release's channel when a delete races the deploy into it", async () => {
294
360
  const channel = await api.ensureChannel(`race-${namespace}`);
295
361
  const [deleted, release] = await Promise.all([admin(`/channels/${channel.id}`, jsonRequest("DELETE")), api.deploy({
@@ -434,6 +500,36 @@ const setupCoreAdminTestSuite = (options) => {
434
500
  destination: "testflight",
435
501
  version: "1.0.0 (7)"
436
502
  }))).data).toBeNull();
503
+ const androidBuiltIn = bundleRow("64");
504
+ const androidResponse = await admin("/native-builds", jsonRequest("POST", {
505
+ id: bundleRow("864").id,
506
+ platform: "android",
507
+ channel,
508
+ fingerprintHash: "android-fingerprint",
509
+ appVersion: null,
510
+ minBundleId: androidBuiltIn.id,
511
+ gitCommitHash: null,
512
+ buildKey: null,
513
+ buildNumber: "64",
514
+ artifact: {
515
+ kind: "aab",
516
+ storageUri: "storage://native-builds/android/64/app.aab",
517
+ byteSize: 1e3
518
+ },
519
+ embeddedBundle: {
520
+ manifestStorageUri: androidBuiltIn.manifest_storage_uri,
521
+ manifestFileHash: androidBuiltIn.manifest_file_hash,
522
+ assetBaseStorageUri: androidBuiltIn.asset_base_storage_uri
523
+ }
524
+ }));
525
+ expect(androidResponse.status).toBe(201);
526
+ await androidResponse.text();
527
+ const production = await admin(`/native-builds/${bundleRow("864").id}/submission`, jsonRequest("POST", {
528
+ destination: "play-production",
529
+ version: "1.0.0 (64)"
530
+ }));
531
+ expect(production.status).toBe(200);
532
+ expect((await production.json()).data.submitted_to).toBe("play-production");
437
533
  const wrongStore = await admin(`/native-builds/${newest.id}/submission`, jsonRequest("POST", {
438
534
  destination: "play-internal",
439
535
  version: "1.0.0 (7)"
@@ -455,6 +551,393 @@ const setupCoreAdminTestSuite = (options) => {
455
551
  const after = await adminJson("/bundles?limit=1&total=true");
456
552
  expect(after.total).toBe(before.total);
457
553
  });
554
+ it("marks one store build per native build scope, replacing and clearing it", async () => {
555
+ const channel = `store-build-${namespace}`;
556
+ const register = async (suffix, fingerprintHash) => {
557
+ const builtIn = bundleRow(suffix);
558
+ const response = await admin("/native-builds", jsonRequest("POST", {
559
+ id: bundleRow(`8${suffix}`).id,
560
+ platform: "ios",
561
+ channel,
562
+ fingerprintHash,
563
+ appVersion: null,
564
+ minBundleId: builtIn.id,
565
+ gitCommitHash: null,
566
+ buildKey: null,
567
+ buildNumber: suffix,
568
+ artifact: {
569
+ kind: "ipa",
570
+ storageUri: `storage://native-builds/ios/${suffix}/App.ipa`,
571
+ byteSize: 1e3
572
+ },
573
+ embeddedBundle: {
574
+ manifestStorageUri: builtIn.manifest_storage_uri,
575
+ manifestFileHash: builtIn.manifest_file_hash,
576
+ assetBaseStorageUri: builtIn.asset_base_storage_uri
577
+ }
578
+ }));
579
+ expect(response.status).toBe(201);
580
+ return (await response.json()).data;
581
+ };
582
+ const mark = (id, storeBuild) => admin(`/native-builds/${id}/store-build`, jsonRequest("POST", { storeBuild }));
583
+ const markRead = (fingerprintHash) => `/native-builds/latest?platform=ios&channel=${encodeURIComponent(channel)}&fingerprintHash=${fingerprintHash}&storeBuild=true`;
584
+ const older = await register("64", "store-fingerprint");
585
+ const newer = await register("65", "store-fingerprint");
586
+ const otherScope = await register("66", "store-fingerprint-b");
587
+ expect(older.is_store_build).toBe(false);
588
+ expect((await adminJson(markRead("store-fingerprint"))).data).toBeNull();
589
+ const marked = await mark(older.id, true);
590
+ expect(marked.status).toBe(200);
591
+ expect(await marked.json()).toMatchObject({ data: {
592
+ nativeBuild: {
593
+ id: older.id,
594
+ is_store_build: true
595
+ },
596
+ previous: null
597
+ } });
598
+ expect((await adminJson(markRead("store-fingerprint"))).data).toEqual({
599
+ ...older,
600
+ is_store_build: true
601
+ });
602
+ expect((await adminJson(`/native-builds/latest?platform=ios&channel=${encodeURIComponent(channel)}&fingerprintHash=store-fingerprint`)).data).toEqual(newer);
603
+ expect((await adminJson(markRead("store-fingerprint-b"))).data).toBeNull();
604
+ const replaced = await mark(newer.id, true);
605
+ expect(await replaced.json()).toMatchObject({ data: {
606
+ nativeBuild: {
607
+ id: newer.id,
608
+ is_store_build: true
609
+ },
610
+ previous: {
611
+ id: older.id,
612
+ is_store_build: false
613
+ }
614
+ } });
615
+ expect((await adminJson(`/native-builds/${older.id}`)).data).toEqual(older);
616
+ expect((await adminJson(markRead("store-fingerprint"))).data).toEqual({
617
+ ...newer,
618
+ is_store_build: true
619
+ });
620
+ const race = async (ids) => {
621
+ const responses = await Promise.all(ids.map((id) => mark(id, true)));
622
+ expect(responses.map(({ status }) => status)).toEqual(ids.map(() => 200));
623
+ const results = await Promise.all(responses.map((response) => response.json()));
624
+ expect(results.map(({ data }) => data.nativeBuild.is_store_build)).toEqual(ids.map(() => true));
625
+ const holders = (await Promise.all([older, newer].map(async ({ id }) => (await adminJson(`/native-builds/${id}`)).data))).filter(({ is_store_build }) => is_store_build);
626
+ expect(holders).toHaveLength(1);
627
+ expect(ids).toContain(holders[0].id);
628
+ };
629
+ await race([
630
+ older.id,
631
+ newer.id,
632
+ older.id
633
+ ]);
634
+ await mark(older.id, false).then((response) => response.text());
635
+ await mark(newer.id, false).then((response) => response.text());
636
+ expect((await adminJson(markRead("store-fingerprint"))).data).toBeNull();
637
+ await race([older.id, newer.id]);
638
+ await (await mark(newer.id, false)).text();
639
+ await mark(older.id, false).then((response) => response.text());
640
+ expect((await adminJson(markRead("store-fingerprint"))).data).toBeNull();
641
+ expect(await (await mark(bundleRow("869").id, true)).json()).toMatchObject({ data: null });
642
+ const refused = await admin(`/native-builds/${older.id}/store-build`, jsonRequest("POST", {}));
643
+ expect(refused.status).toBe(400);
644
+ await refused.text();
645
+ await mark(otherScope.id, true).then((response) => response.text());
646
+ await adminJson(`/native-builds/${otherScope.id}`, jsonRequest("DELETE"));
647
+ expect((await adminJson(markRead("store-fingerprint-b"))).data).toBeNull();
648
+ });
649
+ it("records a sandbox build on any channel, finds it through its sandbox scope, and refuses one its artifact doesn't describe", async () => {
650
+ const sandboxChannel = `pr-${namespace}`;
651
+ const channel = `plain-${namespace}`;
652
+ const sandboxFields = {
653
+ isSandbox: true,
654
+ sandboxUrlScheme: "acme-preview",
655
+ sandboxAppId: "com.example.app",
656
+ exportMethod: "ad-hoc"
657
+ };
658
+ const post = (suffix, body) => {
659
+ const builtIn = bundleRow(suffix);
660
+ return admin("/native-builds", jsonRequest("POST", {
661
+ id: bundleRow(`8${suffix}`).id,
662
+ platform: "ios",
663
+ fingerprintHash: "sandbox-fingerprint",
664
+ appVersion: null,
665
+ minBundleId: builtIn.id,
666
+ gitCommitHash: null,
667
+ buildKey: null,
668
+ artifact: {
669
+ kind: "ipa",
670
+ storageUri: `storage://native-builds/ios/${suffix}/App.ipa`,
671
+ byteSize: 1e3
672
+ },
673
+ embeddedBundle: {
674
+ manifestStorageUri: builtIn.manifest_storage_uri,
675
+ manifestFileHash: builtIn.manifest_file_hash,
676
+ assetBaseStorageUri: builtIn.asset_base_storage_uri
677
+ },
678
+ ...body
679
+ }));
680
+ };
681
+ const refusal = async (suffix, body) => {
682
+ const response = await post(suffix, body);
683
+ await response.text();
684
+ return response.status;
685
+ };
686
+ expect(await refusal("74", {
687
+ channel,
688
+ isSandbox: true
689
+ })).toBe(400);
690
+ expect(await refusal("74", {
691
+ channel,
692
+ ...sandboxFields,
693
+ sandboxAppId: void 0
694
+ })).toBe(400);
695
+ expect(await refusal("74", {
696
+ channel,
697
+ sandboxAppId: "com.example.app"
698
+ })).toBe(400);
699
+ expect(await refusal("74", {
700
+ channel: sandboxChannel,
701
+ isSandbox: null
702
+ })).toBe(400);
703
+ expect(await refusal("74", {
704
+ channel: sandboxChannel,
705
+ isSandbox: "yes"
706
+ })).toBe(400);
707
+ expect(await refusal("74", {
708
+ channel,
709
+ sandboxUrlScheme: "acme-preview"
710
+ })).toBe(400);
711
+ expect(await refusal("74", {
712
+ channel: sandboxChannel,
713
+ ...sandboxFields,
714
+ sandboxUrlScheme: "Acme"
715
+ })).toBe(400);
716
+ expect(await refusal("74", {
717
+ channel: sandboxChannel,
718
+ ...sandboxFields,
719
+ sandboxUrlScheme: 42
720
+ })).toBe(400);
721
+ expect(await refusal("74", {
722
+ channel,
723
+ nativeAppVersion: 42
724
+ })).toBe(400);
725
+ expect(await refusal("74", {
726
+ channel,
727
+ nativeAppVersion: " "
728
+ })).toBe(400);
729
+ const tagged = await post("72", {
730
+ channel: sandboxChannel,
731
+ ...sandboxFields,
732
+ nativeAppVersion: "1.6.0"
733
+ });
734
+ expect(tagged.status).toBe(201);
735
+ const sandboxBuild = (await tagged.json()).data;
736
+ const plain = await post("73", {
737
+ channel: sandboxChannel,
738
+ isSandbox: false
739
+ });
740
+ expect(plain.status).toBe(201);
741
+ const plainBuild = (await plain.json()).data;
742
+ expect(sandboxBuild).toMatchObject({
743
+ is_sandbox: true,
744
+ is_store_build: false,
745
+ sandbox_url_scheme: "acme-preview",
746
+ native_app_version: "1.6.0"
747
+ });
748
+ expect(plainBuild).toMatchObject({
749
+ is_sandbox: false,
750
+ is_store_build: false,
751
+ sandbox_url_scheme: null,
752
+ export_method: null,
753
+ native_app_version: null
754
+ });
755
+ const sandboxLookup = "sandboxAppId=com.example.app&sandboxUrlScheme=acme-preview&artifactKind=ipa&distribution=direct";
756
+ expect((await adminJson(`/native-builds/${sandboxBuild.id}`)).data).toEqual(sandboxBuild);
757
+ expect((await adminJson(`/native-builds/${plainBuild.id}`)).data).toEqual(plainBuild);
758
+ expect((await adminJson(`/native-builds/latest?platform=ios&channel=other-${namespace}&fingerprintHash=sandbox-fingerprint&${sandboxLookup}`)).data).toEqual(sandboxBuild);
759
+ expect((await adminJson(`/native-builds/latest?platform=ios&channel=${encodeURIComponent(sandboxChannel)}&fingerprintHash=sandbox-fingerprint`)).data).toEqual(plainBuild);
760
+ const partial = await admin(`/native-builds/latest?platform=ios&channel=${encodeURIComponent(sandboxChannel)}&fingerprintHash=sandbox-fingerprint&sandboxAppId=com.example.app`);
761
+ expect(partial.status).toBe(400);
762
+ await partial.text();
763
+ const invalid = await admin(`/native-builds/latest?platform=ios&channel=${encodeURIComponent(sandboxChannel)}&fingerprintHash=sandbox-fingerprint&${sandboxLookup.replace("artifactKind=ipa", "artifactKind=apk")}`);
764
+ expect(invalid.status).toBe(400);
765
+ await invalid.text();
766
+ expect((await adminJson(`/native-builds/latest?platform=ios&channel=${encodeURIComponent(sandboxChannel)}&fingerprintHash=sandbox-fingerprint&${sandboxLookup}&builtInOlderThan=ffffffff-ffff-7fff-bfff-ffffffffffff`)).data).toBeNull();
767
+ const patched = await admin(`/bundles/${plainBuild.min_bundle_id}`, jsonRequest("PATCH", { patches: [{
768
+ baseBundleId: sandboxBuild.min_bundle_id,
769
+ baseFileHash: "base-hash",
770
+ byteSize: 42,
771
+ patchFileHash: "patch-hash",
772
+ patchStorageUri: "storage://patches/sandbox.patch"
773
+ }] }));
774
+ expect(patched.status).toBe(400);
775
+ expect(await patched.text()).toContain("A sandbox build's built-in bundle is no patch base.");
776
+ const deployed = await admin("/releases", jsonRequest("POST", { deployments: [{
777
+ bundle: {
778
+ ...toDeployBundle(bundleRow("76")),
779
+ patches: [{
780
+ baseBundleId: sandboxBuild.min_bundle_id,
781
+ baseFileHash: "base-hash",
782
+ byteSize: 42,
783
+ patchFileHash: "patch-hash",
784
+ patchStorageUri: "storage://patches/sandbox-deploy.patch"
785
+ }]
786
+ },
787
+ release: policy("sandbox-patch")
788
+ }] }));
789
+ expect(deployed.status).toBe(400);
790
+ expect(await deployed.text()).toContain("A sandbox build's built-in bundle is no patch base.");
791
+ const notDeployed = await admin(`/bundles/${bundleRow("76").id}`);
792
+ expect(notDeployed.status).toBe(404);
793
+ await notDeployed.text();
794
+ const marked = await admin(`/native-builds/${sandboxBuild.id}/store-build`, jsonRequest("POST", { storeBuild: true }));
795
+ expect(marked.status).toBe(400);
796
+ await marked.text();
797
+ });
798
+ it("finds a scope's build of one kind, and a sandbox build's other install target", async () => {
799
+ const channel = `kinds-${namespace}`;
800
+ const register = async (suffix, kind, body = {}) => {
801
+ const builtIn = bundleRow(suffix);
802
+ const response = await admin("/native-builds", jsonRequest("POST", {
803
+ id: bundleRow(`8${suffix}`).id,
804
+ platform: "ios",
805
+ channel,
806
+ fingerprintHash: "kind-fingerprint",
807
+ appVersion: null,
808
+ minBundleId: builtIn.id,
809
+ gitCommitHash: null,
810
+ buildKey: null,
811
+ artifact: {
812
+ kind,
813
+ storageUri: `storage://native-builds/ios/${suffix}/App.${kind === "ipa" ? "ipa" : "app.zip"}`,
814
+ byteSize: 1e3
815
+ },
816
+ embeddedBundle: {
817
+ manifestStorageUri: builtIn.manifest_storage_uri,
818
+ manifestFileHash: builtIn.manifest_file_hash,
819
+ assetBaseStorageUri: builtIn.asset_base_storage_uri
820
+ },
821
+ ...body
822
+ }));
823
+ expect(response.status).toBe(201);
824
+ return (await response.json()).data;
825
+ };
826
+ const sandbox = (exportMethod) => ({
827
+ isSandbox: true,
828
+ sandboxUrlScheme: "acme-preview",
829
+ sandboxAppId: "com.example.app",
830
+ exportMethod
831
+ });
832
+ const ipa = await register("81", "ipa");
833
+ const app = await register("82", "app");
834
+ const latest = `/native-builds/latest?platform=ios&channel=${encodeURIComponent(channel)}&fingerprintHash=kind-fingerprint`;
835
+ expect((await adminJson(latest)).data).toEqual(app);
836
+ expect((await adminJson(`${latest}&kind=ipa`)).data).toEqual(ipa);
837
+ const refused = await admin(`${latest}&kind=apk`);
838
+ expect(refused.status).toBe(400);
839
+ await refused.text();
840
+ const sandboxIpa = await register("83", "ipa", sandbox("ad-hoc"));
841
+ const sandboxApp = await register("84", "app", sandbox(null));
842
+ expect((await adminJson(`/native-builds/${sandboxIpa.id}/sibling`)).data).toEqual(sandboxApp);
843
+ expect((await adminJson(`/native-builds/${sandboxApp.id}/sibling`)).data).toEqual(sandboxIpa);
844
+ expect((await adminJson(`/native-builds/${ipa.id}/sibling`)).data).toBeNull();
845
+ expect((await adminJson(`/native-builds/${bundleRow("899").id}/sibling`)).data).toBeNull();
846
+ expect((await adminJson(`/native-builds/built-in/${ipa.min_bundle_id}`)).data).toEqual(ipa);
847
+ expect((await adminJson(`/native-builds/built-in/${bundleRow("899").id}`)).data).toBeNull();
848
+ });
849
+ it("requests, approves, renames, records, and removes iOS devices", async () => {
850
+ const udid = namespace.replaceAll("-", "").padEnd(40, "0");
851
+ const device = async (path, init) => (await adminJson(path, init)).data;
852
+ const requested = await adminJson("/ios-devices", jsonRequest("POST", {
853
+ udid: udid.toUpperCase(),
854
+ name: "Kim's iPhone",
855
+ requestedBy: "kim@team.dev"
856
+ }));
857
+ expect(requested.data.created).toBe(true);
858
+ const { id } = requested.data.device;
859
+ expect(requested.data.device).toMatchObject({
860
+ udid,
861
+ status: "pending",
862
+ requested_by: "kim@team.dev"
863
+ });
864
+ try {
865
+ const again = await adminJson("/ios-devices", jsonRequest("POST", {
866
+ udid,
867
+ name: "Other",
868
+ requestedBy: null
869
+ }));
870
+ expect(again.data).toEqual({
871
+ device: requested.data.device,
872
+ created: false
873
+ });
874
+ const raced = `${udid.slice(0, 39)}f`;
875
+ const racing = await Promise.all(["Other", "Another"].map((name) => adminJson("/ios-devices", jsonRequest("POST", {
876
+ udid: raced,
877
+ name,
878
+ requestedBy: null
879
+ }))));
880
+ expect(racing.map(({ data }) => data.created).sort()).toEqual([false, true]);
881
+ expect(racing[0].data.device.id).toBe(racing[1].data.device.id);
882
+ await adminJson(`/ios-devices/${racing[0].data.device.id}`, jsonRequest("DELETE"));
883
+ expect(await device(`/ios-devices/udid/${udid}`)).toEqual(requested.data.device);
884
+ const pending = await adminJson("/ios-devices?status=pending&limit=500");
885
+ expect(pending.data.map((row) => row.id)).toContain(id);
886
+ const approval = await device(`/ios-devices/${id}/approval`, jsonRequest("POST", { approvedBy: "lead@team.dev" }));
887
+ expect(approval).toMatchObject({
888
+ status: "approved",
889
+ approved_by: "lead@team.dev"
890
+ });
891
+ expect(await device(`/ios-devices/${id}`, jsonRequest("PATCH", { name: "Kim's work iPhone" }))).toMatchObject({
892
+ name: "Kim's work iPhone",
893
+ status: "approved"
894
+ });
895
+ const registered = await device(`/ios-devices/${id}/outcome`, jsonRequest("POST", {
896
+ seen: {
897
+ status: "approved",
898
+ approvedAtMs: approval.approved_at_ms
899
+ },
900
+ issuerId: "issuer-a",
901
+ outcome: "registered"
902
+ }));
903
+ expect(registered).toMatchObject({
904
+ status: "registered",
905
+ apple_issuer_id: "issuer-a"
906
+ });
907
+ expect(await device(`/ios-devices/${id}/outcome`, jsonRequest("POST", {
908
+ seen: {
909
+ status: "approved",
910
+ approvedAtMs: 1
911
+ },
912
+ issuerId: "issuer-a",
913
+ outcome: "missing"
914
+ }))).toBeNull();
915
+ const claims = await Promise.all(["issuer-a", "issuer-b"].map((issuerId) => adminJson("/ios-devices/account", jsonRequest("POST", { issuerId }))));
916
+ const owner = claims.find(({ data }) => data.claimed)?.data.issuerId;
917
+ expect(claims.filter(({ data }) => data.claimed)).toHaveLength(1);
918
+ expect(claims.map(({ data }) => data.issuerId)).toEqual([owner, owner]);
919
+ expect(await adminJson("/ios-devices/account")).toEqual({ data: { issuerId: owner } });
920
+ const buildId = bundleRow("90").id;
921
+ const marked = await admin("/ios-devices/in-build", jsonRequest("POST", {
922
+ buildId,
923
+ ids: [id]
924
+ }));
925
+ expect(marked.status).toBe(204);
926
+ expect((await device(`/ios-devices/udid/${udid}`))?.build_id).toBe(buildId);
927
+ const refused = await admin("/ios-devices", jsonRequest("POST", {
928
+ udid: "1234",
929
+ name: "x",
930
+ requestedBy: null
931
+ }));
932
+ expect(refused.status).toBe(400);
933
+ await refused.text();
934
+ } finally {
935
+ await adminJson(`/ios-devices/${id}`, jsonRequest("DELETE"));
936
+ }
937
+ expect(await device(`/ios-devices/udid/${udid}`)).toBeNull();
938
+ expect(await device(`/ios-devices/${id}`, jsonRequest("DELETE"))).toBeNull();
939
+ expect((await adminJson("/ios-devices/account")).data).toMatchObject({ issuerId: expect.any(String) });
940
+ });
458
941
  it("lists the patches that start from a bundle", async () => {
459
942
  const base = bundleRow("50");
460
943
  const target = bundleRow("51");
@@ -1152,7 +1635,7 @@ const setupReleaseCatalogTestSuite = (options) => {
1152
1635
  expect((await request(otherPath)).status).toBe(404);
1153
1636
  });
1154
1637
  it("caches an unknown scope's 404 like a catalog", async () => {
1155
- const response = await request(catalogPath());
1638
+ const response = await request(catalogPath(scope("unknown")));
1156
1639
  expect(response.status).toBe(404);
1157
1640
  expect(response.headers.get("cache-control")).toBe("public, max-age=0, s-maxage=5");
1158
1641
  expect(response.headers.get("cdn-cache-control")).toBe("public, max-age=5, stale-while-revalidate=5, stale-if-error=0");
@@ -1554,6 +2037,15 @@ const conformanceItems = {
1554
2037
  type: "string",
1555
2038
  nullable: true
1556
2039
  },
2040
+ (
2041
+ /** A unique slot only some rows hold, as long as a scope key. */
2042
+ {
2043
+ name: "slot",
2044
+ type: "string",
2045
+ nullable: true,
2046
+ maxLength: 2048,
2047
+ ascii: true
2048
+ }),
1557
2049
  {
1558
2050
  name: "_v",
1559
2051
  type: "integer",
@@ -1587,6 +2079,12 @@ const conformanceItems = {
1587
2079
  name: "byTag",
1588
2080
  eq: ["tags"],
1589
2081
  sort: ["score"]
2082
+ },
2083
+ {
2084
+ name: "bySlot",
2085
+ eq: ["slot"],
2086
+ sort: [],
2087
+ unique: true
1590
2088
  }
1591
2089
  ]
1592
2090
  };
@@ -1697,6 +2195,7 @@ const item = (id, values = {}) => ({
1697
2195
  tags: null,
1698
2196
  payload: null,
1699
2197
  note: null,
2198
+ slot: null,
1700
2199
  _v: 0,
1701
2200
  ...values
1702
2201
  });
@@ -2007,6 +2506,37 @@ const setupDatabaseAdapterConformanceSuite = (options) => {
2007
2506
  eq: ["L"]
2008
2507
  }))).toEqual(["f"]);
2009
2508
  });
2509
+ it("moves a unique slot between rows in one write, and holds a long ASCII value", async () => {
2510
+ const adapter = await setup();
2511
+ const slot = `s:${"a".repeat(998)}`;
2512
+ await ok(adapter, [
2513
+ insert(item("a", { slot })),
2514
+ insert(item("b")),
2515
+ insert(item("c"))
2516
+ ]);
2517
+ expect(await adapter.write([insert(item("d", { slot }))])).toEqual({
2518
+ ok: false,
2519
+ failedOp: 0
2520
+ });
2521
+ const patch = (id, from, to) => ({
2522
+ type: "patch",
2523
+ table: conformanceItems,
2524
+ key: [id],
2525
+ set: { slot: to },
2526
+ guard: { v: 0 },
2527
+ previous: item(id, { slot: from })
2528
+ });
2529
+ expect(await adapter.write([patch("b", null, slot)])).toEqual({
2530
+ ok: false,
2531
+ failedOp: 0
2532
+ });
2533
+ await ok(adapter, [patch("a", slot, null), patch("b", null, slot)]);
2534
+ expect(ids(await query(adapter, {
2535
+ index: "bySlot",
2536
+ eq: [slot]
2537
+ }))).toEqual(["b"]);
2538
+ expect(await one(adapter, "a")).toMatchObject({ slot: null });
2539
+ });
2010
2540
  it("orders strings by UTF-8 bytes and numbers numerically", async () => {
2011
2541
  const adapter = await setup();
2012
2542
  const names = [
@@ -2202,6 +2732,60 @@ const setupDatabaseAdapterConformanceSuite = (options) => {
2202
2732
  "r8"
2203
2733
  ]);
2204
2734
  });
2735
+ it("reads every write committed before the read starts", async () => {
2736
+ const adapter = await setup();
2737
+ await ok(adapter, [insert(item("s", { score: 1 }))]);
2738
+ for (let score = 2; score <= 5; score += 1) {
2739
+ const previous = await one(adapter, "s");
2740
+ await ok(adapter, [{
2741
+ type: "patch",
2742
+ table: conformanceItems,
2743
+ key: ["s"],
2744
+ set: { score },
2745
+ guard: { v: previous._v },
2746
+ previous
2747
+ }]);
2748
+ expect((await one(adapter, "s"))?.score).toBe(score);
2749
+ expect((await query(adapter, {
2750
+ index: "byGroup",
2751
+ eq: ["g"]
2752
+ })).map((row) => row.score)).toEqual([score]);
2753
+ }
2754
+ });
2755
+ it("writes the index items of rows written without the index (migrations.fillIndex)", async () => {
2756
+ const adapter = await setup();
2757
+ const fillIndex = adapter.migrations?.fillIndex;
2758
+ if (fillIndex === void 0) return;
2759
+ const earlier = {
2760
+ ...conformanceItems,
2761
+ indexes: conformanceItems.indexes.filter(({ name }) => name !== "byGroup")
2762
+ };
2763
+ await ok(adapter, [
2764
+ "r0",
2765
+ "r1",
2766
+ "r2"
2767
+ ].map((id) => ({
2768
+ type: "insert",
2769
+ table: earlier,
2770
+ row: item(id, { score: Number(id.slice(1)) })
2771
+ })));
2772
+ await ok(adapter, [insert(item("r3", { score: 3 }))]);
2773
+ const byGroup = () => query(adapter, {
2774
+ index: "byGroup",
2775
+ eq: ["g"]
2776
+ }).then(ids);
2777
+ await expect(byGroup()).resolves.toEqual(["r3"]);
2778
+ await expect(fillIndex(conformanceItems, "byGroup", { dryRun: true })).resolves.toBe(3);
2779
+ await expect(byGroup()).resolves.toEqual(["r3"]);
2780
+ await expect(fillIndex(conformanceItems, "byGroup")).resolves.toBe(3);
2781
+ await expect(byGroup()).resolves.toEqual([
2782
+ "r0",
2783
+ "r1",
2784
+ "r2",
2785
+ "r3"
2786
+ ]);
2787
+ await expect(fillIndex(conformanceItems, "byGroup", { dryRun: true })).resolves.toBe(0);
2788
+ });
2205
2789
  it(`lets exactly one of ${writers} concurrent writers win a contested key`, async () => {
2206
2790
  const adapter = await setup();
2207
2791
  const row = item("a");
@@ -2997,6 +3581,49 @@ const failureOf = (n, install, check = false) => eventOf(200 + n, {
2997
3581
  },
2998
3582
  received_at_ms: T0 + 3 * DAY + n * 10 * 6e4
2999
3583
  });
3584
+ /** Where a client floods update failures: Android `flood`, day 5. */
3585
+ const FLOOD = {
3586
+ platform: "android",
3587
+ channel: "flood",
3588
+ start: T0 + 5 * DAY
3589
+ };
3590
+ /** The flood's failed checks: more breakdown rows than a read takes from an hour. */
3591
+ const FLOOD_CHECKS = 24;
3592
+ /**
3593
+ * Installations whose IDs fall on all 8 counter shards: each flood row is
3594
+ * reported by all of them, so it is stored on every shard.
3595
+ */
3596
+ const FLOOD_INSTALLS = Array.from({ length: 8 }, (_, n) => `flood-${n}`);
3597
+ /**
3598
+ * Flood failure `n`: below {@link FLOOD_CHECKS} × 8, a failed check of HTTP
3599
+ * status 100 + n / 8 by installation n % 8, all in day 5's first hour; at
3600
+ * it, a real failure, a failed download in the hour after.
3601
+ */
3602
+ const floodFailureOf = (n) => {
3603
+ const real = n === FLOOD_CHECKS * FLOOD_INSTALLS.length;
3604
+ return eventOf(1e3 + n, {
3605
+ type: "UPDATE_FAILED",
3606
+ install_id: real ? "flood-real" : FLOOD_INSTALLS[n % 8],
3607
+ user_id: null,
3608
+ to_release_id: real ? "release-b" : null,
3609
+ to_bundle_id: real ? "bundle-b" : "bundle-a",
3610
+ platform: FLOOD.platform,
3611
+ channel: FLOOD.channel,
3612
+ metadata: {
3613
+ ...eventOf(0).metadata,
3614
+ failure: real ? {
3615
+ stage: "download",
3616
+ reason: "http",
3617
+ http_status: 403
3618
+ } : {
3619
+ stage: "check",
3620
+ reason: "http",
3621
+ http_status: 100 + Math.floor(n / 8)
3622
+ }
3623
+ },
3624
+ received_at_ms: FLOOD.start + (real ? HOUR : n * 1e3)
3625
+ });
3626
+ };
3000
3627
  /**
3001
3628
  * History event `n` of the day before T0, three an hour, on its own release
3002
3629
  * and bundles: every windowed read, which starts at T0 or later, skips it.
@@ -3028,6 +3655,41 @@ const nativeBuildScope = {
3028
3655
  fingerprintHash: "native-fingerprint",
3029
3656
  appVersion: null
3030
3657
  };
3658
+ /** A sandbox scope of `nativeBuildScope`'s fingerprint, which no build has. */
3659
+ const nativeBuildSandboxScope = {
3660
+ appId: "com.example.app",
3661
+ urlScheme: "acme-preview",
3662
+ artifactKind: "ipa",
3663
+ distribution: "direct"
3664
+ };
3665
+ /**
3666
+ * A sandbox ad hoc .ipa of `nativeBuildScope`'s fingerprint, as a build page
3667
+ * holds its row: the source of a sibling read.
3668
+ */
3669
+ const sandboxIpaRow = {
3670
+ id: "01ffffff-ffff-7fff-bfff-ffffffffffff",
3671
+ scope_key: `v1:sandbox:ios:${nativeBuildSandboxScope.appId}:${nativeBuildSandboxScope.urlScheme}:ipa:direct:fingerprint:${nativeBuildScope.fingerprintHash}`,
3672
+ platform: "ios",
3673
+ channel_id: "channel:pr-140",
3674
+ fingerprint_hash: nativeBuildScope.fingerprintHash,
3675
+ app_version: null,
3676
+ min_bundle_id: "01ffffff-ffff-7fff-bfff-fffffffffffe",
3677
+ artifact_kind: "ipa",
3678
+ artifact_storage_uri: "storage://read-budgets/native-builds/ipa/App.ipa",
3679
+ byte_size: 1e3,
3680
+ git_commit_hash: null,
3681
+ created_at_ms: 0,
3682
+ build_key: null,
3683
+ build_number: null,
3684
+ submitted_to: null,
3685
+ submitted_at_ms: null,
3686
+ submitted_version: null,
3687
+ is_store_build: false,
3688
+ is_sandbox: true,
3689
+ sandbox_url_scheme: nativeBuildSandboxScope.urlScheme,
3690
+ export_method: "ad-hoc",
3691
+ native_app_version: null
3692
+ };
3031
3693
  /** The native build key the older of the two native builds is registered with. */
3032
3694
  const nativeBuildKey = `nbk1:${"0".repeat(64)}`;
3033
3695
  const bundleEvents = {
@@ -3109,6 +3771,39 @@ const seed = async (database) => {
3109
3771
  assetBaseStorageUri: "storage://read-budgets/assets"
3110
3772
  }
3111
3773
  });
3774
+ await core.markNativeBuild(createBundleFixture("8011").id, { storeBuild: true });
3775
+ await core.registerNativeBuild({
3776
+ ...nativeBuildScope,
3777
+ channel: "beta",
3778
+ id: createBundleFixture("8005").id,
3779
+ minBundleId: createBundleFixture("005").id,
3780
+ gitCommitHash: null,
3781
+ buildKey: null,
3782
+ isSandbox: true,
3783
+ sandboxAppId: nativeBuildSandboxScope.appId,
3784
+ sandboxUrlScheme: nativeBuildSandboxScope.urlScheme,
3785
+ artifact: {
3786
+ kind: "app",
3787
+ storageUri: "storage://read-budgets/native-builds/005/App.app.zip",
3788
+ byteSize: 1e3
3789
+ },
3790
+ embeddedBundle: {
3791
+ manifestStorageUri: "storage://bundles/005/manifest.json",
3792
+ manifestFileHash: "manifest-hash-005",
3793
+ assetBaseStorageUri: "storage://read-budgets/assets"
3794
+ }
3795
+ });
3796
+ const pendingDevice = (await core.requestIosDevice({
3797
+ udid: BUDGET_PENDING_UDID,
3798
+ name: "Pending iPhone",
3799
+ requestedBy: "kim@team.dev"
3800
+ })).device;
3801
+ const { device: requestedDevice } = await core.requestIosDevice({
3802
+ udid: BUDGET_APPROVED_UDID,
3803
+ name: "Approved iPhone",
3804
+ requestedBy: "kim@team.dev"
3805
+ });
3806
+ const approvedDevice = await core.approveIosDevice(requestedDevice.id, { approvedBy: "lead@team.dev" });
3112
3807
  const { apiKey } = await api.apiKeys.create({ name: "Read budgets" });
3113
3808
  for (let n = 1; n <= 24; n += 1) await api.insights.recordEvent(eventOf(n));
3114
3809
  await api.insights.recordEvent(eventOf(25, {
@@ -3128,6 +3823,7 @@ const seed = async (database) => {
3128
3823
  await api.insights.recordEvent(failureOf(1, 3));
3129
3824
  await api.insights.recordEvent(failureOf(2, 5));
3130
3825
  await api.insights.recordEvent(failureOf(3, 7, true));
3826
+ for (let n = 0; n <= FLOOD_CHECKS * FLOOD_INSTALLS.length; n += 1) await api.insights.recordEvent(floodFailureOf(n));
3131
3827
  for (const [baseVersion, greeting] of [
3132
3828
  "Hi",
3133
3829
  "Hello",
@@ -3146,6 +3842,8 @@ const seed = async (database) => {
3146
3842
  apiKey,
3147
3843
  productionId,
3148
3844
  nightlyId: (await channel("nightly")).id,
3845
+ pendingDevice,
3846
+ approvedDevice,
3149
3847
  /** The auto-patch base key of a new production iOS 1.0.0 bundle. */
3150
3848
  candidateKey: targetBaseCandidateKey({
3151
3849
  channel: "production",
@@ -3156,6 +3854,8 @@ const seed = async (database) => {
3156
3854
  };
3157
3855
  };
3158
3856
  const budget = (entry) => entry;
3857
+ const BUDGET_PENDING_UDID = "00008030-000000000000000a";
3858
+ const BUDGET_APPROVED_UDID = "00008030-000000000000000b";
3159
3859
  const reads = (gets, keys, queries, rows) => ({
3160
3860
  gets,
3161
3861
  keys,
@@ -3336,6 +4036,46 @@ const READ_BUDGETS = [
3336
4036
  rows: 1
3337
4037
  }
3338
4038
  }),
4039
+ budget({
4040
+ api: "catalog preflight: 1 catalog point read and the scope's enabled releases",
4041
+ read: ({ core }) => core.preflightReleaseCatalogRebuild(scopeKey),
4042
+ adapter: reads(1, 1, 1, 4),
4043
+ engine: {
4044
+ calls: 2,
4045
+ rows: 5
4046
+ },
4047
+ check: (preflight) => expect(preflight.changed).toBe(false)
4048
+ }),
4049
+ budget({
4050
+ api: "release scopes: one limit-1 seek per scope, past each scope's releases",
4051
+ read: ({ core }) => core.listReleaseScopeKeys({ limit: 4 }),
4052
+ adapter: reads(0, 0, 4, 4),
4053
+ engine: {
4054
+ calls: 4,
4055
+ rows: 4
4056
+ },
4057
+ returned: (scopeKeys) => scopeKeys.length,
4058
+ check: (scopeKeys) => expect(scopeKeys).toEqual([
4059
+ "v1:app-version:android:cHJvZHVjdGlvbg",
4060
+ "v1:app-version:ios:YmV0YQ",
4061
+ "v1:app-version:ios:c3RhZ2luZw",
4062
+ scopeKey
4063
+ ])
4064
+ }),
4065
+ budget({
4066
+ api: "release scopes past the last: 1 empty query",
4067
+ read: ({ core }) => core.listReleaseScopeKeys({
4068
+ after: scopeKey,
4069
+ limit: 4
4070
+ }),
4071
+ adapter: reads(0, 0, 1, 0),
4072
+ engine: {
4073
+ calls: 1,
4074
+ rows: 0
4075
+ },
4076
+ returned: (scopeKeys) => scopeKeys.length,
4077
+ check: (scopeKeys) => expect(scopeKeys).toEqual([])
4078
+ }),
3339
4079
  budget({
3340
4080
  api: "native build by ID: 1 point read",
3341
4081
  read: ({ core }) => core.getNativeBuild(createBundleFixture("8012").id),
@@ -3346,6 +4086,16 @@ const READ_BUDGETS = [
3346
4086
  },
3347
4087
  check: (build) => expect(build).toMatchObject({ min_bundle_id: createBundleFixture("012").id })
3348
4088
  }),
4089
+ budget({
4090
+ api: "native build by its built-in bundle: 1 unique read",
4091
+ read: ({ core }) => core.findNativeBuildByBuiltInBundle(createBundleFixture("011").id),
4092
+ adapter: reads(0, 0, 1, 1),
4093
+ engine: {
4094
+ calls: 1,
4095
+ rows: 1
4096
+ },
4097
+ check: (build) => expect(build).toMatchObject({ id: createBundleFixture("8011").id })
4098
+ }),
3349
4099
  budget({
3350
4100
  api: "native build by scope: byScope descending, limit 1",
3351
4101
  read: ({ core }) => core.findNativeBuild(nativeBuildScope),
@@ -3356,6 +4106,79 @@ const READ_BUDGETS = [
3356
4106
  },
3357
4107
  check: (build) => expect(build).toMatchObject({ min_bundle_id: createBundleFixture("012").id })
3358
4108
  }),
4109
+ budget({
4110
+ api: "native build store mark: byStoreBuild, 1 row",
4111
+ read: ({ core }) => core.findNativeBuild(nativeBuildScope, { storeBuild: true }),
4112
+ adapter: reads(0, 0, 1, 1),
4113
+ engine: {
4114
+ calls: 1,
4115
+ rows: 1
4116
+ },
4117
+ check: (build) => expect(build).toMatchObject({
4118
+ min_bundle_id: createBundleFixture("011").id,
4119
+ is_store_build: true
4120
+ })
4121
+ }),
4122
+ budget({
4123
+ api: "native build store mark of a scope with none: byStoreBuild, no row",
4124
+ read: ({ core }) => core.findNativeBuild({
4125
+ ...nativeBuildScope,
4126
+ channel: "no-such-channel"
4127
+ }, { storeBuild: true }),
4128
+ adapter: reads(0, 0, 1, 0),
4129
+ engine: {
4130
+ calls: 1,
4131
+ rows: 0
4132
+ },
4133
+ check: (build) => expect(build).toBeNull()
4134
+ }),
4135
+ budget({
4136
+ api: "native build older than a bundle, the newest is: byScope, limit 1",
4137
+ read: ({ core }) => core.findNativeBuild(nativeBuildScope, { builtInOlderThan: "ffffffff-ffff-7fff-bfff-ffffffffffff" }),
4138
+ adapter: reads(0, 0, 1, 1),
4139
+ engine: {
4140
+ calls: 1,
4141
+ rows: 1
4142
+ },
4143
+ check: (build) => expect(build).toMatchObject({ min_bundle_id: createBundleFixture("012").id })
4144
+ }),
4145
+ budget({
4146
+ api: "native build older than a bundle, past the newest: byScope twice",
4147
+ read: ({ core }) => core.findNativeBuild(nativeBuildScope, { builtInOlderThan: createBundleFixture("012").id }),
4148
+ adapter: reads(0, 0, 2, 2),
4149
+ engine: {
4150
+ calls: 2,
4151
+ rows: 2
4152
+ },
4153
+ check: (build) => expect(build).toMatchObject({ min_bundle_id: createBundleFixture("011").id })
4154
+ }),
4155
+ budget({
4156
+ api: "native build older than a bundle in a sandbox scope: no read",
4157
+ read: ({ core }) => core.findNativeBuild({
4158
+ ...nativeBuildScope,
4159
+ sandbox: nativeBuildSandboxScope
4160
+ }, { builtInOlderThan: "ffffffff-ffff-7fff-bfff-ffffffffffff" }),
4161
+ adapter: reads(0, 0, 0, 0),
4162
+ engine: {
4163
+ calls: 0,
4164
+ rows: 0
4165
+ },
4166
+ check: (build) => expect(build).toBeNull()
4167
+ }),
4168
+ budget({
4169
+ api: "sandbox build on any channel: byScope descending, limit 1",
4170
+ read: ({ core }) => core.findNativeBuild({
4171
+ ...nativeBuildScope,
4172
+ channel: "pr-140",
4173
+ sandbox: nativeBuildSandboxScope
4174
+ }),
4175
+ adapter: reads(0, 0, 1, 0),
4176
+ engine: {
4177
+ calls: 1,
4178
+ rows: 0
4179
+ },
4180
+ check: (build) => expect(build).toBeNull()
4181
+ }),
3359
4182
  budget({
3360
4183
  api: "native build by key: byBuildKey descending, limit 1",
3361
4184
  read: ({ core }) => core.findNativeBuild(nativeBuildScope, { buildKey: nativeBuildKey }),
@@ -3369,6 +4192,53 @@ const READ_BUDGETS = [
3369
4192
  build_key: nativeBuildKey
3370
4193
  })
3371
4194
  }),
4195
+ budget({
4196
+ api: "native build of a kind: byScopeKind descending, limit 1",
4197
+ read: ({ core }) => core.findNativeBuild(nativeBuildScope, { artifactKind: "ipa" }),
4198
+ adapter: reads(0, 0, 1, 1),
4199
+ engine: {
4200
+ calls: 1,
4201
+ rows: 1
4202
+ },
4203
+ check: (build) => expect(build).toMatchObject({ min_bundle_id: createBundleFixture("012").id })
4204
+ }),
4205
+ budget({
4206
+ api: "native build of a kind with none: byScopeKind, then byScope, limit 1",
4207
+ read: ({ core }) => core.findNativeBuild(nativeBuildScope, { artifactKind: "app" }),
4208
+ adapter: reads(0, 0, 2, 1),
4209
+ engine: {
4210
+ calls: 2,
4211
+ rows: 1
4212
+ },
4213
+ check: (build) => expect(build).toBeNull()
4214
+ }),
4215
+ budget({
4216
+ api: "sandbox build's other install target: byScope descending, limit 1",
4217
+ read: ({ core }) => core.findNativeBuildSibling(sandboxIpaRow),
4218
+ adapter: reads(0, 0, 1, 1),
4219
+ engine: {
4220
+ calls: 1,
4221
+ rows: 1
4222
+ },
4223
+ check: (build) => expect(build).toMatchObject({
4224
+ id: createBundleFixture("8005").id,
4225
+ artifact_kind: "app"
4226
+ })
4227
+ }),
4228
+ budget({
4229
+ api: "normal build's other install target: no read",
4230
+ read: ({ core }) => core.findNativeBuildSibling({
4231
+ ...sandboxIpaRow,
4232
+ is_sandbox: false,
4233
+ scope_key: "normal"
4234
+ }),
4235
+ adapter: reads(0, 0, 0, 0),
4236
+ engine: {
4237
+ calls: 0,
4238
+ rows: 0
4239
+ },
4240
+ check: (build) => expect(build).toBeNull()
4241
+ }),
3372
4242
  budget({
3373
4243
  api: "native build list: all descending, limit rows",
3374
4244
  read: ({ core }) => core.listNativeBuilds({
@@ -3406,6 +4276,35 @@ const READ_BUDGETS = [
3406
4276
  },
3407
4277
  returned: (channel) => channel === null ? 0 : 1
3408
4278
  }),
4279
+ budget({
4280
+ api: "channels by ID: 1 batch get of their keys",
4281
+ read: ({ core, productionId, nightlyId }) => core.getChannels([
4282
+ nightlyId,
4283
+ productionId,
4284
+ nightlyId
4285
+ ]),
4286
+ adapter: reads(1, 2, 0, 0),
4287
+ engine: {
4288
+ calls: 1,
4289
+ rows: 2
4290
+ },
4291
+ returned: (channels) => channels.length,
4292
+ check: (channels) => expect(channels.map(({ name }) => name)).toEqual(["nightly", "production"])
4293
+ }),
4294
+ budget({
4295
+ api: "channel page by name: limit rows from one query",
4296
+ read: ({ core }) => core.listChannels({
4297
+ limit: 2,
4298
+ after: "beta"
4299
+ }),
4300
+ adapter: reads(0, 0, 1, 2),
4301
+ engine: {
4302
+ calls: 1,
4303
+ rows: 2
4304
+ },
4305
+ returned: (channels) => channels.length,
4306
+ check: (channels) => expect(channels.map(({ name }) => name)).toEqual(["canary", "nightly"])
4307
+ }),
3409
4308
  budget({
3410
4309
  api: "list events of a dense day: limit rows from one query",
3411
4310
  read: ({ insights }) => insights.listEvents({
@@ -3623,6 +4522,32 @@ const READ_BUDGETS = [
3623
4522
  checks: { failures: 1 }
3624
4523
  })
3625
4524
  }),
4525
+ budget({
4526
+ api: "update failures of a flooded channel: 20 breakdown rows of the flooded hour, every other hour whole",
4527
+ read: ({ insights }) => insights.getUpdateFailures({
4528
+ platform: FLOOD.platform,
4529
+ channel: FLOOD.channel,
4530
+ timeRange: {
4531
+ start: FLOOD.start,
4532
+ end: FLOOD.start + 2 * HOUR
4533
+ }
4534
+ }),
4535
+ adapter: reads(1, 1, 5, 177),
4536
+ engine: {
4537
+ calls: 5,
4538
+ rows: 24
4539
+ },
4540
+ check: (failures) => expect(failures).toMatchObject({
4541
+ coverage: { kind: "partial" },
4542
+ cappedHours: [FLOOD.start],
4543
+ failedUpdates: 1,
4544
+ failedInstallations: 1,
4545
+ checks: {
4546
+ failures: 160,
4547
+ failedInstallations: 8
4548
+ }
4549
+ })
4550
+ }),
3626
4551
  budget({
3627
4552
  api: "update failures of a release since its first: two kept rows × shards, all used",
3628
4553
  read: ({ insights }) => insights.getUpdateFailures({
@@ -3692,6 +4617,23 @@ const READ_BUDGETS = [
3692
4617
  submitted_version: "1.0.0 (12)"
3693
4618
  })
3694
4619
  }),
4620
+ budget({
4621
+ api: "native build store mark write: the build, the holder, and 1 write",
4622
+ read: ({ core }) => core.markNativeBuild(createBundleFixture("8012").id, { storeBuild: true }),
4623
+ adapter: (indexCopies) => indexCopies ? reads(2, 2, 1, 1) : reads(1, 1, 1, 1),
4624
+ engine: {
4625
+ calls: 2,
4626
+ rows: 2
4627
+ },
4628
+ writes: 1,
4629
+ check: (result) => expect(result).toMatchObject({
4630
+ nativeBuild: {
4631
+ min_bundle_id: createBundleFixture("012").id,
4632
+ is_store_build: true
4633
+ },
4634
+ previous: { min_bundle_id: createBundleFixture("011").id }
4635
+ })
4636
+ }),
3695
4637
  budget({
3696
4638
  api: "native build delete: the build, its built-in bundle, and 1 write",
3697
4639
  read: ({ core }) => core.deleteNativeBuild(createBundleFixture("8011").id),
@@ -3706,6 +4648,146 @@ const READ_BUDGETS = [
3706
4648
  nativeBuild: { min_bundle_id: createBundleFixture("011").id }
3707
4649
  })
3708
4650
  }),
4651
+ budget({
4652
+ api: "iOS devices by status: 1 query, the rows used",
4653
+ read: ({ core }) => core.listIosDevices({
4654
+ status: "approved",
4655
+ limit: 50
4656
+ }),
4657
+ adapter: reads(0, 0, 1, 1),
4658
+ engine: {
4659
+ calls: 1,
4660
+ rows: 1
4661
+ },
4662
+ returned: (rows) => rows.length,
4663
+ check: (rows) => expect(rows.map((row) => row.udid)).toEqual([BUDGET_APPROVED_UDID])
4664
+ }),
4665
+ budget({
4666
+ api: "iOS device by UDID: 1 unique read",
4667
+ read: ({ core }) => core.findIosDevice(BUDGET_PENDING_UDID.toUpperCase()),
4668
+ adapter: reads(0, 0, 1, 1),
4669
+ engine: {
4670
+ calls: 1,
4671
+ rows: 1
4672
+ },
4673
+ check: (device) => expect(device?.status).toBe("pending")
4674
+ }),
4675
+ budget({
4676
+ api: "iOS device request: the UDID's read and 1 write",
4677
+ read: ({ core }) => core.requestIosDevice({
4678
+ udid: "00008030-000000000000000c",
4679
+ name: "New iPhone",
4680
+ requestedBy: null
4681
+ }),
4682
+ adapter: reads(0, 0, 1, 0),
4683
+ engine: {
4684
+ calls: 1,
4685
+ rows: 0
4686
+ },
4687
+ writes: 1,
4688
+ check: (result) => expect(result.created).toBe(true)
4689
+ }),
4690
+ budget({
4691
+ api: "iOS device approval: the row and 1 write",
4692
+ read: ({ core, pendingDevice }) => core.approveIosDevice(pendingDevice.id, { approvedBy: null }),
4693
+ adapter: reads(1, 1, 0, 0),
4694
+ engine: {
4695
+ calls: 1,
4696
+ rows: 1
4697
+ },
4698
+ writes: 1,
4699
+ check: (device) => expect(device?.status).toBe("approved")
4700
+ }),
4701
+ budget({
4702
+ api: "iOS device outcome: the row and 1 write",
4703
+ read: ({ core, approvedDevice }) => core.recordIosDeviceOutcome({
4704
+ id: approvedDevice.id,
4705
+ seen: {
4706
+ status: "approved",
4707
+ approvedAtMs: approvedDevice.approved_at_ms
4708
+ },
4709
+ issuerId: "issuer-a",
4710
+ outcome: "registered"
4711
+ }),
4712
+ adapter: reads(1, 1, 0, 0),
4713
+ engine: {
4714
+ calls: 1,
4715
+ rows: 1
4716
+ },
4717
+ writes: 1,
4718
+ check: (device) => expect(device?.status).toBe("registered")
4719
+ }),
4720
+ budget({
4721
+ api: "iOS devices in a build: the row and 1 write each",
4722
+ read: ({ core, approvedDevice }) => core.markIosDevicesInBuild({
4723
+ buildId: createBundleFixture("8012").id,
4724
+ ids: [approvedDevice.id]
4725
+ }),
4726
+ adapter: reads(1, 1, 0, 0),
4727
+ engine: {
4728
+ calls: 1,
4729
+ rows: 1
4730
+ },
4731
+ writes: 1
4732
+ }),
4733
+ budget({
4734
+ api: "iOS device delete: the row and 1 write",
4735
+ read: ({ core, pendingDevice }) => core.deleteIosDevice(pendingDevice.id),
4736
+ adapter: reads(1, 1, 0, 0),
4737
+ engine: {
4738
+ calls: 1,
4739
+ rows: 1
4740
+ },
4741
+ writes: 1,
4742
+ check: (device) => expect(device?.udid).toBe(BUDGET_PENDING_UDID)
4743
+ }),
4744
+ budget({
4745
+ api: "iOS device account read, no claim yet: its row, then the earliest registration",
4746
+ read: ({ core }) => core.findIosDeviceAccount(),
4747
+ adapter: reads(1, 1, 1, 1),
4748
+ engine: {
4749
+ calls: 2,
4750
+ rows: 1
4751
+ },
4752
+ check: (account) => expect(account).toEqual({ issuerId: "issuer-a" })
4753
+ }),
4754
+ budget({
4755
+ api: "iOS device account, first claim: its one row's read, the earliest registration, and 1 write",
4756
+ read: ({ core }) => core.claimIosDeviceAccount("issuer-a"),
4757
+ adapter: reads(1, 1, 1, 1),
4758
+ engine: {
4759
+ calls: 2,
4760
+ rows: 1
4761
+ },
4762
+ writes: 1,
4763
+ check: (claim) => expect(claim).toEqual({
4764
+ issuerId: "issuer-a",
4765
+ claimed: true
4766
+ })
4767
+ }),
4768
+ budget({
4769
+ api: "iOS device account read, claimed: its one row's read",
4770
+ read: ({ core }) => core.findIosDeviceAccount(),
4771
+ adapter: reads(1, 1, 0, 0),
4772
+ engine: {
4773
+ calls: 1,
4774
+ rows: 1
4775
+ },
4776
+ check: (account) => expect(account).toEqual({ issuerId: "issuer-a" })
4777
+ }),
4778
+ budget({
4779
+ api: "iOS device account, claimed: its one row's read",
4780
+ read: ({ core }) => core.claimIosDeviceAccount("issuer-b"),
4781
+ adapter: reads(1, 1, 0, 0),
4782
+ engine: {
4783
+ calls: 1,
4784
+ rows: 1
4785
+ },
4786
+ check: (claim) => expect(claim).toEqual({
4787
+ issuerId: "issuer-a",
4788
+ claimed: false
4789
+ })
4790
+ }),
3709
4791
  budget({
3710
4792
  api: "record an insights event: 2 dependent rounds of batch gets and 1 write",
3711
4793
  read: ({ insights }) => insights.recordEvent(eventOf(27, {
@@ -3736,6 +4818,7 @@ const READ_BUDGETS = [
3736
4818
  const setupReadBudgetTestSuite = (options) => {
3737
4819
  describe(`${options.name} read budgets`, () => {
3738
4820
  let created;
4821
+ let tables;
3739
4822
  let database;
3740
4823
  let seeded;
3741
4824
  let writes = 0;
@@ -3746,8 +4829,9 @@ const setupReadBudgetTestSuite = (options) => {
3746
4829
  apiKeys(),
3747
4830
  remoteConfig()
3748
4831
  ];
4832
+ tables = [...toolingTargetOf(plugins).schema.tables, SETTINGS_TABLE];
3749
4833
  created = await options.createAdapter({
3750
- tables: [...toolingTargetOf(plugins).schema.tables, SETTINGS_TABLE],
4834
+ tables,
3751
4835
  nativePageSize: NATIVE_PAGE_SIZE
3752
4836
  });
3753
4837
  const { adapter } = created;
@@ -3787,6 +4871,42 @@ const setupReadBudgetTestSuite = (options) => {
3787
4871
  expect(await examined.total(), "rows examined").toBeLessThanOrEqual((examined.perRow ?? 1) * (keys + rows) + (examined.perRead ?? 0) * (gets + queries));
3788
4872
  }
3789
4873
  });
4874
+ /** Install `n`'s first event, all in one hour of day 4: the same rows each. */
4875
+ const newInstall = (n) => eventOf(400 + n, {
4876
+ install_id: `new-install-${n}`,
4877
+ user_id: null,
4878
+ received_at_ms: T0 + 4 * DAY + n * 1e3
4879
+ });
4880
+ /** Events of later days, which no prune below reaches. */
4881
+ const store = async (from, count) => {
4882
+ for (let n = from; n < from + count; n += 1) await seeded.insights.recordEvent(newInstall(n));
4883
+ };
4884
+ 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) => {
4885
+ const { written } = created;
4886
+ if (written === void 0) return context.skip();
4887
+ const most = async (n) => {
4888
+ written.reset();
4889
+ await seeded.insights.recordEvent(newInstall(n));
4890
+ return Math.max(...await written.rows());
4891
+ };
4892
+ await store(1, 60);
4893
+ expect(await most(61)).toBeLessThanOrEqual(2);
4894
+ await store(62, 60);
4895
+ expect(await most(122)).toBeLessThanOrEqual(2);
4896
+ });
4897
+ it("prune: deletes 5 expired events reading no more rows with 60 more events stored", async (context) => {
4898
+ const { adapter, written } = created;
4899
+ if (written === void 0) return context.skip();
4900
+ const events = tables.find(({ name }) => name === "bundle_events");
4901
+ const prune = async () => {
4902
+ written.reset();
4903
+ expect(await adapter.prune(events, T0 - DAY, 5)).toBe(5);
4904
+ return (await written.rows()).reduce((sum, rows) => sum + rows, 0);
4905
+ };
4906
+ const before = await prune();
4907
+ await store(200, 60);
4908
+ expect(await prune()).toBeLessThanOrEqual(before);
4909
+ });
3790
4910
  });
3791
4911
  };
3792
4912
  //#endregion
@@ -3970,8 +5090,8 @@ const snapshot = async (db) => {
3970
5090
  };
3971
5091
  /**
3972
5092
  * 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.
5093
+ * writes with each transaction and a compaction merges once, read back
5094
+ * exactly as transactional writes read.
3975
5095
  */
3976
5096
  const setupAggregateBatchingTestSuite = ({ name, createAdapter, oversizedRows }) => {
3977
5097
  const tables = [...toolingTargetOf([plugin]).schema.tables, ...aggregateBatchingTables];
@@ -4007,21 +5127,15 @@ const setupAggregateBatchingTestSuite = ({ name, createAdapter, oversizedRows })
4007
5127
  afterEach(async () => {
4008
5128
  for (const cleanup of cleanups.splice(0)) await cleanup();
4009
5129
  });
4010
- for (const mode of ["log", "memory"]) it(`reads what transactional writes read, in ${mode} mode`, async () => {
4011
- const { db } = server(await store(), { mode });
5130
+ it("reads what transactional writes read", async () => {
5131
+ const { db } = server(await store(), {});
4012
5132
  for (let step = 0; step < 36; step += 1) await open(db, step);
4013
5133
  expect(await snapshot(db)).toEqual(await expected(36));
4014
5134
  }, 12e4);
4015
5135
  it("applies each log row once when two servers compact while 16 writers commit", async () => {
4016
5136
  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
- });
5137
+ const first = server(adapter, { windowMs: 0 });
5138
+ const second = server(adapter, { windowMs: 0 });
4025
5139
  const report = await runContentionHarness({
4026
5140
  transactions: 12,
4027
5141
  ratePerSecond: 1e3,
@@ -4039,7 +5153,7 @@ const setupAggregateBatchingTestSuite = ({ name, createAdapter, oversizedRows })
4039
5153
  expect(await snapshot(second.db)).toEqual(await expected(48));
4040
5154
  }, 3e5);
4041
5155
  it("applies a log row larger than one write in parts, each change once", async () => {
4042
- const { db, flush } = server(await store(), { mode: "log" });
5156
+ const { db, flush } = server(await store(), {});
4043
5157
  await db.transaction(async (tx) => {
4044
5158
  for (let day = 1; day <= oversizedRows; day += 1) tx.aggregate("opens", { day }, { opens: day }, { shardBy: "i" });
4045
5159
  });
@@ -4231,18 +5345,13 @@ const createPluginTestHarness = async (plugin, options = {}) => {
4231
5345
  * bundles through the engine. A patch's base comes before it in `bundles`.
4232
5346
  */
4233
5347
  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
- }
5348
+ await createEngine(database).core.transaction(async (tx) => {
5349
+ for (const bundle of bundles) {
5350
+ tx.create("bundles", bundleToRow(bundle));
5351
+ for (const platformKey of [bundle.platform, "*"]) tx.aggregate("bundle_totals", { platform_key: platformKey }, { bundles: 1 });
5352
+ for (const row of bundleToPatchRows(bundle)) tx.create("bundle_patches", row);
5353
+ }
5354
+ });
4246
5355
  };
4247
5356
  //#endregion
4248
5357
  //#region src/insights/expectInsightsIndex.ts