@hot-updater/cloudflare 1.0.0-rc.2 → 1.0.0-rc.22
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.cjs +95 -870
- package/dist/index.d.cts +724 -6
- package/dist/index.d.mts +724 -6
- package/dist/index.mjs +93 -870
- package/dist/init/index.cjs +11768 -0
- package/dist/init/index.d.cts +5 -1
- package/dist/init/index.d.mts +5 -1
- package/dist/init/index.mjs +11761 -1
- package/dist/worker/index.cjs +59 -859
- package/dist/worker/index.d.cts +725 -11
- package/dist/worker/index.d.mts +725 -11
- package/dist/worker/index.mjs +62 -863
- package/package.json +9 -13
- package/sql/bundles.sql +109 -190
- package/src/d1Database.ts +61 -40
- package/src/d1Executor.ts +84 -0
- package/src/d1Schema.ts +26 -0
- package/src/index.ts +1 -0
- package/src/plugins.ts +8 -0
- package/src/r2S3Storage.ts +4 -4
- package/src/r2Storage.ts +2 -2
- package/src/r2WorkerStorage.ts +4 -4
- package/src/worker/d1Database.ts +21 -27
- package/src/worker/index.ts +1 -0
- package/worker/dist/README.md +1 -1
- package/worker/dist/index.js +9682 -6206
- package/worker/dist/index.js.map +4 -4
- package/worker/migrations/0001_hot-updater_1.0.0.sql +109 -205
- package/worker/src/index.ts +2 -2
- package/dist/iac/index.cjs +0 -12566
- package/dist/iac/index.d.cts +0 -9
- package/dist/iac/index.d.mts +0 -9
- package/dist/iac/index.mjs +0 -12558
- package/src/d1Database.spec.ts +0 -178
- package/src/d1Implementation.spec.ts +0 -252
- package/src/d1Implementation.ts +0 -742
- package/src/d1Query.spec.ts +0 -46
- package/src/d1Query.ts +0 -89
- package/src/d1Rows.spec.ts +0 -111
- package/src/d1Rows.ts +0 -326
- package/src/d1Sql.spec.ts +0 -30
- package/src/d1Sql.ts +0 -175
- package/src/r2Storage.spec.ts +0 -346
- package/src/r2WorkerStorage.spec.ts +0 -184
- package/src/utils/createWrangler.spec.ts +0 -75
- package/src/worker/d1Database.spec.ts +0 -33
- package/worker/src/databaseMigration.integration.spec.ts +0 -130
- package/worker/src/databasePlugins.integration.spec.ts +0 -292
- package/worker/src/index.integration.spec.ts +0 -190
- package/worker/src/storagePlugin.integration.spec.ts +0 -59
- package/worker/src/testWorker.ts +0 -5
package/dist/index.cjs
CHANGED
|
@@ -16,904 +16,120 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
16
16
|
}
|
|
17
17
|
return to;
|
|
18
18
|
};
|
|
19
|
-
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
|
|
19
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
|
|
20
20
|
value: mod,
|
|
21
21
|
enumerable: true
|
|
22
22
|
}) : target, mod));
|
|
23
23
|
//#endregion
|
|
24
24
|
let _hot_updater_plugin_core = require("@hot-updater/plugin-core");
|
|
25
|
-
let _hot_updater_plugin_core_internal = require("@hot-updater/plugin-core/internal");
|
|
26
25
|
let cloudflare = require("cloudflare");
|
|
27
|
-
cloudflare = __toESM(cloudflare);
|
|
26
|
+
cloudflare = __toESM(cloudflare, 1);
|
|
28
27
|
let _aws_sdk_client_s3 = require("@aws-sdk/client-s3");
|
|
29
28
|
let _aws_sdk_lib_storage = require("@aws-sdk/lib-storage");
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
29
|
+
let _hot_updater_server_plugins_api_keys = require("@hot-updater/server/plugins/api-keys");
|
|
30
|
+
let _hot_updater_server_plugins_insights = require("@hot-updater/server/plugins/insights");
|
|
31
|
+
//#region src/d1Executor.ts
|
|
32
|
+
var D1ExecutionError = class extends Error {
|
|
33
|
+
name = "D1ExecutionError";
|
|
34
|
+
constructor() {
|
|
35
|
+
super("D1 did not successfully execute every requested statement");
|
|
37
36
|
}
|
|
38
37
|
};
|
|
39
|
-
const
|
|
40
|
-
|
|
41
|
-
const value = row[field];
|
|
42
|
-
if (typeof value !== "string") throw new InvalidD1RowError(model);
|
|
43
|
-
return value;
|
|
44
|
-
};
|
|
45
|
-
const nullableString = (row, field, model) => {
|
|
46
|
-
const value = row[field];
|
|
47
|
-
if (value === null) return null;
|
|
48
|
-
if (typeof value !== "string") throw new InvalidD1RowError(model);
|
|
49
|
-
return value;
|
|
50
|
-
};
|
|
51
|
-
const numberValue = (row, field, model) => {
|
|
52
|
-
const value = row[field];
|
|
53
|
-
if (typeof value !== "number") throw new InvalidD1RowError(model);
|
|
54
|
-
return value;
|
|
55
|
-
};
|
|
56
|
-
const byteSizeValue = (row, field, model) => {
|
|
57
|
-
const value = row[field];
|
|
58
|
-
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) throw new InvalidD1RowError(model);
|
|
59
|
-
return value;
|
|
60
|
-
};
|
|
61
|
-
const booleanValue = (row, field, model) => {
|
|
62
|
-
const value = row[field];
|
|
63
|
-
if (value === true || value === 1) return true;
|
|
64
|
-
if (value === false || value === 0) return false;
|
|
65
|
-
throw new InvalidD1RowError(model);
|
|
66
|
-
};
|
|
67
|
-
const jsonValue = (value, model) => {
|
|
68
|
-
if (typeof value !== "string") throw new InvalidD1RowError(model);
|
|
69
|
-
try {
|
|
70
|
-
return JSON.parse(value);
|
|
71
|
-
} catch (error) {
|
|
72
|
-
if (error instanceof SyntaxError) throw new InvalidD1RowError(model);
|
|
73
|
-
throw error;
|
|
74
|
-
}
|
|
75
|
-
};
|
|
76
|
-
const metadata = (row) => {
|
|
77
|
-
const value = jsonValue(row["metadata"], "bundles");
|
|
78
|
-
if (!(0, _hot_updater_plugin_core.isDatabaseMetadataObject)(value)) throw new InvalidD1RowError("bundles");
|
|
79
|
-
return value;
|
|
80
|
-
};
|
|
81
|
-
const bundleRow = (row) => {
|
|
82
|
-
const platform = stringValue(row, "platform", "bundles");
|
|
83
|
-
if (platform !== "ios" && platform !== "android") throw new InvalidD1RowError("bundles");
|
|
84
|
-
return {
|
|
85
|
-
id: stringValue(row, "id", "bundles"),
|
|
86
|
-
platform,
|
|
87
|
-
file_hash: stringValue(row, "file_hash", "bundles"),
|
|
88
|
-
git_commit_hash: nullableString(row, "git_commit_hash", "bundles"),
|
|
89
|
-
storage_uri: stringValue(row, "storage_uri", "bundles"),
|
|
90
|
-
archive_byte_size: row["archive_byte_size"] === void 0 ? 0 : byteSizeValue(row, "archive_byte_size", "bundles"),
|
|
91
|
-
metadata: metadata(row),
|
|
92
|
-
manifest_storage_uri: nullableString(row, "manifest_storage_uri", "bundles"),
|
|
93
|
-
manifest_file_hash: nullableString(row, "manifest_file_hash", "bundles"),
|
|
94
|
-
asset_base_storage_uri: nullableString(row, "asset_base_storage_uri", "bundles")
|
|
95
|
-
};
|
|
96
|
-
};
|
|
97
|
-
const patchRow = (row) => ({
|
|
98
|
-
id: stringValue(row, "id", "bundle_patches"),
|
|
99
|
-
bundle_id: stringValue(row, "bundle_id", "bundle_patches"),
|
|
100
|
-
base_bundle_id: stringValue(row, "base_bundle_id", "bundle_patches"),
|
|
101
|
-
base_file_hash: stringValue(row, "base_file_hash", "bundle_patches"),
|
|
102
|
-
patch_file_hash: stringValue(row, "patch_file_hash", "bundle_patches"),
|
|
103
|
-
patch_storage_uri: stringValue(row, "patch_storage_uri", "bundle_patches"),
|
|
104
|
-
byte_size: byteSizeValue(row, "byte_size", "bundle_patches"),
|
|
105
|
-
order_index: numberValue(row, "order_index", "bundle_patches")
|
|
106
|
-
});
|
|
107
|
-
const channelRow = (row) => ({
|
|
108
|
-
id: stringValue(row, "id", "channels"),
|
|
109
|
-
name: stringValue(row, "name", "channels")
|
|
110
|
-
});
|
|
111
|
-
const eventRow = (row) => {
|
|
112
|
-
const type = stringValue(row, "type", "bundle_events");
|
|
113
|
-
const platform = stringValue(row, "platform", "bundle_events");
|
|
114
|
-
const fromBundleId = nullableString(row, "from_bundle_id", "bundle_events");
|
|
115
|
-
const updateStrategy = nullableString(row, "update_strategy", "bundle_events");
|
|
116
|
-
if (platform !== "ios" && platform !== "android" || !((type === "UPDATE_APPLIED" || type === "RECOVERED" || type === "RELEASE_ADOPTED") && typeof fromBundleId === "string" && (updateStrategy === "fingerprint" || updateStrategy === "appVersion") || type === "UNCHANGED" && fromBundleId === null && updateStrategy === null)) throw new InvalidD1RowError("bundle_events");
|
|
117
|
-
return {
|
|
118
|
-
id: stringValue(row, "id", "bundle_events"),
|
|
119
|
-
type,
|
|
120
|
-
install_id: stringValue(row, "install_id", "bundle_events"),
|
|
121
|
-
user_id: nullableString(row, "user_id", "bundle_events"),
|
|
122
|
-
username: nullableString(row, "username", "bundle_events"),
|
|
123
|
-
from_release_id: nullableString(row, "from_release_id", "bundle_events"),
|
|
124
|
-
from_bundle_id: fromBundleId,
|
|
125
|
-
to_release_id: nullableString(row, "to_release_id", "bundle_events"),
|
|
126
|
-
to_bundle_id: stringValue(row, "to_bundle_id", "bundle_events"),
|
|
127
|
-
platform,
|
|
128
|
-
app_version: stringValue(row, "app_version", "bundle_events"),
|
|
129
|
-
channel: stringValue(row, "channel", "bundle_events"),
|
|
130
|
-
cohort: stringValue(row, "cohort", "bundle_events"),
|
|
131
|
-
update_strategy: updateStrategy,
|
|
132
|
-
fingerprint_hash: nullableString(row, "fingerprint_hash", "bundle_events"),
|
|
133
|
-
sdk_version: nullableString(row, "sdk_version", "bundle_events"),
|
|
134
|
-
received_at_ms: numberValue(row, "received_at_ms", "bundle_events")
|
|
135
|
-
};
|
|
136
|
-
};
|
|
137
|
-
const apiKeyRow = (row) => {
|
|
138
|
-
const role = stringValue(row, "role", "api_keys");
|
|
139
|
-
if (role !== "client") throw new InvalidD1RowError("api_keys");
|
|
140
|
-
const revokedAt = row["revoked_at_ms"];
|
|
141
|
-
return {
|
|
142
|
-
id: stringValue(row, "id", "api_keys"),
|
|
143
|
-
hash: stringValue(row, "hash", "api_keys"),
|
|
144
|
-
name: stringValue(row, "name", "api_keys"),
|
|
145
|
-
prefix: stringValue(row, "prefix", "api_keys"),
|
|
146
|
-
role,
|
|
147
|
-
created_at_ms: numberValue(row, "created_at_ms", "api_keys"),
|
|
148
|
-
revoked_at_ms: revokedAt === null ? null : numberValue(row, "revoked_at_ms", "api_keys")
|
|
149
|
-
};
|
|
150
|
-
};
|
|
151
|
-
const releaseTargetCohorts = (row) => {
|
|
152
|
-
const value = jsonValue(row["target_cohorts"], "releases");
|
|
153
|
-
if (!Array.isArray(value) || value.some((item) => typeof item !== "string")) throw new InvalidD1RowError("releases");
|
|
154
|
-
return value.filter((item) => typeof item === "string");
|
|
155
|
-
};
|
|
156
|
-
const releaseRow = (row) => {
|
|
157
|
-
const platform = stringValue(row, "platform", "releases");
|
|
158
|
-
const kind = stringValue(row, "kind", "releases");
|
|
159
|
-
const strategy = stringValue(row, "strategy", "releases");
|
|
160
|
-
const operation = stringValue(row, "operation", "releases");
|
|
161
|
-
if (platform !== "ios" && platform !== "android" || kind !== "BUNDLE" && kind !== "EMBEDDED" || strategy !== "APP_VERSION" && strategy !== "FINGERPRINT" || operation !== "DEPLOY" && operation !== "PROMOTE" && operation !== "ROLLBACK") throw new InvalidD1RowError("releases");
|
|
162
|
-
return {
|
|
163
|
-
id: stringValue(row, "id", "releases"),
|
|
164
|
-
revision: numberValue(row, "revision", "releases"),
|
|
165
|
-
scope_key: stringValue(row, "scope_key", "releases"),
|
|
166
|
-
channel_id: stringValue(row, "channel_id", "releases"),
|
|
167
|
-
platform,
|
|
168
|
-
kind,
|
|
169
|
-
bundle_id: nullableString(row, "bundle_id", "releases"),
|
|
170
|
-
strategy,
|
|
171
|
-
target_app_version: nullableString(row, "target_app_version", "releases"),
|
|
172
|
-
fingerprint_hash: nullableString(row, "fingerprint_hash", "releases"),
|
|
173
|
-
enabled: booleanValue(row, "enabled", "releases"),
|
|
174
|
-
should_force_update: booleanValue(row, "should_force_update", "releases"),
|
|
175
|
-
message: nullableString(row, "message", "releases"),
|
|
176
|
-
rollout_cohort_count: numberValue(row, "rollout_cohort_count", "releases"),
|
|
177
|
-
target_cohorts: releaseTargetCohorts(row),
|
|
178
|
-
operation,
|
|
179
|
-
source_release_id: nullableString(row, "source_release_id", "releases"),
|
|
180
|
-
created_at_ms: numberValue(row, "created_at_ms", "releases"),
|
|
181
|
-
updated_at_ms: numberValue(row, "updated_at_ms", "releases")
|
|
182
|
-
};
|
|
183
|
-
};
|
|
184
|
-
const releaseCatalogRow = (row) => {
|
|
185
|
-
const platform = stringValue(row, "platform", "release_catalogs");
|
|
186
|
-
const strategy = stringValue(row, "strategy", "release_catalogs");
|
|
187
|
-
if (platform !== "ios" && platform !== "android" || strategy !== "APP_VERSION" && strategy !== "FINGERPRINT") throw new InvalidD1RowError("release_catalogs");
|
|
188
|
-
return {
|
|
189
|
-
scope_key: stringValue(row, "scope_key", "release_catalogs"),
|
|
190
|
-
catalog_id: stringValue(row, "catalog_id", "release_catalogs"),
|
|
191
|
-
strategy,
|
|
192
|
-
channel_id: stringValue(row, "channel_id", "release_catalogs"),
|
|
193
|
-
channel_key: stringValue(row, "channel_key", "release_catalogs"),
|
|
194
|
-
platform,
|
|
195
|
-
fingerprint_hash: nullableString(row, "fingerprint_hash", "release_catalogs"),
|
|
196
|
-
generation: numberValue(row, "generation", "release_catalogs"),
|
|
197
|
-
payload: stringValue(row, "payload", "release_catalogs"),
|
|
198
|
-
catalog_hash: stringValue(row, "catalog_hash", "release_catalogs"),
|
|
199
|
-
byte_size: numberValue(row, "byte_size", "release_catalogs"),
|
|
200
|
-
is_tombstone: booleanValue(row, "is_tombstone", "release_catalogs"),
|
|
201
|
-
updated_at_ms: numberValue(row, "updated_at_ms", "release_catalogs")
|
|
202
|
-
};
|
|
203
|
-
};
|
|
204
|
-
function parseD1Row(model, value) {
|
|
205
|
-
if (!isRecord(value)) throw new InvalidD1RowError(model);
|
|
206
|
-
switch (model) {
|
|
207
|
-
case "bundles": return bundleRow(value);
|
|
208
|
-
case "bundle_patches": return patchRow(value);
|
|
209
|
-
case "channels": return channelRow(value);
|
|
210
|
-
case "bundle_events": return eventRow(value);
|
|
211
|
-
case "api_keys": return apiKeyRow(value);
|
|
212
|
-
case "releases": return releaseRow(value);
|
|
213
|
-
case "release_catalogs": return releaseCatalogRow(value);
|
|
214
|
-
}
|
|
215
|
-
}
|
|
216
|
-
//#endregion
|
|
217
|
-
//#region src/d1Sql.ts
|
|
218
|
-
var InvalidD1PredicateError = class extends Error {
|
|
219
|
-
name = "InvalidD1PredicateError";
|
|
220
|
-
};
|
|
221
|
-
const encodeD1Value = (value) => {
|
|
222
|
-
const encoded = JSON.stringify(value);
|
|
223
|
-
if (encoded === void 0) throw new TypeError("D1 values must be JSON-serializable.");
|
|
224
|
-
return encoded;
|
|
225
|
-
};
|
|
226
|
-
const bind = (value) => ({
|
|
227
|
-
sql: "json_extract(?, '$')",
|
|
228
|
-
params: [encodeD1Value(value)]
|
|
229
|
-
});
|
|
230
|
-
const escapeLikePattern = (value) => value.replaceAll("\\", "\\\\").replaceAll("%", "\\%").replaceAll("_", "\\_");
|
|
231
|
-
const stringPredicate = (condition, operator) => {
|
|
232
|
-
if (typeof condition.value !== "string") throw new InvalidD1PredicateError();
|
|
233
|
-
if (condition.mode !== "insensitive") {
|
|
234
|
-
const parameter = bind(condition.value);
|
|
235
|
-
const column = `${condition.field} COLLATE BINARY`;
|
|
236
|
-
const value = `${parameter.sql} COLLATE BINARY`;
|
|
237
|
-
if (operator === "contains" || operator === "starts_with") return {
|
|
238
|
-
sql: `instr(${column}, ${value}) ${operator === "contains" ? "> 0" : "= 1"}`,
|
|
239
|
-
params: parameter.params
|
|
240
|
-
};
|
|
241
|
-
return {
|
|
242
|
-
sql: `substr(${column}, length(${condition.field}) - length(${parameter.sql}) + 1) = ${value}`,
|
|
243
|
-
params: [...parameter.params, ...parameter.params]
|
|
244
|
-
};
|
|
245
|
-
}
|
|
246
|
-
const literal = escapeLikePattern(condition.value);
|
|
247
|
-
const parameter = bind(operator === "contains" ? `%${literal}%` : operator === "starts_with" ? `${literal}%` : `%${literal}`);
|
|
38
|
+
const toSqlResult = (result) => {
|
|
39
|
+
if (result.success === false) throw new D1ExecutionError();
|
|
248
40
|
return {
|
|
249
|
-
|
|
250
|
-
|
|
41
|
+
rows: result.results ?? [],
|
|
42
|
+
changes: result.meta?.changes ?? 0
|
|
251
43
|
};
|
|
252
44
|
};
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
switch (operator) {
|
|
256
|
-
case "eq":
|
|
257
|
-
case "ne": {
|
|
258
|
-
if (condition.value === null) return {
|
|
259
|
-
sql: `${condition.field} IS ${operator === "ne" ? "NOT " : ""}NULL`,
|
|
260
|
-
params: []
|
|
261
|
-
};
|
|
262
|
-
const parameter = bind(condition.value);
|
|
263
|
-
const insensitive = "mode" in condition && condition.mode === "insensitive";
|
|
264
|
-
const column = insensitive ? `lower(${condition.field})` : condition.field;
|
|
265
|
-
const value = insensitive ? `lower(${parameter.sql})` : parameter.sql;
|
|
266
|
-
return {
|
|
267
|
-
sql: `${column} ${operator === "eq" ? "=" : "<>"} ${value}`,
|
|
268
|
-
params: parameter.params
|
|
269
|
-
};
|
|
270
|
-
}
|
|
271
|
-
case "gt":
|
|
272
|
-
case "gte":
|
|
273
|
-
case "lt":
|
|
274
|
-
case "lte": {
|
|
275
|
-
const sqlOperator = {
|
|
276
|
-
gt: ">",
|
|
277
|
-
gte: ">=",
|
|
278
|
-
lt: "<",
|
|
279
|
-
lte: "<="
|
|
280
|
-
}[operator];
|
|
281
|
-
const parameter = bind(condition.value);
|
|
282
|
-
return {
|
|
283
|
-
sql: `${condition.field} ${sqlOperator} ${parameter.sql}`,
|
|
284
|
-
params: parameter.params
|
|
285
|
-
};
|
|
286
|
-
}
|
|
287
|
-
case "in":
|
|
288
|
-
case "not_in":
|
|
289
|
-
if (!Array.isArray(condition.value)) throw new InvalidD1PredicateError();
|
|
290
|
-
if (condition.value.length === 0) return {
|
|
291
|
-
sql: operator === "not_in" ? "1 = 1" : "1 = 0",
|
|
292
|
-
params: []
|
|
293
|
-
};
|
|
294
|
-
return {
|
|
295
|
-
sql: `${condition.field} ${operator === "not_in" ? "NOT " : ""}IN (SELECT value FROM json_each(?))`,
|
|
296
|
-
params: [encodeD1Value(condition.value)]
|
|
297
|
-
};
|
|
298
|
-
case "contains":
|
|
299
|
-
case "starts_with":
|
|
300
|
-
case "ends_with": return stringPredicate(condition, operator);
|
|
301
|
-
}
|
|
302
|
-
};
|
|
303
|
-
const buildD1Where = (where) => {
|
|
304
|
-
const [first, ...rest] = where ?? [];
|
|
305
|
-
if (first === void 0) return {
|
|
306
|
-
sql: "",
|
|
307
|
-
params: []
|
|
308
|
-
};
|
|
309
|
-
const initial = predicate(first);
|
|
310
|
-
let sql = initial.sql;
|
|
311
|
-
const params = [...initial.params];
|
|
312
|
-
for (const condition of rest) {
|
|
313
|
-
const next = predicate(condition);
|
|
314
|
-
sql = `(${sql} ${condition.connector === "OR" ? "OR" : "AND"} ${next.sql})`;
|
|
315
|
-
params.push(...next.params);
|
|
316
|
-
}
|
|
317
|
-
return {
|
|
318
|
-
sql: ` WHERE ${sql}`,
|
|
319
|
-
params
|
|
320
|
-
};
|
|
321
|
-
};
|
|
322
|
-
const buildD1Order = (orderBy) => orderBy === void 0 ? "" : ` ORDER BY ${orderBy.map((clause) => `${clause.field} ${clause.direction.toUpperCase()}${clause.nulls ? ` NULLS ${clause.nulls.toUpperCase()}` : ""}`).join(", ")}`;
|
|
323
|
-
const d1Placeholders = (count) => Array.from({ length: count }, () => "json_extract(?, '$')").join(", ");
|
|
324
|
-
const encodeD1Values = (values) => values.map(encodeD1Value);
|
|
325
|
-
//#endregion
|
|
326
|
-
//#region src/d1Query.ts
|
|
327
|
-
const d1TableNames = {
|
|
328
|
-
bundles: "bundles",
|
|
329
|
-
bundle_patches: "bundle_patches",
|
|
330
|
-
channels: "channels",
|
|
331
|
-
bundle_events: "bundle_events",
|
|
332
|
-
api_keys: "api_keys",
|
|
333
|
-
release_catalogs: "release_catalogs",
|
|
334
|
-
releases: "releases"
|
|
335
|
-
};
|
|
336
|
-
var D1QueryResultError = class extends Error {
|
|
337
|
-
name = "D1QueryResultError";
|
|
338
|
-
operation = "count";
|
|
339
|
-
constructor(result) {
|
|
340
|
-
super("D1 count query returned a malformed first row");
|
|
341
|
-
this.result = result;
|
|
342
|
-
}
|
|
343
|
-
};
|
|
344
|
-
const countD1Rows = async (executor, input) => {
|
|
345
|
-
const where = buildD1Where(input.where);
|
|
346
|
-
const table = d1TableNames[input.model];
|
|
347
|
-
const source = input.distinct === void 0 ? `${table}${where.sql}` : `(SELECT DISTINCT ${input.distinct.join(", ")} FROM ${table}${where.sql}) AS distinct_rows`;
|
|
348
|
-
const row = (await executor.query(`SELECT COUNT(*) AS count FROM ${source}`, where.params))[0];
|
|
349
|
-
if (typeof row !== "object" || row === null || Array.isArray(row)) throw new D1QueryResultError(row);
|
|
350
|
-
const count = Reflect.get(row, "count");
|
|
351
|
-
if (typeof count !== "number" || !Number.isFinite(count)) throw new D1QueryResultError(row);
|
|
352
|
-
return count;
|
|
353
|
-
};
|
|
354
|
-
const findManyD1Rows = async (executor, input) => {
|
|
355
|
-
const where = buildD1Where(input.where);
|
|
356
|
-
const orderBy = input.orderBy;
|
|
357
|
-
const order = buildD1Order(orderBy);
|
|
358
|
-
const table = d1TableNames[input.model];
|
|
359
|
-
const source = input.distinctOn === void 0 ? `SELECT * FROM ${table}${where.sql}${order}` : `SELECT * FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY ${input.distinctOn.fields.join(", ")}${order}) AS __hot_updater_rank FROM ${table}${where.sql}) AS distinct_rows WHERE __hot_updater_rank = 1${order}`;
|
|
360
|
-
const pageParams = encodeD1Values([input.limit, input.offset]);
|
|
361
|
-
const rows = await executor.query(`${source} LIMIT json_extract(?, '$') OFFSET json_extract(?, '$')`, [...where.params, ...pageParams]);
|
|
362
|
-
switch (input.model) {
|
|
363
|
-
case "bundles": return rows.map((row) => parseD1Row("bundles", row));
|
|
364
|
-
case "bundle_patches": return rows.map((row) => parseD1Row("bundle_patches", row));
|
|
365
|
-
case "channels": return rows.map((row) => parseD1Row("channels", row));
|
|
366
|
-
case "bundle_events": return rows.map((row) => parseD1Row("bundle_events", row));
|
|
367
|
-
case "api_keys": return rows.map((row) => parseD1Row("api_keys", row));
|
|
368
|
-
case "releases": return rows.map((row) => parseD1Row("releases", row));
|
|
369
|
-
case "release_catalogs": return rows.map((row) => parseD1Row("release_catalogs", row));
|
|
370
|
-
}
|
|
371
|
-
};
|
|
372
|
-
//#endregion
|
|
373
|
-
//#region src/d1Implementation.ts
|
|
374
|
-
const EXPECTATION_CONFLICT_MARKER = "HOT_UPDATER_COMMIT_EXPECTATION_CONFLICT";
|
|
375
|
-
const expectationGuard = (expectations) => {
|
|
376
|
-
const clauses = [];
|
|
377
|
-
const params = [];
|
|
378
|
-
for (const expectation of expectations) {
|
|
379
|
-
const isRelease = expectation.model === "releases";
|
|
380
|
-
const table = isRelease ? "releases" : "release_catalogs";
|
|
381
|
-
const keyField = isRelease ? "id" : "scope_key";
|
|
382
|
-
const versionField = isRelease ? "revision" : "generation";
|
|
383
|
-
const key = isRelease ? expectation.id : expectation.scopeKey;
|
|
384
|
-
const version = isRelease ? expectation.revision : expectation.generation;
|
|
385
|
-
if (version === null) {
|
|
386
|
-
clauses.push(`NOT EXISTS (SELECT 1 FROM ${table} WHERE ${keyField} = json_extract(?, '$'))`);
|
|
387
|
-
params.push(...encodeD1Values([key]));
|
|
388
|
-
} else {
|
|
389
|
-
clauses.push(`EXISTS (SELECT 1 FROM ${table} WHERE ${keyField} = json_extract(?, '$') AND ${versionField} = json_extract(?, '$'))`);
|
|
390
|
-
params.push(...encodeD1Values([key, version]));
|
|
391
|
-
}
|
|
392
|
-
}
|
|
393
|
-
return {
|
|
394
|
-
sql: clauses.join(" AND ") || "1",
|
|
395
|
-
params
|
|
396
|
-
};
|
|
397
|
-
};
|
|
398
|
-
const readVersion = (row, field) => {
|
|
399
|
-
if (typeof row !== "object" || row === null) return null;
|
|
400
|
-
const value = Reflect.get(row, field);
|
|
401
|
-
return typeof value === "number" ? value : null;
|
|
402
|
-
};
|
|
403
|
-
const expectationConflict = async (executor, expectations) => {
|
|
404
|
-
for (const expectation of expectations) {
|
|
405
|
-
const isRelease = expectation.model === "releases";
|
|
406
|
-
const table = isRelease ? "releases" : "release_catalogs";
|
|
407
|
-
const keyField = isRelease ? "id" : "scope_key";
|
|
408
|
-
const versionField = isRelease ? "revision" : "generation";
|
|
409
|
-
const key = isRelease ? expectation.id : expectation.scopeKey;
|
|
410
|
-
const expectedVersion = isRelease ? expectation.revision : expectation.generation;
|
|
411
|
-
const actualVersion = readVersion((await executor.query(`SELECT ${versionField} FROM ${table} WHERE ${keyField} = json_extract(?, '$') LIMIT 1`, encodeD1Values([key])))[0], versionField);
|
|
412
|
-
if (actualVersion !== expectedVersion) return {
|
|
413
|
-
committed: false,
|
|
414
|
-
conflict: {
|
|
415
|
-
actualVersion,
|
|
416
|
-
changeIndex: -1,
|
|
417
|
-
expectedVersion,
|
|
418
|
-
key,
|
|
419
|
-
model: expectation.model,
|
|
420
|
-
reason: "version_conflict"
|
|
421
|
-
}
|
|
422
|
-
};
|
|
423
|
-
}
|
|
424
|
-
return null;
|
|
425
|
-
};
|
|
426
|
-
const isExpectationConflictError = (error) => {
|
|
45
|
+
/** D1 reports SQLite errors in the message; the SQL core classifies codes. */
|
|
46
|
+
const withSqliteCode = (error) => {
|
|
427
47
|
const message = error instanceof Error ? error.message : String(error);
|
|
428
|
-
|
|
429
|
-
};
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
];
|
|
452
|
-
const channelValues = (row) => [row.id, row.name];
|
|
453
|
-
const insertQuery = (input, guard, conflictMode = "returnExisting") => {
|
|
454
|
-
let columns;
|
|
455
|
-
let values;
|
|
456
|
-
switch (input.model) {
|
|
457
|
-
case "bundles":
|
|
458
|
-
columns = [
|
|
459
|
-
"id",
|
|
460
|
-
"platform",
|
|
461
|
-
"file_hash",
|
|
462
|
-
"git_commit_hash",
|
|
463
|
-
"storage_uri",
|
|
464
|
-
"archive_byte_size",
|
|
465
|
-
"metadata",
|
|
466
|
-
"manifest_storage_uri",
|
|
467
|
-
"manifest_file_hash",
|
|
468
|
-
"asset_base_storage_uri"
|
|
469
|
-
];
|
|
470
|
-
values = bundleValues(input.data);
|
|
471
|
-
break;
|
|
472
|
-
case "bundle_patches":
|
|
473
|
-
columns = [
|
|
474
|
-
"id",
|
|
475
|
-
"bundle_id",
|
|
476
|
-
"base_bundle_id",
|
|
477
|
-
"base_file_hash",
|
|
478
|
-
"patch_file_hash",
|
|
479
|
-
"patch_storage_uri",
|
|
480
|
-
"byte_size",
|
|
481
|
-
"order_index"
|
|
482
|
-
];
|
|
483
|
-
values = patchValues(input.data);
|
|
484
|
-
break;
|
|
485
|
-
case "channels":
|
|
486
|
-
columns = ["id", "name"];
|
|
487
|
-
values = channelValues(input.data);
|
|
488
|
-
break;
|
|
489
|
-
case "bundle_events":
|
|
490
|
-
case "api_keys":
|
|
491
|
-
case "release_catalogs":
|
|
492
|
-
case "releases":
|
|
493
|
-
columns = Object.keys(input.data);
|
|
494
|
-
values = Object.values(input.data);
|
|
495
|
-
break;
|
|
496
|
-
}
|
|
497
|
-
const conflict = input.onConflict !== "ignore" ? "" : input.model === "channels" ? conflictMode === "ignore" ? " ON CONFLICT(name) DO NOTHING" : " ON CONFLICT(name) DO UPDATE SET name = excluded.name" : input.model === "api_keys" ? conflictMode === "ignore" ? " ON CONFLICT(hash) DO NOTHING" : " ON CONFLICT(hash) DO UPDATE SET hash = excluded.hash" : "";
|
|
498
|
-
return {
|
|
499
|
-
sql: `INSERT INTO ${d1TableNames[input.model]} (${columns.join(", ")}) ${guard === void 0 ? `VALUES (${d1Placeholders(values.length)})` : `SELECT ${d1Placeholders(values.length)} WHERE ${guard.sql}`}${conflict} RETURNING *`,
|
|
500
|
-
params: [...encodeD1Values(values), ...guard?.params ?? []]
|
|
501
|
-
};
|
|
502
|
-
};
|
|
503
|
-
const updateEntries = (update) => Object.entries(update);
|
|
504
|
-
const updateQuery = (input, guard) => {
|
|
505
|
-
const entries = updateEntries(input.update);
|
|
506
|
-
const where = buildD1Where(input.where);
|
|
507
|
-
if (entries.length === 0) return {
|
|
508
|
-
sql: `SELECT * FROM ${d1TableNames[input.model]}${where.sql}${guard ? ` AND ${guard.sql}` : ""} LIMIT 1`,
|
|
509
|
-
params: [...where.params, ...guard?.params ?? []]
|
|
510
|
-
};
|
|
511
|
-
const assignments = entries.map(([field]) => `${field} = json_extract(?, '$')`).join(", ");
|
|
512
|
-
return {
|
|
513
|
-
sql: `UPDATE ${d1TableNames[input.model]} SET ${assignments}${where.sql}${guard ? ` AND ${guard.sql}` : ""} RETURNING *`,
|
|
514
|
-
params: [
|
|
515
|
-
...encodeD1Values(entries.map(([, value]) => value)),
|
|
516
|
-
...where.params,
|
|
517
|
-
...guard?.params ?? []
|
|
518
|
-
]
|
|
519
|
-
};
|
|
520
|
-
};
|
|
521
|
-
const deleteQuery = (input, guard) => {
|
|
522
|
-
const where = buildD1Where(input.where);
|
|
523
|
-
return {
|
|
524
|
-
sql: `DELETE FROM ${d1TableNames[input.model]}${where.sql}${guard ? ` AND ${guard.sql}` : ""}`,
|
|
525
|
-
params: [...where.params, ...guard?.params ?? []]
|
|
526
|
-
};
|
|
527
|
-
};
|
|
528
|
-
const insertedKey = (change) => {
|
|
529
|
-
if (change.operation !== "insert") return void 0;
|
|
530
|
-
if (change.model === "bundles") return `bundles:${change.row.id}`;
|
|
531
|
-
if (change.model === "apiKeys") return `api_keys:${change.row.id}`;
|
|
532
|
-
if (change.model === "releases") return `releases:${change.row.id}`;
|
|
533
|
-
};
|
|
534
|
-
const requiredRow = (change, changeIndex) => {
|
|
535
|
-
if (change.operation !== "update") return void 0;
|
|
536
|
-
if (change.model === "bundles") return {
|
|
537
|
-
model: "bundles",
|
|
538
|
-
id: change.where.id,
|
|
539
|
-
changeIndex
|
|
540
|
-
};
|
|
541
|
-
if (change.model === "apiKeys") return {
|
|
542
|
-
model: "api_keys",
|
|
543
|
-
id: change.where.id,
|
|
544
|
-
changeIndex
|
|
545
|
-
};
|
|
546
|
-
if (change.model === "releases") return {
|
|
547
|
-
model: "releases",
|
|
548
|
-
id: change.where.id,
|
|
549
|
-
changeIndex
|
|
550
|
-
};
|
|
551
|
-
};
|
|
552
|
-
const channelDeletePrecondition = (changes, changeIndex, channelId) => {
|
|
553
|
-
const releaseEffects = /* @__PURE__ */ new Map();
|
|
554
|
-
for (const change of changes.slice(0, changeIndex)) {
|
|
555
|
-
if (change.model !== "releases") continue;
|
|
556
|
-
switch (change.operation) {
|
|
557
|
-
case "insert":
|
|
558
|
-
releaseEffects.set(change.row.id, change.row.channel_id);
|
|
559
|
-
break;
|
|
560
|
-
case "update": break;
|
|
561
|
-
case "delete":
|
|
562
|
-
releaseEffects.set(change.where.id, null);
|
|
563
|
-
break;
|
|
564
|
-
}
|
|
565
|
-
}
|
|
566
|
-
return {
|
|
567
|
-
id: channelId,
|
|
568
|
-
excludedReleaseIds: [...releaseEffects.keys()],
|
|
569
|
-
addedReferenceReleaseIds: [...releaseEffects].filter(([, finalChannelId]) => finalChannelId === channelId).map(([releaseId]) => releaseId)
|
|
570
|
-
};
|
|
571
|
-
};
|
|
572
|
-
const changeQuery = (change, guard) => {
|
|
573
|
-
switch (change.model) {
|
|
574
|
-
case "bundles": switch (change.operation) {
|
|
575
|
-
case "insert": return insertQuery({
|
|
576
|
-
model: "bundles",
|
|
577
|
-
data: change.row
|
|
578
|
-
}, guard);
|
|
579
|
-
case "update": return updateQuery({
|
|
580
|
-
model: "bundles",
|
|
581
|
-
where: [{
|
|
582
|
-
field: "id",
|
|
583
|
-
value: change.where.id
|
|
584
|
-
}],
|
|
585
|
-
update: change.update
|
|
586
|
-
}, guard);
|
|
587
|
-
case "delete": return deleteQuery({
|
|
588
|
-
model: "bundles",
|
|
589
|
-
where: [{
|
|
590
|
-
field: "id",
|
|
591
|
-
value: change.where.id
|
|
592
|
-
}]
|
|
593
|
-
}, guard);
|
|
594
|
-
}
|
|
595
|
-
case "bundlePatches": return change.operation === "insert" ? insertQuery({
|
|
596
|
-
model: "bundle_patches",
|
|
597
|
-
data: change.row
|
|
598
|
-
}, guard) : deleteQuery({
|
|
599
|
-
model: "bundle_patches",
|
|
600
|
-
where: [{
|
|
601
|
-
field: "bundle_id",
|
|
602
|
-
value: change.where.bundleId
|
|
603
|
-
}]
|
|
604
|
-
}, guard);
|
|
605
|
-
case "releases": switch (change.operation) {
|
|
606
|
-
case "insert": return insertQuery({
|
|
607
|
-
model: "releases",
|
|
608
|
-
data: change.row
|
|
609
|
-
}, guard);
|
|
610
|
-
case "update": return updateQuery({
|
|
611
|
-
model: "releases",
|
|
612
|
-
where: [{
|
|
613
|
-
field: "id",
|
|
614
|
-
value: change.where.id
|
|
615
|
-
}],
|
|
616
|
-
update: change.update
|
|
617
|
-
}, guard);
|
|
618
|
-
case "delete": return deleteQuery({
|
|
619
|
-
model: "releases",
|
|
620
|
-
where: [{
|
|
621
|
-
field: "id",
|
|
622
|
-
value: change.where.id
|
|
623
|
-
}]
|
|
624
|
-
}, guard);
|
|
625
|
-
}
|
|
626
|
-
case "releaseCatalogs": return {
|
|
627
|
-
sql: `INSERT INTO release_catalogs (${Object.keys(change.row).join(", ")}) SELECT ${d1Placeholders(Object.keys(change.row).length)} WHERE ${guard.sql} ON CONFLICT(scope_key) DO UPDATE SET ${Object.keys(change.row).filter((field) => field !== "scope_key").map((field) => `${field} = excluded.${field}`).join(", ")} RETURNING *`,
|
|
628
|
-
params: [...encodeD1Values(Object.values(change.row)), ...guard.params]
|
|
629
|
-
};
|
|
630
|
-
case "channels": return change.operation === "insert" ? insertQuery({
|
|
631
|
-
model: "channels",
|
|
632
|
-
data: change.row,
|
|
633
|
-
onConflict: change.onConflict
|
|
634
|
-
}, guard, "ignore") : {
|
|
635
|
-
sql: `DELETE FROM channels WHERE id = json_extract(?, '$') AND NOT EXISTS (SELECT 1 FROM releases WHERE channel_id = json_extract(?, '$')) AND ${guard.sql}`,
|
|
636
|
-
params: [...encodeD1Values([change.where.id, change.where.id]), ...guard.params]
|
|
637
|
-
};
|
|
638
|
-
case "insights": return insertQuery({
|
|
639
|
-
model: "bundle_events",
|
|
640
|
-
data: change.row
|
|
641
|
-
}, guard);
|
|
642
|
-
case "apiKeys": return change.operation === "insert" ? insertQuery({
|
|
643
|
-
model: "api_keys",
|
|
644
|
-
data: change.row,
|
|
645
|
-
onConflict: change.onConflict
|
|
646
|
-
}, guard, "ignore") : updateQuery({
|
|
647
|
-
model: "api_keys",
|
|
648
|
-
where: [{
|
|
649
|
-
field: "id",
|
|
650
|
-
value: change.where.id
|
|
651
|
-
}],
|
|
652
|
-
update: { revoked_at_ms: change.update.revokedAtMs }
|
|
653
|
-
}, guard);
|
|
654
|
-
}
|
|
655
|
-
};
|
|
656
|
-
const createCommitPlan = (input) => {
|
|
657
|
-
const checks = [];
|
|
658
|
-
const statements = [];
|
|
659
|
-
const expectations = input.expectations ?? [];
|
|
660
|
-
if (expectations.length > 0) {
|
|
661
|
-
const guard = expectationGuard(expectations);
|
|
662
|
-
statements.push({
|
|
663
|
-
sql: `SELECT CASE WHEN ${guard.sql} THEN 1 ELSE json_extract('${EXPECTATION_CONFLICT_MARKER}', '$') END AS expectation_guard`,
|
|
664
|
-
params: guard.params
|
|
665
|
-
});
|
|
666
|
-
}
|
|
667
|
-
const requiredRows = [];
|
|
668
|
-
const channelDeletes = [];
|
|
669
|
-
const inserted = /* @__PURE__ */ new Set();
|
|
670
|
-
for (const [changeIndex, change] of input.changes.entries()) {
|
|
671
|
-
const required = requiredRow(change, changeIndex);
|
|
672
|
-
if (required !== void 0) {
|
|
673
|
-
if (!inserted.has(`${required.model}:${required.id}`)) {
|
|
674
|
-
requiredRows.push(required);
|
|
675
|
-
checks.push({
|
|
676
|
-
changeIndex,
|
|
677
|
-
resultIndex: statements.length,
|
|
678
|
-
conflictWhen: "empty",
|
|
679
|
-
reason: "not_found"
|
|
680
|
-
});
|
|
681
|
-
statements.push({
|
|
682
|
-
sql: `SELECT id FROM ${d1TableNames[required.model]} WHERE id = json_extract(?, '$') LIMIT 1`,
|
|
683
|
-
params: encodeD1Values([required.id])
|
|
684
|
-
});
|
|
685
|
-
}
|
|
686
|
-
}
|
|
687
|
-
if (change.model === "channels" && change.operation === "delete") {
|
|
688
|
-
const precondition = channelDeletePrecondition(input.changes, changeIndex, change.where.id);
|
|
689
|
-
channelDeletes.push(precondition);
|
|
690
|
-
checks.push({
|
|
691
|
-
changeIndex,
|
|
692
|
-
resultIndex: statements.length,
|
|
693
|
-
conflictWhen: "nonempty",
|
|
694
|
-
reason: "referenced"
|
|
695
|
-
});
|
|
696
|
-
statements.push({
|
|
697
|
-
sql: "SELECT id FROM releases WHERE channel_id = json_extract(?, '$') AND id NOT IN (SELECT value FROM json_each(?)) UNION ALL SELECT value AS id FROM json_each(?) LIMIT 1",
|
|
698
|
-
params: encodeD1Values([
|
|
699
|
-
precondition.id,
|
|
700
|
-
precondition.excludedReleaseIds,
|
|
701
|
-
precondition.addedReferenceReleaseIds
|
|
702
|
-
])
|
|
703
|
-
});
|
|
704
|
-
}
|
|
705
|
-
const key = insertedKey(change);
|
|
706
|
-
if (key !== void 0) inserted.add(key);
|
|
707
|
-
}
|
|
708
|
-
const guard = {
|
|
709
|
-
sql: `NOT EXISTS (
|
|
710
|
-
SELECT 1 FROM json_each(?) AS required
|
|
711
|
-
WHERE NOT EXISTS (
|
|
712
|
-
SELECT 1 FROM bundles
|
|
713
|
-
WHERE json_extract(required.value, '$.model') = 'bundles'
|
|
714
|
-
AND bundles.id = json_extract(required.value, '$.id')
|
|
715
|
-
UNION ALL
|
|
716
|
-
SELECT 1 FROM api_keys
|
|
717
|
-
WHERE json_extract(required.value, '$.model') = 'api_keys'
|
|
718
|
-
AND api_keys.id = json_extract(required.value, '$.id')
|
|
719
|
-
UNION ALL
|
|
720
|
-
SELECT 1 FROM channels
|
|
721
|
-
WHERE json_extract(required.value, '$.model') = 'channels'
|
|
722
|
-
AND channels.id = json_extract(required.value, '$.id')
|
|
723
|
-
UNION ALL
|
|
724
|
-
SELECT 1 FROM releases
|
|
725
|
-
WHERE json_extract(required.value, '$.model') = 'releases'
|
|
726
|
-
AND releases.id = json_extract(required.value, '$.id')
|
|
727
|
-
)
|
|
728
|
-
) AND NOT EXISTS (
|
|
729
|
-
SELECT 1 FROM json_each(?) AS channel_delete
|
|
730
|
-
WHERE EXISTS (
|
|
731
|
-
SELECT 1 FROM releases
|
|
732
|
-
WHERE releases.channel_id = json_extract(channel_delete.value, '$.id')
|
|
733
|
-
AND releases.id NOT IN (
|
|
734
|
-
SELECT value FROM json_each(
|
|
735
|
-
json_extract(channel_delete.value, '$.excludedReleaseIds')
|
|
736
|
-
)
|
|
737
|
-
)
|
|
738
|
-
UNION ALL
|
|
739
|
-
SELECT value FROM json_each(
|
|
740
|
-
json_extract(channel_delete.value, '$.addedReferenceReleaseIds')
|
|
741
|
-
)
|
|
742
|
-
)
|
|
743
|
-
)`,
|
|
744
|
-
params: encodeD1Values([requiredRows.map(({ model, id }) => ({
|
|
745
|
-
model,
|
|
746
|
-
id
|
|
747
|
-
})), channelDeletes])
|
|
748
|
-
};
|
|
749
|
-
statements.push(...input.changes.map((change) => changeQuery(change, guard)));
|
|
750
|
-
return {
|
|
751
|
-
checks,
|
|
752
|
-
statements
|
|
753
|
-
};
|
|
754
|
-
};
|
|
755
|
-
const resultForPlan = (plan, results) => {
|
|
756
|
-
const missing = plan.checks.find(({ conflictWhen, resultIndex }) => conflictWhen === "empty" ? (results[resultIndex]?.length ?? 0) === 0 : (results[resultIndex]?.length ?? 0) > 0);
|
|
757
|
-
return missing === void 0 ? { committed: true } : {
|
|
758
|
-
committed: false,
|
|
759
|
-
conflict: {
|
|
760
|
-
changeIndex: missing.changeIndex,
|
|
761
|
-
reason: missing.reason
|
|
762
|
-
}
|
|
763
|
-
};
|
|
764
|
-
};
|
|
765
|
-
const insertChannel = async (executor, input) => {
|
|
766
|
-
const insert = insertQuery({
|
|
767
|
-
model: "channels",
|
|
768
|
-
data: input.row,
|
|
769
|
-
onConflict: "ignore"
|
|
770
|
-
}, void 0, "ignore");
|
|
771
|
-
const select = {
|
|
772
|
-
sql: "SELECT id, name FROM channels WHERE name = json_extract(?, '$') LIMIT 1",
|
|
773
|
-
params: encodeD1Values([input.row.name])
|
|
774
|
-
};
|
|
775
|
-
const [insertedRows = [], canonicalRows = []] = await executor.batch([insert, select]);
|
|
776
|
-
return {
|
|
777
|
-
row: parseD1Row("channels", canonicalRows[0]),
|
|
778
|
-
inserted: insertedRows.length > 0
|
|
779
|
-
};
|
|
780
|
-
};
|
|
781
|
-
const deleteChannel = async (executor, input) => {
|
|
782
|
-
const [channelRows = [], referenceRows = [], deletedRows = []] = await executor.batch([
|
|
783
|
-
{
|
|
784
|
-
sql: "SELECT id FROM channels WHERE id = json_extract(?, '$') LIMIT 1",
|
|
785
|
-
params: encodeD1Values([input.id])
|
|
786
|
-
},
|
|
787
|
-
{
|
|
788
|
-
sql: "SELECT id FROM releases WHERE channel_id = json_extract(?, '$') LIMIT 1",
|
|
789
|
-
params: encodeD1Values([input.id])
|
|
790
|
-
},
|
|
791
|
-
{
|
|
792
|
-
sql: "DELETE FROM channels WHERE id = json_extract(?, '$') AND NOT EXISTS (SELECT 1 FROM releases WHERE channel_id = json_extract(?, '$')) RETURNING id",
|
|
793
|
-
params: encodeD1Values([input.id, input.id])
|
|
794
|
-
}
|
|
795
|
-
]);
|
|
796
|
-
if (channelRows.length === 0) return {
|
|
797
|
-
deleted: false,
|
|
798
|
-
reason: "not_found"
|
|
799
|
-
};
|
|
800
|
-
if (referenceRows.length > 0) return {
|
|
801
|
-
deleted: false,
|
|
802
|
-
reason: "not_empty"
|
|
803
|
-
};
|
|
804
|
-
return deletedRows.length > 0 ? { deleted: true } : {
|
|
805
|
-
deleted: false,
|
|
806
|
-
reason: "not_empty"
|
|
807
|
-
};
|
|
808
|
-
};
|
|
809
|
-
const createD1Implementation = (executor) => ({
|
|
810
|
-
async create(input) {
|
|
811
|
-
const query = insertQuery(input);
|
|
812
|
-
const rows = await executor.query(query.sql, query.params);
|
|
813
|
-
switch (input.model) {
|
|
814
|
-
case "bundles": return parseD1Row("bundles", rows[0]);
|
|
815
|
-
case "bundle_patches": return parseD1Row("bundle_patches", rows[0]);
|
|
816
|
-
case "channels": return parseD1Row("channels", rows[0]);
|
|
817
|
-
case "bundle_events": return parseD1Row("bundle_events", rows[0]);
|
|
818
|
-
case "api_keys": return parseD1Row("api_keys", rows[0]);
|
|
819
|
-
case "releases": return parseD1Row("releases", rows[0]);
|
|
820
|
-
case "release_catalogs": return parseD1Row("release_catalogs", rows[0]);
|
|
821
|
-
}
|
|
822
|
-
},
|
|
823
|
-
async update(input) {
|
|
824
|
-
const query = updateQuery(input);
|
|
825
|
-
const rows = await executor.query(query.sql, query.params);
|
|
826
|
-
if (rows[0] === void 0) return null;
|
|
827
|
-
switch (input.model) {
|
|
828
|
-
case "bundles": return parseD1Row("bundles", rows[0]);
|
|
829
|
-
case "api_keys": return parseD1Row("api_keys", rows[0]);
|
|
830
|
-
case "releases": return parseD1Row("releases", rows[0]);
|
|
831
|
-
case "release_catalogs": return parseD1Row("release_catalogs", rows[0]);
|
|
832
|
-
}
|
|
833
|
-
},
|
|
834
|
-
async delete(input) {
|
|
835
|
-
const query = deleteQuery(input);
|
|
836
|
-
await executor.query(query.sql, query.params);
|
|
837
|
-
},
|
|
838
|
-
count: (input) => countD1Rows(executor, input),
|
|
839
|
-
async findOne(input) {
|
|
840
|
-
const where = buildD1Where(input.where);
|
|
841
|
-
const rows = await executor.query(`SELECT * FROM ${d1TableNames[input.model]}${where.sql} LIMIT 1`, where.params);
|
|
842
|
-
if (rows[0] === void 0) return null;
|
|
843
|
-
switch (input.model) {
|
|
844
|
-
case "bundles": return parseD1Row("bundles", rows[0]);
|
|
845
|
-
case "bundle_patches": return parseD1Row("bundle_patches", rows[0]);
|
|
846
|
-
case "channels": return parseD1Row("channels", rows[0]);
|
|
847
|
-
case "api_keys": return parseD1Row("api_keys", rows[0]);
|
|
848
|
-
case "releases": return parseD1Row("releases", rows[0]);
|
|
849
|
-
case "release_catalogs": return parseD1Row("release_catalogs", rows[0]);
|
|
850
|
-
}
|
|
851
|
-
},
|
|
852
|
-
findMany: (input) => findManyD1Rows(executor, input),
|
|
853
|
-
insertChannel: (input) => insertChannel(executor, input),
|
|
854
|
-
deleteChannel: (input) => deleteChannel(executor, input),
|
|
855
|
-
async commit(input) {
|
|
856
|
-
if (input.changes.length === 0) return { committed: true };
|
|
857
|
-
const expectations = input.expectations ?? [];
|
|
858
|
-
const conflict = await expectationConflict(executor, expectations);
|
|
859
|
-
if (conflict !== null) return conflict;
|
|
860
|
-
const plan = createCommitPlan(input);
|
|
861
|
-
try {
|
|
862
|
-
return resultForPlan(plan, await executor.batch(plan.statements));
|
|
863
|
-
} catch (error) {
|
|
864
|
-
if (expectations.length === 0 || !isExpectationConflictError(error)) throw error;
|
|
865
|
-
return await expectationConflict(executor, expectations) ?? {
|
|
866
|
-
committed: false,
|
|
867
|
-
conflict: {
|
|
868
|
-
actualVersion: expectations[0].model === "releases" ? expectations[0].revision : expectations[0].generation,
|
|
869
|
-
changeIndex: -1,
|
|
870
|
-
expectedVersion: expectations[0].model === "releases" ? expectations[0].revision : expectations[0].generation,
|
|
871
|
-
key: expectations[0].model === "releases" ? expectations[0].id : expectations[0].scopeKey,
|
|
872
|
-
model: expectations[0].model,
|
|
873
|
-
reason: "version_conflict"
|
|
48
|
+
const code = /UNIQUE constraint failed|constraint failed: .*PRIMARY/iu.test(message) ? "SQLITE_CONSTRAINT_UNIQUE" : /SQLITE_BUSY|database is locked/iu.test(message) ? "SQLITE_BUSY" : void 0;
|
|
49
|
+
return code === void 0 ? error : Object.assign(new Error(message, { cause: error }), { code });
|
|
50
|
+
};
|
|
51
|
+
/**
|
|
52
|
+
* Hot Updater's database on D1: the storage engine through the shared SQL
|
|
53
|
+
* core, fenced by the schema settings. D1 has no interactive transactions,
|
|
54
|
+
* so each write is one atomic batch that evaluates its guards first
|
|
55
|
+
* (`_hu_write`).
|
|
56
|
+
*/
|
|
57
|
+
const createD1Database = (runner) => {
|
|
58
|
+
return (0, _hot_updater_plugin_core.createEngineDatabase)({
|
|
59
|
+
name: "d1Database",
|
|
60
|
+
adapter: (0, _hot_updater_plugin_core.createSqlAdapter)({
|
|
61
|
+
executor: {
|
|
62
|
+
dialect: "sqlite",
|
|
63
|
+
execute: (statement) => runner.query(statement).catch((error) => {
|
|
64
|
+
throw withSqliteCode(error);
|
|
65
|
+
}),
|
|
66
|
+
batch: (statements) => runner.batch(statements).catch((error) => {
|
|
67
|
+
throw withSqliteCode(error);
|
|
68
|
+
}),
|
|
69
|
+
transaction: () => {
|
|
70
|
+
throw new Error("D1 has no interactive transactions; writes are batches.");
|
|
874
71
|
}
|
|
875
|
-
}
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
})
|
|
72
|
+
},
|
|
73
|
+
maxOps: 450,
|
|
74
|
+
maxParams: 100
|
|
75
|
+
})
|
|
76
|
+
});
|
|
77
|
+
};
|
|
78
|
+
//#endregion
|
|
79
|
+
//#region src/d1Schema.ts
|
|
80
|
+
/**
|
|
81
|
+
* D1's schema: the guard table batch writes need, then the shared SQL
|
|
82
|
+
* schema of core and the target's plugins, settings last. Every statement can
|
|
83
|
+
* run again, so a migration for a server's plugin tables repeats core's.
|
|
84
|
+
*/
|
|
85
|
+
const d1SchemaStatements = ({ schema, settings } = _hot_updater_plugin_core.coreTarget) => [...(0, _hot_updater_plugin_core.createTableStatements)("sqlite", [_hot_updater_plugin_core.WRITE_GUARD_TABLE]), ...(0, _hot_updater_plugin_core.generateEngineSql)("sqlite", schema, settings)];
|
|
86
|
+
/** The schema as a D1 migration, which `wrangler d1 migrations apply` runs. */
|
|
87
|
+
const d1SchemaSql = (target) => `-- HotUpdater.schema\n\n${d1SchemaStatements(target).map((statement) => `${statement};`).join("\n\n")}\n`;
|
|
879
88
|
//#endregion
|
|
880
89
|
//#region src/d1Database.ts
|
|
90
|
+
/** The REST API binds text: each value goes as JSON and is read back with `json_extract`. */
|
|
91
|
+
const encode = ({ sql, params }) => ({
|
|
92
|
+
sql: sql.replaceAll("?", () => "json_extract(?, '$')"),
|
|
93
|
+
params: params.map((value) => JSON.stringify(value ?? null))
|
|
94
|
+
});
|
|
95
|
+
/**
|
|
96
|
+
* Hot Updater's database on D1 through the Cloudflare REST API, for the CLI
|
|
97
|
+
* and console. `hot-updater db generate` writes a D1 migration of the built-in
|
|
98
|
+
* tables and the server's plugin tables to `migrations`, and
|
|
99
|
+
* `hot-updater db migrate` applies them through the API.
|
|
100
|
+
*/
|
|
881
101
|
const d1Database = (config) => {
|
|
882
102
|
const cloudflare$1 = new cloudflare.default({ apiToken: config.cloudflareApiToken });
|
|
883
103
|
const execute = async (statements) => {
|
|
884
|
-
const first = statements
|
|
104
|
+
const [first] = statements;
|
|
885
105
|
if (first === void 0) return [];
|
|
886
106
|
const body = statements.length === 1 ? {
|
|
887
107
|
account_id: config.accountId,
|
|
888
|
-
|
|
889
|
-
params: [...first.params]
|
|
108
|
+
...encode(first)
|
|
890
109
|
} : {
|
|
891
110
|
account_id: config.accountId,
|
|
892
|
-
batch: statements.map(
|
|
893
|
-
sql,
|
|
894
|
-
params: [...params]
|
|
895
|
-
}))
|
|
111
|
+
batch: statements.map(encode)
|
|
896
112
|
};
|
|
897
|
-
const page = await cloudflare$1.d1.database.query(config.databaseId,
|
|
113
|
+
const page = await cloudflare$1.d1.database.query(config.databaseId, body);
|
|
898
114
|
const results = [];
|
|
899
|
-
for await (const resultPage of page.iterPages()) for (const result of resultPage.result) results.push(result
|
|
115
|
+
for await (const resultPage of page.iterPages()) for (const result of resultPage.result) results.push(toSqlResult(result));
|
|
116
|
+
if (results.length !== statements.length) throw new D1ExecutionError();
|
|
900
117
|
return results;
|
|
901
118
|
};
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
});
|
|
119
|
+
return {
|
|
120
|
+
...createD1Database({
|
|
121
|
+
query: async (statement) => (await execute([statement]))[0],
|
|
122
|
+
batch: execute
|
|
123
|
+
}),
|
|
124
|
+
generateSchema: ((version, _name, target = _hot_updater_plugin_core.coreTarget) => {
|
|
125
|
+
if (version !== "latest" && version !== _hot_updater_plugin_core.coreSettings["schema.core"]) throw new Error(`Invalid version ${version}`);
|
|
126
|
+
const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/\D/g, "").slice(0, 14);
|
|
127
|
+
return {
|
|
128
|
+
code: d1SchemaSql(target),
|
|
129
|
+
path: `migrations/${timestamp}_hot-updater.sql`
|
|
130
|
+
};
|
|
131
|
+
})
|
|
132
|
+
};
|
|
917
133
|
};
|
|
918
134
|
//#endregion
|
|
919
135
|
//#region src/r2S3Storage.ts
|
|
@@ -936,7 +152,7 @@ const createR2S3Storage = (config) => {
|
|
|
936
152
|
if (parsed.bucket !== bucketName) throw new Error(`Bucket name mismatch: expected "${bucketName}", but found "${parsed.bucket}".`);
|
|
937
153
|
return parsed;
|
|
938
154
|
};
|
|
939
|
-
return (0, _hot_updater_plugin_core.
|
|
155
|
+
return (0, _hot_updater_plugin_core.createStorageAdapter)({
|
|
940
156
|
name: "r2Storage",
|
|
941
157
|
protocol: "r2",
|
|
942
158
|
async put({ key, body, contentLength, contentType }) {
|
|
@@ -1009,5 +225,14 @@ const r2Storage = (config) => {
|
|
|
1009
225
|
return createR2S3Storage(config);
|
|
1010
226
|
};
|
|
1011
227
|
//#endregion
|
|
228
|
+
//#region src/plugins.ts
|
|
229
|
+
/**
|
|
230
|
+
* The plugins the managed Cloudflare server runs: Insights, and API keys on every
|
|
231
|
+
* client route. Its Worker imports this list.
|
|
232
|
+
*/
|
|
233
|
+
const plugins = [(0, _hot_updater_server_plugins_insights.insights)(), (0, _hot_updater_server_plugins_api_keys.apiKeys)()];
|
|
234
|
+
//#endregion
|
|
235
|
+
exports.D1ExecutionError = D1ExecutionError;
|
|
1012
236
|
exports.d1Database = d1Database;
|
|
237
|
+
exports.plugins = plugins;
|
|
1013
238
|
exports.r2Storage = r2Storage;
|