@hot-updater/server 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.
@@ -68,6 +68,10 @@ declare const createCoreApi: (db: CoreDatabase, storage: CoreStorage, options?:
68
68
  readonly action?: "copy" | "move";
69
69
  }) => Promise<import("@hot-updater/plugin-core").PromoteReleaseResult>;
70
70
  rebuildReleaseCatalog: (scopeKey: string) => Promise<import("@hot-updater/plugin-core").ReleaseCatalogRebuildResult>;
71
+ fillReleaseLabels: (input?: {
72
+ readonly dryRun?: boolean;
73
+ readonly catalogs?: boolean;
74
+ }) => Promise<import("@hot-updater/plugin-core").ReleaseLabelFill>;
71
75
  preflightReleaseCatalogRebuild: (scopeKey: string) => Promise<import("@hot-updater/plugin-core").ReleaseCatalogRebuildPreflight>;
72
76
  ensureChannel: (name: string) => Promise<import("@hot-updater/plugin-core").ChannelRow>;
73
77
  deleteChannel: (id: string) => Promise<import("@hot-updater/plugin-core").ChannelDeleteResult>;
@@ -101,6 +105,11 @@ declare const createCoreApi: (db: CoreDatabase, storage: CoreStorage, options?:
101
105
  readonly after?: string;
102
106
  readonly limit: number;
103
107
  }) => Promise<string[]>;
108
+ getReleaseByLabel: (input: {
109
+ readonly channel: string;
110
+ readonly platform: import("@hot-updater/protocol").Platform;
111
+ readonly label: number;
112
+ }) => Promise<import("@hot-updater/plugin-core").ReleaseRow | null>;
104
113
  };
105
114
  type CoreApi = ReturnType<typeof createCoreApi>;
106
115
  //#endregion
@@ -68,6 +68,10 @@ declare const createCoreApi: (db: CoreDatabase, storage: CoreStorage, options?:
68
68
  readonly action?: "copy" | "move";
69
69
  }) => Promise<import("@hot-updater/plugin-core").PromoteReleaseResult>;
70
70
  rebuildReleaseCatalog: (scopeKey: string) => Promise<import("@hot-updater/plugin-core").ReleaseCatalogRebuildResult>;
71
+ fillReleaseLabels: (input?: {
72
+ readonly dryRun?: boolean;
73
+ readonly catalogs?: boolean;
74
+ }) => Promise<import("@hot-updater/plugin-core").ReleaseLabelFill>;
71
75
  preflightReleaseCatalogRebuild: (scopeKey: string) => Promise<import("@hot-updater/plugin-core").ReleaseCatalogRebuildPreflight>;
72
76
  ensureChannel: (name: string) => Promise<import("@hot-updater/plugin-core").ChannelRow>;
73
77
  deleteChannel: (id: string) => Promise<import("@hot-updater/plugin-core").ChannelDeleteResult>;
@@ -101,6 +105,11 @@ declare const createCoreApi: (db: CoreDatabase, storage: CoreStorage, options?:
101
105
  readonly after?: string;
102
106
  readonly limit: number;
103
107
  }) => Promise<string[]>;
108
+ getReleaseByLabel: (input: {
109
+ readonly channel: string;
110
+ readonly platform: import("@hot-updater/protocol").Platform;
111
+ readonly label: number;
112
+ }) => Promise<import("@hot-updater/plugin-core").ReleaseRow | null>;
104
113
  };
105
114
  type CoreApi = ReturnType<typeof createCoreApi>;
106
115
  //#endregion
