-
Notifications
You must be signed in to change notification settings - Fork 0
OUT-4081: harden BaseService transaction handling #282
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
aadbe33
refactor(OUT-4081): add BaseService.withTransaction for safe tx set/u…
SandipBajracharya a208761
refactor(OUT-4081): route product and invoice tx sites through withTr…
SandipBajracharya 046bc74
fix(OUT-4081): make checkAndSuspendAccount writes actually transactional
SandipBajracharya 514f540
docs(OUT-4081): document BaseService transaction pattern; publish doc…
SandipBajracharya File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -44,5 +44,4 @@ next-env.d.ts | |
| .trigger | ||
|
|
||
| # local decision notes (not published) | ||
| /docs | ||
| /supabase/snippets | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,54 @@ | ||
| # BaseService transactions: why `this.db` is mutable, and how to use `withTransaction` | ||
|
|
||
| ## The pattern | ||
|
|
||
| `BaseService` exposes `this.db` (the Drizzle client) and two methods that swap it: | ||
|
|
||
| ```ts | ||
| setTransaction(tx) // this.db = tx — point this service at a transaction | ||
| unsetTransaction() // this.db = pool — restore the shared pool | ||
| ``` | ||
|
|
||
| Every service method reads `this.db`, so swapping it changes which connection all of that service's queries run on. | ||
|
|
||
| ## Why it's built this way | ||
|
|
||
| Two constraints force it: | ||
|
|
||
| 1. **Drizzle only hands you the tx handle inside the callback.** `db.transaction(async (tx) => …)` gives you `tx` only within that closure. But a service operation is usually a _flow_ of methods (`getOne`, `createQBProduct`, `logSync`, …), each of which reads `this.db`. Threading `tx` through every method signature — and through every nested service they call — would be invasive. | ||
| 2. **Services are constructed synchronously.** `new InvoiceService(user)` runs in a normal constructor, and the SDK/DB handles are already in place. There's no async-factory seam to inject a tx at construction time. | ||
|
|
||
| So instead of passing `tx` everywhere, `setTransaction(tx)` temporarily repoints `this.db` at the tx; every method the service calls transparently joins the transaction; `unsetTransaction()` restores the pool afterward. | ||
|
|
||
| ## Use `withTransaction`, not the raw pair | ||
|
|
||
| Pairing `setTransaction`/`unsetTransaction` by hand is error-prone (the unset can be skipped on a throw, or placed inside the callback so it runs before the commit). Use the helper on `BaseService`: | ||
|
|
||
| ```ts | ||
| await this.withTransaction(async () => { | ||
| await this.updateQBInvoice(...) | ||
| await this.syncLogService.updateOrCreateQBSyncLog(...) | ||
| }, [this.syncLogService]) | ||
| ``` | ||
|
|
||
| It runs `fn` inside `db.transaction(...)`, binds `this` **and every service in the array** to the tx, and restores all of them in a `finally` that **wraps** the transaction — so a throw or a failed commit can never leave a service pointing at a closed handle. (Introduced in OUT-4081.) | ||
|
|
||
| ## The sharp edge — the part that bites | ||
|
|
||
| **Each `BaseService` instance has its own independent `this.db`.** A nested service is _not_ in the transaction just because the outer service started one. If a `fn` writes through `this.syncLogService` or a freshly-`new`'d `TokenService`, that instance must be in the `services` array — otherwise its writes run on the **pool, outside the transaction**, silently. | ||
|
|
||
| **TypeScript does not catch this.** The `services` array is completely decoupled from what `fn` actually calls, and a bound vs. unbound `this.db` have the identical type. So this compiles clean and is wrong at runtime: | ||
|
|
||
| ```ts | ||
| await this.withTransaction(async () => { | ||
| await this.syncLogService.updateQBSyncLog(...) // compiles fine… | ||
| }, []) // …but syncLogService was never bound → write escapes the tx | ||
| ``` | ||
|
|
||
| This is not hypothetical: `sync.service#checkAndSuspendAccount` did exactly this before OUT-4081 — the suspend-account and delete-logs writes lived inside `db.transaction(...)` but their services were never bound, so the two writes weren't atomic despite looking like they were. | ||
|
|
||
| **Rule when writing transactional code:** trace every DB call inside `fn` to the service instance it runs on, and confirm that instance is `this` or is in the `services` array. | ||
|
|
||
| ## Why not make it type-safe? | ||
|
|
||
| The only way to get the compiler to enforce completeness is to stop mutating `this.db` and thread `tx` explicitly — e.g. `tx.insert(...)` directly, or DB methods that take a required `tx` parameter. That removes the footgun entirely (you physically cannot write without the handle in hand), but it's a large refactor touching every transactional method and the nested methods they call. It's deliberately deferred; `withTransaction` is the pragmatic middle ground that fixes the _pairing_ bug now while leaving the _completeness_ gap documented. See the OUT-4081 PR and `memory/project_unsetTransaction_bug.md`. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,61 @@ | ||
| # Why `truncateAllTestTables` (and other test helpers) import the real app `db` | ||
|
|
||
| **Date:** 2026-04-13 | ||
| **Context:** Reviewing the integration test scaffolding for `price.created`, the question came up: why does `test/helpers/testDb.ts` import `@/db` — isn't that the production-style module-level singleton? Shouldn't tests use a dedicated test client? | ||
|
|
||
| ## Short answer | ||
|
|
||
| An integration test's contract is: **"the app's code runs against a real Postgres, and we verify observable outcomes in that Postgres."** That requires the test and the app to talk to the _same_ database through the _same_ client. Using a separate test-only DB client would silently decouple "what the test wipes / seeds / asserts on" from "what the app writes to", which defeats the purpose. | ||
|
|
||
| ## Data flow on one test run | ||
|
|
||
| ``` | ||
| globalSetup.ts → starts Postgres container, sets process.env.DATABASE_URL | ||
| ↓ | ||
| test file imports @/db → DBClient.getInstance() constructs once, | ||
| reads DATABASE_URL = container URL, | ||
| opens a postgres-js connection pool | ||
| ↓ | ||
| beforeEach → truncateAllTestTables() uses db → wipes the container's tables | ||
| seedHealthyPortal() uses db → inserts into the container | ||
| ↓ | ||
| POST /api/quickbooks/webhook | ||
| ↓ controller → service code also imports @/db (SAME singleton) | ||
| → reads the seed, writes qb_product_sync, writes qb_sync_logs | ||
| ↓ | ||
| test assertions: db.select(...) → SAME singleton, SAME container, | ||
| reads back what the app wrote | ||
| ``` | ||
|
|
||
| If `truncateAllTestTables` used a _different_ Drizzle client, we'd get a subtle bug: truncate wipes DB "A", app writes to DB "B", assertions check DB "A" and see nothing. Tests pass when they shouldn't, or fail for mysterious reasons. | ||
|
|
||
| ## Why the singleton isn't a risk here | ||
|
|
||
| Normally, a module-level singleton pointing at a DB is something to be nervous about in tests — it implies "shared state across everything, hard to override." Two things make it fine in this setup: | ||
|
|
||
| 1. **Only one DB is reachable from this process.** `DATABASE_URL` is set by `globalSetup.ts` to the testcontainer's URI _before_ any `src/` code is imported by the test worker. The singleton can't bind to anything else. No production DB is reachable. | ||
| 2. **Tests run sequentially.** `vitest.config.ts` sets `fileParallelism: false` and `isolate: false` for the integration project, so no two tests mutate the shared DB concurrently. Truncate + seed in `beforeEach` is enough to guarantee a clean slate. | ||
|
|
||
| ## Alternatives we considered and rejected | ||
|
|
||
| | Approach | Why not | | ||
| | -------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ||
| | `truncateAllTestTables` uses its own `drizzle(postgres(url))` client | Two connection pools to the same DB — works, but pointless; also re-raises the "was URL set in time?" ordering question | | ||
| | Truncate via raw `psql` in a shell script before Vitest starts | Runs once, not per-test; doesn't reset between tests | | ||
| | `BEGIN`/`ROLLBACK` wrapping each test instead of truncate | Cleaner in theory, but **doesn't work for this codebase** — `BaseService.setTransaction()` opens its own transaction, and Postgres doesn't allow nested real transactions (only savepoints). Rolling back at the test level would abort the app's transaction mid-flight and mask real bugs. | | ||
| | A separate test-only Drizzle client with its own schema imports | Adds a second pool for no benefit; more chances for the two to drift (casing, schema refs, pooling behavior) | | ||
|
|
||
| The simplest correct answer is: **use the same `db` the app uses**. That's what integration testing means. | ||
|
|
||
| ## Future consideration: DI refactor | ||
|
|
||
| This pattern works _because_ `@/db` is a singleton. If the codebase ever moves to dependency injection (the 3–5 week refactor noted in the testing-strategy memory), these helpers would change shape — they'd accept a `db` argument rather than importing it. At that point `truncateAllTestTables(db)` becomes natural and the "why is it importing app code" question goes away. | ||
|
|
||
| Until then, the singleton is a constraint we work _with_, not against. | ||
|
|
||
| ## TL;DR for future-me | ||
|
|
||
| - Tests and app must share the DB client. Do **not** open a second Drizzle/postgres-js client just for the test. | ||
| - The singleton is safe because `DATABASE_URL` is fixed to the container before any `src/` import loads. | ||
| - Keep integration tests sequential (`fileParallelism: false`, `isolate: false`) as long as they share a container. | ||
| - If you're tempted to switch to `BEGIN/ROLLBACK` for isolation: check that no code under test opens its own transaction first. In this codebase, `BaseService.setTransaction()` does — so truncate is the right tool. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can we change signature of the function to recieve services as object instead of array. And these services would be passed to fn. So that fn body can call the services from params.
My reasoning is this will help prevent missing the dependency. But let me know yuor opinion on this.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I understand the concern and it's quite right to think that way. But even if we use object and pass param to
fn(), I dont think we can prevent missing dependency. I think that invites complexity only. I might be wrong though.