MCPcopy Create free account
hub / github.com/Effect-TS/effect / makeStorageWithTransaction

Function makeStorageWithTransaction

packages/sql-sqlite-do/src/SqliteClient.ts:205–265  ·  view source on GitHub ↗
(
  storage: DurableObjectStorage,
  connection: Connection,
  semaphore: Effect.Semaphore,
  spanAttributes: ReadonlyArray<[string, unknown]>
)

Source from the content-addressed store, hash-verified

203 })
204
205const makeStorageWithTransaction = (
206 storage: DurableObjectStorage,
207 connection: Connection,
208 semaphore: Effect.Semaphore,
209 spanAttributes: ReadonlyArray<[string, unknown]>
210): Client.SqlClient["withTransaction"] =>
211<A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E | SqlError, R> =>
212 Effect.flatMap(Effect.serviceOption(Client.TransactionConnection), (outer) => {
213 if (outer._tag === "Some" && outer.value[0] !== connection) {
214 return Effect.fail(
215 new SqlError({ message: "Transactions cannot use a connection from a different SQL client" })
216 )
217 }
218 const depth = outer._tag === "Some" ? outer.value[1] + 1 : 0
219 const body = Effect.provideService(effect, Client.TransactionConnection, [connection, depth])
220
221 const transaction = Effect.async<A, E | SqlError, R>((resume) => {
222 let interrupted = false
223 let complete: (() => void) | undefined
224 const result: Promise<Exit.Exit<void, SqlError>> = storage.transaction((txn) =>
225 new Promise<void>((resolve) => {
226 complete = resolve
227 if (interrupted) return resolve()
228 resume(Effect.uninterruptibleMask((restore) =>
229 Effect.flatMap(Effect.exit(restore(body)), (exit) => {
230 if (Exit.isFailure(exit)) {
231 txn.rollback()
232 }
233 // Rejecting would also abort the parent of a nested transaction
234 resolve()
235 return Effect.zipRight(Effect.flatten(Effect.promise(() => result)), exit)
236 })
237 ))
238 })
239 ).then(
240 () => Exit.void,
241 (cause) => {
242 const exit = Exit.fail(new SqlError({ cause, message: "Failed to execute transaction" }))
243 // Only reaches the fiber if the transaction failed before running the body
244 resume(exit)
245 return exit
246 }
247 )
248 return Effect.suspend(() => {
249 interrupted = true
250 complete?.()
251 return Effect.asVoid(Effect.promise(() => result))
252 })
253 })
254
255 return depth === 0 ? semaphore.withPermits(1)(transaction) : transaction
256 }).pipe(
257 Effect.withSpan("sql.transaction", {
258 kind: "client",
259 captureStackTrace: false,
260 attributes: Object.fromEntries(spanAttributes)
261 }),
262 // The storage transaction closes the input gate, which blocks scheduler

Callers 1

makeFunction · 0.85

Calls 9

resolveFunction · 0.85
restoreFunction · 0.85
transactionMethod · 0.80
rollbackMethod · 0.80
withPermitsMethod · 0.80
pipeMethod · 0.65
failMethod · 0.65
resumeFunction · 0.50
completeFunction · 0.50

Tested by

no test coverage detected