Skip to content
Closed
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
132 changes: 77 additions & 55 deletions src/js/bun/sql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,13 +34,17 @@ enum ReservedConnectionState {
acceptQueries = 1 << 0,
closed = 1 << 1,
released = 1 << 2,
/// transaction.close() accepted its arguments: the transaction ends in ROLLBACK, never in COMMIT.
closing = 1 << 3,
}

interface TransactionState {
connectionState: ReservedConnectionState;
reject: (err: Error) => void;
storedError?: Error | null | undefined;
queries: Set<Query<any, any>>;
/// The ROLLBACK of a closing transaction. close() and the transaction runner share it.
rollback?: Promise<void> | null;
}

/// Bound as `this` to both callbacks of a reserve({ signal }) call, so each can
Expand All @@ -63,6 +67,21 @@ function settleReservedTransaction(
settle(value);
}

function onPendingWorkSettled(timer: ReturnType<typeof setTimeout>, resolve: () => void) {
clearTimeout(timer);
resolve();
}

/// The grace period of close({ timeout }): resolves once `pending` has settled or after `timeout` seconds.
function waitForPendingWork(pending: PromiseLike<unknown>[], timeout: number): Promise<void> {
const { promise, resolve } = Promise.withResolvers<void>();
const timer = setTimeout(resolve, timeout * 1000);
Comment thread
robobun marked this conversation as resolved.
Resolved
timer.unref(); // dont block the event loop
// allSettled: one rejected query must not cut the grace period short for the rest
Promise.allSettled(pending).then(onPendingWorkSettled.bind(null, timer, resolve));
return promise;
}