@@ -0,0 +1,317 @@
1
+ const require_reads = require("./reads.cjs");
2
+ let _hot_updater_plugin_core = require("@hot-updater/plugin-core");
3
+ //#region src/core/labels.ts
4
+ /**
5
+ * The counter of a channel and platform's release labels: one
6
+ * `label_sequences` row, which every writer of the pair reads and bumps.
7
+ */
8
+ const labelSequenceId = (channelId, platform) => `releases/${platform}/${channelId}`;
9
+ /** The pairs a channel's counters belong to, which deleting it removes. */
10
+ const LABEL_PLATFORMS = ["ios", "android"];
11
+ /**
12
+ * A channel and platform whose releases written before labels have none
13
+ * yet, or that has no counter: the write stops before taking a label, the
14
+ * core labels the pair with `fillLabels`, and the write runs again.
15
+ */
16
+ var NeedsLabelFill = class extends Error {
17
+ channelId;
18
+ platform;
19
+ constructor(channelId, platform) {
20
+ super(`Release labels of ${platform} ${channelId} need a fill first.`);
21
+ this.channelId = channelId;
22
+ this.platform = platform;
23
+ }
24
+ };
25
+ const createLabelAllocator = (tx, used, caughtUp) => {
26
+ const sequences = /* @__PURE__ */ new Map();
27
+ return {
28
+ async next(channelId, platform) {
29
+ const id = labelSequenceId(channelId, platform);
30
+ let sequence = sequences.get(id);
31
+ if (sequence === void 0) {
32
+ const row = await tx.findOne("label_sequences", { id });
33
+ if (row === null || !row.is_filled) {
34
+ const channel = row === null ? await tx.findOne("channels", { id: channelId }) : null;
35
+ if (channel === null || (channel._refs_releases_channel_id ?? 0) > 0) throw new NeedsLabelFill(channelId, platform);
36
+ }
37
+ const read = row?.last_label ?? 0;
38
+ sequence = {
39
+ row,
40
+ read,
41
+ last: read
42
+ };
43
+ sequences.set(id, sequence);
44
+ used.set(id, {
45
+ channelId,
46
+ platform,
47
+ read
48
+ });
49
+ }
50
+ sequence.last += 1;
51
+ return sequence.last;
52
+ },
53
+ caughtUp(channelId, platform) {
54
+ caughtUp.set(labelSequenceId(channelId, platform), {
55
+ channelId,
56
+ platform
57
+ });
58
+ },
59
+ flush() {
60
+ for (const [id, { row, read, last }] of sequences) if (row === null) tx.create("label_sequences", {
61
+ id,
62
+ last_label: last,
63
+ is_filled: true
64
+ });
65
+ else if (last !== read) tx.update("label_sequences", row, { last_label: last });
66
+ }
67
+ };
68
+ };
69
+ const FILL_BATCH = 25;
70
+ const PAGE = 500;
71
+ /**
72
+ * Labels a channel and platform's releases that have none, in ID order,
73
+ * which is the order they were created in, and marks its counter filled:
74
+ * each batch reads the counter and its rows guarded, so a concurrent fill or
75
+ * write serializes on the counter and skips what another labeled. With
76
+ * `dryRun`, it only counts them. Answers how many it labeled.
77
+ */
78
+ const fillLabels = async (db, { channelId, platform }, { dryRun = false } = {}) => {
79
+ const id = labelSequenceId(channelId, platform);
80
+ let labeled = 0;
81
+ let batchSize = FILL_BATCH;
82
+ const label = async (ids) => {
83
+ for (let at = 0; at < ids.length;) {
84
+ const batch = ids.slice(at, at + batchSize);
85
+ try {
86
+ labeled += await db.transaction(async (tx) => {
87
+ const counter = await tx.findOne("label_sequences", { id });
88
+ let last = counter?.last_label ?? 0;
89
+ let count = 0;
90
+ for (const releaseId of batch) {
91
+ const row = await tx.findOne("releases", { id: releaseId });
92
+ if (row === null || typeof row.label === "number") continue;
93
+ last += 1;
94
+ count += 1;
95
+ tx.update("releases", row, { label: last });
96
+ }
97
+ if (counter === null) tx.create("label_sequences", {
98
+ id,
99
+ last_label: last,
100
+ is_filled: false
101
+ });
102
+ else if (last !== counter.last_label) tx.update("label_sequences", counter, { last_label: last });
103
+ return count;
104
+ });
105
+ at += batch.length;
106
+ } catch (error) {
107
+ if (batchSize > 1 && error instanceof _hot_updater_plugin_core.DatabaseConstraintError && error.reason === "too_large") {
108
+ batchSize = Math.max(1, Math.floor(batchSize / 2));
109
+ continue;
110
+ }
111
+ throw error;
112
+ }
113
+ }
114
+ };
115
+ let cursor;
116
+ do {
117
+ const page = await db.findMany("releases", {
118
+ index: "byChannelPlatform",
119
+ where: {
120
+ channel_id: channelId,
121
+ platform
122
+ },
123
+ limit: PAGE,
124
+ ...cursor === void 0 ? {} : { cursor }
125
+ });
126
+ const unlabeled = page.rows.filter((row) => typeof row.label !== "number").map((row) => row.id);
127
+ if (dryRun) labeled += unlabeled.length;
128
+ else await label(unlabeled);
129
+ cursor = page.next;
130
+ } while (cursor !== void 0);
131
+ if (dryRun) return labeled;
132
+ await db.transaction(async (tx) => {
133
+ const counter = await tx.findOne("label_sequences", { id });
134
+ if (counter === null) tx.create("label_sequences", {
135
+ id,
136
+ last_label: 0,
137
+ is_filled: true
138
+ });
139
+ else if (!counter.is_filled) tx.update("label_sequences", counter, { is_filled: true });
140
+ });
141
+ return labeled;
142
+ };
143
+ /**
144
+ * Reads what a pair's fill writes, its counter and its label index, without
145
+ * writing: a database without release labels' schema, such as one a 1.2
146
+ * prerelease migrated, fails here as the fill would. The schema is the
147
+ * database's, so one pair tells. Two reads.
148
+ */
149
+ const probeLabelSchema = async (db, { channelId, platform }) => {
150
+ await db.findOne("label_sequences", { id: labelSequenceId(channelId, platform) });
151
+ await db.findMany("releases", {
152
+ index: "byLabel",
153
+ where: {
154
+ channel_id: channelId,
155
+ platform,
156
+ label: 0
157
+ },
158
+ limit: 1
159
+ });
160
+ };
161
+ const REPAIRS = 4;
162
+ const RACES = 32;
163
+ /**
164
+ * Runs a release write that takes labels, in one transaction with the
165
+ * counters it bumps. A pair that still needs its fill is filled, and the
166
+ * write runs again; so is a pair whose catch-up made the write too large for
167
+ * the store. A label another row holds, such as an index item a release
168
+ * deleted by a server of an earlier release left on a key-value store, is
169
+ * skipped: its counters move past it and the write runs again.
170
+ */
171
+ const writeWithLabels = async (db, write) => {
172
+ const filled = /* @__PURE__ */ new Set();
173
+ const fill = async (pairs) => {
174
+ for (const pair of pairs) {
175
+ filled.add(labelSequenceId(pair.channelId, pair.platform));
176
+ await fillLabels(db, pair);
177
+ }
178
+ };
179
+ for (let repairs = 0, races = 0;;) {
180
+ const used = /* @__PURE__ */ new Map();
181
+ const caughtUp = /* @__PURE__ */ new Map();
182
+ try {
183
+ return await db.transaction(async (tx) => {
184
+ used.clear();
185
+ caughtUp.clear();
186
+ const labels = createLabelAllocator(tx, used, caughtUp);
187
+ const result = await write(tx, labels);
188
+ labels.flush();
189
+ return result;
190
+ });
191
+ } catch (error) {
192
+ const needs = error instanceof NeedsLabelFill ? [error] : error instanceof _hot_updater_plugin_core.DatabaseConstraintError && error.reason === "too_large" ? [...caughtUp.values()] : [];
193
+ if (needs.length > 0) {
194
+ const fresh = needs.some(({ channelId, platform }) => !filled.has(labelSequenceId(channelId, platform)));
195
+ if (fresh || repairs < REPAIRS) {
196
+ if (!fresh) repairs += 1;
197
+ await fill(needs);
198
+ continue;
199
+ }
200
+ }
201
+ if (error instanceof _hot_updater_plugin_core.DatabaseConstraintError && error.reason === "unique" && error.model === "releases" && used.size > 0) {
202
+ if (await db.transaction(async (tx) => {
203
+ const moves = [];
204
+ for (const [id, { channelId, read }] of used) {
205
+ const counter = await tx.findOne("label_sequences", { id });
206
+ if (counter !== null) {
207
+ if (counter.last_label !== read) return false;
208
+ moves.push(() => tx.update("label_sequences", counter, { last_label: read + 1 }));
209
+ continue;
210
+ }
211
+ const channel = await tx.findOne("channels", { id: channelId });
212
+ if (channel === null || (channel._refs_releases_channel_id ?? 0) > 0) return false;
213
+ moves.push(() => tx.create("label_sequences", {
214
+ id,
215
+ last_label: read + 1,
216
+ is_filled: true
217
+ }));
218
+ }
219
+ for (const move of moves) move();
220
+ return true;
221
+ }) ? (repairs += 1) <= REPAIRS : (races += 1) <= RACES) continue;
222
+ }
223
+ throw error;
224
+ }
225
+ }
226
+ };
227
+ /**
228
+ * Labels a scope's releases a server of an earlier release wrote after its
229
+ * newest labeled one, oldest first, before the write takes its own label:
230
+ * `latest` is the scope's newest release, so a labeled one costs no read.
231
+ * Answers the labels it gave, by release ID.
232
+ */
233
+ const catchUpLabels = async (tx, labels, latest) => {
234
+ const given = /* @__PURE__ */ new Map();
235
+ if (latest === null || typeof latest.label === "number") return given;
236
+ const unlabeled = [];
237
+ let cursor;
238
+ scan: do {
239
+ const page = await tx.findMany("releases", {
240
+ index: "byScope",
241
+ where: { scope_key: latest.scope_key },
242
+ order: "desc",
243
+ limit: FILL_BATCH,
244
+ ...cursor === void 0 ? {} : { cursor }
245
+ });
246
+ for (const row of page.rows) {
247
+ if (typeof row.label === "number") break scan;
248
+ unlabeled.push(row);
249
+ }
250
+ cursor = page.next;
251
+ } while (cursor !== void 0);
252
+ labels.caughtUp(latest.channel_id, latest.platform);
253
+ for (const row of unlabeled.reverse()) {
254
+ const { id, channel_id, platform } = require_reads.toReleaseRow(row);
255
+ const label = await labels.next(channel_id, platform);
256
+ tx.update("releases", row, { label });
257
+ given.set(id, label);
258
+ }
259
+ return given;
260
+ };
261
+ /**
262
+ * The channels and platforms whose releases need labels: a scope whose
263
+ * newest release has none, or a pair without a filled counter. Releases a
264
+ * server of an earlier release wrote in a filled pair come after its
265
+ * labeled ones in their scope, so the newest release of each scope tells.
266
+ * Two reads per scope, one per pair.
267
+ */
268
+ const pendingLabelPairs = async (db) => {
269
+ const pairs = /* @__PURE__ */ new Map();
270
+ for (let last = "";;) {
271
+ const { rows } = await db.findMany("releases", {
272
+ index: "scopes",
273
+ where: {},
274
+ limit: 1,
275
+ range: { gt: last }
276
+ });
277
+ if (rows[0] === void 0) break;
278
+ last = rows[0].scope_key;
279
+ const { rows: newest } = await db.findMany("releases", {
280
+ index: "byScope",
281
+ where: { scope_key: last },
282
+ order: "desc",
283
+ limit: 1
284
+ });
285
+ if (newest[0] === void 0) continue;
286
+ const { channel_id: channelId, platform, label } = require_reads.toReleaseRow(newest[0]);
287
+ const id = labelSequenceId(channelId, platform);
288
+ const pair = pairs.get(id) ?? {
289
+ channelId,
290
+ platform,
291
+ pending: false
292
+ };
293
+ pair.pending ||= label === null;
294
+ pairs.set(id, pair);
295
+ }
296
+ const pending = [];
297
+ for (const [id, { channelId, platform, pending: unlabeled }] of pairs) {
298
+ if (!unlabeled) {
299
+ const counter = await db.findOne("label_sequences", { id });
300
+ if (counter !== null && counter.is_filled) continue;
301
+ }
302
+ pending.push({
303
+ channelId,
304
+ platform
305
+ });
306
+ }
307
+ return pending;
308
+ };
309
+ //#endregion
310
+ exports.LABEL_PLATFORMS = LABEL_PLATFORMS;
311
+ exports.NeedsLabelFill = NeedsLabelFill;
312
+ exports.catchUpLabels = catchUpLabels;
313
+ exports.fillLabels = fillLabels;
314
+ exports.labelSequenceId = labelSequenceId;
315
+ exports.pendingLabelPairs = pendingLabelPairs;
316
+ exports.probeLabelSchema = probeLabelSchema;
317
+ exports.writeWithLabels = writeWithLabels;
@@ -0,0 +1,310 @@
1
+ import { toReleaseRow } from "./reads.mjs";
2
+ import { DatabaseConstraintError } from "@hot-updater/plugin-core";
3
+ //#region src/core/labels.ts
4
+ /**
5
+ * The counter of a channel and platform's release labels: one
6
+ * `label_sequences` row, which every writer of the pair reads and bumps.
7
+ */
8
+ const labelSequenceId = (channelId, platform) => `releases/${platform}/${channelId}`;
9
+ /** The pairs a channel's counters belong to, which deleting it removes. */
10
+ const LABEL_PLATFORMS = ["ios", "android"];
11
+ /**
12
+ * A channel and platform whose releases written before labels have none
13
+ * yet, or that has no counter: the write stops before taking a label, the
14
+ * core labels the pair with `fillLabels`, and the write runs again.
15
+ */
16
+ var NeedsLabelFill = class extends Error {
17
+ channelId;
18
+ platform;
19
+ constructor(channelId, platform) {
20
+ super(`Release labels of ${platform} ${channelId} need a fill first.`);
21
+ this.channelId = channelId;
22
+ this.platform = platform;
23
+ }
24
+ };
25
+ const createLabelAllocator = (tx, used, caughtUp) => {
26
+ const sequences = /* @__PURE__ */ new Map();
27
+ return {
28
+ async next(channelId, platform) {
29
+ const id = labelSequenceId(channelId, platform);
30
+ let sequence = sequences.get(id);
31
+ if (sequence === void 0) {
32
+ const row = await tx.findOne("label_sequences", { id });
33
+ if (row === null || !row.is_filled) {
34
+ const channel = row === null ? await tx.findOne("channels", { id: channelId }) : null;
35
+ if (channel === null || (channel._refs_releases_channel_id ?? 0) > 0) throw new NeedsLabelFill(channelId, platform);
36
+ }
37
+ const read = row?.last_label ?? 0;
38
+ sequence = {
39
+ row,
40
+ read,
41
+ last: read
42
+ };
43
+ sequences.set(id, sequence);
44
+ used.set(id, {
45
+ channelId,
46
+ platform,
47
+ read
48
+ });
49
+ }
50
+ sequence.last += 1;
51
+ return sequence.last;
52
+ },
53
+ caughtUp(channelId, platform) {
54
+ caughtUp.set(labelSequenceId(channelId, platform), {
55
+ channelId,
56
+ platform
57
+ });
58
+ },
59
+ flush() {
60
+ for (const [id, { row, read, last }] of sequences) if (row === null) tx.create("label_sequences", {
61
+ id,
62
+ last_label: last,
63
+ is_filled: true
64
+ });
65
+ else if (last !== read) tx.update("label_sequences", row, { last_label: last });
66
+ }
67
+ };
68
+ };
69
+ const FILL_BATCH = 25;
70
+ const PAGE = 500;
71
+ /**
72
+ * Labels a channel and platform's releases that have none, in ID order,
73
+ * which is the order they were created in, and marks its counter filled:
74
+ * each batch reads the counter and its rows guarded, so a concurrent fill or
75
+ * write serializes on the counter and skips what another labeled. With
76
+ * `dryRun`, it only counts them. Answers how many it labeled.
77
+ */
78
+ const fillLabels = async (db, { channelId, platform }, { dryRun = false } = {}) => {
79
+ const id = labelSequenceId(channelId, platform);
80
+ let labeled = 0;
81
+ let batchSize = FILL_BATCH;
82
+ const label = async (ids) => {
83
+ for (let at = 0; at < ids.length;) {
84
+ const batch = ids.slice(at, at + batchSize);
85
+ try {
86
+ labeled += await db.transaction(async (tx) => {
87
+ const counter = await tx.findOne("label_sequences", { id });
88
+ let last = counter?.last_label ?? 0;
89
+ let count = 0;
90
+ for (const releaseId of batch) {
91
+ const row = await tx.findOne("releases", { id: releaseId });
92
+ if (row === null || typeof row.label === "number") continue;
93
+ last += 1;
94
+ count += 1;
95
+ tx.update("releases", row, { label: last });
96
+ }
97
+ if (counter === null) tx.create("label_sequences", {
98
+ id,
99
+ last_label: last,
100
+ is_filled: false
101
+ });
102
+ else if (last !== counter.last_label) tx.update("label_sequences", counter, { last_label: last });
103
+ return count;
104
+ });
105
+ at += batch.length;
106
+ } catch (error) {
107
+ if (batchSize > 1 && error instanceof DatabaseConstraintError && error.reason === "too_large") {
108
+ batchSize = Math.max(1, Math.floor(batchSize / 2));
109
+ continue;
110
+ }
111
+ throw error;
112
+ }
113
+ }
114
+ };
115
+ let cursor;
116
+ do {
117
+ const page = await db.findMany("releases", {
118
+ index: "byChannelPlatform",
119
+ where: {
120
+ channel_id: channelId,
121
+ platform
122
+ },
123
+ limit: PAGE,
124
+ ...cursor === void 0 ? {} : { cursor }
125
+ });
126
+ const unlabeled = page.rows.filter((row) => typeof row.label !== "number").map((row) => row.id);
127
+ if (dryRun) labeled += unlabeled.length;
128
+ else await label(unlabeled);
129
+ cursor = page.next;
130
+ } while (cursor !== void 0);
131
+ if (dryRun) return labeled;
132
+ await db.transaction(async (tx) => {
133
+ const counter = await tx.findOne("label_sequences", { id });
134
+ if (counter === null) tx.create("label_sequences", {
135
+ id,
136
+ last_label: 0,
137
+ is_filled: true
138
+ });
139
+ else if (!counter.is_filled) tx.update("label_sequences", counter, { is_filled: true });
140
+ });
141
+ return labeled;
142
+ };
143
+ /**
144
+ * Reads what a pair's fill writes, its counter and its label index, without
145
+ * writing: a database without release labels' schema, such as one a 1.2
146
+ * prerelease migrated, fails here as the fill would. The schema is the
147
+ * database's, so one pair tells. Two reads.
148
+ */
149
+ const probeLabelSchema = async (db, { channelId, platform }) => {
150
+ await db.findOne("label_sequences", { id: labelSequenceId(channelId, platform) });
151
+ await db.findMany("releases", {
152
+ index: "byLabel",
153
+ where: {
154
+ channel_id: channelId,
155
+ platform,
156
+ label: 0
157
+ },
158
+ limit: 1
159
+ });
160
+ };
161
+ const REPAIRS = 4;
162
+ const RACES = 32;
163
+ /**
164
+ * Runs a release write that takes labels, in one transaction with the
165
+ * counters it bumps. A pair that still needs its fill is filled, and the
166
+ * write runs again; so is a pair whose catch-up made the write too large for
167
+ * the store. A label another row holds, such as an index item a release
168
+ * deleted by a server of an earlier release left on a key-value store, is
169
+ * skipped: its counters move past it and the write runs again.
170
+ */
171
+ const writeWithLabels = async (db, write) => {
172
+ const filled = /* @__PURE__ */ new Set();
173
+ const fill = async (pairs) => {
174
+ for (const pair of pairs) {
175
+ filled.add(labelSequenceId(pair.channelId, pair.platform));
176
+ await fillLabels(db, pair);
177
+ }
178
+ };
179
+ for (let repairs = 0, races = 0;;) {
180
+ const used = /* @__PURE__ */ new Map();
181
+ const caughtUp = /* @__PURE__ */ new Map();
182
+ try {
183
+ return await db.transaction(async (tx) => {
184
+ used.clear();
185
+ caughtUp.clear();
186
+ const labels = createLabelAllocator(tx, used, caughtUp);
187
+ const result = await write(tx, labels);
188
+ labels.flush();
189
+ return result;
190
+ });
191
+ } catch (error) {
192
+ const needs = error instanceof NeedsLabelFill ? [error] : error instanceof DatabaseConstraintError && error.reason === "too_large" ? [...caughtUp.values()] : [];
193
+ if (needs.length > 0) {
194
+ const fresh = needs.some(({ channelId, platform }) => !filled.has(labelSequenceId(channelId, platform)));
195
+ if (fresh || repairs < REPAIRS) {
196
+ if (!fresh) repairs += 1;
197
+ await fill(needs);
198
+ continue;
199
+ }
200
+ }
201
+ if (error instanceof DatabaseConstraintError && error.reason === "unique" && error.model === "releases" && used.size > 0) {
202
+ if (await db.transaction(async (tx) => {
203
+ const moves = [];
204
+ for (const [id, { channelId, read }] of used) {
205
+ const counter = await tx.findOne("label_sequences", { id });
206
+ if (counter !== null) {
207
+ if (counter.last_label !== read) return false;
208
+ moves.push(() => tx.update("label_sequences", counter, { last_label: read + 1 }));
209
+ continue;
210
+ }
211
+ const channel = await tx.findOne("channels", { id: channelId });
212
+ if (channel === null || (channel._refs_releases_channel_id ?? 0) > 0) return false;
213
+ moves.push(() => tx.create("label_sequences", {
214
+ id,
215
+ last_label: read + 1,
216
+ is_filled: true
217
+ }));
218
+ }
219
+ for (const move of moves) move();
220
+ return true;
221
+ }) ? (repairs += 1) <= REPAIRS : (races += 1) <= RACES) continue;
222
+ }
223
+ throw error;
224
+ }
225
+ }
226
+ };
227
+ /**
228
+ * Labels a scope's releases a server of an earlier release wrote after its
229
+ * newest labeled one, oldest first, before the write takes its own label:
230
+ * `latest` is the scope's newest release, so a labeled one costs no read.
231
+ * Answers the labels it gave, by release ID.
232
+ */
233
+ const catchUpLabels = async (tx, labels, latest) => {
234
+ const given = /* @__PURE__ */ new Map();
235
+ if (latest === null || typeof latest.label === "number") return given;
236
+ const unlabeled = [];
237
+ let cursor;
238
+ scan: do {
239
+ const page = await tx.findMany("releases", {
240
+ index: "byScope",
241
+ where: { scope_key: latest.scope_key },
242
+ order: "desc",
243
+ limit: FILL_BATCH,
244
+ ...cursor === void 0 ? {} : { cursor }
245
+ });
246
+ for (const row of page.rows) {
247
+ if (typeof row.label === "number") break scan;
248
+ unlabeled.push(row);
249
+ }
250
+ cursor = page.next;
251
+ } while (cursor !== void 0);
252
+ labels.caughtUp(latest.channel_id, latest.platform);
253
+ for (const row of unlabeled.reverse()) {
254
+ const { id, channel_id, platform } = toReleaseRow(row);
255
+ const label = await labels.next(channel_id, platform);
256
+ tx.update("releases", row, { label });
257
+ given.set(id, label);
258
+ }
259
+ return given;
260
+ };
261
+ /**
262
+ * The channels and platforms whose releases need labels: a scope whose
263
+ * newest release has none, or a pair without a filled counter. Releases a
264
+ * server of an earlier release wrote in a filled pair come after its
265
+ * labeled ones in their scope, so the newest release of each scope tells.
266
+ * Two reads per scope, one per pair.
267
+ */
268
+ const pendingLabelPairs = async (db) => {
269
+ const pairs = /* @__PURE__ */ new Map();
270
+ for (let last = "";;) {
271
+ const { rows } = await db.findMany("releases", {
272
+ index: "scopes",
273
+ where: {},
274
+ limit: 1,
275
+ range: { gt: last }
276
+ });
277
+ if (rows[0] === void 0) break;
278
+ last = rows[0].scope_key;
279
+ const { rows: newest } = await db.findMany("releases", {
280
+ index: "byScope",
281
+ where: { scope_key: last },
282
+ order: "desc",
283
+ limit: 1
284
+ });
285
+ if (newest[0] === void 0) continue;
286
+ const { channel_id: channelId, platform, label } = toReleaseRow(newest[0]);
287
+ const id = labelSequenceId(channelId, platform);
288
+ const pair = pairs.get(id) ?? {
289
+ channelId,
290
+ platform,
291
+ pending: false
292
+ };
293
+ pair.pending ||= label === null;
294
+ pairs.set(id, pair);
295
+ }
296
+ const pending = [];
297
+ for (const [id, { channelId, platform, pending: unlabeled }] of pairs) {
298
+ if (!unlabeled) {
299
+ const counter = await db.findOne("label_sequences", { id });
300
+ if (counter !== null && counter.is_filled) continue;
301
+ }
302
+ pending.push({
303
+ channelId,
304
+ platform
305
+ });
306
+ }
307
+ return pending;
308
+ };
309
+ //#endregion
310
+ export { LABEL_PLATFORMS, NeedsLabelFill, catchUpLabels, fillLabels, labelSequenceId, pendingLabelPairs, probeLabelSchema, writeWithLabels };