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

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, 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) => ({
@@ -128,7 +128,8 @@ const createReleaseRowFixture = (suffix, bundle, channel) => ({
128
128
  source_release_id: null,
129
129
  revision: 1,
130
130
  created_at_ms: Number(suffix),
131
- updated_at_ms: Number(suffix)
131
+ updated_at_ms: Number(suffix),
132
+ label: null
132
133
  });
133
134
  const createBundleFixture = (suffix, _channel = "production") => ({
134
135
  id: fixtureId$1(suffix),
@@ -238,9 +239,9 @@ const setupBundleMethodsTestSuite = (options) => {
238
239
  /**
239
240
  * Core's operations through admin API protocol 2 that the bundle and catalog
240
241
  * 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.
242
+ * bundle's patch children, the native build registry, and the iOS device
243
+ * registry. Each test deletes what it wrote, except a native build, which the
244
+ * registry keeps: its IDs and channel are the test's own.
244
245
  */
245
246
  const setupCoreAdminTestSuite = (options) => {
246
247
  describe("Core admin API", () => {
@@ -290,6 +291,72 @@ const setupCoreAdminTestSuite = (options) => {
290
291
  expect(missing.status).toBe(404);
291
292
  await missing.text();
292
293
  });
294
+ it("reads channels by ID and pages them by name", async () => {
295
+ const [a, b, c] = await Promise.all([
296
+ "a",
297
+ "b",
298
+ "c"
299
+ ].map((suffix) => api.ensureChannel(`page-${namespace}-${suffix}`)));
300
+ expect((await adminJson(`/channels?ids=${c.id},${a.id},${namespace}`)).data).toEqual([c, a]);
301
+ const first = await adminJson(`/channels?limit=2&cursor=${encodeURIComponent(`page-${namespace}-`)}`);
302
+ expect(first).toEqual({
303
+ data: [a, b],
304
+ next: b.name
305
+ });
306
+ const second = await adminJson(`/channels?limit=2&cursor=${encodeURIComponent(first.next)}`);
307
+ expect(second.data[0]).toEqual(c);
308
+ for (const channel of [
309
+ a,
310
+ b,
311
+ c
312
+ ]) {
313
+ const deleted = await admin(`/channels/${channel.id}`, jsonRequest("DELETE"));
314
+ expect(deleted.status).toBe(204);
315
+ await deleted.text();
316
+ }
317
+ });
318
+ it("lists every scope that has releases by keyset pages", async () => {
319
+ const deployed = [
320
+ await api.deploy({
321
+ bundle: toDeployBundle(bundleRow("21")),
322
+ release: policy("scopes-a")
323
+ }),
324
+ await api.deploy({
325
+ bundle: toDeployBundle(bundleRow("22")),
326
+ release: policy("scopes-a")
327
+ }),
328
+ await api.deploy({
329
+ bundle: toDeployBundle(bundleRow("23")),
330
+ release: policy("scopes-b")
331
+ })
332
+ ];
333
+ const scopeKeys = [];
334
+ for (let cursor;;) {
335
+ const page = await adminJson(`/release-scopes?limit=2${cursor === void 0 ? "" : `&cursor=${encodeURIComponent(cursor)}`}`);
336
+ scopeKeys.push(...page.data);
337
+ if (page.next === void 0) break;
338
+ expect(page.next).toBe(page.data.at(-1));
339
+ cursor = page.next;
340
+ }
341
+ expect(scopeKeys).toEqual([...new Set(scopeKeys)].sort());
342
+ expect(scopeKeys).toEqual(expect.arrayContaining([...new Set(deployed.map(({ scope_key }) => scope_key))]));
343
+ const refusals = await Promise.all(["/release-scopes?limit=101", "/release-scopes?order=desc"].map(async (path) => (await admin(path)).status));
344
+ expect(refusals).toEqual([400, 400]);
345
+ });
346
+ it("takes at most 100 IDs a request", async () => {
347
+ const ids = Array.from({ length: 101 }, () => crypto.randomUUID());
348
+ 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", {
349
+ buildId: crypto.randomUUID(),
350
+ ids
351
+ })), "Marking iOS devices in a build takes at most 100 ids a request."]];
352
+ expect(await Promise.all(refusals.map(async ([response]) => ({
353
+ status: response.status,
354
+ body: await response.json().catch(() => null)
355
+ })))).toEqual(refusals.map(([, error]) => ({
356
+ status: 400,
357
+ body: expect.objectContaining({ error })
358
+ })));
359
+ });
293
360
  it("keeps a release's channel when a delete races the deploy into it", async () => {
294
361
  const channel = await api.ensureChannel(`race-${namespace}`);
295
362
  const [deleted, release] = await Promise.all([admin(`/channels/${channel.id}`, jsonRequest("DELETE")), api.deploy({
@@ -434,6 +501,36 @@ const setupCoreAdminTestSuite = (options) => {
434
501
  destination: "testflight",
435
502
  version: "1.0.0 (7)"
436
503
  }))).data).toBeNull();
504
+ const androidBuiltIn = bundleRow("64");
505
+ const androidResponse = await admin("/native-builds", jsonRequest("POST", {
506
+ id: bundleRow("864").id,
507
+ platform: "android",
508
+ channel,
509
+ fingerprintHash: "android-fingerprint",
510
+ appVersion: null,
511
+ minBundleId: androidBuiltIn.id,
512
+ gitCommitHash: null,
513
+ buildKey: null,
514
+ buildNumber: "64",
515
+ artifact: {
516
+ kind: "aab",
517
+ storageUri: "storage://native-builds/android/64/app.aab",
518
+ byteSize: 1e3
519
+ },
520
+ embeddedBundle: {
521
+ manifestStorageUri: androidBuiltIn.manifest_storage_uri,
522
+ manifestFileHash: androidBuiltIn.manifest_file_hash,
523
+ assetBaseStorageUri: androidBuiltIn.asset_base_storage_uri
524
+ }
525
+ }));
526
+ expect(androidResponse.status).toBe(201);
527
+ await androidResponse.text();
528
+ const production = await admin(`/native-builds/${bundleRow("864").id}/submission`, jsonRequest("POST", {
529
+ destination: "play-production",
530
+ version: "1.0.0 (64)"
531
+ }));
532
+ expect(production.status).toBe(200);
533
+ expect((await production.json()).data.submitted_to).toBe("play-production");
437
534
  const wrongStore = await admin(`/native-builds/${newest.id}/submission`, jsonRequest("POST", {
438
535
  destination: "play-internal",
439
536
  version: "1.0.0 (7)"
@@ -455,6 +552,393 @@ const setupCoreAdminTestSuite = (options) => {
455
552
  const after = await adminJson("/bundles?limit=1&total=true");
456
553
  expect(after.total).toBe(before.total);
457
554
  });
555
+ it("marks one store build per native build scope, replacing and clearing it", async () => {
556
+ const channel = `store-build-${namespace}`;
557
+ const register = async (suffix, fingerprintHash) => {
558
+ const builtIn = bundleRow(suffix);
559
+ const response = await admin("/native-builds", jsonRequest("POST", {
560
+ id: bundleRow(`8${suffix}`).id,
561
+ platform: "ios",
562
+ channel,
563
+ fingerprintHash,
564
+ appVersion: null,
565
+ minBundleId: builtIn.id,
566
+ gitCommitHash: null,
567
+ buildKey: null,
568
+ buildNumber: suffix,
569
+ artifact: {
570
+ kind: "ipa",
571
+ storageUri: `storage://native-builds/ios/${suffix}/App.ipa`,
572
+ byteSize: 1e3
573
+ },
574
+ embeddedBundle: {
575
+ manifestStorageUri: builtIn.manifest_storage_uri,
576
+ manifestFileHash: builtIn.manifest_file_hash,
577
+ assetBaseStorageUri: builtIn.asset_base_storage_uri
578
+ }
579
+ }));
580
+ expect(response.status).toBe(201);
581
+ return (await response.json()).data;
582
+ };
583
+ const mark = (id, storeBuild) => admin(`/native-builds/${id}/store-build`, jsonRequest("POST", { storeBuild }));
584
+ const markRead = (fingerprintHash) => `/native-builds/latest?platform=ios&channel=${encodeURIComponent(channel)}&fingerprintHash=${fingerprintHash}&storeBuild=true`;
585
+ const older = await register("64", "store-fingerprint");
586
+ const newer = await register("65", "store-fingerprint");
587
+ const otherScope = await register("66", "store-fingerprint-b");
588
+ expect(older.is_store_build).toBe(false);
589
+ expect((await adminJson(markRead("store-fingerprint"))).data).toBeNull();
590
+ const marked = await mark(older.id, true);
591
+ expect(marked.status).toBe(200);
592
+ expect(await marked.json()).toMatchObject({ data: {
593
+ nativeBuild: {
594
+ id: older.id,
595
+ is_store_build: true
596
+ },
597
+ previous: null
598
+ } });
599
+ expect((await adminJson(markRead("store-fingerprint"))).data).toEqual({
600
+ ...older,
601
+ is_store_build: true
602
+ });
603
+ expect((await adminJson(`/native-builds/latest?platform=ios&channel=${encodeURIComponent(channel)}&fingerprintHash=store-fingerprint`)).data).toEqual(newer);
604
+ expect((await adminJson(markRead("store-fingerprint-b"))).data).toBeNull();
605
+ const replaced = await mark(newer.id, true);
606
+ expect(await replaced.json()).toMatchObject({ data: {
607
+ nativeBuild: {
608
+ id: newer.id,
609
+ is_store_build: true
610
+ },
611
+ previous: {
612
+ id: older.id,
613
+ is_store_build: false
614
+ }
615
+ } });
616
+ expect((await adminJson(`/native-builds/${older.id}`)).data).toEqual(older);
617
+ expect((await adminJson(markRead("store-fingerprint"))).data).toEqual({
618
+ ...newer,
619
+ is_store_build: true
620
+ });
621
+ const race = async (ids) => {
622
+ const responses = await Promise.all(ids.map((id) => mark(id, true)));
623
+ expect(responses.map(({ status }) => status)).toEqual(ids.map(() => 200));
624
+ const results = await Promise.all(responses.map((response) => response.json()));
625
+ expect(results.map(({ data }) => data.nativeBuild.is_store_build)).toEqual(ids.map(() => true));
626
+ const holders = (await Promise.all([older, newer].map(async ({ id }) => (await adminJson(`/native-builds/${id}`)).data))).filter(({ is_store_build }) => is_store_build);
627
+ expect(holders).toHaveLength(1);
628
+ expect(ids).toContain(holders[0].id);
629
+ };
630
+ await race([
631
+ older.id,
632
+ newer.id,
633
+ older.id
634
+ ]);
635
+ await mark(older.id, false).then((response) => response.text());
636
+ await mark(newer.id, false).then((response) => response.text());
637
+ expect((await adminJson(markRead("store-fingerprint"))).data).toBeNull();
638
+ await race([older.id, newer.id]);
639
+ await (await mark(newer.id, false)).text();
640
+ await mark(older.id, false).then((response) => response.text());
641
+ expect((await adminJson(markRead("store-fingerprint"))).data).toBeNull();
642
+ expect(await (await mark(bundleRow("869").id, true)).json()).toMatchObject({ data: null });
643
+ const refused = await admin(`/native-builds/${older.id}/store-build`, jsonRequest("POST", {}));
644
+ expect(refused.status).toBe(400);
645
+ await refused.text();
646
+ await mark(otherScope.id, true).then((response) => response.text());
647
+ await adminJson(`/native-builds/${otherScope.id}`, jsonRequest("DELETE"));
648
+ expect((await adminJson(markRead("store-fingerprint-b"))).data).toBeNull();
649
+ });
650
+ it("records a sandbox build on any channel, finds it through its sandbox scope, and refuses one its artifact doesn't describe", async () => {
651
+ const sandboxChannel = `pr-${namespace}`;
652
+ const channel = `plain-${namespace}`;
653
+ const sandboxFields = {
654
+ isSandbox: true,
655
+ sandboxUrlScheme: "acme-preview",
656
+ sandboxAppId: "com.example.app",
657
+ exportMethod: "ad-hoc"
658
+ };
659
+ const post = (suffix, body) => {
660
+ const builtIn = bundleRow(suffix);
661
+ return admin("/native-builds", jsonRequest("POST", {
662
+ id: bundleRow(`8${suffix}`).id,
663
+ platform: "ios",
664
+ fingerprintHash: "sandbox-fingerprint",
665
+ appVersion: null,
666
+ minBundleId: builtIn.id,
667
+ gitCommitHash: null,
668
+ buildKey: null,
669
+ artifact: {
670
+ kind: "ipa",
671
+ storageUri: `storage://native-builds/ios/${suffix}/App.ipa`,
672
+ byteSize: 1e3
673
+ },
674
+ embeddedBundle: {
675
+ manifestStorageUri: builtIn.manifest_storage_uri,
676
+ manifestFileHash: builtIn.manifest_file_hash,
677
+ assetBaseStorageUri: builtIn.asset_base_storage_uri
678
+ },
679
+ ...body
680
+ }));
681
+ };
682
+ const refusal = async (suffix, body) => {
683
+ const response = await post(suffix, body);
684
+ await response.text();
685
+ return response.status;
686
+ };
687
+ expect(await refusal("74", {
688
+ channel,
689
+ isSandbox: true
690
+ })).toBe(400);
691
+ expect(await refusal("74", {
692
+ channel,
693
+ ...sandboxFields,
694
+ sandboxAppId: void 0
695
+ })).toBe(400);
696
+ expect(await refusal("74", {
697
+ channel,
698
+ sandboxAppId: "com.example.app"
699
+ })).toBe(400);
700
+ expect(await refusal("74", {
701
+ channel: sandboxChannel,
702
+ isSandbox: null
703
+ })).toBe(400);
704
+ expect(await refusal("74", {
705
+ channel: sandboxChannel,
706
+ isSandbox: "yes"
707
+ })).toBe(400);
708
+ expect(await refusal("74", {
709
+ channel,
710
+ sandboxUrlScheme: "acme-preview"
711
+ })).toBe(400);
712
+ expect(await refusal("74", {
713
+ channel: sandboxChannel,
714
+ ...sandboxFields,
715
+ sandboxUrlScheme: "Acme"
716
+ })).toBe(400);
717
+ expect(await refusal("74", {
718
+ channel: sandboxChannel,
719
+ ...sandboxFields,
720
+ sandboxUrlScheme: 42
721
+ })).toBe(400);
722
+ expect(await refusal("74", {
723
+ channel,
724
+ nativeAppVersion: 42
725
+ })).toBe(400);
726
+ expect(await refusal("74", {
727
+ channel,
728
+ nativeAppVersion: " "
729
+ })).toBe(400);
730
+ const tagged = await post("72", {
731
+ channel: sandboxChannel,
732
+ ...sandboxFields,
733
+ nativeAppVersion: "1.6.0"
734
+ });
735
+ expect(tagged.status).toBe(201);
736
+ const sandboxBuild = (await tagged.json()).data;
737
+ const plain = await post("73", {
738
+ channel: sandboxChannel,
739
+ isSandbox: false
740
+ });
741
+ expect(plain.status).toBe(201);
742
+ const plainBuild = (await plain.json()).data;
743
+ expect(sandboxBuild).toMatchObject({
744
+ is_sandbox: true,
745
+ is_store_build: false,
746
+ sandbox_url_scheme: "acme-preview",
747
+ native_app_version: "1.6.0"
748
+ });
749
+ expect(plainBuild).toMatchObject({
750
+ is_sandbox: false,
751
+ is_store_build: false,
752
+ sandbox_url_scheme: null,
753
+ export_method: null,
754
+ native_app_version: null
755
+ });
756
+ const sandboxLookup = "sandboxAppId=com.example.app&sandboxUrlScheme=acme-preview&artifactKind=ipa&distribution=direct";
757
+ expect((await adminJson(`/native-builds/${sandboxBuild.id}`)).data).toEqual(sandboxBuild);
758
+ expect((await adminJson(`/native-builds/${plainBuild.id}`)).data).toEqual(plainBuild);
759
+ expect((await adminJson(`/native-builds/latest?platform=ios&channel=other-${namespace}&fingerprintHash=sandbox-fingerprint&${sandboxLookup}`)).data).toEqual(sandboxBuild);
760
+ expect((await adminJson(`/native-builds/latest?platform=ios&channel=${encodeURIComponent(sandboxChannel)}&fingerprintHash=sandbox-fingerprint`)).data).toEqual(plainBuild);
761
+ const partial = await admin(`/native-builds/latest?platform=ios&channel=${encodeURIComponent(sandboxChannel)}&fingerprintHash=sandbox-fingerprint&sandboxAppId=com.example.app`);
762
+ expect(partial.status).toBe(400);
763
+ await partial.text();
764
+ const invalid = await admin(`/native-builds/latest?platform=ios&channel=${encodeURIComponent(sandboxChannel)}&fingerprintHash=sandbox-fingerprint&${sandboxLookup.replace("artifactKind=ipa", "artifactKind=apk")}`);
765
+ expect(invalid.status).toBe(400);
766
+ await invalid.text();
767
+ expect((await adminJson(`/native-builds/latest?platform=ios&channel=${encodeURIComponent(sandboxChannel)}&fingerprintHash=sandbox-fingerprint&${sandboxLookup}&builtInOlderThan=ffffffff-ffff-7fff-bfff-ffffffffffff`)).data).toBeNull();
768
+ const patched = await admin(`/bundles/${plainBuild.min_bundle_id}`, jsonRequest("PATCH", { patches: [{
769
+ baseBundleId: sandboxBuild.min_bundle_id,
770
+ baseFileHash: "base-hash",
771
+ byteSize: 42,
772
+ patchFileHash: "patch-hash",
773
+ patchStorageUri: "storage://patches/sandbox.patch"
774
+ }] }));
775
+ expect(patched.status).toBe(400);
776
+ expect(await patched.text()).toContain("A sandbox build's built-in bundle is no patch base.");
777
+ const deployed = await admin("/releases", jsonRequest("POST", { deployments: [{
778
+ bundle: {
779
+ ...toDeployBundle(bundleRow("76")),
780
+ patches: [{
781
+ baseBundleId: sandboxBuild.min_bundle_id,
782
+ baseFileHash: "base-hash",
783
+ byteSize: 42,
784
+ patchFileHash: "patch-hash",
785
+ patchStorageUri: "storage://patches/sandbox-deploy.patch"
786
+ }]
787
+ },
788
+ release: policy("sandbox-patch")
789
+ }] }));
790
+ expect(deployed.status).toBe(400);
791
+ expect(await deployed.text()).toContain("A sandbox build's built-in bundle is no patch base.");
792
+ const notDeployed = await admin(`/bundles/${bundleRow("76").id}`);
793
+ expect(notDeployed.status).toBe(404);
794
+ await notDeployed.text();
795
+ const marked = await admin(`/native-builds/${sandboxBuild.id}/store-build`, jsonRequest("POST", { storeBuild: true }));
796
+ expect(marked.status).toBe(400);
797
+ await marked.text();
798
+ });
799
+ it("finds a scope's build of one kind, and a sandbox build's other install target", async () => {
800
+ const channel = `kinds-${namespace}`;
801
+ const register = async (suffix, kind, body = {}) => {
802
+ const builtIn = bundleRow(suffix);
803
+ const response = await admin("/native-builds", jsonRequest("POST", {
804
+ id: bundleRow(`8${suffix}`).id,
805
+ platform: "ios",
806
+ channel,
807
+ fingerprintHash: "kind-fingerprint",
808
+ appVersion: null,
809
+ minBundleId: builtIn.id,
810
+ gitCommitHash: null,
811
+ buildKey: null,
812
+ artifact: {
813
+ kind,
814
+ storageUri: `storage://native-builds/ios/${suffix}/App.${kind === "ipa" ? "ipa" : "app.zip"}`,
815
+ byteSize: 1e3
816
+ },
817
+ embeddedBundle: {
818
+ manifestStorageUri: builtIn.manifest_storage_uri,
819
+ manifestFileHash: builtIn.manifest_file_hash,
820
+ assetBaseStorageUri: builtIn.asset_base_storage_uri
821
+ },
822
+ ...body
823
+ }));
824
+ expect(response.status).toBe(201);
825
+ return (await response.json()).data;
826
+ };
827
+ const sandbox = (exportMethod) => ({
828
+ isSandbox: true,
829
+ sandboxUrlScheme: "acme-preview",
830
+ sandboxAppId: "com.example.app",
831
+ exportMethod
832
+ });
833
+ const ipa = await register("81", "ipa");
834
+ const app = await register("82", "app");
835
+ const latest = `/native-builds/latest?platform=ios&channel=${encodeURIComponent(channel)}&fingerprintHash=kind-fingerprint`;
836
+ expect((await adminJson(latest)).data).toEqual(app);
837
+ expect((await adminJson(`${latest}&kind=ipa`)).data).toEqual(ipa);
838
+ const refused = await admin(`${latest}&kind=apk`);
839
+ expect(refused.status).toBe(400);
840
+ await refused.text();
841
+ const sandboxIpa = await register("83", "ipa", sandbox("ad-hoc"));
842
+ const sandboxApp = await register("84", "app", sandbox(null));
843
+ expect((await adminJson(`/native-builds/${sandboxIpa.id}/sibling`)).data).toEqual(sandboxApp);
844
+ expect((await adminJson(`/native-builds/${sandboxApp.id}/sibling`)).data).toEqual(sandboxIpa);
845
+ expect((await adminJson(`/native-builds/${ipa.id}/sibling`)).data).toBeNull();
846
+ expect((await adminJson(`/native-builds/${bundleRow("899").id}/sibling`)).data).toBeNull();
847
+ expect((await adminJson(`/native-builds/built-in/${ipa.min_bundle_id}`)).data).toEqual(ipa);
848
+ expect((await adminJson(`/native-builds/built-in/${bundleRow("899").id}`)).data).toBeNull();
849
+ });
850
+ it("requests, approves, renames, records, and removes iOS devices", async () => {
851
+ const udid = namespace.replaceAll("-", "").padEnd(40, "0");
852
+ const device = async (path, init) => (await adminJson(path, init)).data;
853
+ const requested = await adminJson("/ios-devices", jsonRequest("POST", {
854
+ udid: udid.toUpperCase(),
855
+ name: "Kim's iPhone",
856
+ requestedBy: "kim@team.dev"
857
+ }));
858
+ expect(requested.data.created).toBe(true);
859
+ const { id } = requested.data.device;
860
+ expect(requested.data.device).toMatchObject({
861
+ udid,
862
+ status: "pending",
863
+ requested_by: "kim@team.dev"
864
+ });
865
+ try {
866
+ const again = await adminJson("/ios-devices", jsonRequest("POST", {
867
+ udid,
868
+ name: "Other",
869
+ requestedBy: null
870
+ }));
871
+ expect(again.data).toEqual({
872
+ device: requested.data.device,
873
+ created: false
874
+ });
875
+ const raced = `${udid.slice(0, 39)}f`;
876
+ const racing = await Promise.all(["Other", "Another"].map((name) => adminJson("/ios-devices", jsonRequest("POST", {
877
+ udid: raced,
878
+ name,
879
+ requestedBy: null
880
+ }))));
881
+ expect(racing.map(({ data }) => data.created).sort()).toEqual([false, true]);
882
+ expect(racing[0].data.device.id).toBe(racing[1].data.device.id);
883
+ await adminJson(`/ios-devices/${racing[0].data.device.id}`, jsonRequest("DELETE"));
884
+ expect(await device(`/ios-devices/udid/${udid}`)).toEqual(requested.data.device);
885
+ const pending = await adminJson("/ios-devices?status=pending&limit=500");
886
+ expect(pending.data.map((row) => row.id)).toContain(id);
887
+ const approval = await device(`/ios-devices/${id}/approval`, jsonRequest("POST", { approvedBy: "lead@team.dev" }));
888
+ expect(approval).toMatchObject({
889
+ status: "approved",
890
+ approved_by: "lead@team.dev"
891
+ });
892
+ expect(await device(`/ios-devices/${id}`, jsonRequest("PATCH", { name: "Kim's work iPhone" }))).toMatchObject({
893
+ name: "Kim's work iPhone",
894
+ status: "approved"
895
+ });
896
+ const registered = await device(`/ios-devices/${id}/outcome`, jsonRequest("POST", {
897
+ seen: {
898
+ status: "approved",
899
+ approvedAtMs: approval.approved_at_ms
900
+ },
901
+ issuerId: "issuer-a",
902
+ outcome: "registered"
903
+ }));
904
+ expect(registered).toMatchObject({
905
+ status: "registered",
906
+ apple_issuer_id: "issuer-a"
907
+ });
908
+ expect(await device(`/ios-devices/${id}/outcome`, jsonRequest("POST", {
909
+ seen: {
910
+ status: "approved",
911
+ approvedAtMs: 1
912
+ },
913
+ issuerId: "issuer-a",
914
+ outcome: "missing"
915
+ }))).toBeNull();
916
+ const claims = await Promise.all(["issuer-a", "issuer-b"].map((issuerId) => adminJson("/ios-devices/account", jsonRequest("POST", { issuerId }))));
917
+ const owner = claims.find(({ data }) => data.claimed)?.data.issuerId;
918
+ expect(claims.filter(({ data }) => data.claimed)).toHaveLength(1);
919
+ expect(claims.map(({ data }) => data.issuerId)).toEqual([owner, owner]);
920
+ expect(await adminJson("/ios-devices/account")).toEqual({ data: { issuerId: owner } });
921
+ const buildId = bundleRow("90").id;
922
+ const marked = await admin("/ios-devices/in-build", jsonRequest("POST", {
923
+ buildId,
924
+ ids: [id]
925
+ }));
926
+ expect(marked.status).toBe(204);
927
+ expect((await device(`/ios-devices/udid/${udid}`))?.build_id).toBe(buildId);
928
+ const refused = await admin("/ios-devices", jsonRequest("POST", {
929
+ udid: "1234",
930
+ name: "x",
931
+ requestedBy: null
932
+ }));
933
+ expect(refused.status).toBe(400);
934
+ await refused.text();
935
+ } finally {
936
+ await adminJson(`/ios-devices/${id}`, jsonRequest("DELETE"));
937
+ }
938
+ expect(await device(`/ios-devices/udid/${udid}`)).toBeNull();
939
+ expect(await device(`/ios-devices/${id}`, jsonRequest("DELETE"))).toBeNull();
940
+ expect((await adminJson("/ios-devices/account")).data).toMatchObject({ issuerId: expect.any(String) });
941
+ });
458
942
  it("lists the patches that start from a bundle", async () => {
459
943
  const base = bundleRow("50");
460
944
  const target = bundleRow("51");
@@ -486,6 +970,338 @@ const setupCoreAdminTestSuite = (options) => {
486
970
  });
487
971
  };
488
972
  //#endregion
973
+ //#region src/createMeasuredDatabase.ts
974
+ const storageOf = (storage) => ({
975
+ name: "measuredStorage",
976
+ protocol: "storage",
977
+ get: async ({ storageUri }) => {
978
+ const text = await storage.readStorageText?.(storageUri) ?? null;
979
+ return { response: text === null ? null : new Response(text) };
980
+ },
981
+ getDownloadUrl: async ({ storageUri }) => ({ url: await storage.resolveFileUrl(storageUri) })
982
+ });
983
+ /**
984
+ * Core and the plugins over `adapter` as `createHotUpdater` runs them: what
985
+ * read-budget suites measure. The database is `meterReads` over
986
+ * `verifyAdapter(adapter)`, so every adapter call is checked against the
987
+ * contract and `measureReads` reports each call's reads; the adapter runs
988
+ * as given, without the schema fence. It loads `@hot-updater/server`, an
989
+ * optional peer, when called.
990
+ */
991
+ const createMeasuredDatabase = async (adapter, plugins, options = {}) => {
992
+ const { createHotUpdater } = await import("@hot-updater/server");
993
+ let clientAuth;
994
+ const observed = plugins.map((plugin) => Object.defineProperties({}, {
995
+ ...Object.getOwnPropertyDescriptors(plugin),
996
+ init: {
997
+ configurable: true,
998
+ enumerable: true,
999
+ writable: true,
1000
+ value: (context) => {
1001
+ const instance = plugin.init(options.now === void 0 ? context : {
1002
+ ...context,
1003
+ now: options.now
1004
+ });
1005
+ if (instance.clientAuth !== void 0) clientAuth = instance.clientAuth;
1006
+ return instance;
1007
+ }
1008
+ }
1009
+ }));
1010
+ const database = meterReads({
1011
+ name: "measured",
1012
+ adapter: verifyAdapter(adapter)
1013
+ });
1014
+ const hotUpdater = createHotUpdater({
1015
+ database,
1016
+ storage: options.storage === void 0 ? {
1017
+ name: "measuredStorage",
1018
+ protocol: "none"
1019
+ } : storageOf(options.storage),
1020
+ plugins: observed,
1021
+ ...plugins.some((plugin) => plugin.provides?.clientAuth === true) ? {} : { clientAccess: "public" }
1022
+ });
1023
+ return {
1024
+ core: hotUpdater.core,
1025
+ api: hotUpdater.api,
1026
+ ...clientAuth === void 0 ? {} : { clientAuth },
1027
+ measureReads: database.measureReads
1028
+ };
1029
+ };
1030
+ //#endregion
1031
+ //#region src/setupReleaseLabelEngineTestSuite.ts
1032
+ const NATIVE_PAGE_SIZE$1 = 2;
1033
+ /**
1034
+ * Release labels on a backend's own rows, which no HTTP API writes: the
1035
+ * releases a server of an earlier release left without labels and without
1036
+ * counters, which the fill labels per channel and platform in ID order,
1037
+ * concurrent fills and a deploy included, rebuilding the catalogs compiled
1038
+ * without them; and the label index, which refuses a second row with a label
1039
+ * and holds any number without one. Rows are written as an earlier server
1040
+ * wrote them through a second engine on the same adapter. Register it beside
1041
+ * `setupReadBudgetTestSuite`, with the same options.
1042
+ */
1043
+ const setupReleaseLabelEngineTestSuite = (options) => {
1044
+ describe(`${options.name} release labels`, () => {
1045
+ let created;
1046
+ let core;
1047
+ let raw;
1048
+ beforeAll(async () => {
1049
+ created = await options.createAdapter({
1050
+ tables: [...toolingTargetOf([]).schema.tables, SETTINGS_TABLE],
1051
+ nativePageSize: NATIVE_PAGE_SIZE$1
1052
+ });
1053
+ ({core} = await createMeasuredDatabase(created.adapter, []));
1054
+ raw = createEngine({
1055
+ name: "raw",
1056
+ adapter: created.adapter
1057
+ }).core;
1058
+ }, 18e4);
1059
+ afterAll(async () => {
1060
+ await created?.cleanup?.();
1061
+ }, 6e4);
1062
+ let suffix = 0;
1063
+ let namespace = 0;
1064
+ const channel = (name) => `${name}-${namespace}`;
1065
+ const deploy = async (name, { platform = "ios", fingerprintHash = null } = {}) => {
1066
+ suffix += 1;
1067
+ const deployment = {
1068
+ bundle: {
1069
+ ...createBundleFixture(String(9e3 + suffix)),
1070
+ platform
1071
+ },
1072
+ release: {
1073
+ channel: channel(name),
1074
+ enabled: true,
1075
+ fingerprintHash,
1076
+ message: null,
1077
+ shouldForceUpdate: false,
1078
+ targetAppVersion: fingerprintHash === null ? "1.0.x" : null
1079
+ }
1080
+ };
1081
+ const [result] = await core.deploy([deployment]);
1082
+ return result.release;
1083
+ };
1084
+ /** Takes the labels off `releases` and drops their pairs' counters, as an earlier server left them. */
1085
+ const asBeforeLabels = async (releases) => {
1086
+ await raw.transaction(async (tx) => {
1087
+ const counters = /* @__PURE__ */ new Set();
1088
+ for (const { id } of releases) {
1089
+ const row = await tx.findOne("releases", { id });
1090
+ tx.update("releases", row, { label: null });
1091
+ counters.add(`releases/${row.platform}/${row.channel_id}`);
1092
+ }
1093
+ for (const id of counters) {
1094
+ const counter = await tx.findOne("label_sequences", { id });
1095
+ if (counter !== null) await tx.delete("label_sequences", counter);
1096
+ }
1097
+ });
1098
+ };
1099
+ const labelOf = async (id) => (await core.getRelease(id))?.label;
1100
+ 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 () => {
1101
+ namespace += 1;
1102
+ const releases = [
1103
+ await deploy("fill"),
1104
+ await deploy("fill", { fingerprintHash: "fp-a" }),
1105
+ await deploy("fill"),
1106
+ await deploy("fill", { platform: "android" }),
1107
+ await deploy("fill", { fingerprintHash: "fp-b" })
1108
+ ];
1109
+ await asBeforeLabels(releases);
1110
+ for (const scope of new Set(releases.map((row) => row.scope_key))) await core.rebuildReleaseCatalog(scope);
1111
+ await expect(core.fillReleaseLabels({ dryRun: true })).resolves.toEqual({
1112
+ releases: 5,
1113
+ catalogs: 0
1114
+ });
1115
+ await expect(core.fillReleaseLabels()).resolves.toEqual({
1116
+ releases: 5,
1117
+ catalogs: 4
1118
+ });
1119
+ const inIdOrder = (rows) => rows.map(({ id }) => id).sort();
1120
+ const ios = inIdOrder(releases.filter(({ platform }) => platform === "ios"));
1121
+ const labels = {};
1122
+ for (const { id } of releases) labels[id] = await labelOf(id);
1123
+ expect(labels).toEqual({
1124
+ ...Object.fromEntries(ios.map((id, index) => [id, index + 1])),
1125
+ [releases[3].id]: 1
1126
+ });
1127
+ const served = JSON.parse((await core.getReleaseCatalogRow(releases[0].scope_key)).payload).releaseDescriptors;
1128
+ expect(Object.fromEntries(served.map(({ releaseId, label }) => [releaseId, label]))).toEqual({
1129
+ [releases[0].id]: labels[releases[0].id],
1130
+ [releases[2].id]: labels[releases[2].id]
1131
+ });
1132
+ await expect(core.fillReleaseLabels({ dryRun: true })).resolves.toEqual({
1133
+ releases: 0,
1134
+ catalogs: 0
1135
+ });
1136
+ await expect(deploy("fill")).resolves.toMatchObject({ label: 5 });
1137
+ });
1138
+ it("labels each release once when fills run beside a deploy that needs one", async () => {
1139
+ namespace += 1;
1140
+ const releases = [];
1141
+ for (let index = 0; index < 5; index += 1) releases.push(await deploy("race"));
1142
+ await asBeforeLabels(releases);
1143
+ const [, , deployed] = await Promise.all([
1144
+ core.fillReleaseLabels(),
1145
+ core.fillReleaseLabels(),
1146
+ deploy("race")
1147
+ ]);
1148
+ const labels = {};
1149
+ for (const { id } of releases) labels[id] = await labelOf(id);
1150
+ expect(labels).toEqual(Object.fromEntries(releases.map(({ id }) => id).sort().map((id, index) => [id, index + 1])));
1151
+ expect(deployed.label).toBe(6);
1152
+ });
1153
+ it("refuses a second release with a label in its channel and platform, and holds any number without one", async () => {
1154
+ namespace += 1;
1155
+ const releases = [
1156
+ await deploy("unique"),
1157
+ await deploy("unique"),
1158
+ await deploy("unique")
1159
+ ];
1160
+ const set = (id, label) => raw.transaction(async (tx) => {
1161
+ const row = await tx.findOne("releases", { id });
1162
+ tx.update("releases", row, { label });
1163
+ });
1164
+ await set(releases[0].id, null);
1165
+ await set(releases[1].id, null);
1166
+ await expect(set(releases[2].id, 2)).resolves.toBeUndefined();
1167
+ await expect(set(releases[0].id, 2)).rejects.toBeInstanceOf(DatabaseConstraintError);
1168
+ const other = await deploy("unique-other");
1169
+ expect(other.label).toBe(1);
1170
+ await expect(set(other.id, 2)).resolves.toBeUndefined();
1171
+ await set(other.id, 1);
1172
+ await set(releases[2].id, 3);
1173
+ await set(releases[1].id, 2);
1174
+ await set(releases[0].id, 1);
1175
+ await expect(core.getReleaseByLabel({
1176
+ channel: channel("unique"),
1177
+ platform: "ios",
1178
+ label: 3
1179
+ })).resolves.toMatchObject({ id: releases[2].id });
1180
+ });
1181
+ });
1182
+ };
1183
+ //#endregion
1184
+ //#region src/setupReleaseLabelTestSuite.ts
1185
+ /**
1186
+ * Release labels through a provider's admin and client HTTP APIs: deploys
1187
+ * take each channel and platform's next label, concurrent ones never the
1188
+ * same, a promotion takes the target's next, a delete leaves a gap, the
1189
+ * list, detail and label lookup answer it, and the scope's catalog serves
1190
+ * it. The backfill and the label index's uniqueness, which need rows an
1191
+ * earlier server wrote, are `setupReleaseLabelEngineTestSuite`'s.
1192
+ */
1193
+ const setupReleaseLabelTestSuite = (options) => {
1194
+ describe("Release labels", () => {
1195
+ const api = createAdminApiTestClient(options.getClient);
1196
+ const { adminJson } = api;
1197
+ let namespace;
1198
+ beforeEach(() => {
1199
+ namespace = crypto.randomUUID();
1200
+ });
1201
+ afterEach(async () => {
1202
+ await api.cleanup();
1203
+ });
1204
+ const bundleRow = (suffix) => ({
1205
+ ...createBundleRowFixture(suffix),
1206
+ id: `${namespace.slice(0, 8)}-0000-7000-8000-${suffix.padStart(12, "0")}`
1207
+ });
1208
+ const channel = (name = "labels") => `${name}-${namespace}`;
1209
+ const deploy = (suffix, { fingerprintHash = null, platform = "ios", channelName = channel() } = {}) => api.deploy({
1210
+ bundle: {
1211
+ ...toDeployBundle(bundleRow(suffix)),
1212
+ platform
1213
+ },
1214
+ release: {
1215
+ channel: channelName,
1216
+ enabled: true,
1217
+ fingerprintHash,
1218
+ message: null,
1219
+ shouldForceUpdate: false,
1220
+ targetAppVersion: fingerprintHash === null ? "1.0.x" : null
1221
+ }
1222
+ });
1223
+ const byLabel = async (label, { platform = "ios", channelName = channel() } = {}) => (await adminJson(`/release-labels?channel=${encodeURIComponent(channelName)}&platform=${platform}&label=${label}`)).data;
1224
+ const detail = async (id) => (await adminJson(`/releases/${encodeURIComponent(id)}`)).data;
1225
+ it("labels each channel and platform's deploys in order, and answers the label in the list, the detail and the lookup", async () => {
1226
+ const first = await deploy("1");
1227
+ const second = await deploy("2");
1228
+ const android = await deploy("3", { platform: "android" });
1229
+ expect([
1230
+ first.label,
1231
+ second.label,
1232
+ android.label
1233
+ ]).toEqual([
1234
+ 1,
1235
+ 2,
1236
+ 1
1237
+ ]);
1238
+ const { data: listed } = await adminJson(`/releases?channelId=${encodeURIComponent(first.channel_id)}&platform=ios&limit=10`);
1239
+ expect(Object.fromEntries(listed.map(({ id, label }) => [id, label]))).toEqual({
1240
+ [first.id]: 1,
1241
+ [second.id]: 2
1242
+ });
1243
+ await expect(detail(second.id)).resolves.toMatchObject({ label: 2 });
1244
+ await expect(byLabel(2)).resolves.toMatchObject({
1245
+ id: second.id,
1246
+ label: 2
1247
+ });
1248
+ await expect(byLabel(1, { platform: "android" })).resolves.toMatchObject({ id: android.id });
1249
+ await expect(byLabel(3)).resolves.toBeNull();
1250
+ });
1251
+ it("never gives concurrent deploys one label", async () => {
1252
+ await deploy("10");
1253
+ const releases = await Promise.all([
1254
+ "11",
1255
+ "12",
1256
+ "13",
1257
+ "14"
1258
+ ].map((suffix) => deploy(suffix, { fingerprintHash: `fingerprint-${suffix}` })));
1259
+ expect(releases.map(({ label }) => label).sort()).toEqual([
1260
+ 2,
1261
+ 3,
1262
+ 4,
1263
+ 5
1264
+ ]);
1265
+ });
1266
+ it("keeps a label through disable and enable, leaves a gap on delete, and gives a promotion the target's next label", async () => {
1267
+ const first = await deploy("21");
1268
+ const second = await deploy("22");
1269
+ await adminJson(`/releases/${encodeURIComponent(first.id)}`, jsonRequest("PATCH", { patch: { enabled: false } }));
1270
+ await adminJson(`/releases/${encodeURIComponent(first.id)}`, jsonRequest("PATCH", { patch: { enabled: true } }));
1271
+ await expect(detail(first.id)).resolves.toMatchObject({ label: 1 });
1272
+ await api.removeRelease(second.id);
1273
+ api.forget(second.id);
1274
+ await expect(deploy("23")).resolves.toMatchObject({ label: 3 });
1275
+ await deploy("24", { channelName: channel("target") });
1276
+ const { data: promoted } = await adminJson(`/releases/${encodeURIComponent(first.id)}/promote`, jsonRequest("POST", {
1277
+ targetChannel: channel("target"),
1278
+ action: "copy"
1279
+ }));
1280
+ api.track(promoted.target.release.id);
1281
+ expect(promoted.target.release).toMatchObject({ label: 2 });
1282
+ await expect(detail(first.id)).resolves.toMatchObject({ label: 1 });
1283
+ });
1284
+ it("serves each release's label in its scope's catalog", async () => {
1285
+ const first = await deploy("31");
1286
+ const second = await deploy("32");
1287
+ const response = await options.getClient().client(`/release-catalogs/app-version/ios/${encodeChannelKey(channel())}/1.0.0`);
1288
+ expect(response.status).toBe(200);
1289
+ const catalog = await response.json();
1290
+ expect(Object.fromEntries(catalog.releases.map(({ releaseId, label }) => [releaseId, label]))).toEqual({
1291
+ [first.id]: 1,
1292
+ [second.id]: 2
1293
+ });
1294
+ });
1295
+ it("has nothing to fill on a database whose releases all have labels", async () => {
1296
+ await deploy("41");
1297
+ await expect(adminJson("/release-labels/fill", jsonRequest("POST", { dryRun: true }))).resolves.toEqual({ data: {
1298
+ releases: 0,
1299
+ catalogs: 0
1300
+ } });
1301
+ });
1302
+ });
1303
+ };
1304
+ //#endregion
489
1305
  //#region src/setupSemverSatisfiesTestSuite.ts
490
1306
  /**
491
1307
  *
@@ -1152,7 +1968,7 @@ const setupReleaseCatalogTestSuite = (options) => {
1152
1968
  expect((await request(otherPath)).status).toBe(404);
1153
1969
  });
1154
1970
  it("caches an unknown scope's 404 like a catalog", async () => {
1155
- const response = await request(catalogPath());
1971
+ const response = await request(catalogPath(scope("unknown")));
1156
1972
  expect(response.status).toBe(404);
1157
1973
  expect(response.headers.get("cache-control")).toBe("public, max-age=0, s-maxage=5");
1158
1974
  expect(response.headers.get("cdn-cache-control")).toBe("public, max-age=5, stale-while-revalidate=5, stale-if-error=0");
@@ -1491,6 +2307,7 @@ const setupDatabaseTestSuite = (options) => {
1491
2307
  setupCoreAdminTestSuite({ getClient });
1492
2308
  setupBundleMethodsTestSuite({ getClient });
1493
2309
  setupReleaseCatalogTestSuite({ getClient });
2310
+ setupReleaseLabelTestSuite({ getClient });
1494
2311
  for (const suite of options.plugins ?? []) describe(suite.name, () => {
1495
2312
  suite.register({
1496
2313
  getClient,
@@ -1554,6 +2371,15 @@ const conformanceItems = {
1554
2371
  type: "string",
1555
2372
  nullable: true
1556
2373
  },
2374
+ (
2375
+ /** A unique slot only some rows hold, as long as a scope key. */
2376
+ {
2377
+ name: "slot",
2378
+ type: "string",
2379
+ nullable: true,
2380
+ maxLength: 2048,
2381
+ ascii: true
2382
+ }),
1557
2383
  {
1558
2384
  name: "_v",
1559
2385
  type: "integer",
@@ -1587,6 +2413,12 @@ const conformanceItems = {
1587
2413
  name: "byTag",
1588
2414
  eq: ["tags"],
1589
2415
  sort: ["score"]
2416
+ },
2417
+ {
2418
+ name: "bySlot",
2419
+ eq: ["slot"],
2420
+ sort: [],
2421
+ unique: true
1590
2422
  }
1591
2423
  ]
1592
2424
  };
@@ -1697,6 +2529,7 @@ const item = (id, values = {}) => ({
1697
2529
  tags: null,
1698
2530
  payload: null,
1699
2531
  note: null,
2532
+ slot: null,
1700
2533
  _v: 0,
1701
2534
  ...values
1702
2535
  });
@@ -2007,6 +2840,37 @@ const setupDatabaseAdapterConformanceSuite = (options) => {
2007
2840
  eq: ["L"]
2008
2841
  }))).toEqual(["f"]);
