Hyperlinkv0.8.0-beta.28

Effect

<A, E, R>(effect: Effect<A, E, R>): Effect<A, E, Exclude<R, Transaction>>

Defines a transaction boundary. Transactions are "all or nothing" with respect to changes made to transactional values (i.e. TxRef) that occur within the transaction body.

Details

If called inside an active transaction, tx composes with the current transaction and reuses its journal and retry state instead of creating a nested boundary.

Effect transactions are optimistic with retry. A transaction is retried when its body explicitly calls Effect.txRetry and any accessed transactional value changes, or when any accessed transactional value changes because a different transaction commits before the current one.

The outermost tx call creates the transaction boundary and commits or rolls back the full composed transaction.

Example (Running a transaction)

import { Effect, TxRef } from "effect"

const program = Effect.gen(function*() {
  const ref1 = yield* TxRef.make(0)
  const ref2 = yield* TxRef.make(0)

  // Nested tx calls compose into the same transaction
  yield* Effect.tx(Effect.gen(function*() {
    yield* TxRef.set(ref1, 10)
    yield* Effect.tx(TxRef.set(ref2, 20))
    const sum = (yield* TxRef.get(ref1)) + (yield* TxRef.get(ref2))
    console.log(`Transaction sum: ${sum}`)
  }))

  console.log(`Final ref1: ${yield* TxRef.get(ref1)}`) // 10
  console.log(`Final ref2: ${yield* TxRef.get(ref2)}`) // 20
})
transactions
Source effect/Effect.ts:1465240 lines
export const tx = <A, E, R>(
  effect: Effect<A, E, R>
): Effect<A, E, Exclude<R, Transaction>> =>
  withFiber((fiber) => {
    if (fiber.context.mapUnsafe.has(Transaction.key)) {
      return effect as Effect<A, E, Exclude<R, Transaction>>
    }
    // Create transaction state only at the outermost boundary
    const state: Transaction["Service"] = { journal: new Map(), retry: false }
    let result: Exit.Exit<A, E> | undefined
    return uninterruptibleMask((restore) =>
      flatMap(
        whileLoop({
          while: () => !result,
          body: constant(
            restore(effect).pipe(
              provideService(Transaction, state),
              tapCause(() => {
                if (!state.retry) return void_
                return restore(awaitPendingTransaction(state))
              }),
              exit
            )
          ),
          step(exit: Exit.Exit<A, E>) {
            if (state.retry || !isTransactionConsistent(state)) {
              return clearTransaction(state)
            }
            if (Exit.isSuccess(exit)) {
              commitTransaction(fiber, state)
            } else {
              clearTransaction(state)
            }
            result = exit
          }
        }),
        () => result!
      )
    )
  })
Referenced by 60 symbols