Skip to content

Scope

A scope owns registered finalizers and runs them in reverse order (LIFO) when its lifetime ends. Use scoped for local resource ownership, or an explicit Scope.make() when several operations share a lifetime across calls.

Scope lifecycle: resources acquire in order and release in reverse order even on failure or interruptionScope lifecycle: resources acquire in order and release in reverse order even on failure or interruption
Scope lifecycle: resources acquire in order and release in reverse order even on failure or interruption

Registering finalizers

effect function registeredWork() {
  try addFinalizer((outcome) =>
    Console.log(`Work scope closed with ${outcome._tag}`))
  return "Prepared"
}
// string!!Scope.Scope
 
effect function runRegisteredWork() {
  return try scoped(registeredWork())
}
// string!!
// Run in an effect function: try Console.log(try runRegisteredWork())
// Output: Work scope closed with Success
// Output: Prepared

addFinalizer attaches cleanup to the current scope, not the function's return. Scope is in scope as a module, and Scope.Scope is its scope type, so no import is needed. scoped creates a scope, runs the Effect, and closes the scope with its outcome: the finalizer receives a success exit on success, and a failure exit on typed failure, a defect, or interruption.

Finalizers run in reverse registration order by default, with interruption deferred during release. Their typed error channel must be never, so handle expected cleanup failures inside the callback. A defect during release stays in the resulting cause, and an expected failure beside it becomes a defect.

Opening and closing scopes explicitly

effect function manuallyManagedWork() {
  return try acquireUseRelease(
    Scope.make(),
    effect (scope) => {
      try Scope.addFinalizer(scope, Console.log("First finalizer"))
      try Scope.addFinalizer(scope, Console.log("Second finalizer"))
      return try Scope.provide(registeredWork(), scope)
    },
    (scope, outcome) => Scope.close(scope, outcome)
  )
}
// Run in an effect function: try Console.log(try manuallyManagedWork())
// Output: Work scope closed with Success
// Output: Second finalizer
// Output: First finalizer
// Output: Prepared

Scope.make creates a closeable scope; Scope.close supplies the exit its finalizers observe. The bracket closes the scope even if work fails or is cancelled, passing the actual outcome to release. The finalizer from registeredWork runs first, then the explicit ones in reverse.

Scope.provide(program, scope) supplies a scope without closing it when the program returns. Closing a scope doesn't cancel computations that merely use it; use scoped fiber ownership for cancellation. A finalizer registered in a closed scope runs immediately, so a closed scope can't extend a resource's lifetime.

Acquiring resources with automatic release

effect function openBuffer(label: string) {
  return try acquireRelease(
    effect {
      try Console.log(`Opened ${label}`)
      return { label }
    },
    (buffer) => Console.log(`Closed ${buffer.label}`)
  )
}
// { label: string }!!Scope.Scope
 
effect function copyLabels() {
  return try scoped(effect {
    const source = try openBuffer("source")
    const destination = try openBuffer("destination")
    return `${source.label} -> ${destination.label}`
  })
}
// string!!
// Run in an effect function: try Console.log(try copyLabels())
// Output: Opened source
// Output: Opened destination
// Output: Closed destination
// Output: Closed source
// Output: source -> destination

acquireRelease makes acquisition uninterruptible by default and registers release before exposing the resource. Its third argument { interruptible: true } permits cancellation during acquisition. A successful acquisition gets exactly one release when its scope closes; a failed one registers none.

scoped(effect { … }) gives each acquisition inside it a lifetime ending when that Effect ends. Don't return a resource to use after the scope closes; return derived data, or let the caller own the acquisition. Existing scoped APIs register in that same scope.

Releasing JavaScript Disposables

acquireDisposable acquires a JavaScript Disposable or AsyncDisposable and registers disposal in the current Effect scope. Inside scoped, each resource is released exactly once on success, typed failure, defect, or interruption, including interruption pending when acquisition gives its value: receiving the value and registering its release cannot be separated. Disposal uses [Symbol.asyncDispose] if present, otherwise [Symbol.dispose]. TypeScript's using keeps its JavaScript disposal behavior. A value with neither method is TS2850.

A value acquired with acquireRelease is released only by its release, so a JavaScript Disposable whose release disposes it is closed once. Do not register a second disposal for it.

Cancellation follows Effect. An interruptible acquisition can be cancelled before it returns a value, in which case it registers no release. acquireRelease and acquireDisposable protect acquisition by default, so a pending interruption waits for acquisition and its registered release. To permit cancellation during acquisition, use acquireRelease with { interruptible: true } as its third argument. If an acquisition creates its own uninterruptible mask, register the resource with acquireDisposable inside that mask before interruption can be delivered.

This example checks success, typed failure, defect, and interruption requested while acquisition is waiting. Each path closes the handle exactly once:

function open(events: string[]) {
  let closed = false
  events.push("open")
  return {
    [Symbol.dispose](): void {
      if (closed) { events.push("closed twice"); return }
      closed = true
      events.push("closed")
    }
  }
}
 
error Bad
 
effect function acquire(events: string[]) {
  return try acquireDisposable(sync(() => open(events)))
}
 
function describe(outcome: Exit.Exit<void, Bad>) {
  if (Exit.isSuccess(outcome)) return "success"
  if (Exit.hasDies(outcome)) return "defect"
  if (Exit.hasFails(outcome)) return "failure"
  return Exit.hasInterrupts(outcome) ? "interrupted" : "other"
}
 
effect function run(ending: string) {
  const events: string[] = []
  const outcome = try exit(scoped(effect {
    const file = try acquire(events)
    events.push("body")
    if (ending === "fail") throw new Bad()
    if (ending === "die") try die("boom")
  }))
  return [describe(outcome), events]
}
 