2009
2842
  });
2843
+ it("moves a unique slot between rows in one write, and holds a long ASCII value", async () => {
2844
+ const adapter = await setup();
2845
+ const slot = `s:${"a".repeat(998)}`;
2846
+ await ok(adapter, [
2847
+ insert(item("a", { slot })),
2848
+ insert(item("b")),
2849
+ insert(item("c"))
2850
+ ]);
2851
+ expect(await adapter.write([insert(item("d", { slot }))])).toEqual({
2852
+ ok: false,
2853
+ failedOp: 0
2854
+ });
2855
+ const patch = (id, from, to) => ({
2856
+ type: "patch",
2857
+ table: conformanceItems,
2858
+ key: [id],
2859
+ set: { slot: to },
2860
+ guard: { v: 0 },
2861
+ previous: item(id, { slot: from })
2862
+ });
2863
+ expect(await adapter.write([patch("b", null, slot)])).toEqual({
2864
+ ok: false,
2865
+ failedOp: 0
2866
+ });
2867
+ await ok(adapter, [patch("a", slot, null), patch("b", null, slot)]);
2868
+ expect(ids(await query(adapter, {
2869
+ index: "bySlot",
2870
+ eq: [slot]
2871
+ }))).toEqual(["b"]);
2872
+ expect(await one(adapter, "a")).toMatchObject({ slot: null });
2873
+ });
2010
2874
  it("orders strings by UTF-8 bytes and numbers numerically", async () => {
2011
2875
  const adapter = await setup();
2012
2876
  const names = [
@@ -2202,6 +3066,60 @@ const setupDatabaseAdapterConformanceSuite = (options) => {
2202
3066
  "r8"
2203
3067
  ]);
2204
3068
  });
