@hot-updater/cloudflare 1.2.0-rc.50 → 1.2.0-rc.51
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +33 -1
- package/dist/index.mjs +33 -1
- package/dist/init/index.cjs +43 -1
- package/dist/init/index.mjs +47 -5
- package/dist/worker/index.cjs +33 -1
- package/dist/worker/index.mjs +33 -1
- package/package.json +7 -7
- package/sql/bundles.sql +5 -1
- package/src/d1Executor.ts +46 -1
- package/src/d1Schema.ts +23 -6
- package/worker/dist/README.md +1 -1
- package/worker/dist/index.js +614 -65
- package/worker/dist/index.js.map +4 -4
- package/worker/migrations/0002_hot-updater_1.2.0.sql +6 -0
package/dist/index.cjs
CHANGED
|
@@ -46,18 +46,50 @@ const withSqliteCode = (error) => {
|
|
|
46
46
|
return code === void 0 ? error : Object.assign(new Error(message, { cause: error }), { code });
|
|
47
47
|
};
|
|
48
48
|
/**
|
|
49
|
+
* The D1 errors Cloudflare's D1 guide says to retry ("Retry the operation"):
|
|
50
|
+
* a dropped connection, a reset or restarted database object, a transient
|
|
51
|
+
* failure to reach its node, and a replica cut off from its primary.
|
|
52
|
+
*/
|
|
53
|
+
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;
|
|
54
|
+
/** The SQL core's reads, the only statements a retry can't apply twice. */
|
|
55
|
+
const READ_ONLY_STATEMENT = /^\s*SELECT\b/iu;
|
|
56
|
+
/** Attempts of a read in all, the first included. */
|
|
57
|
+
const READ_ATTEMPTS = 3;
|
|
58
|
+
/** The longest wait before the second attempt, doubling after it, with full jitter. */
|
|
59
|
+
const READ_RETRY_BASE_MS = 25;
|
|
60
|
+
const isTransient = (error) => TRANSIENT_D1_ERROR.test(error instanceof Error ? error.message : String(error));
|
|
61
|
+
/**
|
|
62
|
+
* Runs a read again when D1 failed it with a transient error, at most
|
|
63
|
+
* {@link READ_ATTEMPTS} times, and throws the last error. D1 retries a
|
|
64
|
+
* read-only query twice on its own; an error that outlasts those retries
|
|
65
|
+
* still answers a request with 500, where one more attempt after a short
|
|
66
|
+
* wait usually reads. A write may have committed when it fails, so it never
|
|
67
|
+
* runs again.
|
|
68
|
+
*/
|
|
69
|
+
const retryingReads = (query) => async (statement) => {
|
|
70
|
+
if (!READ_ONLY_STATEMENT.test(statement.sql)) return query(statement);
|
|
71
|
+
for (let attempt = 1;; attempt += 1) try {
|
|
72
|
+
return await query(statement);
|
|
73
|
+
} catch (error) {
|
|
74
|
+
if (attempt >= READ_ATTEMPTS || !isTransient(error)) throw error;
|
|
75
|
+
const wait = Math.random() * READ_RETRY_BASE_MS * 2 ** (attempt - 1);
|
|
76
|
+
await new Promise((resolve) => setTimeout(resolve, wait));
|
|
77
|
+
}
|
|
78
|
+
};
|
|
79
|
+
/**
|
|
49
80
|
* Hot Updater's database on D1: the storage engine through the shared SQL
|
|
50
81
|
* core, fenced by the schema settings. D1 has no interactive transactions,
|
|
51
82
|
* so each write is one atomic batch that evaluates its guards first
|
|
52
83
|
* (`_hu_write`).
|
|
53
84
|
*/
|
|
54
85
|
const createD1Database = (runner) => {
|
|
86
|
+
const query = retryingReads((statement) => runner.query(statement));
|
|
55
87
|
return (0, _hot_updater_plugin_core.createEngineDatabase)({
|
|
56
88
|
name: "d1Database",
|
|
57
89
|
adapter: (0, _hot_updater_plugin_core.createSqlAdapter)({
|
|
58
90
|
executor: {
|
|
59
91
|
dialect: "sqlite",
|
|
60
|
-
execute: (statement) =>
|
|
92
|
+
execute: (statement) => query(statement).catch((error) => {
|
|
61
93
|
throw withSqliteCode(error);
|
|
62
94
|
}),
|
|
63
95
|
batch: (statements) => runner.batch(statements).catch((error) => {
|
package/dist/index.mjs
CHANGED
|
@@ -22,18 +22,50 @@ const withSqliteCode = (error) => {
|
|
|
22
22
|
return code === void 0 ? error : Object.assign(new Error(message, { cause: error }), { code });
|
|
23
23
|
};
|
|
24
24
|
/**
|
|
25
|
+
* The D1 errors Cloudflare's D1 guide says to retry ("Retry the operation"):
|
|
26
|
+
* a dropped connection, a reset or restarted database object, a transient
|
|
27
|
+
* failure to reach its node, and a replica cut off from its primary.
|
|
28
|
+
*/
|
|
29
|
+
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;
|
|
30
|
+
/** The SQL core's reads, the only statements a retry can't apply twice. */
|
|
31
|
+
const READ_ONLY_STATEMENT = /^\s*SELECT\b/iu;
|
|
32
|
+
/** Attempts of a read in all, the first included. */
|
|
33
|
+
const READ_ATTEMPTS = 3;
|
|
34
|
+
/** The longest wait before the second attempt, doubling after it, with full jitter. */
|
|
35
|
+
const READ_RETRY_BASE_MS = 25;
|
|
36
|
+
const isTransient = (error) => TRANSIENT_D1_ERROR.test(error instanceof Error ? error.message : String(error));
|
|
37
|
+
/**
|
|
38
|
+
* Runs a read again when D1 failed it with a transient error, at most
|
|
39
|
+
* {@link READ_ATTEMPTS} times, and throws the last error. D1 retries a
|
|
40
|
+
* read-only query twice on its own; an error that outlasts those retries
|
|
41
|
+
* still answers a request with 500, where one more attempt after a short
|
|
42
|
+
* wait usually reads. A write may have committed when it fails, so it never
|
|
43
|
+
* runs again.
|
|
44
|
+
*/
|
|
45
|
+
const retryingReads = (query) => async (statement) => {
|
|
46
|
+
if (!READ_ONLY_STATEMENT.test(statement.sql)) return query(statement);
|
|
47
|
+
for (let attempt = 1;; attempt += 1) try {
|
|
48
|
+
return await query(statement);
|
|
49
|
+
} catch (error) {
|
|
50
|
+
if (attempt >= READ_ATTEMPTS || !isTransient(error)) throw error;
|
|
51
|
+
const wait = Math.random() * READ_RETRY_BASE_MS * 2 ** (attempt - 1);
|
|
52
|
+
await new Promise((resolve) => setTimeout(resolve, wait));
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
/**
|
|
25
56
|
* Hot Updater's database on D1: the storage engine through the shared SQL
|
|
26
57
|
* core, fenced by the schema settings. D1 has no interactive transactions,
|
|
27
58
|
* so each write is one atomic batch that evaluates its guards first
|
|
28
59
|
* (`_hu_write`).
|
|
29
60
|
*/
|
|
30
61
|
const createD1Database = (runner) => {
|
|
62
|
+
const query = retryingReads((statement) => runner.query(statement));
|
|
31
63
|
return createEngineDatabase({
|
|
32
64
|
name: "d1Database",
|
|
33
65
|
adapter: createSqlAdapter({
|
|
34
66
|
executor: {
|
|
35
67
|
dialect: "sqlite",
|
|
36
|
-
execute: (statement) =>
|
|
68
|
+
execute: (statement) => query(statement).catch((error) => {
|
|
37
69
|
throw withSqliteCode(error);
|
|
38
70
|
}),
|
|
39
71
|
batch: (statements) => runner.batch(statements).catch((error) => {
|
package/dist/init/index.cjs
CHANGED
|
@@ -75,18 +75,50 @@ const withSqliteCode = (error) => {
|
|
|
75
75
|
return code === void 0 ? error : Object.assign(new Error(message, { cause: error }), { code });
|
|
76
76
|
};
|
|
77
77
|
/**
|
|
78
|
+
* The D1 errors Cloudflare's D1 guide says to retry ("Retry the operation"):
|
|
79
|
+
* a dropped connection, a reset or restarted database object, a transient
|
|
80
|
+
* failure to reach its node, and a replica cut off from its primary.
|
|
81
|
+
*/
|
|
82
|
+
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;
|
|
83
|
+
/** The SQL core's reads, the only statements a retry can't apply twice. */
|
|
84
|
+
const READ_ONLY_STATEMENT = /^\s*SELECT\b/iu;
|
|
85
|
+
/** Attempts of a read in all, the first included. */
|
|
86
|
+
const READ_ATTEMPTS = 3;
|
|
87
|
+
/** The longest wait before the second attempt, doubling after it, with full jitter. */
|
|
88
|
+
const READ_RETRY_BASE_MS = 25;
|
|
89
|
+
const isTransient = (error) => TRANSIENT_D1_ERROR.test(error instanceof Error ? error.message : String(error));
|
|
90
|
+
/**
|
|
91
|
+
* Runs a read again when D1 failed it with a transient error, at most
|
|
92
|
+
* {@link READ_ATTEMPTS} times, and throws the last error. D1 retries a
|
|
93
|
+
* read-only query twice on its own; an error that outlasts those retries
|
|
94
|
+
* still answers a request with 500, where one more attempt after a short
|
|
95
|
+
* wait usually reads. A write may have committed when it fails, so it never
|
|
96
|
+
* runs again.
|
|
97
|
+
*/
|
|
98
|
+
const retryingReads = (query) => async (statement) => {
|
|
99
|
+
if (!READ_ONLY_STATEMENT.test(statement.sql)) return query(statement);
|
|
100
|
+
for (let attempt = 1;; attempt += 1) try {
|
|
101
|
+
return await query(statement);
|
|
102
|
+
} catch (error) {
|
|
103
|
+
if (attempt >= READ_ATTEMPTS || !isTransient(error)) throw error;
|
|
104
|
+
const wait = Math.random() * READ_RETRY_BASE_MS * 2 ** (attempt - 1);
|
|
105
|
+
await new Promise((resolve) => setTimeout(resolve, wait));
|
|
106
|
+
}
|
|
107
|
+
};
|
|
108
|
+
/**
|
|
78
109
|
* Hot Updater's database on D1: the storage engine through the shared SQL
|
|
79
110
|
* core, fenced by the schema settings. D1 has no interactive transactions,
|
|
80
111
|
* so each write is one atomic batch that evaluates its guards first
|
|
81
112
|
* (`_hu_write`).
|
|
82
113
|
*/
|
|
83
114
|
const createD1Database = (runner) => {
|
|
115
|
+
const query = retryingReads((statement) => runner.query(statement));
|
|
84
116
|
return (0, _hot_updater_plugin_core.createEngineDatabase)({
|
|
85
117
|
name: "d1Database",
|
|
86
118
|
adapter: (0, _hot_updater_plugin_core.createSqlAdapter)({
|
|
87
119
|
executor: {
|
|
88
120
|
dialect: "sqlite",
|
|
89
|
-
execute: (statement) =>
|
|
121
|
+
execute: (statement) => query(statement).catch((error) => {
|
|
90
122
|
throw withSqliteCode(error);
|
|
91
123
|
}),
|
|
92
124
|
batch: (statements) => runner.batch(statements).catch((error) => {
|
|
@@ -11207,6 +11239,15 @@ const getValidWranglerAuthToken = () => {
|
|
|
11207
11239
|
const resolveCloudflareInfrastructureApiToken = async ({ cwd, nonInteractive }) => {
|
|
11208
11240
|
const existingToken = getValidWranglerAuthToken();
|
|
11209
11241
|
if (existingToken) return existingToken;
|
|
11242
|
+
if (getWranglerLoginAuthToken()?.refresh_token) {
|
|
11243
|
+
await execa("npx", ["wrangler", "whoami"], {
|
|
11244
|
+
cwd,
|
|
11245
|
+
reject: false,
|
|
11246
|
+
stdio: "ignore"
|
|
11247
|
+
});
|
|
11248
|
+
const renewedToken = getValidWranglerAuthToken();
|
|
11249
|
+
if (renewedToken) return renewedToken;
|
|
11250
|
+
}
|
|
11210
11251
|
if (nonInteractive) throw new CloudflareWranglerLoginRequiredError();
|
|
11211
11252
|
await execa("npx", [
|
|
11212
11253
|
"wrangler",
|
|
@@ -11910,6 +11951,7 @@ const runInit = async ({ build, envFile, secretsEnv }) => {
|
|
|
11910
11951
|
});
|
|
11911
11952
|
let credential;
|
|
11912
11953
|
try {
|
|
11954
|
+
await (0, _hot_updater_cli_tools.fillReleaseLabels)(server);
|
|
11913
11955
|
credential = await (0, _hot_updater_cli_tools.provisionClientCredential)(server, {
|
|
11914
11956
|
env: initInputEnv,
|
|
11915
11957
|
name: "Cloudflare init"
|
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, writeHotUpdaterFiles } from "@hot-updater/cli-tools";
|
|
3
|
+
import { ConfigBuilder, InitError, LegacyInfrastructureError, assembleServer, assertInfrastructureGenerationAtUrl, assertInitInputs, assertInitProviderInputs, 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",
|
|
@@ -11903,6 +11944,7 @@ const runInit = async ({ build, envFile, secretsEnv }) => {
|
|
|
11903
11944
|
});
|
|
11904
11945
|
let credential;
|
|
11905
11946
|
try {
|
|
11947
|
+
await fillReleaseLabels(server);
|
|
11906
11948
|
credential = await provisionClientCredential(server, {
|
|
11907
11949
|
env: initInputEnv,
|
|
11908
11950
|
name: "Cloudflare init"
|
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) => {
|
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) => {
|
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.51",
|
|
5
5
|
"description": "React Native OTA solution for self-hosted",
|
|
6
6
|
"main": "dist/index.cjs",
|
|
7
7
|
"module": "dist/index.mjs",
|
|
@@ -52,11 +52,11 @@
|
|
|
52
52
|
"cloudflare": "4.2.0",
|
|
53
53
|
"hono": "4.12.34",
|
|
54
54
|
"uuidv7": "^1.0.2",
|
|
55
|
-
"@hot-updater/cli-tools": "1.2.0-rc.
|
|
56
|
-
"@hot-updater/protocol": "1.2.0-rc.
|
|
57
|
-
"@hot-updater/
|
|
58
|
-
"@hot-updater/
|
|
59
|
-
"@hot-updater/storage-s3": "1.2.0-rc.
|
|
55
|
+
"@hot-updater/cli-tools": "1.2.0-rc.51",
|
|
56
|
+
"@hot-updater/protocol": "1.2.0-rc.51",
|
|
57
|
+
"@hot-updater/plugin-core": "1.2.0-rc.51",
|
|
58
|
+
"@hot-updater/server": "1.2.0-rc.51",
|
|
59
|
+
"@hot-updater/storage-s3": "1.2.0-rc.51"
|
|
60
60
|
},
|
|
61
61
|
"devDependencies": {
|
|
62
62
|
"@aws-sdk/client-s3": "3.1066.0",
|
|
@@ -75,7 +75,7 @@
|
|
|
75
75
|
"vitest": "4.1.4",
|
|
76
76
|
"wrangler": "^4.69.0",
|
|
77
77
|
"xdg-app-paths": "^8.3.0",
|
|
78
|
-
"@hot-updater/test-utils": "1.2.0-rc.
|
|
78
|
+
"@hot-updater/test-utils": "1.2.0-rc.51"
|
|
79
79
|
},
|
|
80
80
|
"scripts": {
|
|
81
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"));
|
|
@@ -60,6 +62,8 @@ CREATE UNIQUE INDEX IF NOT EXISTS "ios_devices_udid" ON "ios_devices" ("udid");
|
|
|
60
62
|
|
|
61
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"));
|
|
62
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
|
+
|
|
63
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"));
|
|
64
68
|
|
|
65
69
|
CREATE INDEX IF NOT EXISTS "bundle_events_movementsByInstall" ON "bundle_events" ("movement_install_id", "received_at_ms", "id");
|
package/src/d1Executor.ts
CHANGED
|
@@ -44,6 +44,50 @@ const withSqliteCode = (error: unknown): unknown => {
|
|
|
44
44
|
: Object.assign(new Error(message, { cause: error }), { code });
|
|
45
45
|
};
|
|
46
46
|
|
|
47
|
+
/**
|
|
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
|
+
|
|
47
91
|
/**
|
|
48
92
|
* The most ops one write sends: one `batch` of at most two statements an op
|
|
49
93
|
* besides its three own, so at most 903 statements. A Worker counts a batch
|
|
@@ -62,10 +106,11 @@ export const createD1Database = (runner: {
|
|
|
62
106
|
query(statement: SqlStatement): Promise<SqlResult>;
|
|
63
107
|
batch(statements: readonly SqlStatement[]): Promise<readonly SqlResult[]>;
|
|
64
108
|
}): ToolingDatabase => {
|
|
109
|
+
const query = retryingReads((statement) => runner.query(statement));
|
|
65
110
|
const executor: SqlExecutor = {
|
|
66
111
|
dialect: "sqlite",
|
|
67
112
|
execute: (statement) =>
|
|
68
|
-
|
|
113
|
+
query(statement).catch((error: unknown) => {
|
|
69
114
|
throw withSqliteCode(error);
|
|
70
115
|
}),
|
|
71
116
|
batch: (statements) =>
|
package/src/d1Schema.ts
CHANGED
|
@@ -3,6 +3,7 @@ import {
|
|
|
3
3
|
createTableStatements,
|
|
4
4
|
WRITE_GUARD_TABLE,
|
|
5
5
|
generateEngineSql,
|
|
6
|
+
lateColumnStatements,
|
|
6
7
|
type ToolingTarget,
|
|
7
8
|
} from "@hot-updater/plugin-core";
|
|
8
9
|
|
|
@@ -36,11 +37,23 @@ export const d1MigrationStatements = (sql: string): string[] =>
|
|
|
36
37
|
.map((statement) => statement.replace(/;\n$/u, "").trim())
|
|
37
38
|
.filter((statement) => statement !== "");
|
|
38
39
|
|
|
40
|
+
/** Whether `sql` creates a table an earlier migration created, which it never does again. */
|
|
41
|
+
const createdBefore = (sql: string, earlier: readonly string[]) => {
|
|
42
|
+
const table = /^CREATE TABLE IF NOT EXISTS ("[^"]+") \(/u.exec(sql)?.[1];
|
|
43
|
+
return (
|
|
44
|
+
table !== undefined &&
|
|
45
|
+
earlier.some((ran) =>
|
|
46
|
+
ran.startsWith(`CREATE TABLE IF NOT EXISTS ${table} (`),
|
|
47
|
+
)
|
|
48
|
+
);
|
|
49
|
+
};
|
|
50
|
+
|
|
39
51
|
/**
|
|
40
|
-
* A managed D1 migration after the first:
|
|
41
|
-
*
|
|
42
|
-
*
|
|
43
|
-
*
|
|
52
|
+
* A managed D1 migration after the first: the columns added to tables an
|
|
53
|
+
* earlier migration created, then each statement of the target's schema that
|
|
54
|
+
* no earlier migration ran, then every settings row, so the migration is
|
|
55
|
+
* never empty and the fence passes once it ran. Shipped migrations are
|
|
56
|
+
* frozen; a schema change goes into the next one.
|
|
44
57
|
*/
|
|
45
58
|
export const d1MigrationSql = (
|
|
46
59
|
target: ToolingTarget,
|
|
@@ -48,9 +61,13 @@ export const d1MigrationSql = (
|
|
|
48
61
|
): string => {
|
|
49
62
|
const statements = d1SchemaStatements(target);
|
|
50
63
|
const settings = Object.keys(target.settings).length;
|
|
51
|
-
const
|
|
64
|
+
const ranStatements = earlier.flatMap(d1MigrationStatements);
|
|
65
|
+
const ran = new Set(ranStatements);
|
|
52
66
|
return toSql([
|
|
53
|
-
...
|
|
67
|
+
...lateColumnStatements("sqlite", target.schema, ranStatements),
|
|
68
|
+
...statements
|
|
69
|
+
.slice(0, -settings)
|
|
70
|
+
.filter((sql) => !ran.has(sql) && !createdBefore(sql, ranStatements)),
|
|
54
71
|
...statements.slice(-settings),
|
|
55
72
|
]);
|
|
56
73
|
};
|
package/worker/dist/README.md
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
This folder contains the built output assets for the worker "hot-updater" generated at 2026-11-
|
|
1
|
+
This folder contains the built output assets for the worker "hot-updater" generated at 2026-11-21T12:22:42.924Z.
|