@hot-updater/cloudflare 1.2.0-rc.6 → 1.2.0-rc.61
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 +39 -86
- package/dist/index.d.cts +9 -8
- package/dist/index.d.mts +9 -8
- package/dist/index.mjs +40 -87
- package/dist/init/index.cjs +61 -20
- package/dist/init/index.d.cts +2 -2
- package/dist/init/index.d.mts +2 -2
- package/dist/init/index.mjs +65 -24
- package/dist/worker/index.cjs +72 -1
- package/dist/worker/index.d.cts +3 -2
- package/dist/worker/index.d.mts +3 -2
- package/dist/worker/index.mjs +72 -1
- package/package.json +11 -10
- package/sql/bundles.sql +22 -2
- package/src/d1Executor.ts +50 -4
- package/src/d1Rest.ts +4 -4
- package/src/d1Schema.ts +23 -6
- package/src/r2S3Storage.ts +18 -141
- package/src/r2Storage.ts +2 -3
- package/src/r2WorkerStorage.ts +56 -3
- package/worker/dist/README.md +1 -1
- package/worker/dist/index.js +3395 -1875
- package/worker/dist/index.js.map +4 -4
- package/worker/migrations/0002_hot-updater_1.2.0.sql +23 -1
package/dist/init/index.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createRequire } from "node:module";
|
|
2
2
|
import path from "path";
|
|
3
|
-
import { ConfigBuilder, InitError, LegacyInfrastructureError, assembleServer, assertInfrastructureGenerationAtUrl, assertInitInputs, assertInitProviderInputs, confirmInitInputPersistence, copyDirToTmp, createHotUpdaterConfigScaffoldFromBuilder, getCwd, getHotUpdaterInitInputEnv, getInitProviderEnvVars, getInitProviderTextPromptValues, link, makeEnv, p, printAppSetup, provisionClientCredential, readHotUpdaterInitEnv, resolveInitProviderInput,
|
|
3
|
+
import { ConfigBuilder, InitError, LegacyInfrastructureError, assembleServer, assertInfrastructureGenerationAtUrl, assertInitInputs, assertInitProviderInputs, backfillInsightsReleaseRefs, confirmInitInputPersistence, copyDirToTmp, createHotUpdaterConfigScaffoldFromBuilder, fillReleaseLabels, getCwd, getHotUpdaterInitInputEnv, getInitProviderEnvVars, getInitProviderTextPromptValues, link, makeEnv, p, printAppSetup, provisionClientCredential, readHotUpdaterInitEnv, resolveInitProviderInput, writeHotUpdaterFiles } from "@hot-updater/cli-tools";
|
|
4
4
|
import { apiKeys, insights, remoteConfig } from "@hot-updater/server/plugins";
|
|
5
5
|
import Cloudflare$1, { Cloudflare } from "cloudflare";
|
|
6
6
|
import { WRITE_GUARD_TABLE, coreSettings, coreTarget, createEngineDatabase, createSqlAdapter, createTableStatements, generateEngineSql } from "@hot-updater/plugin-core";
|
|
@@ -12,7 +12,7 @@ import process$1, { execArgv, execPath, hrtime, platform } from "node:process";
|
|
|
12
12
|
import tty from "node:tty";
|
|
13
13
|
import path$1 from "node:path";
|
|
14
14
|
import fs from "fs";
|
|
15
|
-
import { scheduler, setImmediate, setTimeout } from "node:timers/promises";
|
|
15
|
+
import { scheduler, setImmediate, setTimeout as setTimeout$1 } from "node:timers/promises";
|
|
16
16
|
import { constants } from "node:os";
|
|
17
17
|
import { EventEmitter, addAbortListener, on, once, setMaxListeners } from "node:events";
|
|
18
18
|
import { serialize } from "node:v8";
|
|
@@ -68,18 +68,50 @@ const withSqliteCode = (error) => {
|
|
|
68
68
|
return code === void 0 ? error : Object.assign(new Error(message, { cause: error }), { code });
|
|
69
69
|
};
|
|
70
70
|
/**
|
|
71
|
+
* The D1 errors Cloudflare's D1 guide says to retry ("Retry the operation"):
|
|
72
|
+
* a dropped connection, a reset or restarted database object, a transient
|
|
73
|
+
* failure to reach its node, and a replica cut off from its primary.
|
|
74
|
+
*/
|
|
75
|
+
const TRANSIENT_D1_ERROR = /Network connection lost|storage caused object to be reset|reset because its code was updated|Cannot resolve D1 DB due to transient issue|Replica disconnected from primary/iu;
|
|
76
|
+
/** The SQL core's reads, the only statements a retry can't apply twice. */
|
|
77
|
+
const READ_ONLY_STATEMENT = /^\s*SELECT\b/iu;
|
|
78
|
+
/** Attempts of a read in all, the first included. */
|
|
79
|
+
const READ_ATTEMPTS = 3;
|
|
80
|
+
/** The longest wait before the second attempt, doubling after it, with full jitter. */
|
|
81
|
+
const READ_RETRY_BASE_MS = 25;
|
|
82
|
+
const isTransient = (error) => TRANSIENT_D1_ERROR.test(error instanceof Error ? error.message : String(error));
|
|
83
|
+
/**
|
|
84
|
+
* Runs a read again when D1 failed it with a transient error, at most
|
|
85
|
+
* {@link READ_ATTEMPTS} times, and throws the last error. D1 retries a
|
|
86
|
+
* read-only query twice on its own; an error that outlasts those retries
|
|
87
|
+
* still answers a request with 500, where one more attempt after a short
|
|
88
|
+
* wait usually reads. A write may have committed when it fails, so it never
|
|
89
|
+
* runs again.
|
|
90
|
+
*/
|
|
91
|
+
const retryingReads = (query) => async (statement) => {
|
|
92
|
+
if (!READ_ONLY_STATEMENT.test(statement.sql)) return query(statement);
|
|
93
|
+
for (let attempt = 1;; attempt += 1) try {
|
|
94
|
+
return await query(statement);
|
|
95
|
+
} catch (error) {
|
|
96
|
+
if (attempt >= READ_ATTEMPTS || !isTransient(error)) throw error;
|
|
97
|
+
const wait = Math.random() * READ_RETRY_BASE_MS * 2 ** (attempt - 1);
|
|
98
|
+
await new Promise((resolve) => setTimeout(resolve, wait));
|
|
99
|
+
}
|
|
100
|
+
};
|
|
101
|
+
/**
|
|
71
102
|
* Hot Updater's database on D1: the storage engine through the shared SQL
|
|
72
103
|
* core, fenced by the schema settings. D1 has no interactive transactions,
|
|
73
104
|
* so each write is one atomic batch that evaluates its guards first
|
|
74
105
|
* (`_hu_write`).
|
|
75
106
|
*/
|
|
76
107
|
const createD1Database = (runner) => {
|
|
108
|
+
const query = retryingReads((statement) => runner.query(statement));
|
|
77
109
|
return createEngineDatabase({
|
|
78
110
|
name: "d1Database",
|
|
79
111
|
adapter: createSqlAdapter({
|
|
80
112
|
executor: {
|
|
81
113
|
dialect: "sqlite",
|
|
82
|
-
execute: (statement) =>
|
|
114
|
+
execute: (statement) => query(statement).catch((error) => {
|
|
83
115
|
throw withSqliteCode(error);
|
|
84
116
|
}),
|
|
85
117
|
batch: (statements) => runner.batch(statements).catch((error) => {
|
|
@@ -1846,7 +1878,7 @@ const setKillTimeout = async ({ kill, signal, forceKillAfterDelay, killSignal, k
|
|
|
1846
1878
|
const killOnTimeout = async ({ kill, forceKillAfterDelay, context, controllerSignal }) => {
|
|
1847
1879
|
if (forceKillAfterDelay === false) return;
|
|
1848
1880
|
try {
|
|
1849
|
-
await setTimeout(forceKillAfterDelay, void 0, { signal: controllerSignal });
|
|
1881
|
+
await setTimeout$1(forceKillAfterDelay, void 0, { signal: controllerSignal });
|
|
1850
1882
|
if (kill("SIGKILL")) context.isForcefullyTerminated ??= true;
|
|
1851
1883
|
} catch {}
|
|
1852
1884
|
};
|
|
@@ -2381,7 +2413,7 @@ const validateTimeout = ({ timeout }) => {
|
|
|
2381
2413
|
};
|
|
2382
2414
|
const throwOnTimeout = (subprocess, timeout, context, controller) => timeout === 0 || timeout === void 0 ? [] : [killAfterTimeout(subprocess, timeout, context, controller)];
|
|
2383
2415
|
const killAfterTimeout = async (subprocess, timeout, context, { signal }) => {
|
|
2384
|
-
await setTimeout(timeout, void 0, { signal });
|
|
2416
|
+
await setTimeout$1(timeout, void 0, { signal });
|
|
2385
2417
|
context.terminationReason ??= "timeout";
|
|
2386
2418
|
subprocess.kill();
|
|
2387
2419
|
throw new DiscardedError();
|
|
@@ -11200,6 +11232,15 @@ const getValidWranglerAuthToken = () => {
|
|
|
11200
11232
|
const resolveCloudflareInfrastructureApiToken = async ({ cwd, nonInteractive }) => {
|
|
11201
11233
|
const existingToken = getValidWranglerAuthToken();
|
|
11202
11234
|
if (existingToken) return existingToken;
|
|
11235
|
+
if (getWranglerLoginAuthToken()?.refresh_token) {
|
|
11236
|
+
await execa("npx", ["wrangler", "whoami"], {
|
|
11237
|
+
cwd,
|
|
11238
|
+
reject: false,
|
|
11239
|
+
stdio: "ignore"
|
|
11240
|
+
});
|
|
11241
|
+
const renewedToken = getValidWranglerAuthToken();
|
|
11242
|
+
if (renewedToken) return renewedToken;
|
|
11243
|
+
}
|
|
11203
11244
|
if (nonInteractive) throw new CloudflareWranglerLoginRequiredError();
|
|
11204
11245
|
await execa("npx", [
|
|
11205
11246
|
"wrangler",
|
|
@@ -11413,10 +11454,11 @@ const inputCloudflareInitSecrets = async ({ accountId, bucketName, apiToken, acc
|
|
|
11413
11454
|
//#region iac/configTemplate.ts
|
|
11414
11455
|
/**
|
|
11415
11456
|
* The config init writes. With the `resources` init set up, it names them,
|
|
11416
|
-
* and reads the API token and R2 keys with `
|
|
11457
|
+
* and reads the API token and R2 keys with `secret()`, from the
|
|
11417
11458
|
* environment and `.env.hotupdater`, then the config's `secrets` adapter.
|
|
11418
|
-
* Without them, as the agent scaffold writes it
|
|
11419
|
-
* the environment
|
|
11459
|
+
* Without them, as the agent scaffold writes it before the agent creates the
|
|
11460
|
+
* resources, it reads their IDs from the environment, where the agent
|
|
11461
|
+
* records them, and the credentials with `secret()` alike.
|
|
11420
11462
|
*/
|
|
11421
11463
|
const getConfigScaffold = (build, resources) => {
|
|
11422
11464
|
const builder = new ConfigBuilder().setBuildType(build).setPlugins({
|
|
@@ -11439,8 +11481,8 @@ const getConfigScaffold = (build, resources) => {
|
|
|
11439
11481
|
bucketName: process.env.HOT_UPDATER_CLOUDFLARE_R2_BUCKET_NAME!,
|
|
11440
11482
|
accountId: process.env.HOT_UPDATER_CLOUDFLARE_ACCOUNT_ID!,
|
|
11441
11483
|
credentials: {
|
|
11442
|
-
accessKeyId:
|
|
11443
|
-
secretAccessKey:
|
|
11484
|
+
accessKeyId: secret("HOT_UPDATER_CLOUDFLARE_R2_ACCESS_KEY_ID"),
|
|
11485
|
+
secretAccessKey: secret("HOT_UPDATER_CLOUDFLARE_R2_SECRET_ACCESS_KEY"),
|
|
11444
11486
|
},
|
|
11445
11487
|
})`
|
|
11446
11488
|
}).setDatabase({
|
|
@@ -11451,8 +11493,11 @@ const getConfigScaffold = (build, resources) => {
|
|
|
11451
11493
|
configString: `d1Database({
|
|
11452
11494
|
databaseId: process.env.HOT_UPDATER_CLOUDFLARE_D1_DATABASE_ID!,
|
|
11453
11495
|
accountId: process.env.HOT_UPDATER_CLOUDFLARE_ACCOUNT_ID!,
|
|
11454
|
-
cloudflareApiToken:
|
|
11496
|
+
cloudflareApiToken: secret("HOT_UPDATER_CLOUDFLARE_API_TOKEN"),
|
|
11455
11497
|
})`
|
|
11498
|
+
}).addImport({
|
|
11499
|
+
pkg: "hot-updater",
|
|
11500
|
+
named: ["secret"]
|
|
11456
11501
|
}));
|
|
11457
11502
|
const accountId = JSON.stringify(resources.accountId);
|
|
11458
11503
|
const storageConfig = {
|
|
@@ -11463,12 +11508,9 @@ const getConfigScaffold = (build, resources) => {
|
|
|
11463
11508
|
configString: `r2Storage({
|
|
11464
11509
|
bucketName: ${JSON.stringify(resources.bucketName)},
|
|
11465
11510
|
accountId: ${accountId},
|
|
11466
|
-
credentials:
|
|
11467
|
-
|
|
11468
|
-
|
|
11469
|
-
accessKeyId: env.HOT_UPDATER_CLOUDFLARE_R2_ACCESS_KEY_ID,
|
|
11470
|
-
secretAccessKey: env.HOT_UPDATER_CLOUDFLARE_R2_SECRET_ACCESS_KEY,
|
|
11471
|
-
};
|
|
11511
|
+
credentials: {
|
|
11512
|
+
accessKeyId: secret("HOT_UPDATER_CLOUDFLARE_R2_ACCESS_KEY_ID"),
|
|
11513
|
+
secretAccessKey: secret("HOT_UPDATER_CLOUDFLARE_R2_SECRET_ACCESS_KEY"),
|
|
11472
11514
|
},
|
|
11473
11515
|
})`
|
|
11474
11516
|
};
|
|
@@ -11480,15 +11522,13 @@ const getConfigScaffold = (build, resources) => {
|
|
|
11480
11522
|
configString: `d1Database({
|
|
11481
11523
|
databaseId: ${JSON.stringify(resources.d1DatabaseId)},
|
|
11482
11524
|
accountId: ${accountId},
|
|
11483
|
-
cloudflareApiToken:
|
|
11484
|
-
(await databaseSecrets()).HOT_UPDATER_CLOUDFLARE_API_TOKEN,
|
|
11525
|
+
cloudflareApiToken: secret("HOT_UPDATER_CLOUDFLARE_API_TOKEN"),
|
|
11485
11526
|
})`
|
|
11486
11527
|
};
|
|
11487
|
-
const helperStatements = [secretEnvHelper("storageSecrets", ["HOT_UPDATER_CLOUDFLARE_R2_ACCESS_KEY_ID", "HOT_UPDATER_CLOUDFLARE_R2_SECRET_ACCESS_KEY"]), secretEnvHelper("databaseSecrets", ["HOT_UPDATER_CLOUDFLARE_API_TOKEN"])];
|
|
11488
11528
|
return createHotUpdaterConfigScaffoldFromBuilder(builder.setStorage(storageConfig).setDatabase(databaseConfig).addImport({
|
|
11489
11529
|
pkg: "hot-updater",
|
|
11490
|
-
named: ["
|
|
11491
|
-
})
|
|
11530
|
+
named: ["secret"]
|
|
11531
|
+
}));
|
|
11492
11532
|
};
|
|
11493
11533
|
//#endregion
|
|
11494
11534
|
//#region iac/managedWorker.ts
|
|
@@ -11904,6 +11944,8 @@ const runInit = async ({ build, envFile, secretsEnv }) => {
|
|
|
11904
11944
|
});
|
|
11905
11945
|
let credential;
|
|
11906
11946
|
try {
|
|
11947
|
+
await fillReleaseLabels(server);
|
|
11948
|
+
await backfillInsightsReleaseRefs(server);
|
|
11907
11949
|
credential = await provisionClientCredential(server, {
|
|
11908
11950
|
env: initInputEnv,
|
|
11909
11951
|
name: "Cloudflare init"
|
|
@@ -11926,8 +11968,7 @@ const runInit = async ({ build, envFile, secretsEnv }) => {
|
|
|
11926
11968
|
...credential === void 0 ? {} : { credential },
|
|
11927
11969
|
clientPlugins: server.clientPlugins
|
|
11928
11970
|
});
|
|
11929
|
-
|
|
11930
|
-
p.log.success("Done! 🎉");
|
|
11971
|
+
return { nextSteps: [link("https://hot-updater.dev/docs/managed/cloudflare#step-3-add-hotupdater-to-your-project")] };
|
|
11931
11972
|
};
|
|
11932
11973
|
//#endregion
|
|
11933
11974
|
export { initProvider, runInit };
|
package/dist/worker/index.cjs
CHANGED
|
@@ -21,18 +21,50 @@ const withSqliteCode = (error) => {
|
|
|
21
21
|
return code === void 0 ? error : Object.assign(new Error(message, { cause: error }), { code });
|
|
22
22
|
};
|
|
23
23
|
/**
|
|
24
|
+
* The D1 errors Cloudflare's D1 guide says to retry ("Retry the operation"):
|
|
25
|
+
* a dropped connection, a reset or restarted database object, a transient
|
|
26
|
+
* failure to reach its node, and a replica cut off from its primary.
|
|
27
|
+
*/
|
|
28
|
+
const TRANSIENT_D1_ERROR = /Network connection lost|storage caused object to be reset|reset because its code was updated|Cannot resolve D1 DB due to transient issue|Replica disconnected from primary/iu;
|
|
29
|
+
/** The SQL core's reads, the only statements a retry can't apply twice. */
|
|
30
|
+
const READ_ONLY_STATEMENT = /^\s*SELECT\b/iu;
|
|
31
|
+
/** Attempts of a read in all, the first included. */
|
|
32
|
+
const READ_ATTEMPTS = 3;
|
|
33
|
+
/** The longest wait before the second attempt, doubling after it, with full jitter. */
|
|
34
|
+
const READ_RETRY_BASE_MS = 25;
|
|
35
|
+
const isTransient = (error) => TRANSIENT_D1_ERROR.test(error instanceof Error ? error.message : String(error));
|
|
36
|
+
/**
|
|
37
|
+
* Runs a read again when D1 failed it with a transient error, at most
|
|
38
|
+
* {@link READ_ATTEMPTS} times, and throws the last error. D1 retries a
|
|
39
|
+
* read-only query twice on its own; an error that outlasts those retries
|
|
40
|
+
* still answers a request with 500, where one more attempt after a short
|
|
41
|
+
* wait usually reads. A write may have committed when it fails, so it never
|
|
42
|
+
* runs again.
|
|
43
|
+
*/
|
|
44
|
+
const retryingReads = (query) => async (statement) => {
|
|
45
|
+
if (!READ_ONLY_STATEMENT.test(statement.sql)) return query(statement);
|
|
46
|
+
for (let attempt = 1;; attempt += 1) try {
|
|
47
|
+
return await query(statement);
|
|
48
|
+
} catch (error) {
|
|
49
|
+
if (attempt >= READ_ATTEMPTS || !isTransient(error)) throw error;
|
|
50
|
+
const wait = Math.random() * READ_RETRY_BASE_MS * 2 ** (attempt - 1);
|
|
51
|
+
await new Promise((resolve) => setTimeout(resolve, wait));
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
/**
|
|
24
55
|
* Hot Updater's database on D1: the storage engine through the shared SQL
|
|
25
56
|
* core, fenced by the schema settings. D1 has no interactive transactions,
|
|
26
57
|
* so each write is one atomic batch that evaluates its guards first
|
|
27
58
|
* (`_hu_write`).
|
|
28
59
|
*/
|
|
29
60
|
const createD1Database = (runner) => {
|
|
61
|
+
const query = retryingReads((statement) => runner.query(statement));
|
|
30
62
|
return (0, _hot_updater_plugin_core.createEngineDatabase)({
|
|
31
63
|
name: "d1Database",
|
|
32
64
|
adapter: (0, _hot_updater_plugin_core.createSqlAdapter)({
|
|
33
65
|
executor: {
|
|
34
66
|
dialect: "sqlite",
|
|
35
|
-
execute: (statement) =>
|
|
67
|
+
execute: (statement) => query(statement).catch((error) => {
|
|
36
68
|
throw withSqliteCode(error);
|
|
37
69
|
}),
|
|
38
70
|
batch: (statements) => runner.batch(statements).catch((error) => {
|
|
@@ -121,8 +153,11 @@ const presignR2GetUrl = async ({ accountId, bucketName, credentials, expiresInSe
|
|
|
121
153
|
//#region src/r2WorkerStorage.ts
|
|
122
154
|
/** Devices download right after the update check that returns the URL. */
|
|
123
155
|
const PRESIGNED_URL_EXPIRES_IN_SECONDS = 3600;
|
|
156
|
+
/** Keys the binding deletes in one call. */
|
|
157
|
+
const DELETE_BATCH_SIZE = 1e3;
|
|
124
158
|
function r2WorkerStorage(config) {
|
|
125
159
|
const getStorageKey = (0, _hot_updater_plugin_core.createStorageKeyBuilder)(config.basePath);
|
|
160
|
+
const basePrefix = getStorageKey() ? `${getStorageKey()}/` : "";
|
|
126
161
|
const parseAndValidate = (storageUri) => {
|
|
127
162
|
const parsed = (0, _hot_updater_plugin_core.parseStorageUri)(storageUri, "r2");
|
|
128
163
|
if (parsed.bucket !== config.bucketName) throw new Error(`Bucket name mismatch: expected "${config.bucketName}", but found "${parsed.bucket}".`);
|
|
@@ -178,6 +213,42 @@ function r2WorkerStorage(config) {
|
|
|
178
213
|
const { key } = parseAndValidate(storageUri);
|
|
179
214
|
await config.bucket.delete(key);
|
|
180
215
|
return { deleted: true };
|
|
216
|
+
},
|
|
217
|
+
async listObjects(prefix) {
|
|
218
|
+
const folder = getStorageKey(prefix ?? "");
|
|
219
|
+
const objects = [];
|
|
220
|
+
let cursor;
|
|
221
|
+
do {
|
|
222
|
+
const listed = await config.bucket.list({
|
|
223
|
+
prefix: folder ? `${folder}/` : "",
|
|
224
|
+
...cursor === void 0 ? {} : { cursor }
|
|
225
|
+
});
|
|
226
|
+
for (const object of listed.objects) {
|
|
227
|
+
if (!object.key.startsWith(basePrefix)) continue;
|
|
228
|
+
let storageUri;
|
|
229
|
+
try {
|
|
230
|
+
storageUri = (0, _hot_updater_plugin_core.createStorageUri)({
|
|
231
|
+
protocol: "r2",
|
|
232
|
+
bucket: config.bucketName,
|
|
233
|
+
key: object.key
|
|
234
|
+
});
|
|
235
|
+
} catch {
|
|
236
|
+
continue;
|
|
237
|
+
}
|
|
238
|
+
objects.push({
|
|
239
|
+
key: object.key.slice(basePrefix.length),
|
|
240
|
+
lastModifiedAt: object.uploaded,
|
|
241
|
+
size: object.size,
|
|
242
|
+
storageUri
|
|
243
|
+
});
|
|
244
|
+
}
|
|
245
|
+
cursor = listed.truncated ? listed.cursor : void 0;
|
|
246
|
+
} while (cursor !== void 0);
|
|
247
|
+
return objects;
|
|
248
|
+
},
|
|
249
|
+
async deleteObjects(relativeKeys) {
|
|
250
|
+
const keys = relativeKeys.map((key) => getStorageKey(key));
|
|
251
|
+
for (let offset = 0; offset < keys.length; offset += DELETE_BATCH_SIZE) await config.bucket.delete(keys.slice(offset, offset + DELETE_BATCH_SIZE));
|
|
181
252
|
}
|
|
182
253
|
});
|
|
183
254
|
}
|
package/dist/worker/index.d.cts
CHANGED
|
@@ -48,6 +48,7 @@ type CloudflareWorkerStorageConfig = {
|
|
|
48
48
|
readonly accountId?: undefined;
|
|
49
49
|
readonly credentials?: undefined;
|
|
50
50
|
});
|
|
51
|
+
type R2WorkerOperations = "put" | "get" | "exists" | "delete" | "listObjects" | "deleteObjects";
|
|
51
52
|
/**
|
|
52
53
|
* Storage on the Worker's R2 binding. With R2's S3-compatible credentials,
|
|
53
54
|
* its download URLs are presigned and devices download from the bucket;
|
|
@@ -56,7 +57,7 @@ type CloudflareWorkerStorageConfig = {
|
|
|
56
57
|
*/
|
|
57
58
|
declare function r2WorkerStorage(config: CloudflareWorkerStorageConfig & {
|
|
58
59
|
readonly credentials: R2Credentials;
|
|
59
|
-
}): StorageAdapterWith<
|
|
60
|
-
declare function r2WorkerStorage(config: CloudflareWorkerStorageConfig): StorageAdapterWith<
|
|
60
|
+
}): StorageAdapterWith<R2WorkerOperations | "getDownloadUrl">;
|
|
61
|
+
declare function r2WorkerStorage(config: CloudflareWorkerStorageConfig): StorageAdapterWith<R2WorkerOperations>;
|
|
61
62
|
//#endregion
|
|
62
63
|
export { type CloudflareWorkerStorageConfig, type D1Like, d1Database, r2WorkerStorage as r2Storage };
|
package/dist/worker/index.d.mts
CHANGED
|
@@ -48,6 +48,7 @@ type CloudflareWorkerStorageConfig = {
|
|
|
48
48
|
readonly accountId?: undefined;
|
|
49
49
|
readonly credentials?: undefined;
|
|
50
50
|
});
|
|
51
|
+
type R2WorkerOperations = "put" | "get" | "exists" | "delete" | "listObjects" | "deleteObjects";
|
|
51
52
|
/**
|
|
52
53
|
* Storage on the Worker's R2 binding. With R2's S3-compatible credentials,
|
|
53
54
|
* its download URLs are presigned and devices download from the bucket;
|
|
@@ -56,7 +57,7 @@ type CloudflareWorkerStorageConfig = {
|
|
|
56
57
|
*/
|
|
57
58
|
declare function r2WorkerStorage(config: CloudflareWorkerStorageConfig & {
|
|
58
59
|
readonly credentials: R2Credentials;
|
|
59
|
-
}): StorageAdapterWith<
|
|
60
|
-
declare function r2WorkerStorage(config: CloudflareWorkerStorageConfig): StorageAdapterWith<
|
|
60
|
+
}): StorageAdapterWith<R2WorkerOperations | "getDownloadUrl">;
|
|
61
|
+
declare function r2WorkerStorage(config: CloudflareWorkerStorageConfig): StorageAdapterWith<R2WorkerOperations>;
|
|
61
62
|
//#endregion
|
|
62
63
|
export { type CloudflareWorkerStorageConfig, type D1Like, d1Database, r2WorkerStorage as r2Storage };
|
package/dist/worker/index.mjs
CHANGED
|
@@ -20,18 +20,50 @@ const withSqliteCode = (error) => {
|
|
|
20
20
|
return code === void 0 ? error : Object.assign(new Error(message, { cause: error }), { code });
|
|
21
21
|
};
|
|
22
22
|
/**
|
|
23
|
+
* The D1 errors Cloudflare's D1 guide says to retry ("Retry the operation"):
|
|
24
|
+
* a dropped connection, a reset or restarted database object, a transient
|
|
25
|
+
* failure to reach its node, and a replica cut off from its primary.
|
|
26
|
+
*/
|
|
27
|
+
const TRANSIENT_D1_ERROR = /Network connection lost|storage caused object to be reset|reset because its code was updated|Cannot resolve D1 DB due to transient issue|Replica disconnected from primary/iu;
|
|
28
|
+
/** The SQL core's reads, the only statements a retry can't apply twice. */
|
|
29
|
+
const READ_ONLY_STATEMENT = /^\s*SELECT\b/iu;
|
|
30
|
+
/** Attempts of a read in all, the first included. */
|
|
31
|
+
const READ_ATTEMPTS = 3;
|
|
32
|
+
/** The longest wait before the second attempt, doubling after it, with full jitter. */
|
|
33
|
+
const READ_RETRY_BASE_MS = 25;
|
|
34
|
+
const isTransient = (error) => TRANSIENT_D1_ERROR.test(error instanceof Error ? error.message : String(error));
|
|
35
|
+
/**
|
|
36
|
+
* Runs a read again when D1 failed it with a transient error, at most
|
|
37
|
+
* {@link READ_ATTEMPTS} times, and throws the last error. D1 retries a
|
|
38
|
+
* read-only query twice on its own; an error that outlasts those retries
|
|
39
|
+
* still answers a request with 500, where one more attempt after a short
|
|
40
|
+
* wait usually reads. A write may have committed when it fails, so it never
|
|
41
|
+
* runs again.
|
|
42
|
+
*/
|
|
43
|
+
const retryingReads = (query) => async (statement) => {
|
|
44
|
+
if (!READ_ONLY_STATEMENT.test(statement.sql)) return query(statement);
|
|
45
|
+
for (let attempt = 1;; attempt += 1) try {
|
|
46
|
+
return await query(statement);
|
|
47
|
+
} catch (error) {
|
|
48
|
+
if (attempt >= READ_ATTEMPTS || !isTransient(error)) throw error;
|
|
49
|
+
const wait = Math.random() * READ_RETRY_BASE_MS * 2 ** (attempt - 1);
|
|
50
|
+
await new Promise((resolve) => setTimeout(resolve, wait));
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
/**
|
|
23
54
|
* Hot Updater's database on D1: the storage engine through the shared SQL
|
|
24
55
|
* core, fenced by the schema settings. D1 has no interactive transactions,
|
|
25
56
|
* so each write is one atomic batch that evaluates its guards first
|
|
26
57
|
* (`_hu_write`).
|
|
27
58
|
*/
|
|
28
59
|
const createD1Database = (runner) => {
|
|
60
|
+
const query = retryingReads((statement) => runner.query(statement));
|
|
29
61
|
return createEngineDatabase({
|
|
30
62
|
name: "d1Database",
|
|
31
63
|
adapter: createSqlAdapter({
|
|
32
64
|
executor: {
|
|
33
65
|
dialect: "sqlite",
|
|
34
|
-
execute: (statement) =>
|
|
66
|
+
execute: (statement) => query(statement).catch((error) => {
|
|
35
67
|
throw withSqliteCode(error);
|
|
36
68
|
}),
|
|
37
69
|
batch: (statements) => runner.batch(statements).catch((error) => {
|
|
@@ -120,8 +152,11 @@ const presignR2GetUrl = async ({ accountId, bucketName, credentials, expiresInSe
|
|
|
120
152
|
//#region src/r2WorkerStorage.ts
|
|
121
153
|
/** Devices download right after the update check that returns the URL. */
|
|
122
154
|
const PRESIGNED_URL_EXPIRES_IN_SECONDS = 3600;
|
|
155
|
+
/** Keys the binding deletes in one call. */
|
|
156
|
+
const DELETE_BATCH_SIZE = 1e3;
|
|
123
157
|
function r2WorkerStorage(config) {
|
|
124
158
|
const getStorageKey = createStorageKeyBuilder(config.basePath);
|
|
159
|
+
const basePrefix = getStorageKey() ? `${getStorageKey()}/` : "";
|
|
125
160
|
const parseAndValidate = (storageUri) => {
|
|
126
161
|
const parsed = parseStorageUri(storageUri, "r2");
|
|
127
162
|
if (parsed.bucket !== config.bucketName) throw new Error(`Bucket name mismatch: expected "${config.bucketName}", but found "${parsed.bucket}".`);
|
|
@@ -177,6 +212,42 @@ function r2WorkerStorage(config) {
|
|
|
177
212
|
const { key } = parseAndValidate(storageUri);
|
|
178
213
|
await config.bucket.delete(key);
|
|
179
214
|
return { deleted: true };
|
|
215
|
+
},
|
|
216
|
+
async listObjects(prefix) {
|
|
217
|
+
const folder = getStorageKey(prefix ?? "");
|
|
218
|
+
const objects = [];
|
|
219
|
+
let cursor;
|
|
220
|
+
do {
|
|
221
|
+
const listed = await config.bucket.list({
|
|
222
|
+
prefix: folder ? `${folder}/` : "",
|
|
223
|
+
...cursor === void 0 ? {} : { cursor }
|
|
224
|
+
});
|
|
225
|
+
for (const object of listed.objects) {
|
|
226
|
+
if (!object.key.startsWith(basePrefix)) continue;
|
|
227
|
+
let storageUri;
|
|
228
|
+
try {
|
|
229
|
+
storageUri = createStorageUri({
|
|
230
|
+
protocol: "r2",
|
|
231
|
+
bucket: config.bucketName,
|
|
232
|
+
key: object.key
|
|
233
|
+
});
|
|
234
|
+
} catch {
|
|
235
|
+
continue;
|
|
236
|
+
}
|
|
237
|
+
objects.push({
|
|
238
|
+
key: object.key.slice(basePrefix.length),
|
|
239
|
+
lastModifiedAt: object.uploaded,
|
|
240
|
+
size: object.size,
|
|
241
|
+
storageUri
|
|
242
|
+
});
|
|
243
|
+
}
|
|
244
|
+
cursor = listed.truncated ? listed.cursor : void 0;
|
|
245
|
+
} while (cursor !== void 0);
|
|
246
|
+
return objects;
|
|
247
|
+
},
|
|
248
|
+
async deleteObjects(relativeKeys) {
|
|
249
|
+
const keys = relativeKeys.map((key) => getStorageKey(key));
|
|
250
|
+
for (let offset = 0; offset < keys.length; offset += DELETE_BATCH_SIZE) await config.bucket.delete(keys.slice(offset, offset + DELETE_BATCH_SIZE));
|
|
180
251
|
}
|
|
181
252
|
});
|
|
182
253
|
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hot-updater/cloudflare",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "1.2.0-rc.
|
|
4
|
+
"version": "1.2.0-rc.61",
|
|
5
5
|
"description": "React Native OTA solution for self-hosted",
|
|
6
6
|
"main": "dist/index.cjs",
|
|
7
7
|
"module": "dist/index.mjs",
|
|
@@ -49,18 +49,19 @@
|
|
|
49
49
|
"package.json"
|
|
50
50
|
],
|
|
51
51
|
"dependencies": {
|
|
52
|
-
"@aws-sdk/client-s3": "3.1066.0",
|
|
53
|
-
"@aws-sdk/lib-storage": "3.1008.0",
|
|
54
|
-
"@aws-sdk/s3-request-presigner": "3.1066.0",
|
|
55
52
|
"cloudflare": "4.2.0",
|
|
56
|
-
"hono": "4.
|
|
53
|
+
"hono": "4.13.21",
|
|
57
54
|
"uuidv7": "^1.0.2",
|
|
58
|
-
"@hot-updater/
|
|
59
|
-
"@hot-updater/
|
|
60
|
-
"@hot-updater/
|
|
61
|
-
"@hot-updater/
|
|
55
|
+
"@hot-updater/cli-tools": "1.2.0-rc.61",
|
|
56
|
+
"@hot-updater/protocol": "1.2.0-rc.61",
|
|
57
|
+
"@hot-updater/server": "1.2.0-rc.61",
|
|
58
|
+
"@hot-updater/storage-s3": "1.2.0-rc.61",
|
|
59
|
+
"@hot-updater/plugin-core": "1.2.0-rc.61"
|
|
62
60
|
},
|
|
63
61
|
"devDependencies": {
|
|
62
|
+
"@aws-sdk/client-s3": "3.1066.0",
|
|
63
|
+
"@aws-sdk/lib-storage": "3.1066.0",
|
|
64
|
+
"@aws-sdk/s3-request-presigner": "3.1066.0",
|
|
64
65
|
"@cloudflare/vitest-pool-workers": "0.13.0",
|
|
65
66
|
"@cloudflare/workers-types": "^4.20260312.1",
|
|
66
67
|
"@types/node": "^20",
|
|
@@ -74,7 +75,7 @@
|
|
|
74
75
|
"vitest": "4.1.4",
|
|
75
76
|
"wrangler": "^4.69.0",
|
|
76
77
|
"xdg-app-paths": "^8.3.0",
|
|
77
|
-
"@hot-updater/test-utils": "1.2.0-rc.
|
|
78
|
+
"@hot-updater/test-utils": "1.2.0-rc.61"
|
|
78
79
|
},
|
|
79
80
|
"scripts": {
|
|
80
81
|
"build": "tsdown && pnpm build:worker",
|
package/sql/bundles.sql
CHANGED
|
@@ -14,7 +14,7 @@ CREATE INDEX IF NOT EXISTS "bundle_patches_byBundle" ON "bundle_patches" ("bundl
|
|
|
14
14
|
|
|
15
15
|
CREATE INDEX IF NOT EXISTS "bundle_patches_byBase" ON "bundle_patches" ("base_bundle_id", "bundle_id", "id");
|
|
16
16
|
|
|
17
|
-
CREATE TABLE IF NOT EXISTS "releases" ("id" TEXT NOT NULL, "revision" INTEGER NOT NULL, "scope_key" TEXT NOT NULL, "channel_id" TEXT NOT NULL, "platform" TEXT NOT NULL, "kind" TEXT NOT NULL, "bundle_id" TEXT, "strategy" TEXT NOT NULL, "target_app_version" TEXT, "fingerprint_hash" TEXT, "enabled" INTEGER NOT NULL, "should_force_update" INTEGER NOT NULL, "message" TEXT, "rollout_cohort_count" INTEGER NOT NULL, "target_cohorts" TEXT NOT NULL, "operation" TEXT NOT NULL, "source_release_id" TEXT, "created_at_ms" INTEGER NOT NULL, "updated_at_ms" INTEGER NOT NULL, "_v" INTEGER NOT NULL DEFAULT 0, PRIMARY KEY ("id"));
|
|
17
|
+
CREATE TABLE IF NOT EXISTS "releases" ("id" TEXT NOT NULL, "revision" INTEGER NOT NULL, "scope_key" TEXT NOT NULL, "channel_id" TEXT NOT NULL, "platform" TEXT NOT NULL, "kind" TEXT NOT NULL, "bundle_id" TEXT, "strategy" TEXT NOT NULL, "target_app_version" TEXT, "fingerprint_hash" TEXT, "enabled" INTEGER NOT NULL, "should_force_update" INTEGER NOT NULL, "message" TEXT, "rollout_cohort_count" INTEGER NOT NULL, "target_cohorts" TEXT NOT NULL, "operation" TEXT NOT NULL, "source_release_id" TEXT, "created_at_ms" INTEGER NOT NULL, "updated_at_ms" INTEGER NOT NULL, "label" INTEGER, "_v" INTEGER NOT NULL DEFAULT 0, PRIMARY KEY ("id"));
|
|
18
18
|
|
|
19
19
|
CREATE INDEX IF NOT EXISTS "releases_byScope" ON "releases" ("scope_key", "id");
|
|
20
20
|
|
|
@@ -26,6 +26,8 @@ CREATE INDEX IF NOT EXISTS "releases_byChannelPlatformEnabled" ON "releases" ("c
|
|
|
26
26
|
|
|
27
27
|
CREATE INDEX IF NOT EXISTS "releases_byBundle" ON "releases" ("bundle_id", "id");
|
|
28
28
|
|
|
29
|
+
CREATE UNIQUE INDEX IF NOT EXISTS "releases_byLabel" ON "releases" ("channel_id", "platform", "label");
|
|
30
|
+
|
|
29
31
|
CREATE TABLE IF NOT EXISTS "release_catalogs" ("scope_key" TEXT NOT NULL, "catalog_id" TEXT NOT NULL, "strategy" TEXT NOT NULL, "channel_id" TEXT NOT NULL, "channel_key" TEXT NOT NULL, "platform" TEXT NOT NULL, "fingerprint_hash" TEXT, "generation" INTEGER NOT NULL, "payload" TEXT NOT NULL, "catalog_hash" TEXT NOT NULL, "byte_size" INTEGER NOT NULL, "is_tombstone" INTEGER NOT NULL, "updated_at_ms" INTEGER NOT NULL, "_v" INTEGER NOT NULL DEFAULT 0, PRIMARY KEY ("scope_key"));
|
|
30
32
|
|
|
31
33
|
CREATE TABLE IF NOT EXISTS "channels" ("id" TEXT NOT NULL, "name" TEXT NOT NULL, "_refs_releases_channel_id" INTEGER NOT NULL DEFAULT 0, "_v" INTEGER NOT NULL DEFAULT 0, PRIMARY KEY ("id"));
|
|
@@ -36,22 +38,40 @@ CREATE UNIQUE INDEX IF NOT EXISTS "channels_name" ON "channels" ("name");
|
|
|
36
38
|
|
|
37
39
|
CREATE TABLE IF NOT EXISTS "bundle_totals" ("platform_key" TEXT NOT NULL, "_shard" INTEGER NOT NULL, "bundles" INTEGER NOT NULL, "_v" INTEGER NOT NULL DEFAULT 0, PRIMARY KEY ("platform_key", "_shard"));
|
|
38
40
|
|
|
39
|
-
CREATE TABLE IF NOT EXISTS "native_builds" ("id" TEXT NOT NULL, "scope_key" TEXT NOT NULL, "platform" TEXT NOT NULL, "channel_id" TEXT NOT NULL, "fingerprint_hash" TEXT, "app_version" TEXT, "min_bundle_id" TEXT NOT NULL, "artifact_kind" TEXT NOT NULL, "artifact_storage_uri" TEXT NOT NULL, "byte_size" INTEGER NOT NULL, "git_commit_hash" TEXT, "created_at_ms" INTEGER NOT NULL, "build_key" TEXT, "build_number" TEXT, "submitted_to" TEXT, "submitted_at_ms" INTEGER, "submitted_version" TEXT, "_v" INTEGER NOT NULL DEFAULT 0, PRIMARY KEY ("id"));
|
|
41
|
+
CREATE TABLE IF NOT EXISTS "native_builds" ("id" TEXT NOT NULL, "scope_key" TEXT NOT NULL, "platform" TEXT NOT NULL, "channel_id" TEXT NOT NULL, "fingerprint_hash" TEXT, "app_version" TEXT, "min_bundle_id" TEXT NOT NULL, "artifact_kind" TEXT NOT NULL, "artifact_storage_uri" TEXT NOT NULL, "byte_size" INTEGER NOT NULL, "git_commit_hash" TEXT, "created_at_ms" INTEGER NOT NULL, "build_key" TEXT, "build_number" TEXT, "submitted_to" TEXT, "submitted_at_ms" INTEGER, "submitted_version" TEXT, "is_store_build" INTEGER NOT NULL, "is_sandbox" INTEGER NOT NULL, "sandbox_url_scheme" TEXT, "export_method" TEXT, "native_app_version" TEXT, "store_build_scope_key" TEXT, "_v" INTEGER NOT NULL DEFAULT 0, PRIMARY KEY ("id"));
|
|
40
42
|
|
|
41
43
|
CREATE INDEX IF NOT EXISTS "native_builds_byScope" ON "native_builds" ("scope_key", "id");
|
|
42
44
|
|
|
43
45
|
CREATE INDEX IF NOT EXISTS "native_builds_byBuildKey" ON "native_builds" ("scope_key", "build_key", "id");
|
|
44
46
|
|
|
47
|
+
CREATE INDEX IF NOT EXISTS "native_builds_byScopeKind" ON "native_builds" ("scope_key", "artifact_kind", "id");
|
|
48
|
+
|
|
49
|
+
CREATE UNIQUE INDEX IF NOT EXISTS "native_builds_byStoreBuild" ON "native_builds" ("store_build_scope_key");
|
|
50
|
+
|
|
45
51
|
CREATE INDEX IF NOT EXISTS "native_builds_byChannel" ON "native_builds" ("channel_id", "id");
|
|
46
52
|
|
|
47
53
|
CREATE UNIQUE INDEX IF NOT EXISTS "native_builds_min_bundle_id" ON "native_builds" ("min_bundle_id");
|
|
48
54
|
|
|
55
|
+
CREATE TABLE IF NOT EXISTS "ios_devices" ("id" TEXT NOT NULL, "udid" TEXT NOT NULL, "name" TEXT NOT NULL, "status" TEXT NOT NULL, "requested_by" TEXT, "created_at_ms" INTEGER NOT NULL, "approved_by" TEXT, "approved_at_ms" INTEGER, "registered_at_ms" INTEGER, "apple_issuer_id" TEXT, "apple_error" TEXT, "build_id" TEXT, "_v" INTEGER NOT NULL DEFAULT 0, PRIMARY KEY ("id"));
|
|
56
|
+
|
|
57
|
+
CREATE INDEX IF NOT EXISTS "ios_devices_byStatus" ON "ios_devices" ("status", "id");
|
|
58
|
+
|
|
59
|
+
CREATE INDEX IF NOT EXISTS "ios_devices_byRegistration" ON "ios_devices" ("registered_at_ms", "id");
|
|
60
|
+
|
|
61
|
+
CREATE UNIQUE INDEX IF NOT EXISTS "ios_devices_udid" ON "ios_devices" ("udid");
|
|
62
|
+
|
|
63
|
+
CREATE TABLE IF NOT EXISTS "ios_device_account" ("id" TEXT NOT NULL, "apple_issuer_id" TEXT NOT NULL, "claimed_at_ms" INTEGER NOT NULL, "_v" INTEGER NOT NULL DEFAULT 0, PRIMARY KEY ("id"));
|
|
64
|
+
|
|
65
|
+
CREATE TABLE IF NOT EXISTS "label_sequences" ("id" TEXT NOT NULL, "last_label" INTEGER NOT NULL, "is_filled" INTEGER NOT NULL, "_v" INTEGER NOT NULL DEFAULT 0, PRIMARY KEY ("id"));
|
|
66
|
+
|
|
49
67
|
CREATE TABLE IF NOT EXISTS "bundle_events" ("id" TEXT NOT NULL, "type" TEXT NOT NULL, "install_id" TEXT NOT NULL, "user_id" TEXT, "from_release_id" TEXT, "from_bundle_id" TEXT, "to_release_id" TEXT, "to_bundle_id" TEXT NOT NULL, "platform" TEXT NOT NULL, "app_version" TEXT NOT NULL, "channel" TEXT NOT NULL, "metadata" TEXT NOT NULL, "received_at_ms" INTEGER NOT NULL, "day" INTEGER, "movement_install_id" TEXT, "bundle_ref" TEXT, "_v" INTEGER NOT NULL DEFAULT 0, PRIMARY KEY ("id"));
|
|
50
68
|
|
|
51
69
|
CREATE INDEX IF NOT EXISTS "bundle_events_movementsByInstall" ON "bundle_events" ("movement_install_id", "received_at_ms", "id");
|
|
52
70
|
|
|
53
71
|
CREATE TABLE IF NOT EXISTS "bundle_events__byBundle" ("platform" TEXT NOT NULL, "channel" TEXT NOT NULL, "type" TEXT NOT NULL, "bundle_ref" TEXT NOT NULL, "day" INTEGER NOT NULL, "received_at_ms" INTEGER NOT NULL, "id" TEXT NOT NULL, PRIMARY KEY ("platform", "channel", "type", "bundle_ref", "day", "received_at_ms", "id"));
|
|
54
72
|
|
|
73
|
+
CREATE INDEX IF NOT EXISTS "bundle_events__byBundle__key" ON "bundle_events__byBundle" ("id");
|
|
74
|
+
|
|
55
75
|
CREATE INDEX IF NOT EXISTS "bundle_events_byDay" ON "bundle_events" ("day", "received_at_ms", "id");
|
|
56
76
|
|
|
57
77
|
CREATE TABLE IF NOT EXISTS "bundle_event_heads" ("install_id" TEXT NOT NULL, "id" TEXT NOT NULL, "type" TEXT NOT NULL, "user_id" TEXT, "from_release_id" TEXT, "from_bundle_id" TEXT, "to_release_id" TEXT, "to_bundle_id" TEXT NOT NULL, "platform" TEXT NOT NULL, "app_version" TEXT NOT NULL, "channel" TEXT NOT NULL, "metadata" TEXT NOT NULL, "received_at_ms" INTEGER NOT NULL, "_v" INTEGER NOT NULL DEFAULT 0, PRIMARY KEY ("install_id"));
|
package/src/d1Executor.ts
CHANGED
|
@@ -45,9 +45,54 @@ const withSqliteCode = (error: unknown): unknown => {
|
|
|
45
45
|
};
|
|
46
46
|
|
|
47
47
|
/**
|
|
48
|
-
* The
|
|
49
|
-
*
|
|
50
|
-
*
|
|
48
|
+
* The D1 errors Cloudflare's D1 guide says to retry ("Retry the operation"):
|
|
49
|
+
* a dropped connection, a reset or restarted database object, a transient
|
|
50
|
+
* failure to reach its node, and a replica cut off from its primary.
|
|
51
|
+
*/
|
|
52
|
+
const TRANSIENT_D1_ERROR =
|
|
53
|
+
/Network connection lost|storage caused object to be reset|reset because its code was updated|Cannot resolve D1 DB due to transient issue|Replica disconnected from primary/iu;
|
|
54
|
+
|
|
55
|
+
/** The SQL core's reads, the only statements a retry can't apply twice. */
|
|
56
|
+
const READ_ONLY_STATEMENT = /^\s*SELECT\b/iu;
|
|
57
|
+
|
|
58
|
+
/** Attempts of a read in all, the first included. */
|
|
59
|
+
const READ_ATTEMPTS = 3;
|
|
60
|
+
/** The longest wait before the second attempt, doubling after it, with full jitter. */
|
|
61
|
+
const READ_RETRY_BASE_MS = 25;
|
|
62
|
+
|
|
63
|
+
const isTransient = (error: unknown) =>
|
|
64
|
+
TRANSIENT_D1_ERROR.test(
|
|
65
|
+
error instanceof Error ? error.message : String(error),
|
|
66
|
+
);
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Runs a read again when D1 failed it with a transient error, at most
|
|
70
|
+
* {@link READ_ATTEMPTS} times, and throws the last error. D1 retries a
|
|
71
|
+
* read-only query twice on its own; an error that outlasts those retries
|
|
72
|
+
* still answers a request with 500, where one more attempt after a short
|
|
73
|
+
* wait usually reads. A write may have committed when it fails, so it never
|
|
74
|
+
* runs again.
|
|
75
|
+
*/
|
|
76
|
+
export const retryingReads =
|
|
77
|
+
(query: (statement: SqlStatement) => Promise<SqlResult>) =>
|
|
78
|
+
async (statement: SqlStatement): Promise<SqlResult> => {
|
|
79
|
+
if (!READ_ONLY_STATEMENT.test(statement.sql)) return query(statement);
|
|
80
|
+
for (let attempt = 1; ; attempt += 1) {
|
|
81
|
+
try {
|
|
82
|
+
return await query(statement);
|
|
83
|
+
} catch (error) {
|
|
84
|
+
if (attempt >= READ_ATTEMPTS || !isTransient(error)) throw error;
|
|
85
|
+
const wait = Math.random() * READ_RETRY_BASE_MS * 2 ** (attempt - 1);
|
|
86
|
+
await new Promise((resolve) => setTimeout(resolve, wait));
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* The most ops one write sends: one `batch` of at most two statements an op
|
|
93
|
+
* besides its three own, so at most 903 statements. A Worker counts a batch
|
|
94
|
+
* as one query against its invocation's queries, whatever statements it
|
|
95
|
+
* holds (D1's limits), so this bounds one batch, not an invocation.
|
|
51
96
|
*/
|
|
52
97
|
export const D1_MAX_OPS = 450;
|
|
53
98
|
|
|
@@ -61,10 +106,11 @@ export const createD1Database = (runner: {
|
|
|
61
106
|
query(statement: SqlStatement): Promise<SqlResult>;
|
|
62
107
|
batch(statements: readonly SqlStatement[]): Promise<readonly SqlResult[]>;
|
|
63
108
|
}): ToolingDatabase => {
|
|
109
|
+
const query = retryingReads((statement) => runner.query(statement));
|
|
64
110
|
const executor: SqlExecutor = {
|
|
65
111
|
dialect: "sqlite",
|
|
66
112
|
execute: (statement) =>
|
|
67
|
-
|
|
113
|
+
query(statement).catch((error: unknown) => {
|
|
68
114
|
throw withSqliteCode(error);
|
|
69
115
|
}),
|
|
70
116
|
batch: (statements) =>
|
package/src/d1Rest.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { SqlResult, SqlStatement } from "@hot-updater/plugin-core";
|
|
1
|
+
import type { Lazy, SqlResult, SqlStatement } from "@hot-updater/plugin-core";
|
|
2
2
|
import Cloudflare from "cloudflare";
|
|
3
3
|
|
|
4
4
|
import { D1ExecutionError, type D1ResultLike, toSqlResult } from "./d1Executor";
|
|
@@ -8,10 +8,10 @@ export interface D1RestConfig {
|
|
|
8
8
|
readonly accountId: string;
|
|
9
9
|
/**
|
|
10
10
|
* An API token with D1 edit permission, or a function that returns it,
|
|
11
|
-
* such as
|
|
12
|
-
* so a config loads without the token.
|
|
11
|
+
* such as `secret("<name>")` in `hot-updater.config.ts`: called on the
|
|
12
|
+
* first query, so a config loads without the token.
|
|
13
13
|
*/
|
|
14
|
-
readonly cloudflareApiToken:
|
|
14
|
+
readonly cloudflareApiToken: Lazy<string>;
|
|
15
15
|
}
|
|
16
16
|
|
|
17
17
|
/** The REST API binds text: each value goes as JSON and is read back with `json_extract`. */
|