3069
+ it("reads every write committed before the read starts", async () => {
3070
+ const adapter = await setup();
3071
+ await ok(adapter, [insert(item("s", { score: 1 }))]);
3072
+ for (let score = 2; score <= 5; score += 1) {
3073
+ const previous = await one(adapter, "s");
3074
+ await ok(adapter, [{
3075
+ type: "patch",
3076
+ table: conformanceItems,
3077
+ key: ["s"],
3078
+ set: { score },
3079
+ guard: { v: previous._v },
3080
+ previous
3081
+ }]);
3082
+ expect((await one(adapter, "s"))?.score).toBe(score);
3083
+ expect((await query(adapter, {
3084
+ index: "byGroup",
3085
+ eq: ["g"]
3086
+ })).map((row) => row.score)).toEqual([score]);
3087
+ }
3088
+ });
3089
+ it("writes the index items of rows written without the index (migrations.fillIndex)", async () => {
3090
+ const adapter = await setup();
3091
+ const fillIndex = adapter.migrations?.fillIndex;
3092
+ if (fillIndex === void 0) return;
3093
+ const earlier = {
3094
+ ...conformanceItems,
3095
+ indexes: conformanceItems.indexes.filter(({ name }) => name !== "byGroup")
3096
+ };
3097
+ await ok(adapter, [
3098
+ "r0",
3099
+ "r1",
3100
+ "r2"
3101
+ ].map((id) => ({
3102
+ type: "insert",
3103
+ table: earlier,
3104
+ row: item(id, { score: Number(id.slice(1)) })
3105
+ })));
3106
+ await ok(adapter, [insert(item("r3", { score: 3 }))]);
3107
+ const byGroup = () => query(adapter, {
3108
+ index: "byGroup",
3109
+ eq: ["g"]
3110
+ }).then(ids);
3111
+ await expect(byGroup()).resolves.toEqual(["r3"]);
3112
+ await expect(fillIndex(conformanceItems, "byGroup", { dryRun: true })).resolves.toBe(3);
3113
+ await expect(byGroup()).resolves.toEqual(["r3"]);
3114
+ await expect(fillIndex(conformanceItems, "byGroup")).resolves.toBe(3);
3115
+ await expect(byGroup()).resolves.toEqual([
3116
+ "r0",
3117
+ "r1",
3118
+ "r2",
3119
+ "r3"
3120
+ ]);
3121
+ await expect(fillIndex(conformanceItems, "byGroup", { dryRun: true })).resolves.toBe(0);
3122
+ });
2205
3123
  it(`lets exactly one of ${writers} concurrent writers win a contested key`, async () => {
2206
3124
  const adapter = await setup();
2207
3125
  const row = item("a");
@@ -2859,64 +3777,6 @@ const setupStorageAdapterTestSuite = (options) => {
2859
3777
  });
2860
3778
  };
