@bastani/atomic-storage-libsql 0.9.88 → 0.9.89-alpha.1
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/CHANGELOG.md +8 -0
- package/libsql.js +258 -27
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,14 @@
|
|
|
2
2
|
|
|
3
3
|
## [Unreleased]
|
|
4
4
|
|
|
5
|
+
## [0.9.89-alpha.1] - 2026-11-18
|
|
6
|
+
|
|
7
|
+
### Fixed
|
|
8
|
+
|
|
9
|
+
- A write that follows an outage on a libSQL server (sqld) or Turso database no longer waits for the adapter's next timed resend of the close of a stream the outage cut while it held the write lock. The adapter sent such a close again only on its backoff timer, 250 ms and then twice as long each time, so an outage longer than a wait left the close for the next one, up to seconds after the server was back, while the next write waited on the server for the lock the stream still held. Now every request sends the kept closes ahead of itself. A write waits for them, so that on a server that answers them the close arrives first and frees the lock; a request made only of plain `SELECT` statements does not wait, and any other statement, including `WITH`, `PRAGMA` and `EXPLAIN` queries, is treated as a possible write and may share the same bounded wait. Writes wait at most 2 seconds in all for closes the server takes but does not answer, then go ahead and wait for those closes no more, though a close kept later is waited for again; a caller's abort ends the wait at once. A close the server refuses because the outage lost the answer to a request it had already run still frees nothing: the lock clears when the server expires the stream. The timer still sends the closes while the database sends nothing else, and only its own unanswered resends lengthen its wait, once each. Against sqld after a 300 ms outage, the next write committed 4–14 ms after the server was back instead of 455–466 ms ([#5114](https://github.com/bastani-inc/atomic/issues/5114)).
|
|
10
|
+
- Fixed a worker host crashing after a libSQL server rolled back a write batch. Batch execution now observes every statement, COMMIT and ROLLBACK result, so later timeout rejections cannot escape the reported storage failure. A batch whose COMMIT never ran is no longer reported as successful ([#4768](https://github.com/bastani-inc/atomic/issues/4768))
|
|
11
|
+
- Fixed `run`, `get` and `all` statements failing with `Storage unavailable` on `ws:` and `wss:` URLs. These statements now use WebSockets instead of attempting HTTP requests ([#4768](https://github.com/bastani-inc/atomic/issues/4768))
|
|
12
|
+
|
|
5
13
|
## [0.9.88] - 2026-11-16
|
|
6
14
|
|
|
7
15
|
### Changed
|
package/libsql.js
CHANGED
|
@@ -50,7 +50,8 @@ const REQUEST_TIMEOUT_MS = 30_000;
|
|
|
50
50
|
* The wait before the first resend of the close of a stream abandoned in an outage (#5114); each later wait doubles, up
|
|
51
51
|
* to `ABANDONED_STREAM_CLOSE_LAST_WAIT_MS`. A stream the server keeps holds its open transaction, and with it the
|
|
52
52
|
* database's write lock, until the server expires it: every writer waits for the lock meanwhile, this process's and
|
|
53
|
-
* every other's. A close the server answers, whatever the answer, is done.
|
|
53
|
+
* every other's. A close the server answers, whatever the answer, is done. Each request of the same client also sends
|
|
54
|
+
* the closes ahead of itself, whatever the wait (`AbandonedStreams.start` and `AbandonedStreams.beforeWrite`).
|
|
54
55
|
*/
|
|
55
56
|
const ABANDONED_STREAM_CLOSE_FIRST_WAIT_MS = 250;
|
|
56
57
|
/** The longest wait between two resends of abandoned stream closes. */
|
|
@@ -62,6 +63,13 @@ const ABANDONED_STREAM_CLOSE_LAST_WAIT_MS = 8_000;
|
|
|
62
63
|
const ABANDONED_STREAM_CLOSE_MAX_AGE_MS = 5 * 60_000;
|
|
63
64
|
/** How long one resend of an abandoned stream's close may go unanswered; a later resend tries again. */
|
|
64
65
|
const ABANDONED_STREAM_CLOSE_TIMEOUT_MS = 5_000;
|
|
66
|
+
/**
|
|
67
|
+
* How long writes wait, in all, for a round of abandoned stream closes the server takes but does not answer. A server
|
|
68
|
+
* that is reachable answers a close at once, without waiting for any lock; one that has not answered by then may never
|
|
69
|
+
* answer, and a write that goes ahead waits on the server for the lock as it would have anyway. Writes wait no more
|
|
70
|
+
* until the server answers a close again.
|
|
71
|
+
*/
|
|
72
|
+
const ABANDONED_STREAM_CLOSE_WRITE_WAIT_MS = 2_000;
|
|
65
73
|
/** The most abandoned stream closes kept for resending; the oldest is dropped past it, its stream long expired. */
|
|
66
74
|
const MAX_ABANDONED_STREAM_CLOSES = 16;
|
|
67
75
|
|
|
@@ -124,6 +132,53 @@ async function closesNoStream(request) {
|
|
|
124
132
|
return closesStream(body, true);
|
|
125
133
|
}
|
|
126
134
|
|
|
135
|
+
/**
|
|
136
|
+
* Whether `request`, a Hrana pipeline or cursor request, may take the database's write lock, so it would wait on the
|
|
137
|
+
* server behind a lock an abandoned stream holds: it runs a statement that is not one `SELECT`, a sequence of
|
|
138
|
+
* statements, or SQL it stored earlier. A request without a body, such as a version check, takes no lock; one whose body
|
|
139
|
+
* is not JSON counts as a write.
|
|
140
|
+
* @param {Request} request an unread copy
|
|
141
|
+
*/
|
|
142
|
+
async function mayWrite(request) {
|
|
143
|
+
const text = await request.text();
|
|
144
|
+
if (text === "") return false;
|
|
145
|
+
/** @type {{ requests?: unknown, batch?: { steps?: unknown } }} */
|
|
146
|
+
let body;
|
|
147
|
+
try {
|
|
148
|
+
body = JSON.parse(text);
|
|
149
|
+
} catch {
|
|
150
|
+
return true;
|
|
151
|
+
}
|
|
152
|
+
/** @type {unknown[]} */
|
|
153
|
+
const statements = [];
|
|
154
|
+
const steps = (/** @type {unknown} */ batch) =>
|
|
155
|
+
Array.isArray(batch) ? batch.map((step) => /** @type {{ stmt?: unknown }} */ (step)?.stmt) : [];
|
|
156
|
+
for (const each of Array.isArray(body?.requests) ? body.requests : []) {
|
|
157
|
+
const { type, stmt, batch } = /** @type {{ type?: unknown, stmt?: unknown, batch?: { steps?: unknown } }} */ (each ?? {});
|
|
158
|
+
if (type === "sequence") return true;
|
|
159
|
+
if (type === "execute") statements.push(stmt);
|
|
160
|
+
else if (type === "batch") statements.push(...steps(batch?.steps));
|
|
161
|
+
}
|
|
162
|
+
statements.push(...steps(body?.batch?.steps));
|
|
163
|
+
return statements.some((stmt) => !readsOnly(/** @type {{ sql?: unknown }} */ (stmt)?.sql));
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** The keyword of a statement that only reads. */
|
|
167
|
+
const READ_KEYWORD = /SELECT\b/iy;
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Whether `sql` is one `SELECT`, which never takes the write lock. SQL that is not text, as a statement stored earlier
|
|
171
|
+
* leaves it, may write.
|
|
172
|
+
* @param {unknown} sql
|
|
173
|
+
*/
|
|
174
|
+
function readsOnly(sql) {
|
|
175
|
+
if (typeof sql !== "string") return false;
|
|
176
|
+
const start = firstTokenStart(sql);
|
|
177
|
+
if (start === -1) return false;
|
|
178
|
+
READ_KEYWORD.lastIndex = start;
|
|
179
|
+
return READ_KEYWORD.test(sql) && isOneStatement(sql);
|
|
180
|
+
}
|
|
181
|
+
|
|
127
182
|
/** The answer a server gives a request that only closes a stream. */
|
|
128
183
|
function closedResponse() {
|
|
129
184
|
return new Response(JSON.stringify({ baton: null, base_url: null, results: [{ type: "ok", response: { type: "close" } }] }), {
|
|
@@ -136,15 +191,27 @@ function closedResponse() {
|
|
|
136
191
|
* The closes of streams this client abandoned that never reached the server, sent again until the server answers one.
|
|
137
192
|
* The HTTP client sends a stream's close once, when a request of the stream fails; in an outage that close fails too,
|
|
138
193
|
* and the server keeps the stream, with its open transaction and the write lock it holds, for the stream's whole
|
|
139
|
-
* lifetime. Sending the close again as soon as the server is reachable ends the transaction there and frees the lock
|
|
194
|
+
* lifetime. Sending the close again as soon as the server is reachable ends the transaction there and frees the lock:
|
|
195
|
+
* a timer sends the closes with growing waits while the client sends nothing else, and each request the client sends
|
|
196
|
+
* sends them ahead of itself. A write waits for them (`beforeWrite`), so it does not queue on the server behind a lock
|
|
197
|
+
* its own client's abandoned stream holds; any other request goes at once.
|
|
140
198
|
*/
|
|
141
199
|
class AbandonedStreams {
|
|
142
200
|
/** @type {{ url: string, headers: [string, string][], body: ArrayBuffer, since: number }[]} */
|
|
143
201
|
pending = [];
|
|
144
202
|
/** @type {ReturnType<typeof setTimeout> | undefined} */
|
|
145
203
|
timer;
|
|
146
|
-
/**
|
|
204
|
+
/** Whether a round the timer started, or joined, is under way: the timer plans the next one when it ends. */
|
|
205
|
+
timerRound = false;
|
|
206
|
+
/** @type {Promise<boolean> | undefined} */
|
|
147
207
|
sending;
|
|
208
|
+
/** When the writes waiting for the round under way stop waiting for it. @type {number | undefined} */
|
|
209
|
+
waitUntil;
|
|
210
|
+
/**
|
|
211
|
+
* Whether a round left the writes waiting for it unanswered: writes wait no more for the closes kept then, until one is
|
|
212
|
+
* answered, given up or joined by a newly kept close.
|
|
213
|
+
*/
|
|
214
|
+
stalled = false;
|
|
148
215
|
wait = ABANDONED_STREAM_CLOSE_FIRST_WAIT_MS;
|
|
149
216
|
closed = false;
|
|
150
217
|
|
|
@@ -156,30 +223,83 @@ class AbandonedStreams {
|
|
|
156
223
|
const body = await request.arrayBuffer();
|
|
157
224
|
if (this.closed || !closesStream(new Uint8Array(body))) return;
|
|
158
225
|
this.pending.push({ url: request.url, headers: [...request.headers], body, since: Date.now() });
|
|
226
|
+
// A stall belongs to the closes it was found for: a newly kept close, whose stream may hold the lock now, is waited for.
|
|
227
|
+
this.stalled = false;
|
|
159
228
|
if (this.pending.length > MAX_ABANDONED_STREAM_CLOSES) this.pending.shift();
|
|
160
229
|
this.schedule();
|
|
161
230
|
}
|
|
162
231
|
|
|
163
|
-
/**
|
|
232
|
+
/**
|
|
233
|
+
* Sends the kept closes again after the current wait, unless a resend is already planned or the timer's round is under
|
|
234
|
+
* way. A round the timer started that leaves a close unanswered doubles the wait before the next one, once; a round a
|
|
235
|
+
* request started, which the timer joined, leaves it as it is.
|
|
236
|
+
*/
|
|
164
237
|
schedule() {
|
|
165
|
-
if (this.timer !== undefined || this.pending.length === 0) return;
|
|
238
|
+
if (this.timer !== undefined || this.timerRound || this.pending.length === 0) return;
|
|
166
239
|
this.timer = setTimeout(() => {
|
|
167
240
|
this.timer = undefined;
|
|
168
|
-
|
|
241
|
+
this.timerRound = true;
|
|
242
|
+
const joined = this.sending !== undefined;
|
|
243
|
+
void this.send().then((answered) => {
|
|
244
|
+
this.timerRound = false;
|
|
245
|
+
if (!answered && !joined) this.wait = Math.min(this.wait * 2, ABANDONED_STREAM_CLOSE_LAST_WAIT_MS);
|
|
246
|
+
this.schedule();
|
|
247
|
+
});
|
|
169
248
|
}, this.wait);
|
|
170
249
|
// A close waiting to be sent again never keeps the process alive.
|
|
171
250
|
this.timer.unref();
|
|
172
251
|
}
|
|
173
252
|
|
|
253
|
+
/** Sends the kept closes ahead of a request that does not wait for them, unless a round is under way. */
|
|
254
|
+
start() {
|
|
255
|
+
if (this.pending.length > 0) void this.send();
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* Sends the kept closes ahead of a write, unless a round is under way, and waits for the round. A server reachable
|
|
260
|
+
* again would otherwise take the write while an abandoned stream still holds the write lock, and the write would wait
|
|
261
|
+
* for that lock until the next timed resend. The writes waiting for one round wait for it at most
|
|
262
|
+
* `ABANDONED_STREAM_CLOSE_WRITE_WAIT_MS` in all; a round still unanswered then stalls the closes, and no write waits
|
|
263
|
+
* for them again until the server answers one, they are given up, or another close is kept. A round that fails at once costs nothing: the write finds the server
|
|
264
|
+
* unreachable on its own. Rejects with the reason of `signal` when it aborts first; the round goes on.
|
|
265
|
+
* @param {AbortSignal} signal
|
|
266
|
+
*/
|
|
267
|
+
async beforeWrite(signal) {
|
|
268
|
+
if (this.pending.length === 0) return;
|
|
269
|
+
signal.throwIfAborted();
|
|
270
|
+
const round = this.send();
|
|
271
|
+
if (this.stalled) return;
|
|
272
|
+
this.waitUntil ??= performance.now() + ABANDONED_STREAM_CLOSE_WRITE_WAIT_MS;
|
|
273
|
+
const left = this.waitUntil - performance.now();
|
|
274
|
+
/** @type {ReturnType<typeof setTimeout> | undefined} */
|
|
275
|
+
let timer;
|
|
276
|
+
/** @type {(() => void) | undefined} */
|
|
277
|
+
let abort;
|
|
278
|
+
try {
|
|
279
|
+
const late = await new Promise((resolve, reject) => {
|
|
280
|
+
abort = () => reject(signal.reason);
|
|
281
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
282
|
+
timer = setTimeout(() => resolve(true), Math.max(left, 0));
|
|
283
|
+
void round.then(() => resolve(false));
|
|
284
|
+
});
|
|
285
|
+
if (late && this.sending === round) this.stalled = true;
|
|
286
|
+
} finally {
|
|
287
|
+
clearTimeout(timer);
|
|
288
|
+
if (abort !== undefined) signal.removeEventListener("abort", abort);
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
|
|
174
292
|
/**
|
|
175
|
-
* Sends each kept close again, in order, until one goes unanswered
|
|
176
|
-
*
|
|
177
|
-
*
|
|
293
|
+
* Sends each kept close again, in order, until one goes unanswered; an answered close is done, whatever it says, and
|
|
294
|
+
* resets the wait and any stall. A close older than `ABANDONED_STREAM_CLOSE_MAX_AGE_MS` is given up. Joins the round
|
|
295
|
+
* under way, if any. Resolves whether every kept close was answered.
|
|
296
|
+
* @returns {Promise<boolean>}
|
|
178
297
|
*/
|
|
179
298
|
send() {
|
|
180
299
|
this.sending ??= (async () => {
|
|
181
300
|
const oldest = Date.now() - ABANDONED_STREAM_CLOSE_MAX_AGE_MS;
|
|
182
301
|
this.pending = this.pending.filter((close) => close.since > oldest);
|
|
302
|
+
if (this.pending.length === 0) this.stalled = false;
|
|
183
303
|
while (this.pending.length > 0) {
|
|
184
304
|
const [close] = this.pending;
|
|
185
305
|
try {
|
|
@@ -191,14 +311,16 @@ class AbandonedStreams {
|
|
|
191
311
|
});
|
|
192
312
|
await response.arrayBuffer().catch(() => {});
|
|
193
313
|
} catch {
|
|
194
|
-
|
|
195
|
-
return;
|
|
314
|
+
return false;
|
|
196
315
|
}
|
|
197
316
|
this.wait = ABANDONED_STREAM_CLOSE_FIRST_WAIT_MS;
|
|
317
|
+
this.stalled = false;
|
|
198
318
|
this.pending = this.pending.filter((kept) => kept !== close);
|
|
199
319
|
}
|
|
320
|
+
return true;
|
|
200
321
|
})().finally(() => {
|
|
201
322
|
this.sending = undefined;
|
|
323
|
+
this.waitUntil = undefined;
|
|
202
324
|
});
|
|
203
325
|
return this.sending;
|
|
204
326
|
}
|
|
@@ -213,8 +335,9 @@ class AbandonedStreams {
|
|
|
213
335
|
}
|
|
214
336
|
|
|
215
337
|
/**
|
|
216
|
-
* `fetch` that adds `headers` to every request the libSQL HTTP client sends,
|
|
217
|
-
* `REQUEST_TIMEOUT_MS`, and hands a stream's close
|
|
338
|
+
* `fetch` that adds `headers` to every request the libSQL HTTP client sends, sends the closes `abandoned` keeps ahead of
|
|
339
|
+
* it (a write waits for them), abandons a request after `REQUEST_TIMEOUT_MS`, wait included, and hands a stream's close
|
|
340
|
+
* that failed to `abandoned` for resending.
|
|
218
341
|
* @param {[string, string][]} headers
|
|
219
342
|
* @param {AbandonedStreams} abandoned
|
|
220
343
|
* @returns {(input: RequestInfo | URL, init?: RequestInit) => Promise<Response>}
|
|
@@ -226,8 +349,14 @@ function fetchWith(headers, abandoned) {
|
|
|
226
349
|
const copy = request.clone();
|
|
227
350
|
if (await closesNoStream(request.clone())) return closedResponse();
|
|
228
351
|
const timeout = AbortSignal.timeout(REQUEST_TIMEOUT_MS);
|
|
352
|
+
// The caller's signal: the one `init` passes, or else the one `input`, a request, carries.
|
|
353
|
+
const signal = AbortSignal.any([request.signal, timeout]);
|
|
354
|
+
if (abandoned.pending.length > 0) {
|
|
355
|
+
if (await mayWrite(request.clone())) await abandoned.beforeWrite(signal);
|
|
356
|
+
else abandoned.start();
|
|
357
|
+
}
|
|
229
358
|
try {
|
|
230
|
-
return await fetch(request, { signal
|
|
359
|
+
return await fetch(request, { signal });
|
|
231
360
|
} catch (error) {
|
|
232
361
|
await abandoned.failed(copy).catch(() => {});
|
|
233
362
|
throw error;
|
|
@@ -363,7 +492,7 @@ function hranaCode(hrana, error) {
|
|
|
363
492
|
* answer was lost may have run, so its failure is the caller's, as it is for a statement on a stream of its own.
|
|
364
493
|
*/
|
|
365
494
|
class ReusedStream {
|
|
366
|
-
/** @type {import("@libsql/hrana-client").
|
|
495
|
+
/** @type {import("@libsql/hrana-client").Stream | undefined} */
|
|
367
496
|
stream;
|
|
368
497
|
openedAt = 0;
|
|
369
498
|
usedAt = 0;
|
|
@@ -373,7 +502,7 @@ class ReusedStream {
|
|
|
373
502
|
/**
|
|
374
503
|
* @param {typeof import("@libsql/hrana-client")} hrana
|
|
375
504
|
* @param {typeof import("@libsql/core/api").LibsqlError} LibsqlError
|
|
376
|
-
* @param {() => import("@libsql/hrana-client").
|
|
505
|
+
* @param {() => import("@libsql/hrana-client").Client} client
|
|
377
506
|
*/
|
|
378
507
|
constructor(hrana, LibsqlError, client) {
|
|
379
508
|
this.hrana = hrana;
|
|
@@ -462,6 +591,101 @@ class ReusedStream {
|
|
|
462
591
|
}
|
|
463
592
|
}
|
|
464
593
|
|
|
594
|
+
/**
|
|
595
|
+
* @template T
|
|
596
|
+
* @param {Promise<T>} promise
|
|
597
|
+
* @returns {Promise<{ ok: true, value: T } | { ok: false, error: unknown }>}
|
|
598
|
+
*/
|
|
599
|
+
function settle(promise) {
|
|
600
|
+
return promise.then(
|
|
601
|
+
(value) => ({ ok: true, value }),
|
|
602
|
+
(error) => ({ ok: false, error }),
|
|
603
|
+
);
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
/**
|
|
607
|
+
* @param {typeof import("@libsql/hrana-client")} hrana
|
|
608
|
+
* @param {typeof import("@libsql/core/api")} api
|
|
609
|
+
* @param {import("@libsql/hrana-client").Client} client
|
|
610
|
+
* @param {readonly import("@bastani/atomic/storage").SqliteStatement[]} batched
|
|
611
|
+
* @returns {Promise<import("@bastani/atomic/storage").SqliteDriverResult[]>}
|
|
612
|
+
*/
|
|
613
|
+
async function writeBatch(hrana, api, client, batched) {
|
|
614
|
+
/** @param {unknown} error */
|
|
615
|
+
const mapped = (error) =>
|
|
616
|
+
error instanceof hrana.ClientError
|
|
617
|
+
? new api.LibsqlError(error.message, hranaCode(hrana, error), undefined, undefined, error)
|
|
618
|
+
: error;
|
|
619
|
+
const version = await client.getVersion();
|
|
620
|
+
const stream = client.openStream();
|
|
621
|
+
const { began, ran, committed, executed } = (() => {
|
|
622
|
+
try {
|
|
623
|
+
const batch = stream.batch(false);
|
|
624
|
+
const inTransaction = () => hrana.BatchCond.not(hrana.BatchCond.isAutocommit(batch));
|
|
625
|
+
const begin = batch.step();
|
|
626
|
+
const began = settle(begin.run("BEGIN IMMEDIATE"));
|
|
627
|
+
let last = begin;
|
|
628
|
+
const ran = batched.map(({ sql, params }) => {
|
|
629
|
+
const step = batch.step().condition(hrana.BatchCond.ok(last));
|
|
630
|
+
if (version >= 3) step.condition(inTransaction());
|
|
631
|
+
const statement = new hrana.Stmt(sql);
|
|
632
|
+
statement.bindIndexes(/** @type {import("@libsql/hrana-client").InValue[]} */ ([...params]));
|
|
633
|
+
last = step;
|
|
634
|
+
return settle(step.query(statement));
|
|
635
|
+
});
|
|
636
|
+
const commit = batch.step().condition(hrana.BatchCond.ok(last));
|
|
637
|
+
if (version >= 3) commit.condition(inTransaction());
|
|
638
|
+
const committed = settle(commit.run("COMMIT"));
|
|
639
|
+
void settle(batch.step().condition(hrana.BatchCond.not(hrana.BatchCond.ok(commit))).run("ROLLBACK"));
|
|
640
|
+
return { began, ran, committed, executed: batch.execute() };
|
|
641
|
+
} finally {
|
|
642
|
+
stream.closeGracefully();
|
|
643
|
+
}
|
|
644
|
+
})();
|
|
645
|
+
try {
|
|
646
|
+
await executed;
|
|
647
|
+
} catch (error) {
|
|
648
|
+
throw mapped(error);
|
|
649
|
+
}
|
|
650
|
+
const beginning = await began;
|
|
651
|
+
if (!beginning.ok) throw mapped(beginning.error);
|
|
652
|
+
/** @type {import("@bastani/atomic/storage").SqliteDriverResult[]} */
|
|
653
|
+
const results = [];
|
|
654
|
+
for (const [index, outcome] of (await Promise.all(ran)).entries()) {
|
|
655
|
+
if (!outcome.ok) {
|
|
656
|
+
const failure = mapped(outcome.error);
|
|
657
|
+
if (!(failure instanceof api.LibsqlError)) throw failure;
|
|
658
|
+
throw new api.LibsqlBatchError(
|
|
659
|
+
failure.message,
|
|
660
|
+
index,
|
|
661
|
+
failure.code,
|
|
662
|
+
failure.extendedCode,
|
|
663
|
+
failure.rawCode,
|
|
664
|
+
outcome.error instanceof Error ? outcome.error : undefined,
|
|
665
|
+
);
|
|
666
|
+
}
|
|
667
|
+
if (outcome.value === undefined)
|
|
668
|
+
throw new api.LibsqlBatchError(
|
|
669
|
+
"Statement in a batch was not executed, probably because the transaction has been rolled back",
|
|
670
|
+
index,
|
|
671
|
+
"TRANSACTION_CLOSED",
|
|
672
|
+
);
|
|
673
|
+
results.push({
|
|
674
|
+
columns: outcome.value.columnNames.map((name) => name ?? ""),
|
|
675
|
+
rows: /** @type {import("@bastani/atomic/storage").SqliteDriverResult["rows"]} */ (outcome.value.rows),
|
|
676
|
+
changes: outcome.value.affectedRowCount,
|
|
677
|
+
});
|
|
678
|
+
}
|
|
679
|
+
const commitment = await committed;
|
|
680
|
+
if (!commitment.ok) throw mapped(commitment.error);
|
|
681
|
+
if (commitment.value === undefined)
|
|
682
|
+
throw new api.LibsqlError(
|
|
683
|
+
"The batch did not execute its COMMIT; its transaction ended before completion could be confirmed",
|
|
684
|
+
"TRANSACTION_CLOSED",
|
|
685
|
+
);
|
|
686
|
+
return results;
|
|
687
|
+
}
|
|
688
|
+
|
|
465
689
|
/**
|
|
466
690
|
* @param {() => Promise<import("@libsql/client").Client | import("@libsql/client").Transaction>} connection
|
|
467
691
|
* @param {<T>(operation: () => Promise<T>) => Promise<T>} watch
|
|
@@ -890,18 +1114,19 @@ export async function openLibsqlDatabase({ url, authToken, namespace, headers })
|
|
|
890
1114
|
});
|
|
891
1115
|
// The Hrana client whose stream statements outside a transaction reuse, made on first use inside a driver call, as the
|
|
892
1116
|
// client is, so the facade redacts credentials from a failure to read the URL.
|
|
893
|
-
/** @type {import("@libsql/hrana-client").
|
|
1117
|
+
/** @type {import("@libsql/hrana-client").Client | undefined} */
|
|
894
1118
|
let hranaClient;
|
|
895
1119
|
/** @type {ReusedStream | undefined} */
|
|
896
1120
|
let reused;
|
|
897
1121
|
/** The requests of the reused stream's client not yet answered, which a close waits for. @type {Set<Promise<Response>>} */
|
|
898
1122
|
const streamRequests = new Set();
|
|
899
|
-
const
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
1123
|
+
const remote = () => {
|
|
1124
|
+
const [hrana, { expandConfig }, { encodeBaseUrl }] = /** @type {NonNullable<typeof protocol>} */ (protocol);
|
|
1125
|
+
if (hranaClient === undefined || hranaClient.closed) {
|
|
1126
|
+
const config = expandConfig({ url, authToken }, true);
|
|
1127
|
+
const base = encodeBaseUrl(config.scheme, config.authority, config.path);
|
|
1128
|
+
if (config.scheme === "ws" || config.scheme === "wss") hranaClient = hrana.openWs(base, config.authToken);
|
|
1129
|
+
else {
|
|
905
1130
|
const send = fetchWith(added, abandoned);
|
|
906
1131
|
/** @type {(input: RequestInfo | URL, init?: RequestInit) => Promise<Response>} */
|
|
907
1132
|
const tracked = (input, init) => {
|
|
@@ -910,11 +1135,16 @@ export async function openLibsqlDatabase({ url, authToken, namespace, headers })
|
|
|
910
1135
|
void sent.finally(() => streamRequests.delete(sent)).catch(() => {});
|
|
911
1136
|
return sent;
|
|
912
1137
|
};
|
|
913
|
-
hranaClient = hrana.openHttp(
|
|
914
|
-
hranaClient.intMode = "bigint";
|
|
1138
|
+
hranaClient = hrana.openHttp(base, config.authToken, tracked);
|
|
915
1139
|
}
|
|
916
|
-
|
|
917
|
-
}
|
|
1140
|
+
hranaClient.intMode = "bigint";
|
|
1141
|
+
}
|
|
1142
|
+
return hranaClient;
|
|
1143
|
+
};
|
|
1144
|
+
const shared = async () => {
|
|
1145
|
+
if (protocol === undefined) return undefined;
|
|
1146
|
+
const [hrana, , , { LibsqlError }] = protocol;
|
|
1147
|
+
return (reused ??= new ReusedStream(hrana, LibsqlError, remote));
|
|
918
1148
|
};
|
|
919
1149
|
// A local statement that fails part way, as a write does when another process holds the lock past the busy timeout,
|
|
920
1150
|
// stays active on its connection: the driver resets and finalizes a statement only when it is garbage collected.
|
|
@@ -992,6 +1222,7 @@ export async function openLibsqlDatabase({ url, authToken, namespace, headers })
|
|
|
992
1222
|
// server's batch counts against this process's writes in flight to that server, unless it has priority.
|
|
993
1223
|
batch: (batched, options) => {
|
|
994
1224
|
const send = async () => {
|
|
1225
|
+
if (protocol !== undefined) return writeBatch(protocol[0], protocol[3], remote(), batched);
|
|
995
1226
|
const results = await (await connection()).batch(
|
|
996
1227
|
batched.map(({ sql, params }) => ({ sql, args: [...params] })),
|
|
997
1228
|
"write",
|
package/package.json
CHANGED