@hot-updater/cloudflare 1.2.0-rc.50 → 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.
@@ -628,7 +628,8 @@ var releaseRowToRelease = /* @__PURE__ */ __name((row) => ({
628
628
  operation: row.operation,
629
629
  sourceReleaseId: row.source_release_id,
630
630
  createdAtMs: row.created_at_ms,
631
- updatedAtMs: row.updated_at_ms
631
+ updatedAtMs: row.updated_at_ms,
632
+ label: row.label ?? null
632
633
  }), "releaseRowToRelease");
633
634
  var bundleToRow = /* @__PURE__ */ __name((bundle) => {
634
635
  const metadata = bundleMetadataToRow(bundle.metadata);
@@ -1192,7 +1193,7 @@ function rangeToIntervals(range) {
1192
1193
  }
1193
1194
  }
1194
1195
  __name(rangeToIntervals, "rangeToIntervals");
1195
- function releaseDescriptor(release) {
1196
+ function releaseDescriptor(release, labels) {
1196
1197
  return {
1197
1198
  releaseId: release.id,
1198
1199
  kind: release.kind,
@@ -1200,7 +1201,8 @@ function releaseDescriptor(release) {
1200
1201
  rolloutCohortCount: release.rolloutCohortCount,
1201
1202
  targetCohorts: [...new Set(release.targetCohorts)].sort(),
1202
1203
  shouldForceUpdate: release.shouldForceUpdate,
1203
- message: release.message
1204
+ message: release.message,
1205
+ ...labels && typeof release.label === "number" ? { label: release.label } : {}
1204
1206
  };
1205
1207
  }
1206
1208
  __name(releaseDescriptor, "releaseDescriptor");
@@ -1424,12 +1426,21 @@ async function compileReleaseCatalog(input) {
1424
1426
  const targetCohorts = new Set(releases2.flatMap((release) => release.targetCohorts));
1425
1427
  if (targetCohorts.size > MAX_DISTINCT_TARGET_COHORTS_PER_SCOPE) throw new ReleaseCatalogCompilationError("DISTINCT_TARGET_COHORT_LIMIT", `Scope exceeds ${MAX_DISTINCT_TARGET_COHORTS_PER_SCOPE} distinct target cohorts`);
1426
1428
  const { envelope, retainedReleases } = input.strategy === "APP_VERSION" ? compileAppVersion(releases2) : compileFingerprint(releases2);
1427
- const payload = {
1428
- ...envelope,
1429
- releaseDescriptors: retainedReleases.map(releaseDescriptor)
1430
- };
1431
- const canonicalPayload = canonicalStringify(payload);
1432
- const byteSize = new TextEncoder().encode(canonicalPayload).byteLength;
1429
+ const compile = /* @__PURE__ */ __name((labels) => {
1430
+ const payload2 = {
1431
+ ...envelope,
1432
+ releaseDescriptors: retainedReleases.map((release) => releaseDescriptor(release, labels))
1433
+ };
1434
+ const canonicalPayload2 = canonicalStringify(payload2);
1435
+ return {
1436
+ payload: payload2,
1437
+ canonicalPayload: canonicalPayload2,
1438
+ byteSize: new TextEncoder().encode(canonicalPayload2).byteLength
1439
+ };
1440
+ }, "compile");
1441
+ let compiled = compile(true);
1442
+ if (compiled.byteSize > MAX_COMPILED_CATALOG_BYTES && retainedReleases.some((release) => typeof release.label === "number")) compiled = compile(false);
1443
+ const { payload, canonicalPayload, byteSize } = compiled;
1433
1444
  if (byteSize > MAX_COMPILED_CATALOG_BYTES) throw new ReleaseCatalogCompilationError("CATALOG_OVERSIZE", `Compiled Release catalog is ${byteSize} bytes; maximum is ${MAX_COMPILED_CATALOG_BYTES}`);
1434
1445
  return {
1435
1446
  byteSize,
@@ -2404,7 +2415,11 @@ var releases = defineTable({
2404
2415
  }
2405
2416
  },
2406
2417
  created_at_ms: { type: "integer" },
2407
- updated_at_ms: { type: "integer" }
2418
+ updated_at_ms: { type: "integer" },
2419
+ label: {
2420
+ type: "integer",
2421
+ required: false
2422
+ }
2408
2423
  }, {
2409
2424
  key: ["id"],
2410
2425
  indexes: {
@@ -2441,6 +2456,15 @@ var releases = defineTable({
2441
2456
  scopes: {
2442
2457
  eq: [],
2443
2458
  sort: ["scope_key"]
2459
+ },
2460
+ byLabel: {
2461
+ eq: [
2462
+ "channel_id",
2463
+ "platform",
2464
+ "label"
2465
+ ],
2466
+ sort: [],
2467
+ unique: true
2444
2468
  }
2445
2469
  }
2446
2470
  });
@@ -2448,6 +2472,25 @@ var LATE_INDEXES = [{
2448
2472
  table: "releases",
2449
2473
  index: "scopes"
2450
2474
  }];
2475
+ var LATE_COLUMNS = [{
2476
+ table: "releases",
2477
+ column: "label"
2478
+ }];
2479
+ var labelSequences = defineTable({
2480
+ id: {
2481
+ type: "string",
2482
+ maxLength: 1440,
2483
+ ascii: true
2484
+ },
2485
+ last_label: { type: "integer" },
2486
+ is_filled: { type: "boolean" }
2487
+ }, {
2488
+ key: ["id"],
2489
+ indexes: { all: {
2490
+ eq: [],
2491
+ sort: ["id"]
2492
+ } }
2493
+ });
2451
2494
  var releaseCatalogs = defineTable({
2452
2495
  scope_key: {
2453
2496
  type: "string",
@@ -2755,7 +2798,8 @@ var coreSchema = {
2755
2798
  }),
2756
2799
  native_builds: nativeBuilds,
2757
2800
  ios_devices: iosDevices,
2758
- ios_device_account: iosDeviceAccount
2801
+ ios_device_account: iosDeviceAccount,
2802
+ label_sequences: labelSequences
2759
2803
  };
2760
2804
  var coreModule = {
2761
2805
  id: "core",
@@ -2770,6 +2814,58 @@ var getEmptyMigrationResult = /* @__PURE__ */ __name(() => ({
2770
2814
  getSQL: /* @__PURE__ */ __name(() => "", "getSQL")
2771
2815
  }), "getEmptyMigrationResult");
2772
2816
 
2817
+ // ../plugin-core/dist/engine/db/sqlSchemaState.mjs
2818
+ var POSTGRES_NAME_BYTES = 63;
2819
+ var postgresName = /* @__PURE__ */ __name((name) => {
2820
+ const encoder4 = new TextEncoder();
2821
+ let bytes = 0;
2822
+ let cut = "";
2823
+ for (const character of name) {
2824
+ bytes += encoder4.encode(character).length;
2825
+ if (bytes > POSTGRES_NAME_BYTES) break;
2826
+ cut += character;
2827
+ }
2828
+ return cut;
2829
+ }, "postgresName");
2830
+ var fold = /* @__PURE__ */ __name((dialect, name) => dialect === "mysql" ? String(name).toLowerCase() : dialect === "postgresql" ? postgresName(String(name)) : String(name), "fold");
2831
+ var CATALOG = {
2832
+ postgresql: {
2833
+ tables: "SELECT c.relname AS t FROM pg_class c WHERE c.relkind IN ('r', 'p') AND pg_table_is_visible(c.oid)",
2834
+ indexes: "SELECT t.relname AS t, c.relname AS i FROM pg_index x JOIN pg_class c ON c.oid = x.indexrelid JOIN pg_class t ON t.oid = x.indrelid WHERE pg_table_is_visible(t.oid)",
2835
+ columns: "SELECT c.relname AS t, a.attname AS c FROM pg_attribute a JOIN pg_class c ON c.oid = a.attrelid WHERE c.relkind IN ('r', 'p') AND a.attnum > 0 AND NOT a.attisdropped AND pg_table_is_visible(c.oid)"
2836
+ },
2837
+ mysql: {
2838
+ tables: "SELECT TABLE_NAME AS t FROM information_schema.tables WHERE TABLE_SCHEMA = DATABASE()",
2839
+ indexes: "SELECT DISTINCT TABLE_NAME AS t, INDEX_NAME AS i FROM information_schema.statistics WHERE TABLE_SCHEMA = DATABASE()",
2840
+ columns: "SELECT TABLE_NAME AS t, COLUMN_NAME AS c FROM information_schema.columns WHERE TABLE_SCHEMA = DATABASE()"
2841
+ },
2842
+ sqlite: {
2843
+ tables: "SELECT name AS t FROM sqlite_master WHERE type = 'table'",
2844
+ indexes: "SELECT tbl_name AS t, name AS i FROM sqlite_master WHERE type = 'index'",
2845
+ columns: "SELECT m.name AS t, p.name AS c FROM sqlite_master m JOIN pragma_table_info(m.name) p WHERE m.type = 'table'"
2846
+ }
2847
+ };
2848
+ var readSqlSchemaState = /* @__PURE__ */ __name(async (executor) => {
2849
+ const { dialect } = executor;
2850
+ const read = /* @__PURE__ */ __name((sql) => executor.execute({
2851
+ sql,
2852
+ params: []
2853
+ }), "read");
2854
+ const [tables, indexes, columns] = await Promise.all([
2855
+ read(CATALOG[dialect].tables),
2856
+ read(CATALOG[dialect].indexes),
2857
+ read(CATALOG[dialect].columns)
2858
+ ]);
2859
+ const columnNames = new Set(columns.rows.map(({ t, c }) => JSON.stringify([fold(dialect, t), fold(dialect, c)])));
2860
+ const tableNames = new Set(tables.rows.map(({ t }) => fold(dialect, t)));
2861
+ const indexNames = new Set(indexes.rows.map(({ t, i }) => JSON.stringify([fold(dialect, t), fold(dialect, i)])));
2862
+ return {
2863
+ hasTable: /* @__PURE__ */ __name((table) => tableNames.has(fold(dialect, table)), "hasTable"),
2864
+ hasIndex: /* @__PURE__ */ __name((table, index) => indexNames.has(JSON.stringify([fold(dialect, table), fold(dialect, index)])), "hasIndex"),
2865
+ hasColumn: /* @__PURE__ */ __name((table, column) => columnNames.has(JSON.stringify([fold(dialect, table), fold(dialect, column)])), "hasColumn")
2866
+ };
2867
+ }, "readSqlSchemaState");
2868
+
2773
2869
  // ../plugin-core/dist/engine/db/settingsMigrator.mjs
2774
2870
  var storedSchemaVersion = /* @__PURE__ */ __name((stored2) => {
2775
2871
  const version2 = stored2?.get("schema.core") ?? stored2?.get("version");
@@ -2856,10 +2952,23 @@ var fillLateIndexes = /* @__PURE__ */ __name(async (adapter, tables, { dryRun: d
2856
2952
  }
2857
2953
  return lacking;
2858
2954
  }, "fillLateIndexes");
2955
+ var addLateColumns = /* @__PURE__ */ __name(async (adapter, tables, { dryRun: dryRun2 = false } = {}) => {
2956
+ const addColumns = adapter.migrations?.addColumns;
2957
+ if (addColumns === void 0) return [];
2958
+ const lacking = [];
2959
+ for (const table of tables) {
2960
+ const columns = LATE_COLUMNS.filter(({ table: name }) => name === table.name).map(({ column }) => column);
2961
+ if (columns.length === 0) continue;
2962
+ const added = await addColumns(table, columns, { dryRun: dryRun2 });
2963
+ lacking.push(...added.map((column) => `${table.name}.${column}`));
2964
+ }
2965
+ return lacking;
2966
+ }, "addLateColumns");
2859
2967
  var migrateSchema = /* @__PURE__ */ __name(async (adapter, adapterName, tables, settings, ordered) => {
2860
2968
  if (adapter.migrations === void 0) throw new Error(`${adapterName} creates its tables with its own tooling; write only the settings rows.`);
2861
2969
  const stored2 = await storedSettings(adapter, Object.keys(settings)).catch(() => void 0);
2862
2970
  if (stored2 !== void 0) refuseNewerSchema(adapterName, new Map([...stored2].map(([key, row]) => [key, row?.value])), settings, ordered);
2971
+ await addLateColumns(adapter, tables);
2863
2972
  await adapter.migrations.apply([...tables, SETTINGS_TABLE]);
2864
2973
  await fillLateIndexes(adapter, tables);
2865
2974
  await writeSchemaSettings(adapter, adapterName, settings, ordered);
@@ -3757,23 +3866,45 @@ var createEngineMigrator = /* @__PURE__ */ __name((options) => {
3757
3866
  refuseNewerSchema(options.adapterName, stored2, options.settings, options.ordered);
3758
3867
  const changed = Object.entries(options.settings).filter(([key, value]) => stored2.get(key) !== value);
3759
3868
  if (changed.length === 0) {
3869
+ const columns = await addLateColumns(options.adapter, options.schema.tables, { dryRun: true });
3760
3870
  const lacking = await fillLateIndexes(options.adapter, options.schema.tables, { dryRun: true });
3761
- if (lacking.length === 0) return getEmptyMigrationResult();
3871
+ if (columns.length === 0 && lacking.length === 0) return getEmptyMigrationResult();
3762
3872
  return {
3763
- operations: [{
3764
- type: "custom",
3765
- description: `Write the index items rows lack: ${lacking.join(", ")}`
3766
- }],
3873
+ operations: [
3874
+ ...columns.map((column) => ({
3875
+ type: "custom",
3876
+ description: `Add column: ${column}`
3877
+ })),
3878
+ ...columns.length === 0 ? [] : [{
3879
+ type: "custom",
3880
+ description: "Create the tables and indexes the database lacks"
3881
+ }],
3882
+ ...lacking.length === 0 ? [] : [{
3883
+ type: "custom",
3884
+ description: `Write the index items rows lack: ${lacking.join(", ")}`
3885
+ }]
3886
+ ],
3767
3887
  execute: /* @__PURE__ */ __name(async () => {
3888
+ if (columns.length > 0) {
3889
+ await addLateColumns(options.adapter, options.schema.tables);
3890
+ await options.adapter.migrations.apply([...options.schema.tables, SETTINGS_TABLE]);
3891
+ }
3768
3892
  await fillLateIndexes(options.adapter, options.schema.tables);
3769
3893
  }, "execute")
3770
3894
  };
3771
3895
  }
3772
3896
  return {
3773
- operations: [{
3774
- type: "custom",
3775
- description: "Create the tables and indexes the database lacks"
3776
- }, ...migrate.updateSettings === false ? [] : [settingsOperation(stored2, changed)]],
3897
+ operations: [
3898
+ ...(await addLateColumns(options.adapter, options.schema.tables, { dryRun: true }).catch(() => [])).map((column) => ({
3899
+ type: "custom",
3900
+ description: `Add column: ${column}`
3901
+ })),
3902
+ {
3903
+ type: "custom",
3904
+ description: "Create the tables and indexes the database lacks"
3905
+ },
3906
+ ...migrate.updateSettings === false ? [] : [settingsOperation(stored2, changed)]
3907
+ ],
3777
3908
  execute: /* @__PURE__ */ __name(() => migrateSchema(options.adapter, options.adapterName, options.schema.tables, options.settings, options.ordered), "execute")
3778
3909
  };
3779
3910
  }, "makeResult");
@@ -4798,19 +4929,37 @@ var createSqlAdapter = /* @__PURE__ */ __name(({ executor, tablePrefix = "", max
4798
4929
  return done;
4799
4930
  })).at(-1)?.changes ?? 0;
4800
4931
  },
4801
- migrations: { async apply(tables) {
4802
- const created = executor.batch && !tables.includes(WRITE_GUARD_TABLE) ? [...tables, WRITE_GUARD_TABLE] : tables;
4803
- const statements = createTableStatements(dialect, created, tablePrefix);
4804
- for (const text of statements) await executor.execute({
4805
- sql: text,
4806
- params: []
4807
- });
4808
- } }
4932
+ migrations: {
4933
+ async apply(tables) {
4934
+ const created = executor.batch && !tables.includes(WRITE_GUARD_TABLE) ? [...tables, WRITE_GUARD_TABLE] : tables;
4935
+ const statements = createTableStatements(dialect, created, tablePrefix);
4936
+ for (const text of statements) await executor.execute({
4937
+ sql: text,
4938
+ params: []
4939
+ });
4940
+ },
4941
+ async addColumns(table, columns, { dryRun: dryRun2 = false } = {}) {
4942
+ const [shape] = sqlTableShapes(dialect, [table], tablePrefix);
4943
+ const state = await readSqlSchemaState(executor);
4944
+ if (shape === void 0 || !state.hasTable(shape.name)) return [];
4945
+ const missing = columns.filter((column) => !state.hasColumn(shape.name, column));
4946
+ if (dryRun2) return missing;
4947
+ for (const name of missing) {
4948
+ const column = shape.columns.find((candidate) => candidate.name === name);
4949
+ if (column === void 0 || column.notNull) throw new Error(`${table.name}.${name} can't be added to an existing table: only an optional column can.`);
4950
+ await executor.execute({
4951
+ sql: `ALTER TABLE ${quoteSql(dialect, shape.name)} ADD COLUMN ${quoteSql(dialect, name)} ${column.type}`,
4952
+ params: []
4953
+ });
4954
+ }
4955
+ return missing;
4956
+ }
4957
+ }
4809
4958
  };
4810
4959
  }, "createSqlAdapter");
4811
4960
 
4812
4961
  // ../../packages/server/dist/package.mjs
4813
- var version = "1.2.0-rc.50";
4962
+ var version = "1.2.0-rc.51";
4814
4963
 
4815
4964
  // ../../packages/server/dist/version.mjs
4816
4965
  var HOT_UPDATER_SERVER_VERSION = version;
@@ -5621,7 +5770,7 @@ var toPatchRow = pick([
5621
5770
  "byte_size",
5622
5771
  "order_index"
5623
5772
  ]);
5624
- var toReleaseRow = pick([
5773
+ var pickReleaseRow = pick([
5625
5774
  "id",
5626
5775
  "revision",
5627
5776
  "scope_key",
@@ -5642,6 +5791,12 @@ var toReleaseRow = pick([
5642
5791
  "created_at_ms",
5643
5792
  "updated_at_ms"
5644
5793
  ]);
5794
+ var toReleaseRow = /* @__PURE__ */ __name((row) => {
5795
+ return {
5796
+ ...pickReleaseRow(row),
5797
+ label: typeof row.label === "number" ? row.label : null
5798
+ };
5799
+ }, "toReleaseRow");
5645
5800
  var toCatalogRow = pick([
5646
5801
  "scope_key",
5647
5802
  "catalog_id",
@@ -5795,6 +5950,23 @@ var createCoreReads = /* @__PURE__ */ __name((db, storage) => {
5795
5950
  const row = await db.findOne("releases", { id });
5796
5951
  return row === null ? null : toReleaseRow(row);
5797
5952
  },
5953
+ /**
5954
+ * The release a label names: its unique index, then the row itself,
5955
+ * since a key-value store keeps an index copy a server of an earlier
5956
+ * release may have left behind when it changed or deleted the row.
5957
+ */
5958
+ async getReleaseByLabel({ channel, platform, label }) {
5959
+ const found = await db.findOne("releases", {
5960
+ channel_id: `channel:${encodeChannelKey(channel)}`,
5961
+ platform,
5962
+ label
5963
+ });
5964
+ if (found === null) return null;
5965
+ const row = await db.findOne("releases", { id: found.id });
5966
+ if (row === null) return null;
5967
+ const release = toReleaseRow(row);
5968
+ return release.label === label && release.platform === platform ? release : null;
5969
+ },
5798
5970
  /** One page of releases through the index its filter names. */
5799
5971
  async listReleases(input) {
5800
5972
  const { filter } = input;
@@ -6196,8 +6368,274 @@ var NATIVE_BUILD_SUBMISSION_DESTINATIONS = {
6196
6368
  ios: ["testflight"]
6197
6369
  };
6198
6370
 
6199
- // ../../packages/server/dist/core/writes.mjs
6371
+ // ../../packages/server/dist/core/labels.mjs
6372
+ var labelSequenceId = /* @__PURE__ */ __name((channelId, platform) => `releases/${platform}/${channelId}`, "labelSequenceId");
6373
+ var LABEL_PLATFORMS = ["ios", "android"];
6374
+ var NeedsLabelFill = class extends Error {
6375
+ static {
6376
+ __name(this, "NeedsLabelFill");
6377
+ }
6378
+ channelId;
6379
+ platform;
6380
+ constructor(channelId, platform) {
6381
+ super(`Release labels of ${platform} ${channelId} need a fill first.`);
6382
+ this.channelId = channelId;
6383
+ this.platform = platform;
6384
+ }
6385
+ };
6386
+ var createLabelAllocator = /* @__PURE__ */ __name((tx, used, caughtUp) => {
6387
+ const sequences = /* @__PURE__ */ new Map();
6388
+ return {
6389
+ async next(channelId, platform) {
6390
+ const id = labelSequenceId(channelId, platform);
6391
+ let sequence = sequences.get(id);
6392
+ if (sequence === void 0) {
6393
+ const row = await tx.findOne("label_sequences", { id });
6394
+ if (row === null || !row.is_filled) {
6395
+ const channel = row === null ? await tx.findOne("channels", { id: channelId }) : null;
6396
+ if (channel === null || (channel._refs_releases_channel_id ?? 0) > 0) throw new NeedsLabelFill(channelId, platform);
6397
+ }
6398
+ const read = row?.last_label ?? 0;
6399
+ sequence = {
6400
+ row,
6401
+ read,
6402
+ last: read
6403
+ };
6404
+ sequences.set(id, sequence);
6405
+ used.set(id, {
6406
+ channelId,
6407
+ platform,
6408
+ read
6409
+ });
6410
+ }
6411
+ sequence.last += 1;
6412
+ return sequence.last;
6413
+ },
6414
+ caughtUp(channelId, platform) {
6415
+ caughtUp.set(labelSequenceId(channelId, platform), {
6416
+ channelId,
6417
+ platform
6418
+ });
6419
+ },
6420
+ flush() {
6421
+ for (const [id, { row, read, last }] of sequences) if (row === null) tx.create("label_sequences", {
6422
+ id,
6423
+ last_label: last,
6424
+ is_filled: true
6425
+ });
6426
+ else if (last !== read) tx.update("label_sequences", row, { last_label: last });
6427
+ }
6428
+ };
6429
+ }, "createLabelAllocator");
6430
+ var FILL_BATCH = 25;
6200
6431
  var PAGE2 = 500;
6432
+ var fillLabels = /* @__PURE__ */ __name(async (db, { channelId, platform }, { dryRun: dryRun2 = false } = {}) => {
6433
+ const id = labelSequenceId(channelId, platform);
6434
+ let labeled = 0;
6435
+ let batchSize = FILL_BATCH;
6436
+ const label = /* @__PURE__ */ __name(async (ids) => {
6437
+ for (let at = 0; at < ids.length; ) {
6438
+ const batch = ids.slice(at, at + batchSize);
6439
+ try {
6440
+ labeled += await db.transaction(async (tx) => {
6441
+ const counter = await tx.findOne("label_sequences", { id });
6442
+ let last = counter?.last_label ?? 0;
6443
+ let count = 0;
6444
+ for (const releaseId of batch) {
6445
+ const row = await tx.findOne("releases", { id: releaseId });
6446
+ if (row === null || typeof row.label === "number") continue;
6447
+ last += 1;
6448
+ count += 1;
6449
+ tx.update("releases", row, { label: last });
6450
+ }
6451
+ if (counter === null) tx.create("label_sequences", {
6452
+ id,
6453
+ last_label: last,
6454
+ is_filled: false
6455
+ });
6456
+ else if (last !== counter.last_label) tx.update("label_sequences", counter, { last_label: last });
6457
+ return count;
6458
+ });
6459
+ at += batch.length;
6460
+ } catch (error) {
6461
+ if (batchSize > 1 && error instanceof DatabaseConstraintError && error.reason === "too_large") {
6462
+ batchSize = Math.max(1, Math.floor(batchSize / 2));
6463
+ continue;
6464
+ }
6465
+ throw error;
6466
+ }
6467
+ }
6468
+ }, "label");
6469
+ let cursor;
6470
+ do {
6471
+ const page2 = await db.findMany("releases", {
6472
+ index: "byChannelPlatform",
6473
+ where: {
6474
+ channel_id: channelId,
6475
+ platform
6476
+ },
6477
+ limit: PAGE2,
6478
+ ...cursor === void 0 ? {} : { cursor }
6479
+ });
6480
+ const unlabeled = page2.rows.filter((row) => typeof row.label !== "number").map((row) => row.id);
6481
+ if (dryRun2) labeled += unlabeled.length;
6482
+ else await label(unlabeled);
6483
+ cursor = page2.next;
6484
+ } while (cursor !== void 0);
6485
+ if (dryRun2) return labeled;
6486
+ await db.transaction(async (tx) => {
6487
+ const counter = await tx.findOne("label_sequences", { id });
6488
+ if (counter === null) tx.create("label_sequences", {
6489
+ id,
6490
+ last_label: 0,
6491
+ is_filled: true
6492
+ });
6493
+ else if (!counter.is_filled) tx.update("label_sequences", counter, { is_filled: true });
6494
+ });
6495
+ return labeled;
6496
+ }, "fillLabels");
6497
+ var probeLabelSchema = /* @__PURE__ */ __name(async (db, { channelId, platform }) => {
6498
+ await db.findOne("label_sequences", { id: labelSequenceId(channelId, platform) });
6499
+ await db.findMany("releases", {
6500
+ index: "byLabel",
6501
+ where: {
6502
+ channel_id: channelId,
6503
+ platform,
6504
+ label: 0
6505
+ },
6506
+ limit: 1
6507
+ });
6508
+ }, "probeLabelSchema");
6509
+ var REPAIRS = 4;
6510
+ var RACES = 32;
6511
+ var writeWithLabels = /* @__PURE__ */ __name(async (db, write) => {
6512
+ const filled = /* @__PURE__ */ new Set();
6513
+ const fill = /* @__PURE__ */ __name(async (pairs) => {
6514
+ for (const pair of pairs) {
6515
+ filled.add(labelSequenceId(pair.channelId, pair.platform));
6516
+ await fillLabels(db, pair);
6517
+ }
6518
+ }, "fill");
6519
+ for (let repairs = 0, races = 0; ; ) {
6520
+ const used = /* @__PURE__ */ new Map();
6521
+ const caughtUp = /* @__PURE__ */ new Map();
6522
+ try {
6523
+ return await db.transaction(async (tx) => {
6524
+ used.clear();
6525
+ caughtUp.clear();
6526
+ const labels = createLabelAllocator(tx, used, caughtUp);
6527
+ const result = await write(tx, labels);
6528
+ labels.flush();
6529
+ return result;
6530
+ });
6531
+ } catch (error) {
6532
+ const needs = error instanceof NeedsLabelFill ? [error] : error instanceof DatabaseConstraintError && error.reason === "too_large" ? [...caughtUp.values()] : [];
6533
+ if (needs.length > 0) {
6534
+ const fresh = needs.some(({ channelId, platform }) => !filled.has(labelSequenceId(channelId, platform)));
6535
+ if (fresh || repairs < REPAIRS) {
6536
+ if (!fresh) repairs += 1;
6537
+ await fill(needs);
6538
+ continue;
6539
+ }
6540
+ }
6541
+ if (error instanceof DatabaseConstraintError && error.reason === "unique" && error.model === "releases" && used.size > 0) {
6542
+ if (await db.transaction(async (tx) => {
6543
+ const moves = [];
6544
+ for (const [id, { channelId, read }] of used) {
6545
+ const counter = await tx.findOne("label_sequences", { id });
6546
+ if (counter !== null) {
6547
+ if (counter.last_label !== read) return false;
6548
+ moves.push(() => tx.update("label_sequences", counter, { last_label: read + 1 }));
6549
+ continue;
6550
+ }
6551
+ const channel = await tx.findOne("channels", { id: channelId });
6552
+ if (channel === null || (channel._refs_releases_channel_id ?? 0) > 0) return false;
6553
+ moves.push(() => tx.create("label_sequences", {
6554
+ id,
6555
+ last_label: read + 1,
6556
+ is_filled: true
6557
+ }));
6558
+ }
6559
+ for (const move of moves) move();
6560
+ return true;
6561
+ }) ? (repairs += 1) <= REPAIRS : (races += 1) <= RACES) continue;
6562
+ }
6563
+ throw error;
6564
+ }
6565
+ }
6566
+ }, "writeWithLabels");
6567
+ var catchUpLabels = /* @__PURE__ */ __name(async (tx, labels, latest) => {
6568
+ const given = /* @__PURE__ */ new Map();
6569
+ if (latest === null || typeof latest.label === "number") return given;
6570
+ const unlabeled = [];
6571
+ let cursor;
6572
+ scan: do {
6573
+ const page2 = await tx.findMany("releases", {
6574
+ index: "byScope",
6575
+ where: { scope_key: latest.scope_key },
6576
+ order: "desc",
6577
+ limit: FILL_BATCH,
6578
+ ...cursor === void 0 ? {} : { cursor }
6579
+ });
6580
+ for (const row of page2.rows) {
6581
+ if (typeof row.label === "number") break scan;
6582
+ unlabeled.push(row);
6583
+ }
6584
+ cursor = page2.next;
6585
+ } while (cursor !== void 0);
6586
+ labels.caughtUp(latest.channel_id, latest.platform);
6587
+ for (const row of unlabeled.reverse()) {
6588
+ const { id, channel_id, platform } = toReleaseRow(row);
6589
+ const label = await labels.next(channel_id, platform);
6590
+ tx.update("releases", row, { label });
6591
+ given.set(id, label);
6592
+ }
6593
+ return given;
6594
+ }, "catchUpLabels");
6595
+ var pendingLabelPairs = /* @__PURE__ */ __name(async (db) => {
6596
+ const pairs = /* @__PURE__ */ new Map();
6597
+ for (let last = ""; ; ) {
6598
+ const { rows } = await db.findMany("releases", {
6599
+ index: "scopes",
6600
+ where: {},
6601
+ limit: 1,
6602
+ range: { gt: last }
6603
+ });
6604
+ if (rows[0] === void 0) break;
6605
+ last = rows[0].scope_key;
6606
+ const { rows: newest } = await db.findMany("releases", {
6607
+ index: "byScope",
6608
+ where: { scope_key: last },
6609
+ order: "desc",
6610
+ limit: 1
6611
+ });
6612
+ if (newest[0] === void 0) continue;
6613
+ const { channel_id: channelId, platform, label } = toReleaseRow(newest[0]);
6614
+ const id = labelSequenceId(channelId, platform);
6615
+ const pair = pairs.get(id) ?? {
6616
+ channelId,
6617
+ platform,
6618
+ pending: false
6619
+ };
6620
+ pair.pending ||= label === null;
6621
+ pairs.set(id, pair);
6622
+ }
6623
+ const pending = [];
6624
+ for (const [id, { channelId, platform, pending: unlabeled }] of pairs) {
6625
+ if (!unlabeled) {
6626
+ const counter = await db.findOne("label_sequences", { id });
6627
+ if (counter !== null && counter.is_filled) continue;
6628
+ }
6629
+ pending.push({
6630
+ channelId,
6631
+ platform
6632
+ });
6633
+ }
6634
+ return pending;
6635
+ }, "pendingLabelPairs");
6636
+
6637
+ // ../../packages/server/dist/core/writes.mjs
6638
+ var PAGE3 = 500;
6201
6639
  var countBundle = /* @__PURE__ */ __name((tx, platform, delta) => {
6202
6640
  for (const key of [platform, "*"]) tx.aggregate("bundle_totals", { platform_key: key }, { bundles: delta });
6203
6641
  }, "countBundle");
@@ -6224,7 +6662,7 @@ var replaceBundlePatches = /* @__PURE__ */ __name(async (tx, bundle, rows, check
6224
6662
  const page2 = await tx.findMany("bundle_patches", {
6225
6663
  index: "byBundle",
6226
6664
  where: { bundle_id: bundle.id },
6227
- limit: Math.min(count - seen, PAGE2),
6665
+ limit: Math.min(count - seen, PAGE3),
6228
6666
  ...cursor === void 0 ? {} : { cursor }
6229
6667
  });
6230
6668
  for (const stored2 of page2.rows) {
@@ -6282,6 +6720,10 @@ var deleteChannel = /* @__PURE__ */ __name((db, id) => db.transaction(async (tx)
6282
6720
  deleted: false,
6283
6721
  reason: "not_empty"
6284
6722
  };
6723
+ for (const platform of LABEL_PLATFORMS) {
6724
+ const counter = await tx.findOne("label_sequences", { id: labelSequenceId(id, platform) });
6725
+ if (counter !== null) await tx.delete("label_sequences", counter);
6726
+ }
6285
6727
  await tx.delete("channels", row);
6286
6728
  return { deleted: true };
6287
6729
  }), "deleteChannel");
@@ -6706,7 +7148,7 @@ var createNativeBuildApi = /* @__PURE__ */ __name((db, { now = Date.now } = {})
6706
7148
  }), "createNativeBuildApi");
6707
7149
 
6708
7150
  // ../../packages/server/dist/core/releases.mjs
6709
- var PAGE3 = 500;
7151
+ var PAGE4 = 500;
6710
7152
  var fail2 = /* @__PURE__ */ __name((code, message) => {
6711
7153
  throw new ReleaseCatalogMutationError(code, message);
6712
7154
  }, "fail");
@@ -6740,19 +7182,19 @@ var enabledIn = /* @__PURE__ */ __name((scopeKey, cursor) => ({
6740
7182
  scope_key: scopeKey,
6741
7183
  enabled: true
6742
7184
  },
6743
- limit: PAGE3,
7185
+ limit: PAGE4,
6744
7186
  ...cursor === void 0 ? {} : { cursor }
6745
7187
  }), "enabledIn");
6746
7188
  var enabledReleases = /* @__PURE__ */ __name((tx, scopeKey) => drainReleases((cursor) => tx.findMany("releases", enabledIn(scopeKey, cursor))), "enabledReleases");
6747
- var latestReleaseId = /* @__PURE__ */ __name(async (tx, scopeKey) => {
7189
+ var latestRelease = /* @__PURE__ */ __name(async (tx, scopeKey) => {
6748
7190
  const { rows } = await tx.findMany("releases", {
6749
7191
  index: "byScope",
6750
7192
  where: { scope_key: scopeKey },
6751
7193
  order: "desc",
6752
7194
  limit: 1
6753
7195
  });
6754
- return rows[0]?.id ?? null;
6755
- }, "latestReleaseId");
7196
+ return rows[0] === void 0 ? null : toReleaseRow(rows[0]);
7197
+ }, "latestRelease");
6756
7198
  var nextCatalog = /* @__PURE__ */ __name((scope, stored2, compilation, updatedAtMs) => {
6757
7199
  const generation = (stored2.catalog?.generation ?? 0) + 1;
6758
7200
  if (!Number.isSafeInteger(generation)) fail2("CATALOG_GENERATION_EXHAUSTED", `Catalog "${scope.scopeKey}" exhausted its generation counter`);
@@ -6806,10 +7248,10 @@ var readCatalog = /* @__PURE__ */ __name(async (tx, scopeKey) => {
6806
7248
  var assertHistory = /* @__PURE__ */ __name((stored2, hasReleases) => {
6807
7249
  if (stored2.catalog === null && hasReleases) fail2("CATALOG_IDENTITY_MISSING", "Catalog history is missing. Restore its catalog row from backup before rebuilding or deploying.");
6808
7250
  }, "assertHistory");
6809
- var changeRelease = /* @__PURE__ */ __name(async (tx, { scope, change, bundle, updatedAtMs }) => {
7251
+ var changeRelease = /* @__PURE__ */ __name(async (tx, { scope, change, bundle, updatedAtMs }, labels) => {
6810
7252
  checkScope(scope);
6811
7253
  const stored2 = await readCatalog(tx, scope.scopeKey);
6812
- const enabled = await enabledReleases(tx, scope.scopeKey);
7254
+ let enabled = await enabledReleases(tx, scope.scopeKey);
6813
7255
  if (bundle !== void 0) {
6814
7256
  insertBundle(tx, bundle.row);
6815
7257
  for (const patch of bundle.patches) tx.create("bundle_patches", patch);
@@ -6817,14 +7259,22 @@ var changeRelease = /* @__PURE__ */ __name(async (tx, { scope, change, bundle, u
6817
7259
  let before = null;
6818
7260
  let release;
6819
7261
  if (change.operation === "insert") {
6820
- const latest = await latestReleaseId(tx, scope.scopeKey);
7262
+ if (labels === void 0) throw new Error("A release insert takes its label from an allocator.");
7263
+ const newest = await latestRelease(tx, scope.scopeKey);
7264
+ const latest = newest?.id ?? null;
6821
7265
  assertHistory(stored2, latest !== null);
6822
7266
  const floor = [latest, bundle && isUUIDv7(bundle.row.id) ? bundle.row.id : null].filter((id2) => id2 !== null).sort().at(-1);
6823
7267
  const id = change.row.id ?? createUUIDv7After(floor ?? null);
6824
7268
  if (latest !== null && id <= latest) fail2("NON_MONOTONIC_RELEASE_ID", `Release "${id}" must sort after "${latest}"`);
7269
+ const given = await catchUpLabels(tx, labels, newest);
7270
+ if (given.size > 0) enabled = enabled.map((row) => given.has(row.id) ? {
7271
+ ...row,
7272
+ label: given.get(row.id)
7273
+ } : row);
6825
7274
  release = {
6826
7275
  ...change.row,
6827
- id
7276
+ id,
7277
+ label: await labels.next(scope.channelId, scope.platform)
6828
7278
  };
6829
7279
  if (release.scope_key !== scope.scopeKey || release.channel_id !== scope.channelId || release.platform !== scope.platform || release.strategy !== scope.strategy || release.fingerprint_hash !== scope.fingerprintHash || release.revision !== 1) fail2("INVALID_SCOPE", "Inserted Release does not match its catalog scope");
6830
7280
  tx.create("releases", release);
@@ -6837,8 +7287,9 @@ var changeRelease = /* @__PURE__ */ __name(async (tx, { scope, change, bundle, u
6837
7287
  await tx.delete("releases", row);
6838
7288
  release = null;
6839
7289
  } else {
7290
+ const { label: _label, ...update } = change.update;
6840
7291
  const set = {
6841
- ...change.update,
7292
+ ...update,
6842
7293
  revision: before.revision + 1
6843
7294
  };
6844
7295
  tx.update("releases", row, set);
@@ -6859,13 +7310,21 @@ var changeRelease = /* @__PURE__ */ __name(async (tx, { scope, change, bundle, u
6859
7310
  }, "changeRelease");
6860
7311
  var changeReleases = /* @__PURE__ */ __name((db, inputs) => {
6861
7312
  if (new Set(inputs.map(({ scope }) => scope.scopeKey)).size !== inputs.length) fail2("INVALID_SCOPE", "A batch cannot change one catalog scope twice");
6862
- return db.transaction(async (tx) => {
7313
+ return writeWithLabels(db, async (tx, labels) => {
6863
7314
  const results = [];
6864
- for (const input of inputs) results.push(await changeRelease(tx, input));
7315
+ for (const input of inputs) results.push(await changeRelease(tx, input, labels));
6865
7316
  return results;
6866
7317
  });
6867
7318
  }, "changeReleases");
6868
7319
  var isCurrent = /* @__PURE__ */ __name((scope, current, compilation) => current.strategy === scope.strategy && current.channel_id === scope.channelId && current.channel_key === encodeChannelKey(scope.channelName) && current.platform === scope.platform && current.fingerprint_hash === scope.fingerprintHash && current.catalog_hash === compilation.catalogHash, "isCurrent");
7320
+ var withoutLabels = /* @__PURE__ */ __name((payload) => {
7321
+ const parsed = JSON.parse(payload);
7322
+ return JSON.stringify({
7323
+ ...parsed,
7324
+ releaseDescriptors: (parsed.releaseDescriptors ?? []).map(({ label: _label, ...descriptor }) => descriptor)
7325
+ });
7326
+ }, "withoutLabels");
7327
+ var differsInLabelsOnly = /* @__PURE__ */ __name((current, projected) => current.payload !== projected.payload && current.strategy === projected.strategy && current.channel_id === projected.channel_id && current.channel_key === projected.channel_key && current.platform === projected.platform && current.fingerprint_hash === projected.fingerprint_hash && withoutLabels(current.payload) === withoutLabels(projected.payload), "differsInLabelsOnly");
6869
7328
  var catalogRowScope = /* @__PURE__ */ __name((row) => ({
6870
7329
  channelId: row.channel_id,
6871
7330
  channelName: decodeChannelKey(row.channel_key),
@@ -6883,17 +7342,19 @@ var preflightRebuild = /* @__PURE__ */ __name(async (db, scopeKey, updatedAtMs)
6883
7342
  const enabled = await drainReleases((cursor) => db.findMany("releases", enabledIn(scopeKey, cursor)));
6884
7343
  const compilation = await compileScope(scope, enabled);
6885
7344
  const changed = !isCurrent(scope, current, compilation);
7345
+ const projectedCatalog = changed ? nextCatalog(scope, { catalog: current }, compilation, updatedAtMs) : current;
6886
7346
  return {
6887
7347
  changed,
7348
+ labelsOnly: changed && differsInLabelsOnly(current, projectedCatalog),
6888
7349
  currentCatalog: current,
6889
7350
  diagnostics: compilation.diagnostics,
6890
- projectedCatalog: changed ? nextCatalog(scope, { catalog: current }, compilation, updatedAtMs) : current
7351
+ projectedCatalog
6891
7352
  };
6892
7353
  }, "preflightRebuild");
6893
7354
  var rebuildScope = /* @__PURE__ */ __name(async (tx, scope, updatedAtMs) => {
6894
7355
  checkScope(scope);
6895
7356
  const stored2 = await readCatalog(tx, scope.scopeKey);
6896
- assertHistory(stored2, await latestReleaseId(tx, scope.scopeKey) !== null);
7357
+ assertHistory(stored2, await latestRelease(tx, scope.scopeKey) !== null);
6897
7358
  const enabled = await enabledReleases(tx, scope.scopeKey);
6898
7359
  const compilation = await compileScope(scope, enabled);
6899
7360
  const current = stored2.catalog;
@@ -6913,6 +7374,7 @@ var rebuildScope = /* @__PURE__ */ __name(async (tx, scope, updatedAtMs) => {
6913
7374
  }, "rebuildScope");
6914
7375
 
6915
7376
  // ../../packages/server/dist/core/operations.mjs
7377
+ var CATALOG_PAGE = 100;
6916
7378
  var Preflight = class extends Error {
6917
7379
  static {
6918
7380
  __name(this, "Preflight");
@@ -7134,7 +7596,7 @@ var createCoreOperations = /* @__PURE__ */ __name((db, { now = Date.now } = {})
7134
7596
  if (targetChannel.length === 0) throw new ReleaseManagementError("TARGET_RELEASE_INVALID", "Promotion requires a target channel.");
7135
7597
  const channel = await ensureChannel(targetChannel);
7136
7598
  const updatedAtMs = now();
7137
- return db.transaction(async (tx) => {
7599
+ return writeWithLabels(db, async (tx, labels) => {
7138
7600
  const { release: source, scope: sourceScope } = await loadTarget(tx, input);
7139
7601
  checkSource(source);
7140
7602
  const targetScope = scopeOf(channel, source.platform, source.fingerprint_hash);
@@ -7162,12 +7624,13 @@ var createCoreOperations = /* @__PURE__ */ __name((db, { now = Date.now } = {})
7162
7624
  },
7163
7625
  updatedAtMs
7164
7626
  }) : null;
7627
+ const { label: _label, ...copied } = source;
7165
7628
  const target = await changeRelease(tx, {
7166
7629
  scope: targetScope,
7167
7630
  change: {
7168
7631
  operation: "insert",
7169
7632
  row: {
7170
- ...source,
7633
+ ...copied,
7171
7634
  id: createUUIDv7After(floor ?? null, updatedAtMs),
7172
7635
  revision: 1,
7173
7636
  scope_key: targetScope.scopeKey,
@@ -7182,7 +7645,7 @@ var createCoreOperations = /* @__PURE__ */ __name((db, { now = Date.now } = {})
7182
7645
  }
7183
7646
  },
7184
7647
  updatedAtMs
7185
- });
7648
+ }, labels);
7186
7649
  return {
7187
7650
  source: moved === null ? null : mutationResult(moved),
7188
7651
  target: mutationResult(target)
@@ -7200,6 +7663,38 @@ var createCoreOperations = /* @__PURE__ */ __name((db, { now = Date.now } = {})
7200
7663
  });
7201
7664
  }, "rebuildReleaseCatalog"),
7202
7665
  preflightReleaseCatalogRebuild: /* @__PURE__ */ __name((scopeKey) => preflightRebuild(db, scopeKey, now()), "preflightReleaseCatalogRebuild"),
7666
+ fillReleaseLabels: /* @__PURE__ */ __name(async ({ dryRun: dryRun2 = false, catalogs = true } = {}) => {
7667
+ let releases2 = 0;
7668
+ const pairs = await pendingLabelPairs(db);
7669
+ if (dryRun2 && pairs[0] !== void 0) await probeLabelSchema(db, pairs[0]);
7670
+ for (const pair of pairs) releases2 += await fillLabels(db, pair, { dryRun: dryRun2 });
7671
+ let rebuilt = 0;
7672
+ if (catalogs) {
7673
+ let cursor;
7674
+ do {
7675
+ const page2 = await db.findMany("release_catalogs", {
7676
+ index: "all",
7677
+ where: {},
7678
+ limit: CATALOG_PAGE,
7679
+ ...cursor === void 0 ? {} : { cursor }
7680
+ });
7681
+ for (const row of page2.rows) {
7682
+ if (row.is_tombstone) continue;
7683
+ const preflight = await preflightRebuild(db, row.scope_key, now()).catch(() => null);
7684
+ if (preflight === null || !preflight.labelsOnly) continue;
7685
+ rebuilt += 1;
7686
+ if (dryRun2) continue;
7687
+ const updatedAtMs = now();
7688
+ await db.transaction((tx) => rebuildScope(tx, catalogRowScope(toCatalogRow(row)), updatedAtMs));
7689
+ }
7690
+ cursor = page2.next;
7691
+ } while (cursor !== void 0);
7692
+ }
7693
+ return {
7694
+ releases: releases2,
7695
+ catalogs: rebuilt
7696
+ };
7697
+ }, "fillReleaseLabels"),
7203
7698
  ensureChannel,
7204
7699
  deleteChannel: /* @__PURE__ */ __name((id) => deleteChannel(db, id), "deleteChannel"),
7205
7700
  updateBundle: /* @__PURE__ */ __name((id, update) => db.transaction(async (tx) => {
@@ -7743,6 +8238,30 @@ var createAdminRouteHandlers = /* @__PURE__ */ __name(() => ({
7743
8238
  return row === null ? notFound() : json({ data: row });
7744
8239
  }),
7745
8240
  rebuildReleaseCatalog: onCore(async (core, _request, params) => json({ data: await core.rebuildReleaseCatalog(scopeKeyOf(params)) })),
8241
+ /**
8242
+ * The release a label names, or `null`: never 404, which tells a client
8243
+ * the server has no such route.
8244
+ */
8245
+ getReleaseByLabel: onCore(async (core, request) => {
8246
+ const url = new URL(request.url);
8247
+ const channel = url.searchParams.get("channel");
8248
+ const platform = platformOf(url);
8249
+ const label = Number(url.searchParams.get("label"));
8250
+ if (channel === null || channel.length === 0 || platform === void 0 || !Number.isSafeInteger(label) || label < 1) throw new HandlerBadRequestError("A release label lookup takes channel, platform, and a label of 1 or more.");
8251
+ return json({ data: await core.getReleaseByLabel({
8252
+ channel,
8253
+ platform,
8254
+ label
8255
+ }) });
8256
+ }),
8257
+ fillReleaseLabels: onCore(async (core, request) => {
8258
+ const body2 = await request.json().catch(() => ({}));
8259
+ const input = body2 !== null && typeof body2 === "object" ? body2 : {};
8260
+ return json({ data: await core.fillReleaseLabels({
8261
+ dryRun: input.dryRun === true,
8262
+ catalogs: input.catalogs !== false
8263
+ }) });
8264
+ }),
7746
8265
  updateBundle: onCore(async (core, request, params) => {
7747
8266
  const bundleId = requireRouteParam(params, "id");
7748
8267
  const update = bundleUpdateOf(await request.json(), bundleId);
@@ -7969,6 +8488,16 @@ var ADMIN_ROUTES = [
7969
8488
  path: "/release-scopes",
7970
8489
  handler: "listReleaseScopeKeys"
7971
8490
  },
8491
+ {
8492
+ method: "GET",
8493
+ path: "/release-labels",
8494
+ handler: "getReleaseByLabel"
8495
+ },
8496
+ {
8497
+ method: "POST",
8498
+ path: "/release-labels/fill",
8499
+ handler: "fillReleaseLabels"
8500
+ },
7972
8501
  {
7973
8502
  method: "POST",
7974
8503
  path: "/release-catalogs/:scopeKey/rebuild",
@@ -10737,7 +11266,7 @@ var recordEvent = /* @__PURE__ */ __name((db, event) => {
10737
11266
  }, "recordEvent");
10738
11267
 
10739
11268
  // ../insights/dist/server/reads.mjs
10740
- var PAGE4 = 500;
11269
+ var PAGE5 = 500;
10741
11270
  var hourFloor = /* @__PURE__ */ __name((ms) => ms - ms % HOUR_MS2, "hourFloor");
10742
11271
  var hourCeil = /* @__PURE__ */ __name((ms) => hourFloor(ms + HOUR_MS2 - 1), "hourCeil");
10743
11272
  var dayFloor = /* @__PURE__ */ __name((ms) => ms - ms % DAY_MS2, "dayFloor");
@@ -10861,7 +11390,7 @@ var countRaw = /* @__PURE__ */ __name(async (db, filter, from, to) => {
10861
11390
  gte: from,
10862
11391
  lt: to
10863
11392
  },
10864
- limit: PAGE4,
11393
+ limit: PAGE5,
10865
11394
  ...page2
10866
11395
  }));
10867
11396
  total += rows.length;
@@ -10880,7 +11409,7 @@ var countEvents = /* @__PURE__ */ __name(async (db, input) => {
10880
11409
  gte: start,
10881
11410
  lt: end
10882
11411
  },
10883
- limit: PAGE4,
11412
+ limit: PAGE5,
10884
11413
  ...page2
10885
11414
  }));
10886
11415
  return await countRaw(db, filter, sinceMs, start) + hours.reduce((sum, row) => sum + row.events, 0) + await countRaw(db, filter, end, beforeReceivedAtMs);
@@ -10896,7 +11425,7 @@ var countEventSeries = /* @__PURE__ */ __name(async (db, input) => {
10896
11425
  gte: start,
10897
11426
  lt: end
10898
11427
  },
10899
- limit: PAGE4,
11428
+ limit: PAGE5,
10900
11429
  ...page2
10901
11430
  }));
10902
11431
  for (const row of hours) events[Math.floor((row.bucket_start_ms - start) / intervalMs)] += row.events;
@@ -10930,7 +11459,7 @@ var countLatestEvents = /* @__PURE__ */ __name(async (db, input) => {
10930
11459
  platform
10931
11460
  },
10932
11461
  range: { gte: start },
10933
- limit: PAGE4,
11462
+ limit: PAGE5,
10934
11463
  ...page2
10935
11464
  }));
10936
11465
  total += rows.reduce((sum, row) => sum + row.latest_installations, 0);
@@ -10946,7 +11475,7 @@ var countLatestEvents = /* @__PURE__ */ __name(async (db, input) => {
10946
11475
  type
10947
11476
  },
10948
11477
  range: { gte: start },
10949
- limit: PAGE4,
11478
+ limit: PAGE5,
10950
11479
  ...page2
10951
11480
  }))).reduce((sum, row) => sum + row.installations, 0);
10952
11481
  }, "gauge");
@@ -11022,7 +11551,7 @@ var windowRows = /* @__PURE__ */ __name(async (db, models, parts, range, days, h
11022
11551
  gte: period.start,
11023
11552
  lt: period.end
11024
11553
  },
11025
- limit: PAGE4,
11554
+ limit: PAGE5,
11026
11555
  ...page2
11027
11556
  })));
11028
11557
  }
@@ -11051,7 +11580,7 @@ var lifetimeMetrics = /* @__PURE__ */ __name(async (db, release) => {
11051
11580
  gte: 0,
11052
11581
  lte: 0
11053
11582
  },
11054
- limit: PAGE4
11583
+ limit: PAGE5
11055
11584
  })).rows;
11056
11585
  return {
11057
11586
  downloads: lifetime?.downloads ?? 0,
@@ -11103,7 +11632,7 @@ var getAppUsage = /* @__PURE__ */ __name(async (db, input, now, retention) => {
11103
11632
  platform
11104
11633
  },
11105
11634
  range,
11106
- limit: PAGE4,
11635
+ limit: PAGE5,
11107
11636
  ...page2
11108
11637
  }) : db.findAggregates("insights_distribution", {
11109
11638
  index: "byVersion",
@@ -11113,7 +11642,7 @@ var getAppUsage = /* @__PURE__ */ __name(async (db, input, now, retention) => {
11113
11642
  app_version: input.appVersion
11114
11643
  },
11115
11644
  range,
11116
- limit: PAGE4,
11645
+ limit: PAGE5,
11117
11646
  ...page2
11118
11647
  })));
11119
11648
  builtinDistribution.push(...await drain2((page2) => input.appVersion === void 0 ? db.findAggregates("insights_builtin_distribution", {
@@ -11123,7 +11652,7 @@ var getAppUsage = /* @__PURE__ */ __name(async (db, input, now, retention) => {
11123
11652
  platform
11124
11653
  },
11125
11654
  range,
11126
- limit: PAGE4,
11655
+ limit: PAGE5,
11127
11656
  ...page2
11128
11657
  }) : db.findAggregates("insights_builtin_distribution", {
11129
11658
  index: "byVersion",
@@ -11133,7 +11662,7 @@ var getAppUsage = /* @__PURE__ */ __name(async (db, input, now, retention) => {
11133
11662
  app_version: input.appVersion
11134
11663
  },
11135
11664
  range,
11136
- limit: PAGE4,
11665
+ limit: PAGE5,
11137
11666
  ...page2
11138
11667
  })));
11139
11668
  }
@@ -11235,7 +11764,7 @@ var breakdownOf = /* @__PURE__ */ __name((rows) => {
11235
11764
  });
11236
11765
  }, "breakdownOf");
11237
11766
  var FAILURE_ROWS_PER_HOUR = 20;
11238
- var FAILURE_QUERY_LIMIT = Math.min(PAGE4, 168);
11767
+ var FAILURE_QUERY_LIMIT = Math.min(PAGE5, 168);
11239
11768
  var failureRowsByHour = /* @__PURE__ */ __name(async (db, platform, channel, timeRange) => {
11240
11769
  const read = /* @__PURE__ */ __name((end2, cursor2) => db.findAggregates("insights_failures", {
11241
11770
  index: "byScope",
@@ -11311,7 +11840,7 @@ var getUpdateFailures = /* @__PURE__ */ __name(async (db, input, now, retention)
11311
11840
  gte: 0,
11312
11841
  lte: 0
11313
11842
  },
11314
- limit: PAGE4
11843
+ limit: PAGE5
11315
11844
  }), db.findAggregates("insights_sketches_lifetime", {
11316
11845
  index: "window",
11317
11846
  where: where(failure),
@@ -11319,7 +11848,7 @@ var getUpdateFailures = /* @__PURE__ */ __name(async (db, input, now, retention)
11319
11848
  gte: 0,
11320
11849
  lte: 0
11321
11850
  },
11322
- limit: PAGE4
11851
+ limit: PAGE5
11323
11852
  })]);
11324
11853
  const lifetime = counters3.rows[0];
11325
11854
  return {
@@ -14598,11 +15127,31 @@ var withSqliteCode = /* @__PURE__ */ __name((error) => {
14598
15127
  ) ? "SQLITE_CONSTRAINT_UNIQUE" : /SQLITE_BUSY|database is locked/iu.test(message) ? "SQLITE_BUSY" : void 0;
14599
15128
  return code === void 0 ? error : Object.assign(new Error(message, { cause: error }), { code });
14600
15129
  }, "withSqliteCode");
15130
+ var TRANSIENT_D1_ERROR = /Network connection lost|storage caused object to be reset|reset because its code was updated|Cannot resolve D1 DB due to transient issue|Replica disconnected from primary/iu;
15131
+ var READ_ONLY_STATEMENT = /^\s*SELECT\b/iu;
15132
+ var READ_ATTEMPTS = 3;
15133
+ var READ_RETRY_BASE_MS = 25;
15134
+ var isTransient = /* @__PURE__ */ __name((error) => TRANSIENT_D1_ERROR.test(
15135
+ error instanceof Error ? error.message : String(error)
15136
+ ), "isTransient");
15137
+ var retryingReads = /* @__PURE__ */ __name((query2) => async (statement) => {
15138
+ if (!READ_ONLY_STATEMENT.test(statement.sql)) return query2(statement);
15139
+ for (let attempt = 1; ; attempt += 1) {
15140
+ try {
15141
+ return await query2(statement);
15142
+ } catch (error) {
15143
+ if (attempt >= READ_ATTEMPTS || !isTransient(error)) throw error;
15144
+ const wait = Math.random() * READ_RETRY_BASE_MS * 2 ** (attempt - 1);
15145
+ await new Promise((resolve) => setTimeout(resolve, wait));
15146
+ }
15147
+ }
15148
+ }, "retryingReads");
14601
15149
  var D1_MAX_OPS = 450;
14602
15150
  var createD1Database = /* @__PURE__ */ __name((runner) => {
15151
+ const query2 = retryingReads((statement) => runner.query(statement));
14603
15152
  const executor = {
14604
15153
  dialect: "sqlite",
14605
- execute: /* @__PURE__ */ __name((statement) => runner.query(statement).catch((error) => {
15154
+ execute: /* @__PURE__ */ __name((statement) => query2(statement).catch((error) => {
14606
15155
  throw withSqliteCode(error);
14607
15156
  }), "execute"),
14608
15157
  batch: /* @__PURE__ */ __name((statements) => runner.batch(statements).catch((error) => {