2861
3779
  //#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
3780
  //#region src/setupReadBudgetTestSuite.ts
2921
3781
  /** A published template: a greeting that beta devices get another value of. */
2922
3782
  const remoteConfigTemplate = (greeting) => ({
@@ -2997,6 +3857,49 @@ const failureOf = (n, install, check = false) => eventOf(200 + n, {
2997
3857
  },
2998
3858
  received_at_ms: T0 + 3 * DAY + n * 10 * 6e4
2999
3859
  });
3860
+ /** Where a client floods update failures: Android `flood`, day 5. */
3861
+ const FLOOD = {
3862
+ platform: "android",
3863
+ channel: "flood",
3864
+ start: T0 + 5 * DAY
3865
+ };
3866
+ /** The flood's failed checks: more breakdown rows than a read takes from an hour. */
3867
+ const FLOOD_CHECKS = 24;
3868
+ /**
3869
+ * Installations whose IDs fall on all 8 counter shards: each flood row is
3870
+ * reported by all of them, so it is stored on every shard.
3871
+ */
3872
+ const FLOOD_INSTALLS = Array.from({ length: 8 }, (_, n) => `flood-${n}`);
3873
+ /**
3874
+ * Flood failure `n`: below {@link FLOOD_CHECKS} × 8, a failed check of HTTP
3875
+ * status 100 + n / 8 by installation n % 8, all in day 5's first hour; at
3876
+ * it, a real failure, a failed download in the hour after.
3877
+ */
3878
+ const floodFailureOf = (n) => {
3879
+ const real = n === FLOOD_CHECKS * FLOOD_INSTALLS.length;
3880
+ return eventOf(1e3 + n, {
3881
+ type: "UPDATE_FAILED",
3882
+ install_id: real ? "flood-real" : FLOOD_INSTALLS[n % 8],
3883
+ user_id: null,
3884
+ to_release_id: real ? "release-b" : null,
3885
+ to_bundle_id: real ? "bundle-b" : "bundle-a",
3886
+ platform: FLOOD.platform,
3887
+ channel: FLOOD.channel,
3888
+ metadata: {
3889
+ ...eventOf(0).metadata,
3890
+ failure: real ? {
3891
+ stage: "download",
3892
+ reason: "http",
3893
+ http_status: 403
3894
+ } : {
3895
+ stage: "check",
3896
+ reason: "http",
3897
+ http_status: 100 + Math.floor(n / 8)
3898
+ }
3899
+ },
3900
+ received_at_ms: FLOOD.start + (real ? HOUR : n * 1e3)
3901
+ });
3902
+ };
3000
3903
  /**
3001
3904
  * History event `n` of the day before T0, three an hour, on its own release
3002
3905
  * and bundles: every windowed read, which starts at T0 or later, skips it.
@@ -3028,6 +3931,41 @@ const nativeBuildScope = {
3028
3931
  fingerprintHash: "native-fingerprint",
3029
3932
  appVersion: null
3030
3933
  };
3934
+ /** A sandbox scope of `nativeBuildScope`'s fingerprint, which no build has. */
3935
+ const nativeBuildSandboxScope = {
3936
+ appId: "com.example.app",
3937
+ urlScheme: "acme-preview",
3938
+ artifactKind: "ipa",
3939
+ distribution: "direct"
3940
+ };
3941
+ /**
3942
+ * A sandbox ad hoc .ipa of `nativeBuildScope`'s fingerprint, as a build page
3943
+ * holds its row: the source of a sibling read.
3944
+ */
3945
+ const sandboxIpaRow = {
3946
+ id: "01ffffff-ffff-7fff-bfff-ffffffffffff",
3947
+ scope_key: `v1:sandbox:ios:${nativeBuildSandboxScope.appId}:${nativeBuildSandboxScope.urlScheme}:ipa:direct:fingerprint:${nativeBuildScope.fingerprintHash}`,
3948
+ platform: "ios",
3949
+ channel_id: "channel:pr-140",
3950
+ fingerprint_hash: nativeBuildScope.fingerprintHash,
3951
+ app_version: null,
3952
+ min_bundle_id: "01ffffff-ffff-7fff-bfff-fffffffffffe",
3953
+ artifact_kind: "ipa",
3954
+ artifact_storage_uri: "storage://read-budgets/native-builds/ipa/App.ipa",
3955
+ byte_size: 1e3,
3956
+ git_commit_hash: null,
3957
+ created_at_ms: 0,
3958
+ build_key: null,
3959
+ build_number: null,
3960
+ submitted_to: null,
3961
+ submitted_at_ms: null,
3962
+ submitted_version: null,
3963
+ is_store_build: false,
3964
+ is_sandbox: true,
3965
+ sandbox_url_scheme: nativeBuildSandboxScope.urlScheme,
3966
+ export_method: "ad-hoc",
3967
+ native_app_version: null
3968
+ };
3031
3969
  /** The native build key the older of the two native builds is registered with. */
3032
3970
  const nativeBuildKey = `nbk1:${"0".repeat(64)}`;
3033
3971
  const bundleEvents = {
@@ -3109,6 +4047,39 @@ const seed = async (database) => {
3109
4047
  assetBaseStorageUri: "storage://read-budgets/assets"
3110
4048
  }
3111
4049
  });
