Alloy.Cancel (alloy v0.16.0)

Copy Markdown View Source

Lock-free cooperative cancellation token for Alloy.run/2 and Alloy.stream/3.

Backed by a single unsigned :atomics slot — no processes, no ETS tables, and nothing to clean up or leak. Pass a token via :cancel_token and call cancel/1 from any process to cooperatively stop an in-flight run:

token = Alloy.Cancel.new()
task = Task.async(fn -> Alloy.run("Analyze repo", provider: provider, cancel_token: token) end)
Alloy.Cancel.cancel(token)
{:error, %Alloy.Result{status: :cancelled, error: :cancelled}} = Task.await(task)

Cancellation is idempotent and monotonic: once cancelled, a token remains cancelled. Create a fresh token with new/0 for each new run.

Summary

Functions

Marks the token as cancelled. Safe to call from any process and idempotent.

Returns true if token has been cancelled, or false if uncancelled or nil.

Combines two optional cancellation tokens into a token that is cancelled when either outer or inner is cancelled.

Creates a new, uncancelled token.

Returns true if term is a valid Alloy.Cancel token backed by live :atomics references (including any combined parent tokens).

Types

t()

@type t() :: %Alloy.Cancel{parents: [t()], ref: :atomics.atomics_ref()}

Functions

cancel(cancel)

@spec cancel(t()) :: :ok

Marks the token as cancelled. Safe to call from any process and idempotent.

cancelled?(arg1)

@spec cancelled?(t() | nil) :: boolean()

Returns true if token has been cancelled, or false if uncancelled or nil.

combine(outer, inner)

@spec combine(t() | nil, t() | nil) :: t() | nil

Combines two optional cancellation tokens into a token that is cancelled when either outer or inner is cancelled.

When either argument is nil, the other argument is returned directly (combine(nil, nil) returns nil, combine(outer, nil) returns outer, and combine(nil, inner) returns inner), so cancelling the returned token mutates and cancels that token.

When both arguments are non-nil tokens, returns a combined token backed by inner with outer attached as a parent: cancelling outer propagates to the combined token without mutating inner, while cancelling the returned token cancels inner without mutating outer (unless outer and inner share an underlying reference).

new()

@spec new() :: t()

Creates a new, uncancelled token.

valid?(arg1)

@spec valid?(term()) :: boolean()

Returns true if term is a valid Alloy.Cancel token backed by live :atomics references (including any combined parent tokens).