Now I fully understand the issue. The runWithTransaction function unconditionally calls adapter.transaction(async (trx) => ...) which opens a new transaction every time. But if there's already an active transaction in the async context store, we should reuse it instead.
The fix is to modify runWithTransaction to:
- Check if there's already an active transaction in the async context store
- If yes, run
fn within that existing transaction context (without opening a new one)
- If no, open a new transaction as before
Let me also check what runWithAdapter does - it seems like a non-transactional version that just stores the adapter in the async context.
Looking at the code:
runWithAdapter - stores the adapter in ALS without a transaction
runWithTransaction - opens a transaction and stores the transaction adapter in ALS
getCurrentAdapter - checks ALS for an existing transaction adapter, falls back to the base adapter
The issue is that runWithTransaction always opens a new transaction, even if one is already active. This causes deadlocks with connection pools of size 1.
The fix should be:
- Check if there's already an active transaction (store exists in ALS)
- If yes, run
fn within the existing transaction context (just call als.run(store, fn) with the existing store)
- If no, open a new transaction as before
Actually, looking more carefully, I need to think about this more carefully:
If we're already in a transaction, runWithTransaction should be a no-op in terms of opening new transactions. It should just run fn within the existing transaction context.
But we also need to make sure the hooks are properly handled. The pendingHooks are part of the store, so if we're in an existing transaction, we should use the existing store's pendingHooks.
Let me implement the fix:
export const runWithTransaction = async <R>(
adapter: DBAdapter,
fn: () => R,
): Promise<R> => {
let called = true;
return ensureAsyncStorage()
.then(async (als) => {
called = true;
const store = als.getStore();
// If there's already an active transaction, reuse it
if (store) {
const pendingHooks = store.pendingHooks;
let result: Awaited<R>;
let error: unknown;
let hasError = false;
try {
result = await als.run(store, fn);
} catch (e) {
hasError = true;
error = e;
}
for (const hook of pendingHooks) {
await hook();
}
if (hasError) {
throw error;
}
return result!;
}
// No active transaction, open a new one
const pendingHooks: Array<() => Promise<void>> = [];
let result: Awaited<R>;
let error: unknown;
let hasError = false;
try {
result = await adapter.transaction(async (trx) => {
return als.run({ adapter: trx, pendingHooks }, fn);
});
} catch (e) {
hasError = true;
error = e;
}
for (const hook of pendingHooks) {
await hook();
}
if (hasError) {
throw error;
}
return result!;
})
.catch((err) => {
if (!called) {
return fn();
}
throw err;
});
};
Wait, but this has a problem. If we're reusing the store and the function throws, we don't want to commit the pending hooks because the transaction should be rolled back.
Actually, looking at the original code more carefully, the pendingHooks are only executed after the function completes. So if there's an error, the hooks are not executed. This is correct behavior - if the transaction fails, we don't want to execute the after-hooks.
But there's another issue - if we're reusing the store, we need to make sure the hooks are properly executed when the outer transaction completes. Let me think about this...
Actually, I think the simpler approach is correct. If we're inside an existing transaction, we just run fn within the existing store context. The hooks will be queued on the existing pendingHooks array, and they'll be executed when the outermost transaction completes.
Let me trace through the flow:
- Outer
runWithTransaction(adapter, outerFn):
- No store exists, so it opens a new transaction with
trx1
- Calls
als.run({ adapter: trx1, pendingHooks }, outerFn)
- Inside
outerFn, runWithTransaction(innerFn) is called:
- Store exists (it's
{ adapter: trx1, pendingHooks })
- With my fix, it just runs
als.run(store, innerFn) without opening a new transaction
- The hooks from
innerFn are added to the same pendingHooks
- After
innerFn completes, outerFn continues
- After
outerFn completes, both sets of hooks are executed
This seems correct! The only issue is that the outer transaction's hooks might execute before the outer transaction is committed. But actually, that's also the case in the original code - the hooks are executed right after the function completes, not after the transaction commits. So this should be fine.
Let me also think about the error case:
- Outer
runWithTransaction(adapter, outerFn):
- Opens transaction, runs outerFn
- Inside outerFn,
runWithTransaction(innerFn) throws an error:
- The store exists, so it runs innerFn
- innerFn throws
- We catch the error, execute pending hooks (but the error is re-thrown)
- The error propagates to outerFn's caller
- The outer transaction will be rolled back (adapter.transaction handles this)
Actually, wait. In the original code, when adapter.transaction is called, the adapter is responsible for handling rollback on error. So if innerFn throws, the error propagates up, and adapter.transaction will rollback tx1. The pendingHooks won't be executed because the error is caught and re-thrown before the hooks are executed.
But with my fix, if innerFn throws, I do execute the pendingHooks before re-throwing. Is this correct?
Looking at the original code again:
try {
result = await adapter.transaction(async (trx) => {
return als.run({ adapter: trx, pendingHooks }, fn);
});
} catch (e) {
hasError = true;
error = e;
}
for (const hook of pendingHooks) {
await hook();
}
if (hasError) {
throw error;
}
So even in the original code, if adapter.transaction throws, the pendingHooks are still executed. This is because adapter.transaction might commit before throwing (e.g., for optimistic locking), or the adapter might call the hooks on its own.
Actually no, looking at this more carefully, if adapter.transaction throws, it means the transaction failed. The hooks shouldn't be executed because the transaction was rolled back. But the original code does execute them. This might be a bug in the original code too.
Let me focus on the main fix - making runWithTransaction reuse an existing transaction. I'll keep the same behavior as the original code regarding hooks (execute them regardless of whether there's an error).
Actually, looking at this even more carefully, I think the issue is simpler than I thought. Let me re-read the original code:
export const runWithTransaction = async <R>(
adapter: DBAdapter,
fn: () => R,
): Promise<R> => {
let called = true;
return ensureAsyncStorage()
.then(async (als) => {
called = true;
const pendingHooks: Array<() => Promise<void>> = [];
let result: Awaited<R>;
let error: unknown;
let hasError = false;
try {
result = await adapter.transaction(async (trx) => {
return als.run({ adapter: trx, pendingHooks }, fn);
});
} catch (e) {
hasError = true;
error = e;
}
for (const hook of pendingHooks) {
await hook();
}
if (hasError) {
throw error;
}
return result!;
})
.catch((err) => {
if (!called) {
return fn();
}
throw err;
});
};
The issue is that adapter.transaction(async (trx) => ...) is always called, even when there's already an active transaction.
The fix is:
- Check if there's already an active transaction (store exists in ALS)
- If yes, run
fn within the existing store context without opening a new transaction
- If no, open a new transaction as before
Let me implement this:
export const runWithTransaction = async <R>(
adapter: DBAdapter,
fn: () => R,
): Promise<R> => {
let called = false;
return ensureAsyncStorage()
.then(async (als) => {
called = true;
const store = als.getStore();
const pendingHooks = store?.pendingHooks ?? [];
let result: Awaited<R>;
let error: unknown;
let hasError = false;
if (store) {
// Reuse existing transaction
result = await als.run(store, fn);
} else {
// Open a new transaction
result = await adapter.transaction(async (trx) => {
return als.run({ adapter: trx, pendingHooks }, fn);
});
}
for (const hook of pendingHooks) {
await hook();
}
if (hasError) {
throw error;
}
return result!;
})
.catch((err) => {
if (!called) {
return fn();
}
throw err;
});
};
Wait, I need to be more careful. When reusing an existing transaction, if fn throws, the existing transaction should still be active (just with the error propagating up). The outer transaction handler will handle the rollback.
Let me also think about the pendingHooks. When reusing an existing transaction, the hooks should be added to the existing pendingHooks array. When the outermost transaction completes, all hooks will be executed.
Actually, looking at the original code, there's a subtlety: the pendingHooks array is created fresh for each runWithTransaction call. So if we have nested runWithTransaction calls, each one has its own pendingHooks array. But when the inner call executes, it runs within the outer call's ALS context, so the hooks should be added to the outer call's pendingHooks.
Wait, no. Looking at the original code again:
result = await adapter.transaction(async (trx) => {
return als.run({ adapter: trx, pendingHooks }, fn);
});
Here, pendingHooks is a local variable in the runWithTransaction call. It's passed to als.run as part of the store. But the store only stores the adapter and pendingHooks. When a nested runWithTransaction is called inside fn, it creates its own pendingHooks array and its own store. So the hooks from the nested call would be added to its own pendingHooks, not the outer call's pendingHooks.
But wait, that means the original code has a bug too! If we have nested runWithTransaction calls, the inner call's hooks are added to its own pendingHooks, but the inner call's pendingHooks is executed after the inner call completes, which is inside the outer transaction. Then the outer call's pendingHooks is executed after the outer call completes.
Hmm, let me trace through the original code with nested runWithTransaction calls:
-
runWithTransaction(adapter, outerFn):
pendingHooks = [] (local)
- Calls
adapter.transaction(async (trx) => { return als.run({ adapter: trx, pendingHooks }, outerFn); })
- This opens tx1, stores
{ adapter: trx1, pendingHooks: [] } in ALS
- Runs
outerFn with the above store
-
Inside outerFn, runWithTransaction(adapter, innerFn):
pendingHooks = [] (new local array)
- Calls
adapter.transaction(async (trx) => { return als.run({ adapter: trx, pendingHooks: [] }, innerFn); })
- This opens tx2, stores
{ adapter: trx2, pendingHooks: [] } in ALS (overwriting the previous store)
- Runs
innerFn with the above store
- After innerFn completes, executes
pendingHooks (which is the inner call's local array)
- Returns result
-
Back in outerFn, continue with result from innerFn
-
After outerFn completes, executes pendingHooks (which is the outer call's local array)
-
Returns result
So in the original code, the inner call opens tx2, runs innerFn, closes tx2 (commit or rollback), then returns. The outer call continues with tx1 still open.
Now, with my fix:
-
runWithTransaction(adapter, outerFn):
- No store exists
- Opens tx1, stores
{ adapter: trx1, pendingHooks: [] } in ALS
- Runs
outerFn with the above store
-
Inside outerFn, runWithTransaction(adapter, innerFn):
- Store exists (it's
{ adapter: trx1, pendingHooks: [] })
- Reuses the existing store, calls
als.run(store, innerFn)
- Runs
innerFn with the same store
- After innerFn completes, executes
pendingHooks (which is the same array as the outer call's)
- Returns result
-
Back in outerFn, continue with result from innerFn
-
After outerFn completes, executes pendingHooks (same array as step 2)
-
Returns result
This is the correct behavior! Both outerFn and innerFn run within the same transaction, and the hooks are all queued in the same array.
But wait, there's a subtle issue. In step 2, when we reuse the store, we don't update the store with the new pendingHooks. We just use the existing store. But the existing store's pendingHooks is the same as the outer call's pendingHooks. So the hooks are correctly queued.
But what if the innerFn modifies the store somehow? Actually, looking at the code, the store is immutable. We create it once and only read from it. So this should be fine.
Actually, I realize there might be another issue. When we reuse the store, we don't call als.run(store, fn). We just call als.run(store, fn) directly, which means the store is not updated. But actually, als.run(store, fn) sets the store for the duration of fn. So when innerFn runs, the store is the same as the outer call's store. This is correct.
OK, I'm confident the fix is correct. Let me implement it.
Actually, I just realized there's one more thing to consider. The hasError variable in the original code is used to track whether the function threw an error. In my fix, I removed this because the catch block at the end handles the error. Let me make sure this is correct.
In the original code:
try {
result = await adapter.transaction(...);
} catch (e) {
hasError = true;
error = e;
}
for (const hook of pendingHooks) {
await hook();
}
if (hasError) {
throw error;
}
return result!;
The try/catch is only for the adapter.transaction call. If fn throws, it would throw out of the als.run call, which is inside the adapter.transaction callback, so it would be caught by the catch block.
Wait, actually no. adapter.transaction is responsible for handling the callback. If the callback throws, adapter.transaction might or might not catch it. Let me look at how adapter.transaction works...
Actually, looking at the code, adapter.transaction(async (trx) => { return als.run({ adapter: trx, pendingHooks }, fn); }) means that if fn throws, the error propagates out of the callback. The adapter's transaction method is responsible for handling this. If the adapter properly rolls back on error, then the error is caught by the catch block.
So the original code assumes that if fn throws, the error propagates to the catch block. With my fix, if fn throws while reusing the store, the error should also propagate up. Let me make sure this is correct.
In my fix:
if (store) {
// Reuse existing transaction
result = await als.run(store, fn);
} else {
// Open a new transaction
result = await adapter.transaction(async (trx) => {
return als.run({ adapter: trx, pendingHooks }, fn);
});
}
If fn throws, the error propagates out of als.run(store, fn). This is not caught, so it propagates to the next catch block, which is the outer one. So the function throws, and the outer caller handles the error.
But wait, what about the pendingHooks? In the original code, if fn throws, the pendingHooks are still executed. In my fix, if fn throws, the pendingHooks are not executed (because the error propagates before the hooks are executed).
Hmm, actually let me re-read the original code:
try {
result = await adapter.transaction(async (trx) => {
return als.run({ adapter: trx, pendingHooks }, fn);
});
} catch (e) {
hasError = true;
error = e;
}
for (const hook of pendingHooks) {
await hook();
}
if (hasError) {
throw error;
}
return result!;
If fn throws, the error propagates out of als.run, which propagates out of the callback, which propagates to adapter.transaction. The adapter's transaction method might catch the error and roll back, or it might re-throw. Either way, the error propagates to the catch block, which sets hasError = true and error = e. Then the pendingHooks are executed. Then the error is re-thrown.
So the original code always executes the pendingHooks, even if an error occurred. This is intentional. The hooks are meant to be executed after the transaction, regardless of success or failure.
Actually wait, that doesn't make sense. If the transaction failed, the hooks shouldn't be executed because the data was rolled back. But maybe the hooks are meant to be executed regardless, as a way to notify listeners of the outcome (including failures).
In any case, I should match the original behavior. Let me update my fix:
if (store) {
// Reuse existing transaction
let error: unknown;
let hasError = false;
try {
result = await als.run(store, fn);
} catch (e) {
hasError = true;
error = e;
}
for (const hook of pendingHooks) {
await hook();
}
if (hasError) {
throw error;
}
} else {
// ... original code
}
Hmm, but this duplicates a lot of code. Let me refactor:
Actually, let me think about this differently. The key insight is that when we reuse the store, the pendingHooks is the same as the outer call's pendingHooks. So the hooks should be executed after the outermost transaction completes, not after each individual transaction call.
But the original code executes the hooks after each individual runWithTransaction call. This means that if we have nested runWithTransaction calls, the hooks are executed multiple times (once for each call).
Wait, that's actually what I said earlier. Let me re-trace:
-
runWithTransaction(adapter, outerFn):
- Opens tx1
- Runs outerFn
- innerFn is called within outerFn
- After outerFn completes, hooks are executed
-
runWithTransaction(adapter, innerFn):
- Opens tx2 (different transaction!)
- Runs innerFn
- After innerFn completes, hooks are executed
- tx2 is closed (commit or rollback)
-
Back in outerFn, continue
-
After outerFn completes, hooks are executed again (same hooks? or different hooks?)
Wait, I'm getting confused. Let me look at the store structure again:
{ adapter: trx, pendingHooks }
The pendingHooks is a local variable in each runWithTransaction call. It's not shared between calls. So each call has its own pendingHooks array.
OK so the flow is:
-
runWithTransaction(adapter, outerFn):
pendingHooks1 = []
- Opens tx1
- Stores
{ adapter: trx1, pendingHooks: pendingHooks1 } in ALS
- Runs outerFn
-
Inside outerFn, runWithTransaction(adapter, innerFn):
pendingHooks2 = [] (new array)
- Opens tx2
- Stores
{ adapter: trx2, pendingHooks: pendingHooks2 } in ALS (overwriting the previous store)
- Runs innerFn
- After innerFn completes, executes
pendingHooks2
- Returns result
- tx2 is closed
-
Back in outerFn (with tx1 still open), continue with result from innerFn
-
After outerFn completes, executes pendingHooks1
-
tx1 is closed
So the hooks from outerFn are executed after outerFn completes. The hooks from innerFn are executed after innerFn completes. These are two different arrays.
Now with my fix:
-
runWithTransaction(adapter, outerFn):
- No store exists
- Opens tx1
- Stores
{ adapter: trx1, pendingHooks: pendingHooks1 } in ALS
- Runs outerFn
-
Inside outerFn, runWithTransaction(adapter, innerFn):
- Store exists (it's
{ adapter: trx1, pendingHooks: pendingHooks1 })
- Reuses the existing store
pendingHooks = pendingHooks1 (same array)
- Runs innerFn within the same store context
- After innerFn completes, executes
pendingHooks1
- Returns result
-
Back in outerFn (with tx1 still open), continue with result from innerFn
-
After outerFn completes, executes pendingHooks1 again!
So the hooks are executed twice! This is a problem.
Hmm, but actually, is this a problem? The hooks are just functions that are executed. If they're executed twice, they might have side effects (e.g., sending an email twice). But actually, looking at the code, the hooks are registered per-operation, so they should be idempotent.
Actually, let me re-think this. The hooks are registered within the function being run. So when outerFn runs, it might register some hooks. When innerFn runs, it might register some hooks. Both sets of hooks are added to pendingHooks1. After innerFn completes, pendingHooks1 is executed (including hooks from both innerFn and outerFn that were registered before innerFn was called). Then after outerFn completes, pendingHooks1 is executed again (including all the same hooks, plus any hooks registered during innerFn).
Wait, that doesn't make sense. Let me re-trace with more detail:
-
runWithTransaction(adapter, outerFn):
pendingHooks1 = []
- Opens tx1
- Calls
als.run({ adapter: trx1, pendingHooks: pendingHooks1 }, outerFn)
- Inside outerFn, hooks are registered (added to pendingHooks1)
-
Inside outerFn, runWithTransaction(adapter, innerFn):
- Store exists (it's
{ adapter: trx1, pendingHooks: pendingHooks1 })
pendingHooks = pendingHooks1 (same reference)
- Calls
als.run({ adapter: trx1, pendingHooks: pendingHooks1 }, innerFn)
- Inside innerFn, hooks are registered (added to pendingHooks1)
- After innerFn completes, executes all hooks in pendingHooks1
- Returns result
-
Back in outerFn, continue
-
After outerFn completes, executes all hooks in pendingHooks1 again
So yes, the hooks are executed twice. The hooks registered in step 1 are executed in step 2. The hooks registered in step 2 are also executed in step 2. Then both sets of hooks are executed again in step 4.
This is definitely a problem. The hooks should only be executed once, after the entire operation completes (both outerFn and innerFn).
Let me think about how to fix this...
One option is to not execute the hooks when reusing the store. Only the outermost transaction should execute the hooks.
Another option is to mark the hooks as "already executed" so they're not executed again.
I think the first option is simpler and more correct. The hooks should be executed after the outermost transaction completes, not after each individual transaction call.
Let me update my fix:
export const runWithTransaction = async <R>(
adapter: DBAdapter,
fn: () => R,
): Promise<R> => {
let called = false;
return ensureAsyncStorage()
.then(async (als) => {
called = true;
const store = als.getStore();
if (store) {
// Reuse existing transaction - don't execute hooks here
// The outermost transaction will handle hook execution
let result: Awaited<R>;
let error: unknown;
let hasError = false;
try {
result = await als.run(store, fn);
} catch (e) {
hasError = true;
error = e;
}
if (hasError) {
throw error;
}
return result!;
}
// No active transaction, open a new one
const pendingHooks: Array<() => Promise<void>> = [];
let result: Awaited<R>;
let error: unknown;
let hasError = false;
try {
result = await adapter.transaction(async (trx) => {
return als.run({ adapter: trx, pendingHooks }, fn);
});
} catch (e) {
hasError = true;
error = e;
}
for (const hook of pendingHooks) {
await hook();
}
if (hasError) {
throw error;
}
return result!;
})
.catch((err) => {
if (!called) {
return fn();
}
throw err;
});
};
This ensures that hooks are only executed by the outermost transaction, which is the correct behavior.
But wait, there's still an issue. When the outermost transaction opens, it stores { adapter: trx, pendingHooks } in ALS. When the innermost transaction reuses the store, it just runs als.run(store, fn) without modifying the store. So the store is the same throughout.
But what if there are multiple nested runWithTransaction calls? For example:
-
runWithTransaction(adapter, outerFn):
- Opens tx1
- Stores
{ adapter: trx1, pendingHooks: pendingHooks1 } in ALS
-
Inside outerFn, runWithTransaction(adapter, inner1Fn):
- Reuses store
- Runs inner1Fn
-
Inside inner1Fn, runWithTransaction(adapter, inner2Fn):
- Reuses store
- Runs inner2Fn
-
After inner2Fn completes, back in inner1Fn
-
After inner1Fn completes, back in outerFn
-
After outerFn completes, execute pendingHooks1
So the hooks are only executed once, after the outermost transaction completes. This is correct!
OK, I'm confident in my fix now. Let me implement it.
Wait, one more thing. I need to make sure that the catch block at the end handles the error correctly. Let me look at the original code again:
.catch((err) => {
if (!called) {
return fn();
}
throw err;
});
This catch block is for the ensureAsyncStorage() call. If ensureAsyncStorage() throws (e.g., because ALS is not available), the function falls back to running fn without any transaction. If called is true, it means we got past the ensureAsyncStorage() call, so the error is re-thrown.
With my fix, I moved the called = true to be inside the .then() callback. But actually, looking at the original code, called is set to true both before and inside the .then() callback. So it's set to true before entering the .then() callback.
Actually wait, looking at my fix, I removed the called = true from before the .then() callback. Let me add it back:
Actually, looking at the original code more carefully:
export const runWithTransaction = async <R>(
adapter: DBAdapter,
fn: () => R,
): Promise<R> => {
let called = true; // <-- Set here
return ensureAsyncStorage()
.then(async (als) => {
called = true; // <-- Also set here
...
So called is set to true before entering the .then() callback, and also inside the callback. This is redundant. The first called = true is to handle the case where the function is called but ensureAsyncStorage() throws. But actually, if ensureAsyncStorage() throws, we want called to be false so that the fallback fn() is used. Wait, but if ensureAsyncStorage() throws, we can't know whether we entered the callback or not.
Actually, looking at the catch block:
.catch((err) => {
if (!called) {
return fn();
}
throw err;
});
If called is false, it means ensureAsyncStorage() threw before we entered the .then() callback. In this case, we fall back to running fn without any ALS.
But if called is true, it means we entered the .then() callback, so the error is re-thrown.
So the first called = true is incorrect. It should be called = false. But the original code sets it to true, which means the fallback is never used. This might be intentional (the function always requires ALS to work), or it might be a bug.
In any case, I'll keep the same behavior as the original code. Let me set called = true before the .then() callback:
Actually, I think the original code's use of called is a bit confusing. Let me just keep the same pattern:
let called = true; // Or false, doesn't matter for the fallback behavior
return ensureAsyncStorage()
.then(async (als) => {
called = true;
...
})
.catch((err) => {
if (!called) {
return fn();
}
throw err;
});
OK, I'm overthinking this. Let me just implement the fix and test it.
Let me also consider what happens when adapter.transaction is false (i.e., the adapter doesn't support transactions). Looking at the adapter types:
transaction?:
| (
| false
| (<R>(callback: (trx: TransactionAdapter) => Promise<R>) => Promise<R>)
)
| undefined;
So adapter.transaction can be false, undefined, or a function. If it's false or undefined, calling adapter.transaction(...) would throw an error.
With my fix, if store exists (meaning we're in an existing transaction), we skip opening a new transaction. So even if adapter.transaction is false, we can still run fn.
If store doesn't exist, we try to open a new transaction. If adapter.transaction is false, this will throw. This is the same behavior as the original code.
So my fix handles the case where adapter.transaction is false correctly (it will throw if we try to open a new transaction, but won't throw if we're reusing an existing one).
Actually, wait. If adapter.transaction is false, then we can never enter the else branch (open a new transaction). So runWithTransaction will always fail on the first call. But subsequent calls within the same ALS context might succeed if there's an existing store.
Hmm, but if adapter.transaction is false, how would the store ever exist? The store is created by runWithTransaction when it opens a new transaction. If adapter.transaction is false, the store is never created.
So in practice, if adapter.transaction is false, runWithTransaction will always fail on the first call. This is the same behavior as the original code.
Actually, looking at the code more carefully, the store is created by als.run(store, fn), which sets the store for the duration of fn. So if runWithTransaction is called with fn that also calls runWithTransaction, the store from the first call is available in the second call.
But if adapter.transaction is false, the first call will fail when it tries to open a transaction. So the store is never created, and the second call will also fail.
OK so my fix doesn't change this behavior. If adapter.transaction is false, runWithTransaction always fails.
Now, what about runWithAdapter? Let me look at it:
export const runWithAdapter = async <R>(
adapter: DBAdapter,
fn: () => R,
): Promise<R> => {
...
result = await als.run({ adapter, pendingHooks }, fn);
...
};
runWithAdapter just stores the adapter (not a transaction) in the ALS. This is useful for cases where you want to run code within a specific adapter context without a transaction.
So the flow could be:
-
runWithAdapter(adapter, outerFn):
- Stores
{ adapter, pendingHooks } in ALS
-
Inside outerFn, runWithTransaction(adapter, innerFn):
- Store exists
- Reuses the existing store
- Runs innerFn without opening a transaction
This is correct! The inner function runs within the adapter context, without a transaction.
But wait, is this the intended behavior? If runWithTransaction is called within a runWithAdapter context, should it:
A. Just run within the adapter context (my fix)
B. Throw an error (because there's no transaction)
C. Open a new transaction anyway
I think option A is the most reasonable. If you're already in a context, just run within it. If you need a transaction, open one. If you're in a non-transactional context, just run.
Actually, looking at the original code, option B is what happens. If adapter.transaction is false, calling adapter.transaction(...) would fail. So the original code always tries to open a transaction, even if you're already in an adapter context.
My fix changes this behavior. If you're already in an adapter context (whether from runWithAdapter or runWithTransaction), the code just runs within that context without opening a new transaction.
Is this the right behavior? I think so. The purpose of runWithTransaction is to run code within a transactional context. If we're already in such a context, we should reuse it. If we're in a non-transactional context, we should just run (because the adapter doesn't support transactions anyway).
OK, I'm confident in my fix. Let me implement it now.
Actually, let me also think about what happens if adapter.transaction is undefined (not provided). Looking at the adapter types:
transaction?:
| (
| false
| (<R>(callback: (trx: TransactionAdapter) => Promise<R>) => Promise<R>)
)
| undefined;
So adapter.transaction can be undefined. In this case, calling adapter.transaction(...) would throw a TypeError (because undefined is not callable).
With my fix, if there's an existing store, we skip opening a new transaction. So the code works fine.
If there's no existing store, we try to open a new transaction. If adapter.transaction is undefined, this will throw. This is the same behavior as the original code.
OK, I'm confident in my fix. Let me implement it now.
Let me also check the existing tests to make sure my fix doesn't break anything.
Actually, let me first look at what the existing tests cover:
<tool_call>
<function=bash_terminal>
<parameter=command>
find /better-auth -name "*.test.ts" | xargs grep -l "runWithTransaction" 2>/dev/null | head -5
</tool_call>