4050
+ await core.markNativeBuild(createBundleFixture("8011").id, { storeBuild: true });
4051
+ await core.registerNativeBuild({
4052
+ ...nativeBuildScope,
4053
+ channel: "beta",
4054
+ id: createBundleFixture("8005").id,
4055
+ minBundleId: createBundleFixture("005").id,
4056
+ gitCommitHash: null,
4057
+ buildKey: null,
4058
+ isSandbox: true,
4059
+ sandboxAppId: nativeBuildSandboxScope.appId,
4060
+ sandboxUrlScheme: nativeBuildSandboxScope.urlScheme,
4061
+ artifact: {
4062
+ kind: "app",
4063
+ storageUri: "storage://read-budgets/native-builds/005/App.app.zip",
4064
+ byteSize: 1e3
4065
+ },
4066
+ embeddedBundle: {
4067
+ manifestStorageUri: "storage://bundles/005/manifest.json",
4068
+ manifestFileHash: "manifest-hash-005",
4069
+ assetBaseStorageUri: "storage://read-budgets/assets"
4070
+ }
4071
+ });
4072
+ const pendingDevice = (await core.requestIosDevice({
4073
+ udid: BUDGET_PENDING_UDID,
4074
+ name: "Pending iPhone",
4075
+ requestedBy: "kim@team.dev"
4076
+ })).device;
4077
+ const { device: requestedDevice } = await core.requestIosDevice({
4078
+ udid: BUDGET_APPROVED_UDID,
4079
+ name: "Approved iPhone",
4080
+ requestedBy: "kim@team.dev"
4081
+ });
4082
+ const approvedDevice = await core.approveIosDevice(requestedDevice.id, { approvedBy: "lead@team.dev" });
3112
4083
  const { apiKey } = await api.apiKeys.create({ name: "Read budgets" });