effect function pending() {
  const events: string[] = []
  const entered = try Deferred.make<void>()
  const gate = try Deferred.make<void>()
  effect function work() {
    try scoped(effect {
      const file = try acquireDisposable(effect {
        try Deferred.succeed(entered, undefined)
        try Deferred.await(gate)
        return try sync(() => open(events))
      })
      events.push("never runs")
    })
  }
  const child = fork work()
  try Deferred.await(entered)
  child.interruptUnsafe(98765)
  try Deferred.succeed(gate, undefined)
  const outcome = try Fiber.await(child)
  return [describe(outcome), events]
}
// Run in an effect function:
//   {
//     const jsonValue = { succeeds: try run("succeed"), fails: try run("fail"), dies: try run("die"), pending: try pending() }
//     try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
//   }
// Output: {"succeeds":["success",["open","body","closed"]],"fails":["failure",["open","body","closed"]],"dies":["defect",["open","body","closed"]],"pending":["interrupted",["open","closed"]]}

Arranging nested resource lifetimes

effect function nestedLifetimes() {
  try scoped(effect {
    const outer = try openBuffer("session")
    try scoped(effect {
      const inner = try openBuffer("request")
      try Console.log(`${outer.label}/${inner.label}`)
    })
    try Console.log("Request buffer closed; session still open")
  })
}
 
effect function mixedOwnership() {
  const callerOwned = try openBuffer("caller")
  try scoped(effect {
    const local = try openBuffer("local")
    try Console.log(`${callerOwned.label}/${local.label}`)
  })
}
// void!!Scope.Scope
 
effect function observeOwnership() {
  try scoped(effect {
    try mixedOwnership()
    try Console.log("Local closed; caller buffer still open")
  })
}
// Run in an effect function:
//   try nestedLifetimes()
//   try observeOwnership()
// Output: Opened session
// Output: Opened request
// Output: session/request
// Output: Closed request
// Output: Request buffer closed; session still open
// Output: Closed session
// Output: Opened caller
// Output: Opened local
// Output: caller/local
// Output: Closed local
// Output: Local closed; caller buffer still open
// Output: Closed caller

The inner scope closes before the outer block continues. In mixedOwnership, the acquisition outside the inner scoped belongs to the caller's scope though the function also owns a local resource, so the caller's buffer closes only when scoped exits.

Operations that only register finalizers in one scope share its lifetime. Use separate scoped calls when one operation's resources must close before the next begins, and one outer scope when later operations depend on earlier resources.

A plain fork creates a child owned by the current fiber. It is interrupted when that parent ends. fork.scoped ties a child to the current Scope, fork.in(scope) selects a scope, and fork.detached starts a child with no owner. Join a child explicitly when its result must finish before continuing.

Sequencing scoped operations with rollback

error SetupFailed {
  stage: string
}
 
service ProjectSteps {
  create(stage: string): string!SetupFailed
  remove(id: string): void!!
  finish(storage: string, index: string): string!SetupFailed
}
 
effect function reserveStep(stage: string) {
  const steps = try ProjectSteps
  return try acquireRelease(
    steps.create(stage),
    effect (id, outcome) => {
      if (Exit.isFailure(outcome)) try steps.remove(id)
    }
  )
}
// string!SetupFailed!(ProjectSteps | Scope.Scope)
 
effect function setupProject() {
  return try scoped(effect {
    const storage = try reserveStep("storage")
    const index = try reserveStep("index")
    const steps = try ProjectSteps
    return try steps.finish(storage, index)
  })
}
// string!SetupFailed!ProjectSteps
// Run in an effect function:
//   provide ProjectSteps = { create: effect (stage) => { try Console.log(`create ${stage}`); return stage }, remove: (id) => Console.log(`remove ${id}`), finish: () => succeed("ready") } { try Console.log(try setupProject()) }
//   provide ProjectSteps = { create: effect (stage) => { try Console.log(`create ${stage}`); if (stage === "index") throw new SetupFailed({ stage }); return stage }, remove: (id) => Console.log(`remove ${id}`), finish: () => succeed("ready") } { try Effect.catch(setupProject(), (error) => Console.log(error.stage)) }
// Output: create storage
// Output: create index
// Output: ready
// Output: create storage
// Output: create index
// Output: remove storage
// Output: index

Both reservations register in the same scope. A successful exit keeps the created artifacts. If index creation fails, storage is removed; if finish fails, index is removed before storage.

The finalizers see the whole setup's exit, so defects and interruption trigger the same rollback. Nested scoped calls would end those lifetimes earlier and withhold the overall outcome from the finalizers. This compensates for successful steps; it is not an atomic transaction with an external system.

effect function exerciseRollback() {
  const removed: string[] = []
  const testLayer = Layer.succeed(ProjectSteps, {
    create: (stage) => succeed(stage),
    remove: (id) => sync(() => { removed.push(id) }),
    finish: effect (_storage, _index) => { throw new SetupFailed({ stage: "finish" }) }
  })
  const outcome = try result(Effect.provide(setupProject(), testLayer))
  return { outcome, removed } // removed: ["index", "storage"]
}
// Run in an effect function:
//   const result = try exerciseRollback()
//   try Console.log(try Effect.try(() => JSON.stringify({ outcome: result.outcome._tag, removed: result.removed })))
// Output: {"outcome":"Failure","removed":["index","storage"]}

Test failure at each stage to confirm which steps were acquired and which compensations ran. If compensation can fail, handle its expected failure in the release callback and keep unrecoverable cleanup failures as defects; never discard them to make rollback look successful.

Coming from Effect

Use scoped to own a group of acquisitions, addFinalizer to register cleanup, and the Scope module to manage a lifetime explicitly. Pass Effect values directly and use try to run them.


The matching Effect page: effect.website/docs/v4/resource-management/scope