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