3113
4084
  for (let n = 1; n <= 24; n += 1) await api.insights.recordEvent(eventOf(n));
3114
4085
  await api.insights.recordEvent(eventOf(25, {
@@ -3128,6 +4099,7 @@ const seed = async (database) => {
3128
4099
  await api.insights.recordEvent(failureOf(1, 3));
3129
4100
  await api.insights.recordEvent(failureOf(2, 5));
3130
4101
  await api.insights.recordEvent(failureOf(3, 7, true));
4102
+ for (let n = 0; n <= FLOOD_CHECKS * FLOOD_INSTALLS.length; n += 1) await api.insights.recordEvent(floodFailureOf(n));
3131
4103
  for (const [baseVersion, greeting] of [
3132
4104
  "Hi",
3133
4105
  "Hello",
@@ -3146,6 +4118,8 @@ const seed = async (database) => {
3146
4118
  apiKey,
3147
4119
  productionId,
3148
4120
  nightlyId: (await channel("nightly")).id,
4121
+ pendingDevice,
4122
+ approvedDevice,
3149
4123
  /** The auto-patch base key of a new production iOS 1.0.0 bundle. */
3150
4124
  candidateKey: targetBaseCandidateKey({
3151
4125
  channel: "production",
@@ -3156,6 +4130,8 @@ const seed = async (database) => {
3156
4130
  };
3157
4131
  };
3158
4132
  const budget = (entry) => entry;
4133
+ const BUDGET_PENDING_UDID = "00008030-000000000000000a";
4134
+ const BUDGET_APPROVED_UDID = "00008030-000000000000000b";
3159
4135
  const reads = (gets, keys, queries, rows) => ({
3160
4136
  gets,
3161
4137
  keys,
@@ -3336,6 +4312,46 @@ const READ_BUDGETS = [
3336
4312
  rows: 1
3337
4313
  }
3338
4314
  }),
4315
+ budget({
4316
+ api: "catalog preflight: 1 catalog point read and the scope's enabled releases",
4317
+ read: ({ core }) => core.preflightReleaseCatalogRebuild(scopeKey),
4318
+ adapter: reads(1, 1, 1, 4),
4319
+ engine: {
4320
+ calls: 2,
4321
+ rows: 5
4322
+ },
4323
+ check: (preflight) => expect(preflight.changed).toBe(false)
4324
+ }),
4325
+ budget({
4326
+ api: "release scopes: one limit-1 seek per scope, past each scope's releases",
4327
+ read: ({ core }) => core.listReleaseScopeKeys({ limit: 4 }),
4328
+ adapter: reads(0, 0, 4, 4),
4329
+ engine: {
4330
+ calls: 4,
4331
+ rows: 4
4332
+ },
4333
+ returned: (scopeKeys) => scopeKeys.length,
4334
+ check: (scopeKeys) => expect(scopeKeys).toEqual([
4335
+ "v1:app-version:android:cHJvZHVjdGlvbg",
4336
+ "v1:app-version:ios:YmV0YQ",
4337
+ "v1:app-version:ios:c3RhZ2luZw",
4338
+ scopeKey
4339
+ ])
4340
+ }),
4341
+ budget({
4342
+ api: "release scopes past the last: 1 empty query",
4343
+ read: ({ core }) => core.listReleaseScopeKeys({
4344
+ after: scopeKey,
4345
+ limit: 4
4346
+ }),
4347
+ adapter: reads(0, 0, 1, 0),
4348
+ engine: {
4349
+ calls: 1,
4350
+ rows: 0
4351
+ },
4352
+ returned: (scopeKeys) => scopeKeys.length,
4353
+ check: (scopeKeys) => expect(scopeKeys).toEqual([])
4354
+ }),
3339
4355
  budget({
3340
4356
  api: "native build by ID: 1 point read",
3341
4357
  read: ({ core }) => core.getNativeBuild(createBundleFixture("8012").id),
@@ -3346,6 +4362,16 @@ const READ_BUDGETS = [
3346
4362
  },
3347
4363
  check: (build) => expect(build).toMatchObject({ min_bundle_id: createBundleFixture("012").id })
3348
4364
  }),
4365
+ budget({
4366
+ api: "native build by its built-in bundle: 1 unique read",
4367
+ read: ({ core }) => core.findNativeBuildByBuiltInBundle(createBundleFixture("011").id),
4368
+ adapter: reads(0, 0, 1, 1),
4369
+ engine: {
4370
+ calls: 1,
4371
+ rows: 1
4372
+ },
4373
+ check: (build) => expect(build).toMatchObject({ id: createBundleFixture("8011").id })
4374
+ }),
3349
4375
  budget({
3350
4376
  api: "native build by scope: byScope descending, limit 1",
3351
4377
  read: ({ core }) => core.findNativeBuild(nativeBuildScope),
@@ -3356,6 +4382,79 @@ const READ_BUDGETS = [
3356
4382
  },
3357
4383
  check: (build) => expect(build).toMatchObject({ min_bundle_id: createBundleFixture("012").id })
3358
4384
  }),
4385
+ budget({
4386
+ api: "native build store mark: byStoreBuild, 1 row",
4387
+ read: ({ core }) => core.findNativeBuild(nativeBuildScope, { storeBuild: true }),
4388
+ adapter: reads(0, 0, 1, 1),
4389
+ engine: {
4390
+ calls: 1,
4391
+ rows: 1
4392
+ },
4393
+ check: (build) => expect(build).toMatchObject({
4394
+ min_bundle_id: createBundleFixture("011").id,
4395
+ is_store_build: true
4396
+ })
4397
+ }),
4398
+ budget({
4399
+ api: "native build store mark of a scope with none: byStoreBuild, no row",
4400
+ read: ({ core }) => core.findNativeBuild({
4401
+ ...nativeBuildScope,
4402
+ channel: "no-such-channel"
4403
+ }, { storeBuild: true }),
4404
+ adapter: reads(0, 0, 1, 0),
4405
+ engine: {
4406
+ calls: 1,
4407
+ rows: 0
4408
+ },
4409
+ check: (build) => expect(build).toBeNull()
4410
+ }),
4411
+ budget({
4412
+ api: "native build older than a bundle, the newest is: byScope, limit 1",
4413
+ read: ({ core }) => core.findNativeBuild(nativeBuildScope, { builtInOlderThan: "ffffffff-ffff-7fff-bfff-ffffffffffff" }),
4414
+ adapter: reads(0, 0, 1, 1),
4415
+ engine: {
4416
+ calls: 1,
4417
+ rows: 1
4418
+ },
4419
+ check: (build) => expect(build).toMatchObject({ min_bundle_id: createBundleFixture("012").id })
4420
+ }),
4421
+ budget({
4422
+ api: "native build older than a bundle, past the newest: byScope twice",
4423
+ read: ({ core }) => core.findNativeBuild(nativeBuildScope, { builtInOlderThan: createBundleFixture("012").id }),
4424
+ adapter: reads(0, 0, 2, 2),
4425
+ engine: {
4426
+ calls: 2,
4427
+ rows: 2
4428
+ },
4429
+ check: (build) => expect(build).toMatchObject({ min_bundle_id: createBundleFixture("011").id })
4430
+ }),
4431
+ budget({
4432
+ api: "native build older than a bundle in a sandbox scope: no read",
4433
+ read: ({ core }) => core.findNativeBuild({
4434
+ ...nativeBuildScope,
4435
+ sandbox: nativeBuildSandboxScope
4436
+ }, { builtInOlderThan: "ffffffff-ffff-7fff-bfff-ffffffffffff" }),
4437
+ adapter: reads(0, 0, 0, 0),
4438
+ engine: {
4439
+ calls: 0,
4440
+ rows: 0
4441
+ },
4442
+ check: (build) => expect(build).toBeNull()
4443
+ }),
4444
+ budget({
4445
+ api: "sandbox build on any channel: byScope descending, limit 1",
4446
+ read: ({ core }) => core.findNativeBuild({
4447
+ ...nativeBuildScope,
4448
+ channel: "pr-140",
4449
+ sandbox: nativeBuildSandboxScope
4450
+ }),
4451
+ adapter: reads(0, 0, 1, 0),
4452
+ engine: {
4453
+ calls: 1,
4454
+ rows: 0
4455
+ },
4456
+ check: (build) => expect(build).toBeNull()
4457
+ }),
3359
4458
  budget({
3360
4459
  api: "native build by key: byBuildKey descending, limit 1",
3361
4460
  read: ({ core }) => core.findNativeBuild(nativeBuildScope, { buildKey: nativeBuildKey }),
@@ -3369,6 +4468,53 @@ const READ_BUDGETS = [
3369
4468
  build_key: nativeBuildKey
3370
4469
  })
3371
4470
  }),
4471
+ budget({
4472
+ api: "native build of a kind: byScopeKind descending, limit 1",
4473
+ read: ({ core }) => core.findNativeBuild(nativeBuildScope, { artifactKind: "ipa" }),
4474
+ adapter: reads(0, 0, 1, 1),
4475
+ engine: {
4476
+ calls: 1,
4477
+ rows: 1
4478
+ },
4479
+ check: (build) => expect(build).toMatchObject({ min_bundle_id: createBundleFixture("012").id })
4480
+ }),
4481
+ budget({
4482
+ api: "native build of a kind with none: byScopeKind, then byScope, limit 1",
4483
+ read: ({ core }) => core.findNativeBuild(nativeBuildScope, { artifactKind: "app" }),
4484
+ adapter: reads(0, 0, 2, 1),
4485
+ engine: {
4486
+ calls: 2,
4487
+ rows: 1
4488
+ },
4489
+ check: (build) => expect(build).toBeNull()
4490
+ }),
4491
+ budget({
4492
+ api: "sandbox build's other install target: byScope descending, limit 1",
4493
+ read: ({ core }) => core.findNativeBuildSibling(sandboxIpaRow),
4494
+ adapter: reads(0, 0, 1, 1),
4495
+ engine: {
4496
+ calls: 1,
4497
+ rows: 1
4498
+ },
4499
+ check: (build) => expect(build).toMatchObject({
4500
+ id: createBundleFixture("8005").id,
4501
+ artifact_kind: "app"
4502
+ })
4503
+ }),
4504
+ budget({
4505
+ api: "normal build's other install target: no read",
4506
+ read: ({ core }) => core.findNativeBuildSibling({
4507
+ ...sandboxIpaRow,
4508
+ is_sandbox: false,
4509
+ scope_key: "normal"
4510
+ }),
4511
+ adapter: reads(0, 0, 0, 0),
4512
+ engine: {
4513
+ calls: 0,
4514
+ rows: 0
4515
+ },
4516
+ check: (build) => expect(build).toBeNull()
4517
+ }),
3372
4518
  budget({
3373
4519
  api: "native build list: all descending, limit rows",
3374
4520
  read: ({ core }) => core.listNativeBuilds({
@@ -3406,6 +4552,35 @@ const READ_BUDGETS = [
3406
4552
  },
3407
4553
  returned: (channel) => channel === null ? 0 : 1
3408
4554
  }),
4555
+ budget({
4556
+ api: "channels by ID: 1 batch get of their keys",
4557
+ read: ({ core, productionId, nightlyId }) => core.getChannels([
4558
+ nightlyId,
4559
+ productionId,
4560
+ nightlyId
4561
+ ]),
4562
+ adapter: reads(1, 2, 0, 0),
4563
+ engine: {
4564
+ calls: 1,
4565
+ rows: 2
4566
+ },
4567
+ returned: (channels) => channels.length,
4568
+ check: (channels) => expect(channels.map(({ name }) => name)).toEqual(["nightly", "production"])
4569
+ }),
4570
+ budget({
4571
+ api: "channel page by name: limit rows from one query",
4572
+ read: ({ core }) => core.listChannels({
4573
+ limit: 2,
4574
+ after: "beta"
4575
+ }),
4576
+ adapter: reads(0, 0, 1, 2),
4577
+ engine: {
4578
+ calls: 1,
4579
+ rows: 2
4580
+ },
4581
+ returned: (channels) => channels.length,
4582
+ check: (channels) => expect(channels.map(({ name }) => name)).toEqual(["canary", "nightly"])
4583
+ }),
3409
4584
  budget({
3410
4585
  api: "list events of a dense day: limit rows from one query",
3411
4586
  read: ({ insights }) => insights.listEvents({
@@ -3623,6 +4798,32 @@ const READ_BUDGETS = [
3623
4798
  checks: { failures: 1 }
3624
4799
  })
3625
4800
  }),
4801
+ budget({
4802
+ api: "update failures of a flooded channel: 20 breakdown rows of the flooded hour, every other hour whole",
4803
+ read: ({ insights }) => insights.getUpdateFailures({
4804
+ platform: FLOOD.platform,
4805
+ channel: FLOOD.channel,
4806
+ timeRange: {
4807
+ start: FLOOD.start,
4808
+ end: FLOOD.start + 2 * HOUR
4809
+ }
4810
+ }),
4811
+ adapter: reads(1, 1, 5, 177),
4812
+ engine: {
4813
+ calls: 5,
4814
+ rows: 24
4815
+ },
4816
+ check: (failures) => expect(failures).toMatchObject({
4817
+ coverage: { kind: "partial" },
4818
+ cappedHours: [FLOOD.start],
4819
+ failedUpdates: 1,
4820
+ failedInstallations: 1,
4821
+ checks: {
4822
+ failures: 160,
4823
+ failedInstallations: 8
4824
+ }
4825
+ })
4826
+ }),
3626
4827
  budget({
3627
4828
  api: "update failures of a release since its first: two kept rows × shards, all used",
3628
4829
  read: ({ insights }) => insights.getUpdateFailures({
@@ -3646,13 +4847,27 @@ const READ_BUDGETS = [
3646
4847
  bundle: bundleOf("107"),
3647
4848
  release: production
3648
4849
  }]),
3649
- adapter: (copies) => reads(copies ? 5 : 3, copies ? 8 : 3, 3, 6),
4850
+ adapter: (copies) => reads(copies ? 6 : 4, copies ? 9 : 4, 3, 6),
3650
4851
  engine: {
3651
- calls: 6,
3652
- rows: 9
4852
+ calls: 7,
4853
+ rows: 10
3653
4854
  },
3654
4855
  writes: 1
3655
4856
  }),
4857
+ budget({
4858
+ api: "release by label: its unique index, then the release",
4859
+ read: ({ core }) => core.getReleaseByLabel({
4860
+ channel: "production",
4861
+ platform: "ios",
4862
+ label: 2
4863
+ }),
4864
+ adapter: reads(1, 1, 1, 1),
4865
+ engine: {
4866
+ calls: 2,
4867
+ rows: 2
4868
+ },
4869
+ check: (release) => expect(release).toMatchObject({ label: 2 })
4870
+ }),
3656
4871
  budget({
3657
4872
  api: "channel insert: 1 write, after the name's read finds nothing",
3658
4873
  read: ({ core }) => core.ensureChannel("read-budgets"),
@@ -3664,11 +4879,11 @@ const READ_BUDGETS = [
3664
4879
  writes: 1
3665
4880
  }),
3666
4881
  budget({
3667
- api: "channel delete: the channel, its native builds under it, and 1 write",
4882
+ api: "channel delete: the channel, its native builds under it, its label counters, and 1 write",
3668
4883
  read: ({ core, nightlyId }) => core.deleteChannel(nightlyId),
3669
- adapter: reads(2, 2, 1, 0),
4884
+ adapter: reads(4, 4, 1, 0),
3670
4885
  engine: {
3671
- calls: 3,
4886
+ calls: 5,
3672
4887
  rows: 2
3673
4888
  },
3674
4889
  writes: 1,
@@ -3692,6 +4907,23 @@ const READ_BUDGETS = [
3692
4907
  submitted_version: "1.0.0 (12)"
3693
4908
  })
3694
4909
  }),
4910
+ budget({
4911
+ api: "native build store mark write: the build, the holder, and 1 write",
4912
+ read: ({ core }) => core.markNativeBuild(createBundleFixture("8012").id, { storeBuild: true }),
4913
+ adapter: (indexCopies) => indexCopies ? reads(2, 2, 1, 1) : reads(1, 1, 1, 1),
4914
+ engine: {
4915
+ calls: 2,
4916
+ rows: 2
4917
+ },
4918
+ writes: 1,
4919
+ check: (result) => expect(result).toMatchObject({
4920
+ nativeBuild: {
4921
+ min_bundle_id: createBundleFixture("012").id,
4922
+ is_store_build: true
4923
+ },
4924
+ previous: { min_bundle_id: createBundleFixture("011").id }
4925
+ })
4926
+ }),
3695
4927
  budget({
3696
4928
  api: "native build delete: the build, its built-in bundle, and 1 write",
3697
4929
  read: ({ core }) => core.deleteNativeBuild(createBundleFixture("8011").id),
@@ -3706,6 +4938,146 @@ const READ_BUDGETS = [
3706
4938
  nativeBuild: { min_bundle_id: createBundleFixture("011").id }
3707
4939
  })
3708
4940
  }),
4941
+ budget({
4942
+ api: "iOS devices by status: 1 query, the rows used",
4943
+ read: ({ core }) => core.listIosDevices({
4944
+ status: "approved",
4945
+ limit: 50
4946
+ }),
4947
+ adapter: reads(0, 0, 1, 1),
4948
+ engine: {
4949
+ calls: 1,
4950
+ rows: 1
4951
+ },
4952
+ returned: (rows) => rows.length,
4953
+ check: (rows) => expect(rows.map((row) => row.udid)).toEqual([BUDGET_APPROVED_UDID])
4954
+ }),
4955
+ budget({
4956
+ api: "iOS device by UDID: 1 unique read",
4957
+ read: ({ core }) => core.findIosDevice(BUDGET_PENDING_UDID.toUpperCase()),
4958
+ adapter: reads(0, 0, 1, 1),
4959
+ engine: {
4960
+ calls: 1,
4961
+ rows: 1
4962
+ },
4963
+ check: (device) => expect(device?.status).toBe("pending")
4964
+ }),
4965
+ budget({
4966
+ api: "iOS device request: the UDID's read and 1 write",
4967
+ read: ({ core }) => core.requestIosDevice({
4968
+ udid: "00008030-000000000000000c",
4969
+ name: "New iPhone",
4970
+ requestedBy: null
4971
+ }),
4972
+ adapter: reads(0, 0, 1, 0),
4973
+ engine: {
4974
+ calls: 1,
4975
+ rows: 0
4976
+ },
4977
+ writes: 1,
4978
+ check: (result) => expect(result.created).toBe(true)
4979
+ }),
4980
+ budget({
4981
+ api: "iOS device approval: the row and 1 write",
4982
+ read: ({ core, pendingDevice }) => core.approveIosDevice(pendingDevice.id, { approvedBy: null }),
4983
+ adapter: reads(1, 1, 0, 0),
4984
+ engine: {
4985
+ calls: 1,
4986
+ rows: 1
4987
+ },
4988
+ writes: 1,
4989
+ check: (device) => expect(device?.status).toBe("approved")
4990
+ }),
4991
+ budget({
4992
+ api: "iOS device outcome: the row and 1 write",
4993
+ read: ({ core, approvedDevice }) => core.recordIosDeviceOutcome({
4994
+ id: approvedDevice.id,
4995
+ seen: {
4996
+ status: "approved",
4997
+ approvedAtMs: approvedDevice.approved_at_ms
4998
+ },
4999
+ issuerId: "issuer-a",
5000
+ outcome: "registered"
5001
+ }),
5002
+ adapter: reads(1, 1, 0, 0),
5003
+ engine: {
5004
+ calls: 1,
5005
+ rows: 1
5006
+ },
5007
+ writes: 1,
5008
+ check: (device) => expect(device?.status).toBe("registered")
5009
+ }),
5010
+ budget({
5011
+ api: "iOS devices in a build: the row and 1 write each",
5012
+ read: ({ core, approvedDevice }) => core.markIosDevicesInBuild({
5013
+ buildId: createBundleFixture("8012").id,
5014
+ ids: [approvedDevice.id]
5015
+ }),
5016
+ adapter: reads(1, 1, 0, 0),
5017
+ engine: {
5018
+ calls: 1,
5019
+ rows: 1
5020
+ },
5021
+ writes: 1
5022
+ }),
5023
+ budget({
5024
+ api: "iOS device delete: the row and 1 write",
5025
+ read: ({ core, pendingDevice }) => core.deleteIosDevice(pendingDevice.id),
5026
+ adapter: reads(1, 1, 0, 0),
5027
+ engine: {
5028
+ calls: 1,
5029
+ rows: 1
5030
+ },
5031
+ writes: 1,
5032
+ check: (device) => expect(device?.udid).toBe(BUDGET_PENDING_UDID)
5033
+ }),
5034
+ budget({
5035
+ api: "iOS device account read, no claim yet: its row, then the earliest registration",
5036
+ read: ({ core }) => core.findIosDeviceAccount(),
5037
+ adapter: reads(1, 1, 1, 1),
5038
+ engine: {
5039
+ calls: 2,
5040
+ rows: 1
5041
+ },
5042
+ check: (account) => expect(account).toEqual({ issuerId: "issuer-a" })
5043
+ }),
5044
+ budget({
5045
+ api: "iOS device account, first claim: its one row's read, the earliest registration, and 1 write",
5046
+ read: ({ core }) => core.claimIosDeviceAccount("issuer-a"),
5047
+ adapter: reads(1, 1, 1, 1),
5048
+ engine: {
5049
+ calls: 2,
5050
+ rows: 1
5051
+ },
5052
+ writes: 1,
5053
+ check: (claim) => expect(claim).toEqual({
5054
+ issuerId: "issuer-a",
5055
+ claimed: true
5056
+ })
5057
+ }),
5058
+ budget({
5059
+ api: "iOS device account read, claimed: its one row's read",
5060
+ read: ({ core }) => core.findIosDeviceAccount(),
5061
+ adapter: reads(1, 1, 0, 0),
5062
+ engine: {
5063
+ calls: 1,
5064
+ rows: 1
5065
+ },
5066
+ check: (account) => expect(account).toEqual({ issuerId: "issuer-a" })
5067
+ }),
5068
+ budget({
5069
+ api: "iOS device account, claimed: its one row's read",
5070
+ read: ({ core }) => core.claimIosDeviceAccount("issuer-b"),
5071
+ adapter: reads(1, 1, 0, 0),
5072
+ engine: {
5073
+ calls: 1,
5074
+ rows: 1
5075
+ },
5076
+ check: (claim) => expect(claim).toEqual({
5077
+ issuerId: "issuer-a",
5078
+ claimed: false
5079
+ })
5080
+ }),
3709
5081
  budget({
3710
5082
  api: "record an insights event: 2 dependent rounds of batch gets and 1 write",
3711
5083
  read: ({ insights }) => insights.recordEvent(eventOf(27, {
@@ -3736,6 +5108,7 @@ const READ_BUDGETS = [
3736
5108
  const setupReadBudgetTestSuite = (options) => {
3737
5109
  describe(`${options.name} read budgets`, () => {
3738
5110
  let created;
5111
+ let tables;
3739
5112
  let database;
3740
5113
  let seeded;
3741
5114
  let writes = 0;
@@ -3746,8 +5119,9 @@ const setupReadBudgetTestSuite = (options) => {
3746
5119
  apiKeys(),
3747
5120
  remoteConfig()
3748
5121
  ];
5122
+ tables = [...toolingTargetOf(plugins).schema.tables, SETTINGS_TABLE];
3749
5123
  created = await options.createAdapter({
3750
- tables: [...toolingTargetOf(plugins).schema.tables, SETTINGS_TABLE],
5124
+ tables,
3751
5125
  nativePageSize: NATIVE_PAGE_SIZE
3752
5126
  });
3753
5127
  const { adapter } = created;
@@ -3787,6 +5161,42 @@ const setupReadBudgetTestSuite = (options) => {
3787
5161
  expect(await examined.total(), "rows examined").toBeLessThanOrEqual((examined.perRow ?? 1) * (keys + rows) + (examined.perRead ?? 0) * (gets + queries));
3788
5162
  }
3789
5163
  });
5164
+ /** Install `n`'s first event, all in one hour of day 4: the same rows each. */
5165
+ const newInstall = (n) => eventOf(400 + n, {
5166
+ install_id: `new-install-${n}`,
5167
+ user_id: null,
5168
+ received_at_ms: T0 + 4 * DAY + n * 1e3
5169
+ });
5170
+ /** Events of later days, which no prune below reaches. */
5171
+ const store = async (from, count) => {
5172
+ for (let n = from; n < from + count; n += 1) await seeded.insights.recordEvent(newInstall(n));
5173
+ };
5174
+ 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) => {
5175
+ const { written } = created;
5176
+ if (written === void 0) return context.skip();
5177
+ const most = async (n) => {
5178
+ written.reset();
5179
+ await seeded.insights.recordEvent(newInstall(n));
5180
+ return Math.max(...await written.rows());
5181
+ };
5182
+ await store(1, 60);
5183
+ expect(await most(61)).toBeLessThanOrEqual(2);
5184
+ await store(62, 60);
5185
+ expect(await most(122)).toBeLessThanOrEqual(2);
5186
+ });
5187
+ it("prune: deletes 5 expired events reading no more rows with 60 more events stored", async (context) => {
5188
+ const { adapter, written } = created;
5189
+ if (written === void 0) return context.skip();
5190
+ const events = tables.find(({ name }) => name === "bundle_events");
5191
+ const prune = async () => {
5192
+ written.reset();
5193
+ expect(await adapter.prune(events, T0 - DAY, 5)).toBe(5);
5194
+ return (await written.rows()).reduce((sum, rows) => sum + rows, 0);
5195
+ };
5196
+ const before = await prune();
5197
+ await store(200, 60);
5198
+ expect(await prune()).toBeLessThanOrEqual(before);
5199
+ });
3790
5200
  });
3791
5201
  };
3792
5202
  //#endregion
@@ -3970,8 +5380,8 @@ const snapshot = async (db) => {
3970
5380
  };
3971
5381
  /**
3972
5382
  * 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.
5383
+ * writes with each transaction and a compaction merges once, read back
5384
+ * exactly as transactional writes read.
3975
5385
  */
3976
5386
  const setupAggregateBatchingTestSuite = ({ name, createAdapter, oversizedRows }) => {
3977
5387
  const tables = [...toolingTargetOf([plugin]).schema.tables, ...aggregateBatchingTables];
@@ -4007,21 +5417,15 @@ const setupAggregateBatchingTestSuite = ({ name, createAdapter, oversizedRows })
4007
5417
  afterEach(async () => {
4008
5418
  for (const cleanup of cleanups.splice(0)) await cleanup();
4009
5419
  });
4010
- for (const mode of ["log", "memory"]) it(`reads what transactional writes read, in ${mode} mode`, async () => {
4011
- const { db } = server(await store(), { mode });
5420
+ it("reads what transactional writes read", async () => {
5421
+ const { db } = server(await store(), {});
4012
5422
  for (let step = 0; step < 36; step += 1) await open(db, step);
4013
5423
  expect(await snapshot(db)).toEqual(await expected(36));
4014
5424
  }, 12e4);
4015
5425
  it("applies each log row once when two servers compact while 16 writers commit", async () => {
4016
5426
  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
- });
5427
+ const first = server(adapter, { windowMs: 0 });
5428
+ const second = server(adapter, { windowMs: 0 });
4025
5429
  const report = await runContentionHarness({
4026
5430
  transactions: 12,
4027
5431
  ratePerSecond: 1e3,
@@ -4039,7 +5443,7 @@ const setupAggregateBatchingTestSuite = ({ name, createAdapter, oversizedRows })
4039
5443
  expect(await snapshot(second.db)).toEqual(await expected(48));
4040
5444
  }, 3e5);
4041
5445
  it("applies a log row larger than one write in parts, each change once", async () => {
4042
- const { db, flush } = server(await store(), { mode: "log" });
5446
+ const { db, flush } = server(await store(), {});
4043
5447
  await db.transaction(async (tx) => {
4044
5448
  for (let day = 1; day <= oversizedRows; day += 1) tx.aggregate("opens", { day }, { opens: day }, { shardBy: "i" });
4045
5449
  });
@@ -4231,18 +5635,13 @@ const createPluginTestHarness = async (plugin, options = {}) => {
4231
5635
  * bundles through the engine. A patch's base comes before it in `bundles`.
4232
5636
  */
4233
5637
  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
- }
5638
+ await createEngine(database).core.transaction(async (tx) => {
5639
+ for (const bundle of bundles) {
5640
+ tx.create("bundles", bundleToRow(bundle));
5641
+ for (const platformKey of [bundle.platform, "*"]) tx.aggregate("bundle_totals", { platform_key: platformKey }, { bundles: 1 });
5642
+ for (const row of bundleToPatchRows(bundle)) tx.create("bundle_patches", row);
5643
+ }
5644
+ });
4246
5645
  };
4247
5646
  //#endregion
4248
5647
  //#region src/insights/expectInsightsIndex.ts
@@ -5662,4 +7061,4 @@ async function startHttpTestServer(handlers) {
5662
7061
  };
5663
7062
  }
5664
7063
  //#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 };
7064
+ 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, setupReleaseLabelEngineTestSuite, setupReleaseLabelTestSuite, setupSemverSatisfiesTestSuite, setupStorageAdapterTestSuite, startHttpTestServer, storeBundles, toDeployBundle, withAdapterLatency };