function adapterFromOptions(options: Bun.SQL.__internal.DefinedOptions): Adapter | ListenableAdapter {
switch (options.adapter) {
case "postgres":
Expand Down Expand Up @@ -258,6 +277,23 @@ const SQL = function SQL(
}
}

/// Rolls a closing transaction back. Declared outside onTransactionConnected: no closure per transaction.
async function rollbackTransaction(
state: TransactionState,
pooledConnection: PooledConnection,
before: string | null,
rollback: string,
) {
for (const query of state.queries) {
query.cancel();
}
if (before) {
await unsafeQueryFromTransaction(before, [], pooledConnection, state.queries);
}
await unsafeQueryFromTransaction(rollback, [], pooledConnection, state.queries);
Comment thread
robobun marked this conversation as resolved.
Resolved
state.connectionState |= ReservedConnectionState.closed;
}

function onTransactionDisconnected(this: TransactionState, err: Error) {
const reject = this.reject;
this.connectionState |= ReservedConnectionState.closed;
Expand Down Expand Up @@ -493,39 +529,23 @@ const SQL = function SQL(
throw $ERR_INVALID_ARG_VALUE("options.timeout", timeout, "must be a non-negative integer less than 2^31");
Comment thread
robobun marked this conversation as resolved.
Resolved
}
if (timeout > 0 && (reserveQueries.size > 0 || reservedTransaction.size > 0)) {
const { promise, resolve } = Promise.withResolvers();
// race all queries vs timeout
const pending_queries = Array.from(reserveQueries);
const pending_transactions = Array.from(reservedTransaction);
const timer = setTimeout(() => {
state.connectionState |= ReservedConnectionState.closed;
for (const query of reserveQueries) {
(query as Query<any, any>).cancel();
}
state.connectionState |= ReservedConnectionState.closed;
pooledConnection.close();

resolve();
}, timeout * 1000);
timer.unref(); // dont block the event loop
Promise.all([Promise.all(pending_queries), Promise.all(pending_transactions)]).finally(() => {
clearTimeout(timer);
resolve();
});
return promise;
await waitForPendingWork([...reserveQueries, ...reservedTransaction], timeout);
// release() or a disconnect may have ended the reservation while we waited
if (state.connectionState & ReservedConnectionState.closed) return;
}
}
state.connectionState |= ReservedConnectionState.closed;
for (const query of reserveQueries) {
(query as Query<any, any>).cancel();
}

// the close handler attached above returns the pool slot
pooledConnection.close();
Comment thread
robobun marked this conversation as resolved.
Resolved

return Promise.$resolve(undefined);
};
reserved_sql.release = () => {
if (state.connectionState & ReservedConnectionState.released) {
// closed but not released: close() is closing the socket (TLS defers it), and the close handler returns the slot
if (state.connectionState & (ReservedConnectionState.released | ReservedConnectionState.closed)) {
Comment thread
robobun marked this conversation as resolved.
Resolved
return Promise.$resolve(undefined);
}
// just release the connection back to the pool
Expand Down Expand Up @@ -604,7 +624,7 @@ const SQL = function SQL(
};

let savepoints = 0;
let transactionSavepoints = new Set();
let transactionSavepoints = new Set<Promise<unknown>>();

let BEGIN_COMMAND: string;
let ROLLBACK_COMMAND: string;
Expand Down Expand Up @@ -778,37 +798,26 @@ const SQL = function SQL(
}

if (timeout > 0 && (transactionQueries.size > 0 || transactionSavepoints.size > 0)) {
const { promise, resolve } = Promise.withResolvers();
// race all queries vs timeout
const pending_queries = Array.from(transactionQueries);
const pending_savepoints = Array.from(transactionSavepoints);
const timer = setTimeout(async () => {
for (const query of transactionQueries) {
(query as Query<any, any>).cancel();
}
if (BEFORE_COMMIT_OR_ROLLBACK_COMMAND) {
await run_internal_transaction_sql(BEFORE_COMMIT_OR_ROLLBACK_COMMAND);
}
await run_internal_transaction_sql(ROLLBACK_COMMAND);
state.connectionState |= ReservedConnectionState.closed;
resolve();
}, timeout * 1000);
timer.unref(); // dont block the event loop
Promise.all([Promise.all(pending_queries), Promise.all(pending_savepoints)]).finally(() => {
clearTimeout(timer);
resolve();
});
return promise;
// set before the wait: the callback can settle while close() waits
state.connectionState |= ReservedConnectionState.closing;
await waitForPendingWork([...transactionQueries, ...transactionSavepoints], timeout);
// a disconnect ended the transaction, or the runner already rolls it back
if (state.connectionState & ReservedConnectionState.closed || state.rollback) return;
}
}
for (const query of transactionQueries) {
(query as Query<any, any>).cancel();
}
if (BEFORE_COMMIT_OR_ROLLBACK_COMMAND) {
await run_internal_transaction_sql(BEFORE_COMMIT_OR_ROLLBACK_COMMAND);
state.connectionState |= ReservedConnectionState.closing;
Comment thread
robobun marked this conversation as resolved.
Resolved
try {
await (state.rollback ??= rollbackTransaction(
state,
pooledConnection,
BEFORE_COMMIT_OR_ROLLBACK_COMMAND,
ROLLBACK_COMMAND,
));
} catch (err) {
// close() reports the failure, and the runner sends ROLLBACK again when the callback settles
state.rollback = null;
throw err;
}
await run_internal_transaction_sql(ROLLBACK_COMMAND);
state.connectionState |= ReservedConnectionState.closed;
};
transaction_sql[Symbol.asyncDispose] = () => transaction_sql.close();
transaction_sql.options = sql.options;
Expand Down Expand Up @@ -878,6 +887,8 @@ const SQL = function SQL(
if ($isArray(transaction_result)) {
transaction_result = await Promise.all(transaction_result);
}
// close() was called: the catch below rolls back, nothing is committed
if (state.connectionState & ReservedConnectionState.closing) throw pool.connectionClosedError();
// at this point we dont need to rollback anymore
needs_rollback = false;
if (BEFORE_COMMIT_OR_ROLLBACK_COMMAND) {
Expand All @@ -897,11 +908,22 @@ const SQL = function SQL(
return resolve(transaction_result);
} catch (err) {
try {
if (!(state.connectionState & ReservedConnectionState.closed) && needs_rollback) {
if (BEFORE_COMMIT_OR_ROLLBACK_COMMAND) {
await run_internal_transaction_sql(BEFORE_COMMIT_OR_ROLLBACK_COMMAND);
const { connectionState } = state;
if (!(connectionState & ReservedConnectionState.closed) && needs_rollback) {
if (connectionState & ReservedConnectionState.closing) {
// close() owns the ROLLBACK: join it, or send it if close() still waits
await (state.rollback ??= rollbackTransaction(
state,
pooledConnection,
BEFORE_COMMIT_OR_ROLLBACK_COMMAND,
ROLLBACK_COMMAND,
));
Comment thread
robobun marked this conversation as resolved.
Resolved
Comment thread
robobun marked this conversation as resolved.
Resolved
} else {
if (BEFORE_COMMIT_OR_ROLLBACK_COMMAND) {
await run_internal_transaction_sql(BEFORE_COMMIT_OR_ROLLBACK_COMMAND);
}
await run_internal_transaction_sql(ROLLBACK_COMMAND);
}
await run_internal_transaction_sql(ROLLBACK_COMMAND);
}
} catch (err) {
return reject(err);
Expand Down
10 changes: 2 additions & 8 deletions src/js/internal/sql/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,10 +101,7 @@ class Query<T, Handle extends BaseQueryHandle<any>> extends PublicPromise<T> {
#run() {
const { [_handler]: handler, [_queryStatus]: status } = this;

if (
status &
(SQLQueryStatus.executed | SQLQueryStatus.error | SQLQueryStatus.cancelled | SQLQueryStatus.invalidHandle)
) {
if (status & (SQLQueryStatus.executed | SQLQueryStatus.error | SQLQueryStatus.invalidHandle)) {
Comment thread
robobun marked this conversation as resolved.
Resolved
return;
}

Expand All @@ -131,10 +128,7 @@ class Query<T, Handle extends BaseQueryHandle<any>> extends PublicPromise<T> {
async #runAsync() {
const { [_handler]: handler, [_queryStatus]: status } = this;

if (
status &
(SQLQueryStatus.executed | SQLQueryStatus.error | SQLQueryStatus.cancelled | SQLQueryStatus.invalidHandle)
) {
if (status & (SQLQueryStatus.executed | SQLQueryStatus.error | SQLQueryStatus.invalidHandle)) {
return;
}

Expand Down
Loading
Loading