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

Function tx

packages/effect/src/Effect.ts:16387–16449  ·  view source on GitHub ↗
(
  effect: Effect<A, E, R>
)

Source from the content-addressed store, hash-verified

16385 * @since 4.0.0
16386 */
16387export const tx = <A, E, R>(
16388 effect: Effect<A, E, R>
16389): Effect<A, E, Exclude<R, Transaction>> =>
16390 withFiber((fiber) => {
16391 const state = Context.getOrUndefined(fiber.context, Transaction)
16392 if (state && !completedTransactions.has(state)) {
16393 return effect as Effect<A, E, Exclude<R, Transaction>>
16394 }
16395 const clock = fiber.getRef(internal.ClockRef)
16396 const now = clock.currentTimeMillisUnsafe()
16397 // Create transaction state only at the outermost boundary
16398 const mutable: TransactionMetaInner = {
16399 journal: new Map(),
16400 retry: false,
16401 attempt: 1,
16402 retryReason: undefined,
16403 start: now,
16404 now,
16405 elapsed: 0,
16406 elapsedSincePrevious: 0
16407 }
16408 let result: Exit.Exit<A, E> | undefined
16409 return uninterruptibleMask((restore) => {
16410 const run = restore(effect).pipe(
16411 provideService(Transaction, mutable),
16412 tapCause((cause) => {
16413 if (!mutable.retry) return void_
16414 // txRetry interrupts the body; any other reason in the cause is a real failure.
16415 // Roll back now so the step below fails instead of waiting or rerunning.
16416 if (!internal.hasInterruptsOnly(cause)) return sync(() => clearTransaction(mutable))
16417 return restore(awaitPendingTransaction(mutable))
16418 }),
16419 // A body that recovers the txRetry interrupt succeeds with retry still set, so wait here too.
16420 tap(() => mutable.retry ? restore(awaitPendingTransaction(mutable)) : void_),
16421 exit
16422 )
16423 return flatMap(
16424 whileLoop({
16425 while: () => !result,
16426 body: () => {
16427 if (mutable.attempt > 1) {
16428 stampTransaction(mutable, clock.currentTimeMillisUnsafe())
16429 }
16430 return run
16431 },
16432 step(exit: Exit.Exit<A, E>) {
16433 if (mutable.retry || !isTransactionConsistent(mutable)) {
16434 mutable.attempt++
16435 mutable.retryReason = mutable.retry ? "retry" : "conflict"
16436 return clearTransaction(mutable)
16437 }
16438 if (Exit.isSuccess(exit)) {
16439 commitTransaction(fiber, mutable)
16440 }
16441 clearTransaction(mutable)
16442 completedTransactions.add(mutable)
16443 result = exit
16444 }

Callers 1

Calls 11

clearTransactionFunction · 0.85
awaitPendingTransactionFunction · 0.85
flatMapFunction · 0.85
stampTransactionFunction · 0.85
getRefMethod · 0.80
syncFunction · 0.70
hasMethod · 0.65
pipeMethod · 0.65
restoreFunction · 0.50
tapFunction · 0.50

Tested by

no test coverage detected