@harlan-zw/nuxt-cloudflare 0.0.9 → 0.0.10
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/README.md +14 -3
- package/dist/chunks/binding-types.mjs +24 -1
- package/dist/d1.d.mts +46 -2
- package/dist/d1.mjs +250 -12
- package/dist/module.json +1 -1
- package/dist/module.mjs +5 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -135,9 +135,16 @@ Pass the final generated config explicitly to `types` and `check startup`; Nitro
|
|
|
135
135
|
### D1 sessions and safe retries
|
|
136
136
|
|
|
137
137
|
```ts
|
|
138
|
-
import {
|
|
138
|
+
import {
|
|
139
|
+
getRecoveringRequestD1Session,
|
|
140
|
+
retryIdempotentD1Write,
|
|
141
|
+
} from '@harlan-zw/nuxt-cloudflare/d1'
|
|
139
142
|
|
|
140
|
-
const session =
|
|
143
|
+
const session = getRecoveringRequestD1Session(
|
|
144
|
+
event.context,
|
|
145
|
+
'DB',
|
|
146
|
+
event.context.cloudflare.env.DB,
|
|
147
|
+
)
|
|
141
148
|
|
|
142
149
|
await retryIdempotentD1Write({
|
|
143
150
|
safety: { _tag: 'replay-safe' },
|
|
@@ -145,7 +152,11 @@ await retryIdempotentD1Write({
|
|
|
145
152
|
})
|
|
146
153
|
```
|
|
147
154
|
|
|
148
|
-
|
|
155
|
+
`getRecoveringRequestD1Session` caches one `first-primary` session per request and binding. Use `withD1ResetRecovery` when no request context exists. D1 already retries read-only queries. Recovery handles failures that outlive those retries. It opens a replacement session after `D1_RESET_DO`, carries the last bookmark, and rebuilds the prepared statement with its bound values. Replica disconnects and connection loss retry on the current session.
|
|
156
|
+
|
|
157
|
+
Recovery replays only `SELECT`, read-only CTE, and `EXPLAIN` statements. It never replays writes, PRAGMA statements, mixed batches, or unknown statements. A session reset still opens a healthy session for the next statement. `onRecovery` receives tagged `retrying` or `stopped` events for request telemetry.
|
|
158
|
+
|
|
159
|
+
Write retries require an explicit safety tag. `lock-only` retries SQLite lock contention; `replay-safe` also permits classified network and storage reset failures. Resource pressure, queue delay, CPU, and memory errors are never retried.
|
|
149
160
|
|
|
150
161
|
### D1 parameter plans
|
|
151
162
|
|
|
@@ -47,6 +47,29 @@ function normalizeConfig(config, options) {
|
|
|
47
47
|
}
|
|
48
48
|
return normalized;
|
|
49
49
|
}
|
|
50
|
+
function compareText(left, right) {
|
|
51
|
+
if (left < right)
|
|
52
|
+
return -1;
|
|
53
|
+
if (left > right)
|
|
54
|
+
return 1;
|
|
55
|
+
return 0;
|
|
56
|
+
}
|
|
57
|
+
function canonicalizeBindingEnvironment(environment) {
|
|
58
|
+
return environment.replaceAll("\r\n", "\n").replace(
|
|
59
|
+
/(interface __BaseEnv_CloudflareBindings \{\n)([\s\S]*?)(\n\})/,
|
|
60
|
+
(_, opening, members, closing) => [
|
|
61
|
+
opening,
|
|
62
|
+
members.split("\n").sort((left, right) => compareText(left.trim(), right.trim())).join("\n"),
|
|
63
|
+
closing
|
|
64
|
+
].join("")
|
|
65
|
+
).replace(
|
|
66
|
+
/Pick<Cloudflare\.Env,([^>]+)>/g,
|
|
67
|
+
(_, members) => `Pick<Cloudflare.Env, ${members.split("|").map((member) => member.trim()).sort(compareText).join(" | ")}>`
|
|
68
|
+
);
|
|
69
|
+
}
|
|
70
|
+
function createBindingTypeSignature(environment, runtime) {
|
|
71
|
+
return `${canonicalizeBindingEnvironment(environment)}\0${runtime.replaceAll("\r\n", "\n")}`;
|
|
72
|
+
}
|
|
50
73
|
async function readAuthoredConfig(rootDir) {
|
|
51
74
|
const [path] = discoverWranglerSourceConfigs(rootDir);
|
|
52
75
|
if (!path)
|
|
@@ -77,7 +100,7 @@ async function generateCloudflareBindingTypes(options) {
|
|
|
77
100
|
throw new Error("[nuxt-cloudflare] Wrangler did not generate Cloudflare binding and runtime types.");
|
|
78
101
|
return {
|
|
79
102
|
content: generated.content,
|
|
80
|
-
signature:
|
|
103
|
+
signature: createBindingTypeSignature(generated.env, generated.runtime)
|
|
81
104
|
};
|
|
82
105
|
}
|
|
83
106
|
async function prepareCloudflareBindingTypes(options) {
|
package/dist/d1.d.mts
CHANGED
|
@@ -26,6 +26,18 @@ type D1Consistency = {
|
|
|
26
26
|
interface D1SessionSource<Session> {
|
|
27
27
|
withSession: (constraint: string) => Session;
|
|
28
28
|
}
|
|
29
|
+
interface D1StatementLike {
|
|
30
|
+
bind: (...values: never[]) => D1StatementLike;
|
|
31
|
+
first: (...args: never[]) => unknown;
|
|
32
|
+
run: (...args: never[]) => unknown;
|
|
33
|
+
all: (...args: never[]) => unknown;
|
|
34
|
+
raw: (...args: never[]) => unknown;
|
|
35
|
+
}
|
|
36
|
+
interface D1SessionLike {
|
|
37
|
+
prepare: (sql: string) => D1StatementLike;
|
|
38
|
+
batch: (statements: never[]) => unknown;
|
|
39
|
+
getBookmark: () => string | null;
|
|
40
|
+
}
|
|
29
41
|
interface RetryIdempotentD1WriteOptions<T> {
|
|
30
42
|
maxAttempts?: number;
|
|
31
43
|
random?: () => number;
|
|
@@ -34,19 +46,51 @@ interface RetryIdempotentD1WriteOptions<T> {
|
|
|
34
46
|
sleep?: (milliseconds: number) => Promise<void>;
|
|
35
47
|
}
|
|
36
48
|
type D1RetryErrorKind = {
|
|
49
|
+
_tag: 'session-reset';
|
|
50
|
+
} | {
|
|
37
51
|
_tag: 'lock';
|
|
38
52
|
} | {
|
|
39
53
|
_tag: 'transient';
|
|
40
54
|
} | {
|
|
41
55
|
_tag: 'permanent';
|
|
42
56
|
};
|
|
57
|
+
type D1RecoveryEvent = {
|
|
58
|
+
_tag: 'retrying';
|
|
59
|
+
attempt: number;
|
|
60
|
+
failure: {
|
|
61
|
+
_tag: 'session-reset';
|
|
62
|
+
} | {
|
|
63
|
+
_tag: 'transient';
|
|
64
|
+
};
|
|
65
|
+
sql: string;
|
|
66
|
+
} | {
|
|
67
|
+
_tag: 'stopped';
|
|
68
|
+
attempt: number;
|
|
69
|
+
failure: {
|
|
70
|
+
_tag: 'session-reset';
|
|
71
|
+
} | {
|
|
72
|
+
_tag: 'transient';
|
|
73
|
+
};
|
|
74
|
+
reason: 'attempts-exhausted' | 'unsafe-statement';
|
|
75
|
+
sql: string;
|
|
76
|
+
};
|
|
77
|
+
interface D1ResetRecoveryOptions {
|
|
78
|
+
consistency?: D1Consistency;
|
|
79
|
+
maxAttempts?: number;
|
|
80
|
+
onRecovery?: (event: D1RecoveryEvent) => void;
|
|
81
|
+
random?: () => number;
|
|
82
|
+
sleep?: (milliseconds: number) => Promise<void>;
|
|
83
|
+
}
|
|
43
84
|
declare function defineD1ParameterPlan(input: D1ParameterPlanInput): D1ParameterPlan;
|
|
44
85
|
declare function chunkD1Items<T>(items: readonly T[], plan: D1ParameterPlan): T[][];
|
|
45
86
|
declare function assertD1BoundParameters(parameters: readonly unknown[]): void;
|
|
46
87
|
declare function classifyD1RetryError(error: unknown): D1RetryErrorKind;
|
|
47
88
|
declare function isTransientD1Error(error: unknown): boolean;
|
|
89
|
+
declare function isReplayableD1Sql(sql: string): boolean;
|
|
90
|
+
declare function withD1ResetRecovery<Session extends D1SessionLike>(database: D1SessionSource<Session>, options?: D1ResetRecoveryOptions): Session;
|
|
48
91
|
declare function getRequestD1Session<Session>(requestContext: Record<PropertyKey, unknown>, binding: string, database: D1SessionSource<Session>, consistency?: D1Consistency): Session;
|
|
92
|
+
declare function getRecoveringRequestD1Session<Session extends D1SessionLike>(requestContext: Record<PropertyKey, unknown>, binding: string, database: D1SessionSource<Session>, options?: D1ResetRecoveryOptions): Session;
|
|
49
93
|
declare function retryIdempotentD1Write<T>(options: RetryIdempotentD1WriteOptions<T>): Promise<T>;
|
|
50
94
|
|
|
51
|
-
export { D1_MAX_BOUND_PARAMETERS, assertD1BoundParameters, chunkD1Items, classifyD1RetryError, defineD1ParameterPlan, getRequestD1Session, isTransientD1Error, retryIdempotentD1Write };
|
|
52
|
-
export type { D1Consistency, D1ParameterPlan, D1ParameterPlanInput, D1RetryErrorKind, D1SessionSource, D1WriteSafety, RetryIdempotentD1WriteOptions };
|
|
95
|
+
export { D1_MAX_BOUND_PARAMETERS, assertD1BoundParameters, chunkD1Items, classifyD1RetryError, defineD1ParameterPlan, getRecoveringRequestD1Session, getRequestD1Session, isReplayableD1Sql, isTransientD1Error, retryIdempotentD1Write, withD1ResetRecovery };
|
|
96
|
+
export type { D1Consistency, D1ParameterPlan, D1ParameterPlanInput, D1RecoveryEvent, D1ResetRecoveryOptions, D1RetryErrorKind, D1SessionLike, D1SessionSource, D1StatementLike, D1WriteSafety, RetryIdempotentD1WriteOptions };
|
package/dist/d1.mjs
CHANGED
|
@@ -1,14 +1,22 @@
|
|
|
1
1
|
const D1_MAX_BOUND_PARAMETERS = 100;
|
|
2
2
|
const D1_PARAMETER_PLAN = Symbol("@harlan-zw/nuxt-cloudflare:d1-parameter-plan");
|
|
3
3
|
const REQUEST_D1_SESSIONS = Symbol.for("@harlan-zw/nuxt-cloudflare:d1-sessions");
|
|
4
|
-
const
|
|
5
|
-
|
|
4
|
+
const REQUEST_D1_RECOVERING_SESSIONS = Symbol.for("@harlan-zw/nuxt-cloudflare:d1-recovering-sessions");
|
|
5
|
+
const SESSION_RESET_D1_SIGNALS = [
|
|
6
|
+
"D1_RESET_DO",
|
|
6
7
|
"D1 DB reset because its code was updated",
|
|
7
8
|
"Internal error while starting up D1 DB storage caused object to be reset",
|
|
8
9
|
"Internal error in D1 DB storage caused object to be reset",
|
|
9
|
-
"storage caused object to be reset"
|
|
10
|
-
|
|
10
|
+
"storage caused object to be reset"
|
|
11
|
+
];
|
|
12
|
+
const TRANSIENT_D1_SIGNALS = [
|
|
13
|
+
"Network connection lost",
|
|
14
|
+
"cannot resolve d1 db due to transient issue on remote node",
|
|
15
|
+
"Replica disconnected from primary"
|
|
11
16
|
];
|
|
17
|
+
const D1_STATEMENT_RESOLVER = Symbol("@harlan-zw/nuxt-cloudflare:d1-statement-resolver");
|
|
18
|
+
const D1_STATEMENT_SQL = Symbol("@harlan-zw/nuxt-cloudflare:d1-statement-sql");
|
|
19
|
+
const D1_TERMINAL_METHODS = /* @__PURE__ */ new Set(["first", "run", "all", "raw"]);
|
|
12
20
|
function consistencyConstraint(consistency) {
|
|
13
21
|
if (consistency._tag === "bookmark")
|
|
14
22
|
return consistency.bookmark;
|
|
@@ -32,6 +40,14 @@ function parseParameterCount(name, value, minimum) {
|
|
|
32
40
|
throw new TypeError(`D1 ${name} must be an integer greater than or equal to ${minimum}`);
|
|
33
41
|
return value;
|
|
34
42
|
}
|
|
43
|
+
function getD1SessionCache(requestContext, cacheKey) {
|
|
44
|
+
const existing = requestContext[cacheKey];
|
|
45
|
+
if (existing !== void 0 && !(existing instanceof Map))
|
|
46
|
+
throw new TypeError("Request D1 session cache has an invalid value");
|
|
47
|
+
const sessions = existing ?? /* @__PURE__ */ new Map();
|
|
48
|
+
requestContext[cacheKey] = sessions;
|
|
49
|
+
return sessions;
|
|
50
|
+
}
|
|
35
51
|
function defineD1ParameterPlan(input) {
|
|
36
52
|
const parametersPerItem = parseParameterCount("parametersPerItem", input.parametersPerItem, 1);
|
|
37
53
|
const reservedParameters = parseParameterCount(
|
|
@@ -86,6 +102,12 @@ function classifyD1RetryError(error) {
|
|
|
86
102
|
messages.push(current.message);
|
|
87
103
|
current = "cause" in current ? current.cause : void 0;
|
|
88
104
|
}
|
|
105
|
+
if (messages.some((message) => {
|
|
106
|
+
const normalized = message.toLowerCase();
|
|
107
|
+
return SESSION_RESET_D1_SIGNALS.some((signal) => normalized.includes(signal.toLowerCase()));
|
|
108
|
+
})) {
|
|
109
|
+
return { _tag: "session-reset" };
|
|
110
|
+
}
|
|
89
111
|
if (messages.some((message) => /busy|locked/i.test(message)))
|
|
90
112
|
return { _tag: "lock" };
|
|
91
113
|
if (messages.some((message) => {
|
|
@@ -97,20 +119,236 @@ function classifyD1RetryError(error) {
|
|
|
97
119
|
return { _tag: "permanent" };
|
|
98
120
|
}
|
|
99
121
|
function isTransientD1Error(error) {
|
|
100
|
-
|
|
122
|
+
const kind = classifyD1RetryError(error);
|
|
123
|
+
return kind._tag === "session-reset" || kind._tag === "transient";
|
|
124
|
+
}
|
|
125
|
+
function tokenizeD1Sql(sql) {
|
|
126
|
+
const tokens = [];
|
|
127
|
+
let index = 0;
|
|
128
|
+
while (index < sql.length) {
|
|
129
|
+
const char = sql[index];
|
|
130
|
+
const next = sql[index + 1];
|
|
131
|
+
if (char === "-" && next === "-") {
|
|
132
|
+
index += 2;
|
|
133
|
+
while (index < sql.length && sql[index] !== "\n")
|
|
134
|
+
index++;
|
|
135
|
+
continue;
|
|
136
|
+
}
|
|
137
|
+
if (char === "/" && next === "*") {
|
|
138
|
+
const end = sql.indexOf("*/", index + 2);
|
|
139
|
+
if (end === -1)
|
|
140
|
+
return [];
|
|
141
|
+
index = end + 2;
|
|
142
|
+
continue;
|
|
143
|
+
}
|
|
144
|
+
if (char === "'" || char === '"' || char === "`") {
|
|
145
|
+
const quote = char;
|
|
146
|
+
index++;
|
|
147
|
+
while (index < sql.length) {
|
|
148
|
+
if (sql[index] !== quote) {
|
|
149
|
+
index++;
|
|
150
|
+
continue;
|
|
151
|
+
}
|
|
152
|
+
if (sql[index + 1] === quote) {
|
|
153
|
+
index += 2;
|
|
154
|
+
continue;
|
|
155
|
+
}
|
|
156
|
+
index++;
|
|
157
|
+
break;
|
|
158
|
+
}
|
|
159
|
+
continue;
|
|
160
|
+
}
|
|
161
|
+
if (char === "[") {
|
|
162
|
+
const end = sql.indexOf("]", index + 1);
|
|
163
|
+
if (end === -1)
|
|
164
|
+
return [];
|
|
165
|
+
index = end + 1;
|
|
166
|
+
continue;
|
|
167
|
+
}
|
|
168
|
+
if (char === "(" || char === ")") {
|
|
169
|
+
tokens.push(char);
|
|
170
|
+
index++;
|
|
171
|
+
continue;
|
|
172
|
+
}
|
|
173
|
+
if (/[A-Z_]/i.test(char)) {
|
|
174
|
+
let end = index + 1;
|
|
175
|
+
while (end < sql.length && /[\w$]/.test(sql[end]))
|
|
176
|
+
end++;
|
|
177
|
+
tokens.push(sql.slice(index, end).toLowerCase());
|
|
178
|
+
index = end;
|
|
179
|
+
continue;
|
|
180
|
+
}
|
|
181
|
+
index++;
|
|
182
|
+
}
|
|
183
|
+
return tokens;
|
|
184
|
+
}
|
|
185
|
+
function d1StatementKeyword(sql) {
|
|
186
|
+
const tokens = tokenizeD1Sql(sql);
|
|
187
|
+
const first = tokens[0];
|
|
188
|
+
if (first !== "with")
|
|
189
|
+
return first;
|
|
190
|
+
let depth = 0;
|
|
191
|
+
for (const token of tokens.slice(1)) {
|
|
192
|
+
if (token === "(") {
|
|
193
|
+
depth++;
|
|
194
|
+
continue;
|
|
195
|
+
}
|
|
196
|
+
if (token === ")") {
|
|
197
|
+
depth = Math.max(0, depth - 1);
|
|
198
|
+
continue;
|
|
199
|
+
}
|
|
200
|
+
if (depth === 0 && ["select", "insert", "update", "delete", "replace"].includes(token))
|
|
201
|
+
return token;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
function isReplayableD1Sql(sql) {
|
|
205
|
+
const keyword = d1StatementKeyword(sql);
|
|
206
|
+
return keyword === "select" || keyword === "explain";
|
|
207
|
+
}
|
|
208
|
+
function resolveD1Statement(statement) {
|
|
209
|
+
const resolver = statement[D1_STATEMENT_RESOLVER];
|
|
210
|
+
return typeof resolver === "function" ? resolver : () => statement;
|
|
211
|
+
}
|
|
212
|
+
function getD1StatementSql(statement) {
|
|
213
|
+
const sql = statement[D1_STATEMENT_SQL];
|
|
214
|
+
return typeof sql === "string" ? sql : void 0;
|
|
215
|
+
}
|
|
216
|
+
function withD1ResetRecovery(database, options = {}) {
|
|
217
|
+
const maxAttempts = parseMaxAttempts(options.maxAttempts ?? 3);
|
|
218
|
+
const initialConstraint = consistencyConstraint(options.consistency ?? { _tag: "first-primary" });
|
|
219
|
+
const random = options.random ?? Math.random;
|
|
220
|
+
const sleep = options.sleep ?? defaultSleep;
|
|
221
|
+
let activeSession;
|
|
222
|
+
function currentSession() {
|
|
223
|
+
activeSession ??= database.withSession(initialConstraint);
|
|
224
|
+
return activeSession;
|
|
225
|
+
}
|
|
226
|
+
function renewSession() {
|
|
227
|
+
const bookmark = currentSession().getBookmark();
|
|
228
|
+
activeSession = database.withSession(bookmark ?? initialConstraint);
|
|
229
|
+
return activeSession;
|
|
230
|
+
}
|
|
231
|
+
async function runRecoverable(replayable, sql, run) {
|
|
232
|
+
for (let attempt = 0; ; attempt++) {
|
|
233
|
+
const outcome = await Promise.resolve().then(() => run(currentSession())).then(
|
|
234
|
+
(value) => ({ _tag: "ok", value }),
|
|
235
|
+
(error) => ({ _tag: "error", error })
|
|
236
|
+
);
|
|
237
|
+
if (outcome._tag === "ok")
|
|
238
|
+
return outcome.value;
|
|
239
|
+
const failure = classifyD1RetryError(outcome.error);
|
|
240
|
+
if (failure._tag !== "session-reset" && failure._tag !== "transient")
|
|
241
|
+
throw outcome.error;
|
|
242
|
+
const exhausted = attempt + 1 >= maxAttempts;
|
|
243
|
+
if (failure._tag === "session-reset")
|
|
244
|
+
renewSession();
|
|
245
|
+
if (!replayable || exhausted) {
|
|
246
|
+
options.onRecovery?.({
|
|
247
|
+
_tag: "stopped",
|
|
248
|
+
attempt,
|
|
249
|
+
failure,
|
|
250
|
+
reason: exhausted ? "attempts-exhausted" : "unsafe-statement",
|
|
251
|
+
sql
|
|
252
|
+
});
|
|
253
|
+
throw outcome.error;
|
|
254
|
+
}
|
|
255
|
+
options.onRecovery?.({ _tag: "retrying", attempt, failure, sql });
|
|
256
|
+
await sleep(retryDelay(attempt, random));
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
function wrapStatement(sql, parameters, owner, nativeStatement) {
|
|
260
|
+
const resolver = (session) => {
|
|
261
|
+
if (session === owner)
|
|
262
|
+
return nativeStatement;
|
|
263
|
+
const prepared = session.prepare(sql);
|
|
264
|
+
if (parameters === void 0)
|
|
265
|
+
return prepared;
|
|
266
|
+
const bind = prepared.bind;
|
|
267
|
+
return bind.apply(prepared, parameters);
|
|
268
|
+
};
|
|
269
|
+
return new Proxy(nativeStatement, {
|
|
270
|
+
get(target, property) {
|
|
271
|
+
if (property === D1_STATEMENT_RESOLVER)
|
|
272
|
+
return resolver;
|
|
273
|
+
if (property === D1_STATEMENT_SQL)
|
|
274
|
+
return sql;
|
|
275
|
+
const value = Reflect.get(target, property, target);
|
|
276
|
+
if (typeof value !== "function")
|
|
277
|
+
return value;
|
|
278
|
+
if (property === "bind") {
|
|
279
|
+
return (...values) => wrapStatement(
|
|
280
|
+
sql,
|
|
281
|
+
values,
|
|
282
|
+
owner,
|
|
283
|
+
value.apply(target, values)
|
|
284
|
+
);
|
|
285
|
+
}
|
|
286
|
+
if (typeof property === "string" && D1_TERMINAL_METHODS.has(property)) {
|
|
287
|
+
return (...args) => runRecoverable(
|
|
288
|
+
isReplayableD1Sql(sql),
|
|
289
|
+
sql,
|
|
290
|
+
(session) => {
|
|
291
|
+
const statement = resolver(session);
|
|
292
|
+
const method = Reflect.get(statement, property, statement);
|
|
293
|
+
return method.apply(statement, args);
|
|
294
|
+
}
|
|
295
|
+
);
|
|
296
|
+
}
|
|
297
|
+
return value.bind(target);
|
|
298
|
+
}
|
|
299
|
+
});
|
|
300
|
+
}
|
|
301
|
+
const facade = {
|
|
302
|
+
prepare(sql) {
|
|
303
|
+
const session = currentSession();
|
|
304
|
+
return wrapStatement(sql, void 0, session, session.prepare(sql));
|
|
305
|
+
},
|
|
306
|
+
batch(statements) {
|
|
307
|
+
const resolvers = statements.map(resolveD1Statement);
|
|
308
|
+
const replayable = statements.length > 0 && statements.every((statement) => {
|
|
309
|
+
const sql = getD1StatementSql(statement);
|
|
310
|
+
return sql !== void 0 && isReplayableD1Sql(sql);
|
|
311
|
+
});
|
|
312
|
+
return runRecoverable(
|
|
313
|
+
replayable,
|
|
314
|
+
`batch(${statements.length})`,
|
|
315
|
+
(session) => {
|
|
316
|
+
const batch = session.batch;
|
|
317
|
+
return batch.call(session, resolvers.map((resolve) => resolve(session)));
|
|
318
|
+
}
|
|
319
|
+
);
|
|
320
|
+
}
|
|
321
|
+
};
|
|
322
|
+
return new Proxy(facade, {
|
|
323
|
+
get(target, property, receiver) {
|
|
324
|
+
if (Reflect.has(target, property))
|
|
325
|
+
return Reflect.get(target, property, receiver);
|
|
326
|
+
const session = currentSession();
|
|
327
|
+
const value = session[property];
|
|
328
|
+
return typeof value === "function" ? value.bind(session) : value;
|
|
329
|
+
}
|
|
330
|
+
});
|
|
101
331
|
}
|
|
102
332
|
function getRequestD1Session(requestContext, binding, database, consistency = { _tag: "first-primary" }) {
|
|
103
|
-
const
|
|
104
|
-
if (existing !== void 0 && !(existing instanceof Map))
|
|
105
|
-
throw new TypeError("Request D1 session cache has an invalid value");
|
|
106
|
-
const sessions = existing ?? /* @__PURE__ */ new Map();
|
|
107
|
-
requestContext[REQUEST_D1_SESSIONS] = sessions;
|
|
333
|
+
const sessions = getD1SessionCache(requestContext, REQUEST_D1_SESSIONS);
|
|
108
334
|
const constraint = consistencyConstraint(consistency);
|
|
109
335
|
const key = `${binding}:${constraint}`;
|
|
110
336
|
if (!sessions.has(key))
|
|
111
337
|
sessions.set(key, database.withSession(constraint));
|
|
112
338
|
return sessions.get(key);
|
|
113
339
|
}
|
|
340
|
+
function getRecoveringRequestD1Session(requestContext, binding, database, options = {}) {
|
|
341
|
+
const consistency = options.consistency ?? { _tag: "first-primary" };
|
|
342
|
+
const key = `${binding}:${consistencyConstraint(consistency)}`;
|
|
343
|
+
const sessions = getD1SessionCache(requestContext, REQUEST_D1_RECOVERING_SESSIONS);
|
|
344
|
+
if (!sessions.has(key)) {
|
|
345
|
+
sessions.set(key, withD1ResetRecovery(database, {
|
|
346
|
+
...options,
|
|
347
|
+
consistency
|
|
348
|
+
}));
|
|
349
|
+
}
|
|
350
|
+
return sessions.get(key);
|
|
351
|
+
}
|
|
114
352
|
async function retryIdempotentD1Write(options) {
|
|
115
353
|
const maxAttempts = parseMaxAttempts(options.maxAttempts);
|
|
116
354
|
const random = options.random ?? Math.random;
|
|
@@ -125,7 +363,7 @@ async function retryIdempotentD1Write(options) {
|
|
|
125
363
|
return outcome.value;
|
|
126
364
|
lastError = outcome.error;
|
|
127
365
|
const kind = classifyD1RetryError(outcome.error);
|
|
128
|
-
const retryable = kind._tag === "lock" || kind._tag === "transient" && options.safety._tag === "replay-safe";
|
|
366
|
+
const retryable = kind._tag === "lock" || (kind._tag === "session-reset" || kind._tag === "transient") && options.safety._tag === "replay-safe";
|
|
129
367
|
if (!retryable || attempt + 1 >= maxAttempts)
|
|
130
368
|
throw outcome.error;
|
|
131
369
|
await sleep(retryDelay(attempt, random));
|
|
@@ -133,4 +371,4 @@ async function retryIdempotentD1Write(options) {
|
|
|
133
371
|
throw lastError;
|
|
134
372
|
}
|
|
135
373
|
|
|
136
|
-
export { D1_MAX_BOUND_PARAMETERS, assertD1BoundParameters, chunkD1Items, classifyD1RetryError, defineD1ParameterPlan, getRequestD1Session, isTransientD1Error, retryIdempotentD1Write };
|
|
374
|
+
export { D1_MAX_BOUND_PARAMETERS, assertD1BoundParameters, chunkD1Items, classifyD1RetryError, defineD1ParameterPlan, getRecoveringRequestD1Session, getRequestD1Session, isReplayableD1Sql, isTransientD1Error, retryIdempotentD1Write, withD1ResetRecovery };
|
package/dist/module.json
CHANGED
package/dist/module.mjs
CHANGED
|
@@ -216,7 +216,7 @@ function setupCloudflareModule(options, nuxt) {
|
|
|
216
216
|
);
|
|
217
217
|
let bindingTypeSignature;
|
|
218
218
|
if (options.bindingTypes !== false) {
|
|
219
|
-
addTypeTemplate({
|
|
219
|
+
const bindingTypesTemplate = addTypeTemplate({
|
|
220
220
|
filename: "types/cloudflare-bindings.d.ts",
|
|
221
221
|
getContents: async () => {
|
|
222
222
|
const { prepareCloudflareBindingTypes } = await import('./chunks/binding-types.mjs');
|
|
@@ -231,7 +231,10 @@ function setupCloudflareModule(options, nuxt) {
|
|
|
231
231
|
bindingTypeSignature = artifact.signature;
|
|
232
232
|
return artifact.content;
|
|
233
233
|
}
|
|
234
|
-
}, { nitro: true
|
|
234
|
+
}, { nitro: true });
|
|
235
|
+
nuxt.hook("prepare:types", ({ references }) => {
|
|
236
|
+
references.push({ path: bindingTypesTemplate.dst });
|
|
237
|
+
});
|
|
235
238
|
}
|
|
236
239
|
configure();
|
|
237
240
|
nuxt.hook("modules:done", () => {
|