FlowUnion

PackageAxial

Flow

Specification

Kind
Union
Members
136
Examples
0
ofExitSignature
ofExit exit
scopeDisposableSignature
scopeDisposable resource
scopeAsyncDisposableSignature
scopeAsyncDisposable resource
scopeResourceSignature
scopeResource (Resource(acquire, release)
scopeAcquireReleaseSignature
scopeAcquireRelease acquire release

Summary

NameSignatureSynopsis
Create
ofExitofExit exitCreates a flow from an execution outcome.
okok valueCreates a successful synchronous flow.
succeedsucceed valueSame as ok.
errorerror failureCreates a failing synchronous flow.
failfail failureSame as error.
diedie exnCreates a defective flow that fails with an exception.
fromResultfromResult resultLifts a Result into a synchronous flow.
verifyverify policy inputCreates a flow that verifies an input with an environment-aware policy.
fromOptionfromOption error valueLifts an option into a synchronous flow with the supplied error.
fromValueOptionfromValueOption error valueLifts a value option into a synchronous flow with the supplied error.
nevernever A flow that never completes on its own; it ends only when it is interrupted.
delaydelay factoryDefers flow construction until execution time.
Transform
mapmap mapper flowTransforms the successful value of a flow.
ignoreignore flowMaps the successful value of a synchronous flow to unit.
bindbind binder flowSequences a dependent flow after a successful value.
(>>=)flow >>= binderSequences a synchronous continuation after a successful value.
taptap binder flowRuns an effect on success and preserves the original value.
tapErrortapError binder flowRuns a synchronous side effect on failure and preserves the original error.
mapBothmapBoth onSuccess onFailure flowMaps both the successful value and the failure cause of a synchronous flow.
Combine and sequence
zipzip left rightRuns two flows sequentially and combines their successful values into a tuple.
map2map2 mapper left rightCombines two flows with a mapping function.
applyapply flow valueApplies a flow-wrapped function to a flow-wrapped value.
map3map3 mapper left middle rightCombines three flows with a mapping function.
(<!>)mapper flowMaps the successful value of a synchronous flow.
(<*>)flow <*> valueApplies a flow-wrapped function to a flow-wrapped value.
traversetraverse mapping valuesTransforms a sequence of values into a flow and stops at the first failure.
forEachforEach action valuesRuns a flow for each value in order and stops at the first failure, keeping no results.
traversePartraversePar parallelism mapping valuesMaps values to flows and runs them with bounded concurrency, returning results in input order.
traverseParUsingtraverseParUsing parallelism resource mapping valuesLike traversePar, giving each worker its own resource, acquired once and reused for every value it maps.
forEachParforEachPar parallelism action valuesRuns a flow for each value with bounded concurrency, discarding the results.
forEachParUsingforEachParUsing parallelism resource action valuesLike forEachPar, giving each worker its own resource, acquired once and reused for every value it processes.
sequencesequence flowsTransforms a sequence of flows into a flow of a sequence and stops at the first failure.
Errors and recovery
catchCancellationcatchCancellation handler flowTurns cancellation that a flow raised for its own reasons into a typed error.
orElseFloworElseFlow errorFlow resultAttaches an environment-derived error to a result that failed without one; the error flow runs only on failure.
mapErrormapError mapper flowMaps the error value of a synchronous flow.
widenErrorwidenError flowGives a flow that cannot fail with a typed error any error type.
tracedErrortracedError trace flowAttaches diagnostic trace text to any failure cause of the flow.
foldCauseFlowfoldCauseFlow onSuccess onFailure flowFolds both the successful value and the full failure cause into a new flow.
exitexit sourceRuns a flow and succeeds with its whole outcome as an Exit.
catchcatch handler flowCatches exceptions raised during execution and simple defect outcomes, then maps them to a typed error.
orElseWithorElseWith fallback flowComputes a fallback flow from the typed error when the source flow fails.
recoverrecover handler sourceNo description available.
foldFlowfoldFlow onSuccess onError sourceFolds a successful value or a single typed failure into a new flow.
foldfold onSuccess onError sourceFolds a successful value or a single typed failure into a plain value.
orElseorElse fallback flowFalls back to another flow when the source flow fails.
Operations
fromColdTaskfromColdTask operationCreates a flow from an existing cold task value.
fromColdTaskResultfromColdTaskResult operationCreates a flow from an existing cold task value whose Error enters the typed error channel.
withClockwithClock clock sourceOverrides the clock within this flow and its descendants.
withRandomwithRandom random sourceOverrides random values within this flow and its descendants.
withGuidwithGuid guid sourceOverrides GUID generation within this flow and its descendants.
withLogSinkwithLogSink sink sourceReplaces the log destination within this flow and its descendants.
mapLogSinkmapLogSink mapper sourceDecorates the destination already installed in this scope.
withTelemetrywithTelemetry telemetry sourceReplaces both telemetry slots within this flow and its descendants.
timeoutOptiontimeoutOption after flowReturns Some value when the flow succeeds in time, and None when the timeout wins.
superviseForeversuperviseForever backoff flowRestarts a flow forever on normal return and on unexpected defect, pacing restarts with backoff.
envWithFlowenvWithFlow projectionReads the environment and runs the flow the projection returns.
orDieorDie sourceTurns a typed failure into a defect, so the workflow crashes instead of returning the error.
retryForeverretryForever schedule flowRetries a flow's typed failures forever and never fails with a typed error.
provideprovide environment flowRuns a flow with a fixed environment, ignoring the caller's environment.
syncsync computeRuns a synchronous computation and succeeds with its result.
Run concurrently
runOnrunOn location sourceStarts a flow at the requested execution location.
supervisesupervise schedule flowRestarts a flow that terminates with an unexpected defect, according to a schedule.
forkfork flowStarts a flow in a new fiber without waiting for it to complete.
forkNamedforkNamed name flowStarts a flow in a new fiber carrying a diagnostic name.
forkGracefulforkGraceful stop grace flowStarts a flow in a new fiber that, when its forking scope closes, is asked to stop and given time to finish before it is interrupted.
forkDetachedforkDetached flowStarts a flow in a new fiber that is deliberately never awaited.
disconnectdisconnect flowLets interruption stop waiting for a flow without waiting for that flow to settle.
forkResourceforkResource (Resource(acquire, release)Starts acquiring a resource in a new fiber, keeping the resource in the caller's scope.
memoizememoize flowReturns a flow that runs flow at most once at a time and remembers its value.
forkReplacingforkReplacing slot flowStarts a flow in a new fiber held by slot, interrupting the fiber it replaces.
forkReplacingKeyforkReplacingKey key slots flowStarts a flow in a new fiber held under key, interrupting that key's previous fiber.
zipParzipPar left rightCombines two flows into a tuple of their values, running them concurrently.
sequenceParsequencePar flowsRuns all flows concurrently and returns their values in input order.
racerace left rightRuns two flows concurrently and returns the result of the first one to complete.
sequenceParWithsequenceParWith parallelism flowsRuns flows with bounded concurrency and the placement carried by parallelism.
Manage resources
scopeDisposablescopeDisposable resourceRegisters a disposable resource with the current runtime scope.
scopeAsyncDisposablescopeAsyncDisposable resourceRegisters an asynchronously disposable resource with the current runtime scope.
scopeResourcescopeResource (Resource(acquire, release)Acquires a described resource and registers its release with the current runtime scope.
scopeAcquireReleasescopeAcquireRelease acquire releaseAcquires a value and registers its release with the current runtime scope.
scopeFinalizerscopeFinalizer releaseRegisters a release flow with the current runtime scope.
scopedscoped flowRuns a flow in a child scope and closes that scope before returning.
onExitonExit handler flowRuns a handler with the flow's final outcome, whether it succeeded, failed, or was interrupted.
ensuringensuring finalizer flowRuns a finalizer after the flow, however it ends.
onInterruptonInterrupt handler flowRuns a handler only if the flow is interrupted.
Environment and time
withFiberObserverwithFiberObserver observer flowInstalls runtime fiber-lifecycle hooks for diagnostics and telemetry.
addFiberObserveraddFiberObserver observer flowAdds runtime fiber-lifecycle hooks, composing with any observer already installed.
withFiberRegistrywithFiberRegistry registry flowTracks every fiber forked inside the flow in registry.
withAnnotationSinkwithAnnotationSink sink flowInstalls a runtime annotation sink for integration packages.
addAnnotationSinkaddAnnotationSink sink flowAdds a runtime annotation sink, composing with any sink already installed.
annotateannotate name value flowAdds a runtime annotation for the duration of the supplied flow.
withTraceIdwithTraceId traceId flowAdds the standard trace_id runtime annotation for the duration of the supplied flow.
cancellationTokencancellationToken Reads the current runtime cancellation token.
ensureNotCanceledensureNotCanceled Stops with Cause.Interrupt if the runtime's cancellation token has been cancelled.
sleepsleep delaySuspends the flow for the specified duration, observing cancellation.
scopescope Reads the current runtime scope.
annotationsannotations Reads the current runtime annotations.
traceIdtraceId Reads the current trace id annotation, if one is present.
fiberIdfiberId Reads the current fiber id from the ambient runtime context.
timeouttimeout after timeoutError flowFails with the supplied typed error when the flow does not complete before the timeout.
timeoutToOktimeoutToOk after value flowReturns the supplied success value when the flow does not complete before the timeout.
timeoutToErrortimeoutToError after error flowSame as timeout; named to pair with timeoutToOk.
timeoutWithtimeoutWith after fallback flowRuns a fallback flow when the source flow does not complete before the timeout.
retryretry schedule flowRetries a flow's typed failures according to a schedule.
repeatrepeat schedule flowRepeats a successful flow according to a schedule.
envenv Reads the current environment as the successful flow value.
envWithenvWith projectionProjects one value from the current environment.
localEnvlocalEnv mapping flowRuns a flow against an environment derived from the outer environment.
Run and interop
fromAsyncfromAsync operationCreates a flow from a raw async operation.
fromAsyncResultfromAsyncResult operationCreates a flow from an async operation whose Error enters the typed error channel.
attemptAsyncattemptAsync operationCreates a flow from an async operation and treats thrown exceptions as recoverable typed errors.
fromBlockingfromBlocking operationCreates a flow from synchronous, blocking work, such as a database driver or native library call.
fromBlockingResultfromBlockingResult operationCreates a flow from blocking work whose Error enters the typed error channel.
attemptBlockingattemptBlocking operationCreates a flow from blocking work and treats thrown exceptions as recoverable typed errors.
fromTaskfromTask factoryCreates a flow from a cancellable task factory.
fromTaskResultfromTaskResult factoryCreates a flow from a cold task factory whose Error enters the typed error channel.
attemptTaskattemptTask factoryCreates a flow from a cancellable task factory and treats thrown exceptions as recoverable typed errors.
fromValueTaskfromValueTask factoryCreates a flow from a cancellable value-task factory.
fromValueTaskResultfromValueTaskResult factoryCreates a flow from a cold value-task factory whose Error enters the typed error channel.
attemptValueTaskattemptValueTask factoryCreates a flow from a cancellable value-task factory and treats thrown exceptions as recoverable typed errors.
fromUnitTaskfromUnitTask factoryCreates a flow from a cancellable factory for a Task with no result, such as a write, connect or copy.
attemptUnitTaskattemptUnitTask factoryCreates a flow from a cancellable factory for a Task with no result and treats thrown exceptions as recoverable typed errors.
fromUnitValueTaskfromUnitValueTask factoryCreates a flow from a cancellable factory for a ValueTask with no result.
attemptUnitValueTaskattemptUnitValueTask factoryCreates a flow from a cancellable factory for a ValueTask with no result and treats thrown exceptions as recoverable typed errors.
awaitStartedTaskawaitStartedTask startedTaskObserves a task that has already been started.
awaitStartedTaskResultawaitStartedTaskResult startedTaskObserves an already-started task whose Error enters the typed error channel.
attemptStartedTaskattemptStartedTask startedTaskObserves a task that has already been started and treats thrown exceptions as recoverable typed errors.
awaitStartedValueTaskawaitStartedValueTask startedValueTaskObserves a value task that has already been started.
awaitStartedValueTaskResultawaitStartedValueTaskResult startedValueTaskObserves an already-started value task whose Error enters the typed error channel.
attemptStartedValueTaskattemptStartedValueTask startedValueTaskObserves a value task that has already been started and treats thrown exceptions as recoverable typed errors.
toAsynctoAsync environment flowBuilds a cold async that runs the workflow when it is started.
startTaskstartTask environment flowStarts the workflow immediately and returns a task handle for its final exit.
runrun environment flowRuns the workflow and blocks until the final exit is available.
RunSynchronouslythis.RunSynchronouslyStarts the workflow and blocks until the final exit is available.
StartAsTaskthis.StartAsTaskStarts the workflow immediately and returns a task handle for its final exit.
StartAsValueTaskthis.StartAsValueTaskStarts the workflow immediately and returns a value-task handle for its final exit.
ToAsyncthis.ToAsyncBuilds a cold async that runs the workflow when it is started.

Create

kind:membertask:create

ofExit

ofExit exit
Member
Creates a flow from an execution outcome.

Parameters

NameTypeDescription
exitExit<'value, 'error>

Returns

Flow<'env, 'error, 'value>
kind:membertask:create

ok

ok value
Member
Creates a successful synchronous flow.

Parameters

NameTypeDescription
value'valueThe value to wrap in a successful flow.

Returns

Flow<'env, 'error, 'value>
kind:membertask:create

succeed

succeed value
Member
Same as ok.

Parameters

NameTypeDescription
value'valueThe value to wrap in a successful flow.

Returns

Flow<'env, 'error, 'value>

Verification Examples

let result = Flow.succeed 42 |> Flow.run ()
// result = Success 42
kind:membertask:create

error

error failure
Member
Creates a failing synchronous flow.

Parameters

NameTypeDescription
failure'errorThe error value to wrap in a failing flow.

Returns

Flow<'env, 'error, 'value>
kind:membertask:create

fail

fail failure
Member
Same as error.

Parameters

NameTypeDescription
failure'errorThe error value to wrap in a failing flow.

Returns

Flow<'env, 'error, 'value>

Verification Examples

let result = Flow.fail "error" |> Flow.run ()
// result = Failure (Cause.Fail "error")
kind:membertask:create

die

die exn
Member
Creates a defective flow that fails with an exception.

Parameters

NameTypeDescription
exnexnThe exception representing the defect.

Returns

Flow<'env, 'error, 'value>
kind:membertask:create

fromResult

fromResult result
Member
Lifts a Result`2 into a synchronous flow.

Parameters

NameTypeDescription
resultResult<'value, 'error>The result value to lift.

Returns

Flow<'env, 'error, 'value>

Verification Examples

Flow.fromResult (Ok "success") |> Flow.run ()
kind:membertask:create

verify

verify policy input
Member
Creates a flow that verifies an input with an environment-aware policy.

Parameters

NameTypeDescription
policyPolicy<'env, 'error, 'input, 'output>The reusable verification rule to apply.
input'inputThe input value to verify.

Returns

Flow<'env, 'error, 'output>
kind:membertask:create

fromOption

fromOption error value
Member
Lifts an option into a synchronous flow with the supplied error.

Parameters

NameTypeDescription
error'errorThe error to return if the option is None.
value'value optionThe option to lift.

Returns

Flow<'env, 'error, 'value>

Verification Examples

let opt = Some "value"
Flow.fromOption "missing" opt |> Flow.run ()
kind:membertask:create

fromValueOption

fromValueOption error value
Member
Lifts a value option into a synchronous flow with the supplied error.

Parameters

NameTypeDescription
error'errorThe error to return if the value option is ValueNone.
value'value voptionThe value option to lift.

Returns

Flow<'env, 'error, 'value>
kind:membertask:create

never

never
Member
A flow that never completes on its own; it ends only when it is interrupted.

Returns

Flow<'env, 'error, 'value>

Verification Examples

// Runs the worker until the service is interrupted, then lets it drain its queue.
let serve (jobs: Queue<string>) (worker: Flow<unit, Never, unit>) : Flow<unit, Never, unit> =
    flow {
        let! _ =
            worker |> Flow.forkGraceful (Dequeue.shutdown jobs) (TimeSpan.FromSeconds 5.0)
        return! Flow.never
    }
kind:membertask:create

delay

delay factory
Member
Defers flow construction until execution time.

Parameters

NameTypeDescription
factoryunit -> Flow<'env, 'error, 'value>A function that returns the flow to execute.

Returns

Flow<'env, 'error, 'value>

Verification Examples

let flow = Flow.delay (fun () -> Flow.succeed 42)

Transform

kind:membertask:transform

map

map mapper flow
Member
Transforms the successful value of a flow.

Parameters

NameTypeDescription
mapper'value -> 'nextA function of type 'value -> 'next to transform the successful value.
flowFlow<'env, 'error, 'value>The source flow of type Axial`3 to transform.

Returns

Flow<'env, 'error, 'next>

Verification Examples

let flow = Flow.succeed 1 |> Flow.map (fun x -> x + 1)
kind:membertask:transform

ignore

ignore flow
Member
Maps the successful value of a synchronous flow to unit.

Parameters

NameTypeDescription
flowFlow<'env, 'error, 'value>The source flow.

Returns

Flow<'env, 'error, unit>

Verification Examples

let flow = Flow.succeed 42 |> Flow.ignore
kind:membertask:transform

bind

bind binder flow
Member
Sequences a dependent flow after a successful value.

Parameters

NameTypeDescription
binder'value -> Flow<'env, 'error, 'next>A function that takes the successful value and returns a new flow.
flowFlow<'env, 'error, 'value>The source flow to sequence.

Returns

Flow<'env, 'error, 'next>

Verification Examples

let flow = Flow.succeed 1 |> Flow.bind (fun x -> Flow.succeed (x + 1))
kind:membertask:transform

(>>=)

flow >>= binder
Member
Sequences a synchronous continuation after a successful value.

Parameters

NameTypeDescription
flowFlow<'env, 'error, 'value>
binder'value -> Flow<'env, 'error, 'next>

Returns

Flow<'env, 'error, 'next>
kind:membertask:transform

tap

tap binder flow
Member
Runs an effect on success and preserves the original value.

Parameters

NameTypeDescription
binder'value -> Flow<'env, 'error, unit>A function that produces a side-effect flow from the successful value.
flowFlow<'env, 'error, 'value>The source flow.

Returns

Flow<'env, 'error, 'value>

Verification Examples

let flow = Flow.succeed 42 |> Flow.tap (fun x -> Flow.succeed ())
kind:membertask:transform

tapError

tapError binder flow
Member
Runs a synchronous side effect on failure and preserves the original error.

Parameters

NameTypeDescription
binder'error -> Flow<'env, 'error, unit>A function that produces a side-effect flow from the error value.
flowFlow<'env, 'error, 'value>The source flow.

Returns

Flow<'env, 'error, 'value>

Verification Examples

let flow = Flow.fail "error" |> Flow.tapError (fun err -> Flow.succeed ())
kind:membertask:transform

mapBoth

mapBoth onSuccess onFailure flow
Member
Maps both the successful value and the failure cause of a synchronous flow.

Parameters

NameTypeDescription
onSuccess'value -> 'nextThe function to transform the success value.
onFailureCause<'error> -> Cause<'nextError>The function to transform the failure cause.
flowFlow<'env, 'error, 'value>The source flow.

Returns

Flow<'env, 'nextError, 'next>

Combine and sequence

kind:membertask:combine

zip

zip left right
Member
Runs two flows sequentially and combines their successful values into a tuple.

Parameters

NameTypeDescription
leftFlow<'env, 'error, 'left>The first flow to run.
rightFlow<'env, 'error, 'right>The second flow to run.

Returns

Flow<'env, 'error, ('left * 'right)>

Verification Examples

Flow.zip (Flow.succeed 1) (Flow.succeed 2) |> Flow.run ()
kind:membertask:combine

map2

map2 mapper left right
Member
Combines two flows with a mapping function.

Parameters

NameTypeDescription
mapper'left -> 'right -> 'valueA function that combines the successful values of both flows.
leftFlow<'env, 'error, 'left>The first flow to run.
rightFlow<'env, 'error, 'right>The second flow to run.

Returns

Flow<'env, 'error, 'value>

Verification Examples

let flow = Flow.map2 (fun x y -> x + y) (Flow.succeed 1) (Flow.succeed 2)
kind:membertask:combine

apply

apply flow value
Member
Applies a flow-wrapped function to a flow-wrapped value.

Parameters

NameTypeDescription
flowFlow<'env, 'error, ('value -> 'next)>A flow that contains a function to apply.
valueFlow<'env, 'error, 'value>A flow that contains the value to apply the function to.

Returns

Flow<'env, 'error, 'next>

Verification Examples

let flow = Flow.apply (Flow.succeed (fun x -> x + 1)) (Flow.succeed 1)
kind:membertask:combine

map3

map3 mapper left middle right
Member
Combines three flows with a mapping function.

Parameters

NameTypeDescription
mapper'left -> 'middle -> 'right -> 'valueA function that combines the successful values of all three flows.
leftFlow<'env, 'error, 'left>The first flow to run.
middleFlow<'env, 'error, 'middle>The second flow to run.
rightFlow<'env, 'error, 'right>The third flow to run.

Returns

Flow<'env, 'error, 'value>

Verification Examples

let flow =
    Flow.map3 (fun x y z -> x + y + z) (Flow.succeed 1) (Flow.succeed 2) (Flow.succeed 3)
kind:membertask:combine

(<!>)

mapper <!> flow
Member
Maps the successful value of a synchronous flow.

Parameters

NameTypeDescription
mapper'value -> 'next
flowFlow<'env, 'error, 'value>

Returns

Flow<'env, 'error, 'next>
kind:membertask:combine

(<*>)

flow <*> value
Member
Applies a flow-wrapped function to a flow-wrapped value.

Parameters

NameTypeDescription
flowFlow<'env, 'error, ('value -> 'next)>
valueFlow<'env, 'error, 'value>

Returns

Flow<'env, 'error, 'next>
kind:membertask:combine

traverse

traverse mapping values
Member
Transforms a sequence of values into a flow and stops at the first failure.

Parameters

NameTypeDescription
mapping'value -> Flow<'env, 'error, 'next>A function that maps each value to a flow.
values'value seqThe sequence of values to transform.

Returns

Flow<'env, 'error, 'next list>

Verification Examples

let double n = Flow.sync (fun () -> printfn "double %d" n; n * 2)
[1; 2; 3]
|> Flow.traverse double
|> Flow.run ()
// prints: double 1, double 2, double 3 (one at a time, in order)
// result = Success [2; 4; 6]

let positive n = if n > 0 then double n else Flow.fail $"{n} is not positive"
[1; -2; 3]
|> Flow.traverse positive
|> Flow.run ()
// prints: double 1 (it stops at -2, so 3 never runs)
// result = Failure (Cause.Fail "-2 is not positive")
kind:membertask:combine

forEach

forEach action values
Member
Runs a flow for each value in order and stops at the first failure, keeping no results.

Parameters

NameTypeDescription
action'value -> Flow<'env, 'error, unit>The flow to run for each value.
values'value seqThe values to process.

Returns

Flow<'env, 'error, unit>

Verification Examples

let save n = Flow.sync (fun () -> printfn "saved %d" n)
[1; 2; 3]
|> Flow.forEach save
|> Flow.run ()
// prints: saved 1, saved 2, saved 3 (one at a time, in order)
// result = Success () (no list is kept)

let saveOdd n = if n % 2 = 0 then Flow.fail $"{n} is even" else save n
[1; 2; 3]
|> Flow.forEach saveOdd
|> Flow.run ()
// prints: saved 1 (it stops at 2, so 3 is never saved)
// result = Failure (Cause.Fail "2 is even")
kind:membertask:combine

traversePar

traversePar parallelism mapping values
Member
Maps values to flows and runs them with bounded concurrency, returning results in input order.

Parameters

NameTypeDescription
parallelismParallelismThe maximum number of mappings running at once.
mapping'value -> Flow<'env, 'error, 'next>Maps each value to a flow.
values'value seqThe values to map.

Returns

Flow<'env, 'error, 'next list>

Verification Examples

let fetch (name: string, ms: float) =
    flow {
        printfn "start %s" name
        do! Flow.sleep (TimeSpan.FromMilliseconds ms)
        printfn "done %s" name
        return name.ToUpper()
    }

[ "a", 400.0; "b", 100.0; "c", 100.0 ]
|> Flow.traversePar (Parallelism.bounded 2) fetch
|> Flow.run ()
// prints: start a, start b, done b, start c, done c, done a
// (at most 2 at once: c starts when b is done; about 400 ms in all, not 600)
// result = Success ["A"; "B"; "C"] (input order, though a finished last)

let fetchUnlessB (name, ms) =
    if name = "b" then Flow.fail "b failed" else fetch (name, ms)
[ "a", 400.0; "b", 100.0; "c", 100.0 ]
|> Flow.traversePar (Parallelism.bounded 2) fetchUnlessB
|> Flow.run ()
// prints: start a (b fails at once, so a is interrupted before it is done and c never starts)
// result = Failure (Cause.Fail "b failed")
kind:membertask:combine

traverseParUsing

traverseParUsing parallelism resource mapping values
Member
Like traversePar, giving each worker its own resource, acquired once and reused for every value it maps.

Parameters

NameTypeDescription
parallelismParallelismThe maximum number of workers, and so of resources.
resourceResource<'env, 'error, 'resource>The resource each worker acquires.
mapping'resource -> 'value -> Flow<'env, 'error, 'next>Maps a value to a flow, given the worker's resource.
values'value seqThe values to map.

Returns

Flow<'env, 'error, 'next list>

Verification Examples

let connection =
    Resource.create
        (Flow.sync (fun () -> printfn "open"; "connection"))
        (fun _ -> Flow.sync (fun () -> printfn "close"))

let load connection n =
    Flow.sleep (TimeSpan.FromMilliseconds 10.0)
    |> Flow.map (fun () -> n * 10)

[1..6]
|> Flow.traverseParUsing (Parallelism.bounded 2) connection load
|> Flow.run ()
// prints: open twice and close twice (one connection per worker, reused for all six values)
// result = Success [10; 20; 30; 40; 50; 60] (input order)
kind:membertask:combine

forEachPar

forEachPar parallelism action values
Member
Runs a flow for each value with bounded concurrency, discarding the results.

Parameters

NameTypeDescription
parallelismParallelismThe maximum number of flows running at once.
action'value -> Flow<'env, 'error, unit>The flow to run for each value.
values'value seqThe values to process.

Returns

Flow<'env, 'error, unit>

Verification Examples

let index (name: string, ms: float) =
    flow {
        printfn "start %s" name
        do! Flow.sleep (TimeSpan.FromMilliseconds ms)
        printfn "done %s" name
    }

[ "a", 400.0; "b", 100.0; "c", 100.0 ]
|> Flow.forEachPar (Parallelism.bounded 2) index
|> Flow.run ()
// prints: start a, start b, done b, start c, done c, done a (at most 2 at once)
// result = Success () (no list is kept)

let indexUnlessB (name, ms) =
    if name = "b" then Flow.fail "b failed" else index (name, ms)
[ "a", 400.0; "b", 100.0; "c", 100.0 ]
|> Flow.forEachPar (Parallelism.bounded 2) indexUnlessB
|> Flow.run ()
// prints: start a (b fails at once, so a is interrupted before it is done and c never starts)
// result = Failure (Cause.Fail "b failed")
kind:membertask:combine

forEachParUsing

forEachParUsing parallelism resource action values
Member
Like forEachPar, giving each worker its own resource, acquired once and reused for every value it processes.

Parameters

NameTypeDescription
parallelismParallelismThe maximum number of workers, and so of resources.
resourceResource<'env, 'error, 'resource>The resource each worker acquires.
action'resource -> 'value -> Flow<'env, 'error, unit>The flow to run for each value, given the worker's resource.
values'value seqThe values to process.

Returns

Flow<'env, 'error, unit>

Verification Examples

let connection =
    Resource.create
        (Flow.sync (fun () -> printfn "open"; "connection"))
        (fun _ -> Flow.sync (fun () -> printfn "close"))

let store connection n = Flow.sleep (TimeSpan.FromMilliseconds 10.0)

[1..6]
|> Flow.forEachParUsing (Parallelism.bounded 2) connection store
|> Flow.run ()
// prints: open twice and close twice (one connection per worker, reused for all six values)
// result = Success () (no list is kept)
kind:membertask:combine

sequence

sequence flows
Member
Transforms a sequence of flows into a flow of a sequence and stops at the first failure.

Parameters

NameTypeDescription
flowsFlow<'env, 'error, 'value> seqThe sequence of flows to run.

Returns

Flow<'env, 'error, 'value list>

Verification Examples

let step n = Flow.sync (fun () -> printfn "step %d" n; n)
let steps = [ step 1; step 2; step 3 ] // prints nothing: a flow runs only when it is run
steps
|> Flow.sequence
|> Flow.run ()
// prints: step 1, step 2, step 3 (one at a time, in order)
// result = Success [1; 2; 3]

[ step 1; Flow.fail "stop"; step 3 ]
|> Flow.sequence
|> Flow.run ()
// prints: step 1 (it stops at the failure, so step 3 never runs)
// result = Failure (Cause.Fail "stop")

Errors and recovery

kind:membertask:errors

catchCancellation

catchCancellation handler flow
Member
Turns cancellation that a flow raised for its own reasons into a typed error.

Parameters

NameTypeDescription
handlerOperationCanceledException -> 'errorMaps the cancellation exception into the workflow error type.
flowFlow<'env, 'error, 'value>The source flow.

Returns

Flow<'env, 'error, 'value>
kind:membertask:errors

orElseFlow

orElseFlow errorFlow result
Member
Attaches an environment-derived error to a result that failed without one; the error flow runs only on failure.

Parameters

NameTypeDescription
errorFlowFlow<'env, 'error, 'error>A flow that reads the environment to produce an error value.
resultResult<'value, unit>The pure result to bridge.

Returns

Flow<'env, 'error, 'value>

Verification Examples

let result = Result.Error ()
let flow = Flow.orElseFlow (Flow.envWith (fun env -> "error")) result
kind:membertask:errors

mapError

mapError mapper flow
Member
Maps the error value of a synchronous flow.

Parameters

NameTypeDescription
mapper'error -> 'nextErrorThe function to transform the error value.
flowFlow<'env, 'error, 'value>The source flow.

Returns

Flow<'env, 'nextError, 'value>

Verification Examples

let flow = Flow.fail "error" |> Flow.mapError (fun err -> err + "!")
kind:membertask:errors

widenError

widenError flow
Member
Gives a flow that cannot fail with a typed error any error type.

Parameters

NameTypeDescription
flowFlow<'env, Never, 'value>

Returns

Flow<'env, 'error, 'value>

Verification Examples

let ready : Flow<unit, string, int> = Flow.succeed 1 |> Flow.widenError
kind:membertask:errors

tracedError

tracedError trace flow
Member
Attaches diagnostic trace text to any failure cause of the flow.

Parameters

NameTypeDescription
tracestringThe diagnostic trace text, typically an operation or boundary name.
flowFlow<'env, 'error, 'value>The source flow.

Returns

Flow<'env, 'error, 'value>

Verification Examples

let flow = loadUser |> Flow.tracedError "billing.load-user"
kind:membertask:errors

foldCauseFlow

foldCauseFlow onSuccess onFailure flow
Member
Folds both the successful value and the full failure cause into a new flow.

Parameters

NameTypeDescription
onSuccess'value -> Flow<'env, 'nextError, 'next>A function that returns a new flow from the success value.
onFailureCause<'error> -> Flow<'env, 'nextError, 'next>A function that returns a new flow from the failure cause.
flowFlow<'env, 'error, 'value>The source flow.

Returns

Flow<'env, 'nextError, 'next>
kind:membertask:errors

exit

exit source
Member
Runs a flow and succeeds with its whole outcome as an Exit.

Parameters

NameTypeDescription
sourceFlow<'env, 'error, 'value>The source flow.

Returns

Flow<'env, 'nextError, Exit<'value, 'error>>

Verification Examples

let observed : Flow<'env, Never, Exit<int, string>> =
    Flow.fail "boom" |> Flow.exit
kind:membertask:errors

catch

catch handler flow
Member
Catches exceptions raised during execution and simple defect outcomes, then maps them to a typed error.

Parameters

NameTypeDescription
handlerexn -> 'errorA function of type exn -> 'error to map the exception.
flowFlow<'env, 'error, 'value>The source flow of type Axial`3 to monitor.

Returns

Flow<'env, 'error, 'value>

Verification Examples

let flow =
    Flow.die (System.Exception("boom"))
    |> Flow.catch (fun ex -> "caught: " + ex.Message)
kind:membertask:errors

orElseWith

orElseWith fallback flow
Member
Computes a fallback flow from the typed error when the source flow fails.

Parameters

NameTypeDescription
fallback'error -> Flow<'env, 'error, 'value>A function that produces a new flow from the error value.
flowFlow<'env, 'error, 'value>The source flow.

Returns

Flow<'env, 'error, 'value>

Verification Examples

let flow =
    Flow.fail "error"
    |> Flow.orElseWith (fun err -> Flow.succeed "recovered")
kind:membertask:errors

recover

recover handler source
Member

Parameters

NameTypeDescription
handler'error -> Flow<'env, 'nextError, 'value>
sourceFlow<'env, 'error, 'value>

Returns

Flow<'env, 'nextError, 'value>
kind:membertask:errors

foldFlow

foldFlow onSuccess onError source
Member
Folds a successful value or a single typed failure into a new flow.

Parameters

NameTypeDescription
onSuccess'value -> Flow<'env, 'nextError, 'next>A function that returns a new flow from the success value.
onError'error -> Flow<'env, 'nextError, 'next>A function that returns a new flow from the typed error.
sourceFlow<'env, 'error, 'value>The source flow.

Returns

Flow<'env, 'nextError, 'next>
kind:membertask:errors

fold

fold onSuccess onError source
Member
Folds a successful value or a single typed failure into a plain value.

Parameters

NameTypeDescription
onSuccess'value -> 'nextA function that maps the success value.
onError'error -> 'nextA function that maps the typed error.
sourceFlow<'env, 'error, 'value>The source flow.

Returns

Flow<'env, 'nextError, 'next>

Verification Examples

let response : Flow<'env, Never, Response> =
    loadOrder id
    |> Flow.fold render (fun error -> Http.problem 500 (OrderError.describe error))
kind:membertask:errors

orElse

orElse fallback flow
Member
Falls back to another flow when the source flow fails.

Parameters

NameTypeDescription
fallbackFlow<'env, 'error, 'value>The flow to run if the source flow fails.
flowFlow<'env, 'error, 'value>The source flow.

Returns

Flow<'env, 'error, 'value>

Verification Examples

let flow = Flow.fail "error" |> Flow.orElse (Flow.succeed "recovered")

Operations

kind:member

fromColdTask

fromColdTask operation
Member
Creates a flow from an existing cold task value.

Parameters

NameTypeDescription
operationColdTask<'value>The cold task to run on each execution.

Returns

Flow<'env, 'error, 'value>
kind:member

fromColdTaskResult

fromColdTaskResult operation
Member
Creates a flow from an existing cold task value whose Error enters the typed error channel.

Parameters

NameTypeDescription
operationColdTask<Result<'value, 'error>>The cold task to run on each execution.

Returns

Flow<'env, 'error, 'value>
kind:member

withClock

withClock clock source
Member
Overrides the clock within this flow and its descendants.

Parameters

NameTypeDescription
clockIClock
sourceFlow<'env, 'error, 'value>

Returns

Flow<'env, 'error, 'value>
kind:member

withRandom

withRandom random source
Member
Overrides random values within this flow and its descendants.

Parameters

NameTypeDescription
randomIRandom
sourceFlow<'env, 'error, 'value>

Returns

Flow<'env, 'error, 'value>
kind:member

withGuid

withGuid guid source
Member
Overrides GUID generation within this flow and its descendants.

Parameters

NameTypeDescription
guidIGuid
sourceFlow<'env, 'error, 'value>

Returns

Flow<'env, 'error, 'value>
kind:member

withLogSink

withLogSink sink source
Member
Replaces the log destination within this flow and its descendants.

Parameters

NameTypeDescription
sinkILogSink
sourceFlow<'env, 'error, 'value>

Returns

Flow<'env, 'error, 'value>
kind:member

mapLogSink

mapLogSink mapper source
Member
Decorates the destination already installed in this scope.

Parameters

NameTypeDescription
mapperILogSink -> ILogSink
sourceFlow<'env, 'error, 'value>

Returns

Flow<'env, 'error, 'value>
kind:member

withTelemetry

withTelemetry telemetry source
Member
Replaces both telemetry slots within this flow and its descendants.

Parameters

NameTypeDescription
telemetryITelemetry
sourceFlow<'env, 'error, 'value>

Returns

Flow<'env, 'error, 'value>
kind:member

timeoutOption

timeoutOption after flow
Member
Returns Some value when the flow succeeds in time, and None when the timeout wins.

Parameters

NameTypeDescription
afterTimeSpanThe timeout duration.
flowFlow<'env, 'error, 'value>The source flow.

Returns

Flow<'env, 'error, 'value option>
kind:member

superviseForever

superviseForever backoff flow
Member
Restarts a flow forever on normal return and on unexpected defect, pacing restarts with backoff.

Parameters

NameTypeDescription
backoffBackoffThe delay before each restart.
flowFlow<'env, 'error, 'value>The flow to keep running.

Returns

Flow<'env, 'error, 'value>
kind:member

envWithFlow

envWithFlow projection
Member
Reads the environment and runs the flow the projection returns.

Parameters

NameTypeDescription
projection'env -> Flow<'env, 'error, 'value>A function that returns a flow from the environment.

Returns

Flow<'env, 'error, 'value>
kind:member

orDie

orDie source
Member
Turns a typed failure into a defect, so the workflow crashes instead of returning the error.

Parameters

NameTypeDescription
sourceFlow<'env, 'error, 'value>

Returns

Flow<'env, 'nextError, 'value>
kind:member

retryForever

retryForever schedule flow
Member
Retries a flow's typed failures forever and never fails with a typed error.

Parameters

NameTypeDescription
scheduleSchedule<'env, 'error, 'output>An infinite schedule built with Schedule.spaced or Schedule.exponential.
flowFlow<'env, 'error, 'value>The flow to retry.

Returns

Flow<'env, 'nextError, 'value>
kind:member

provide

provide environment flow
Member
Runs a flow with a fixed environment, ignoring the caller's environment.

Parameters

NameTypeDescription
environment'envThe environment to supply to the flow.
flowFlow<'env, 'error, 'value>The flow to run with the supplied environment.

Returns

Flow<'outer, 'error, 'value>
kind:member

sync

sync compute
Member
Runs a synchronous computation and succeeds with its result.

Parameters

NameTypeDescription
computeunit -> 'valueThe synchronous computation to run at execution time.

Returns

Flow<'env, 'error, 'value>

Run concurrently

kind:membertask:concurrency

runOn

runOn location source
Member
Starts a flow at the requested execution location.

Parameters

NameTypeDescription
locationRunOnWhere the wrapped flow starts.
sourceFlow<'env, 'error, 'value>The flow to start there.

Returns

Flow<'env, 'error, 'value>

Verification Examples

let parallel =
    jobs
    |> List.map (fun job -> compute job |> Flow.runOn RunOn.ThreadPool)
    |> Flow.sequencePar
kind:membertask:concurrency

supervise

supervise schedule flow
Member
Restarts a flow that terminates with an unexpected defect, according to a schedule.

Parameters

NameTypeDescription
scheduleSchedule<'env, exn, 'output>Decides, from each defect, whether to restart and after what delay.
flowFlow<'env, 'error, 'value>The flow to supervise.

Returns

Flow<'env, 'error, 'value>

Verification Examples

worker |> Flow.supervise (Retry.schedule { Retry.defaults with Retries = 5 })
kind:membertask:concurrency

fork

fork flow
Member
Starts a flow in a new fiber without waiting for it to complete.

Parameters

NameTypeDescription
flowFlow<'env, 'error, 'value>The flow to fork.

Returns

Flow<'env, 'none, Fiber<'error, 'value>>
kind:membertask:concurrency

forkNamed

forkNamed name flow
Member
Starts a flow in a new fiber carrying a diagnostic name.

Parameters

NameTypeDescription
namestringThe diagnostic name recorded in the fiber's metadata.
flowFlow<'env, 'error, 'value>The flow to fork.

Returns

Flow<'env, 'none, Fiber<'error, 'value>>
kind:membertask:concurrency

forkGraceful

forkGraceful stop grace flow
Member
Starts a flow in a new fiber that, when its forking scope closes, is asked to stop and given time to finish before it is interrupted.

Parameters

NameTypeDescription
stopFlow<'env, Never, unit>Asks the fiber to finish, for example by shutting down the queue it consumes.
graceTimeSpanHow long to wait after stop before interrupting the fiber.
flowFlow<'env, 'error, 'value>The flow to fork.

Returns

Flow<'env, 'none, Fiber<'error, 'value>>

Verification Examples

flow {
    let! (samples: Queue<float>) = Queue.bounded 1000
    let! _ =
        samples
        |> FlowStream.fromDequeue
        |> FlowStream.runForEachFlow writeSample
        |> Flow.forkGraceful (Dequeue.shutdown samples) (TimeSpan.FromSeconds 5.0)
    do! samples |> Queue.offer 21.5 |> Flow.ignore
}
|> Flow.scoped // closing the scope flushes every offered sample before returning
kind:membertask:concurrency

forkDetached

forkDetached flow
Member
Starts a flow in a new fiber that is deliberately never awaited.

Parameters

NameTypeDescription
flowFlow<'env, 'error, 'value>The flow to fork.

Returns

Flow<'env, 'none, Fiber<'error, 'value>>
kind:membertask:concurrency

disconnect

disconnect flow
Member
Lets interruption stop waiting for a flow without waiting for that flow to settle.

Parameters

NameTypeDescription
flowFlow<'env, 'error, 'value>The flow whose settlement may outlive an interrupted caller.

Returns

Flow<'env, 'error, 'value>
kind:membertask:concurrency

forkResource

forkResource (Resource(acquire, release)
Member
Starts acquiring a resource in a new fiber, keeping the resource in the caller's scope.

Parameters

NameTypeDescription
Resource(acquire, releaseResource<'env, 'error, 'value>

Returns

Flow<'env, 'none, Fiber<'error, 'value>>

Verification Examples

flow {
    let! connecting = Flow.forkResource databaseConnection
    let! config = loadConfig
    let! connection = Fiber.join connecting // still open
    return! migrate connection config
}
|> Flow.scoped // the connection is released here
kind:membertask:concurrency

memoize

memoize flow
Member
Returns a flow that runs flow at most once at a time and remembers its value.

Parameters

NameTypeDescription
flowFlow<'env, 'error, 'value>The computation to share.

Returns

Flow<'env, 'none, Flow<'caller, 'error, 'value>>

Verification Examples

let readConfig : Flow<unit, string, string> =
    Flow.delay (fun () -> Flow.ok "config")

let sameConfig : Flow<unit, string, bool> =
    flow {
        let! loadConfig = Flow.memoize readConfig
        let! a = loadConfig
        let! b = loadConfig // readConfig ran once
        return a = b
    }
kind:membertask:concurrency

forkReplacing

forkReplacing slot flow
Member
Starts a flow in a new fiber held by slot, interrupting the fiber it replaces.

Parameters

NameTypeDescription
slotFiberSlot<'error, 'value>The slot that holds the current fiber.
flowFlow<'env, 'error, 'value>The flow to run.

Returns

Flow<'env, 'none, Fiber<'error, 'value>>

Verification Examples

let onQueryChanged slot query =
    search query |> Flow.forkReplacing slot |> Flow.ignore
kind:membertask:concurrency

forkReplacingKey

forkReplacingKey key slots flow
Member
Starts a flow in a new fiber held under key, interrupting that key's previous fiber.

Parameters

NameTypeDescription
key'keyThe key whose previous fiber is replaced.
slotsKeyedFiberSlot<'key, 'error, 'value>The keyed slot that holds the current fibers.
flowFlow<'env, 'error, 'value>The flow to run.

Returns

Flow<'env, 'none, Fiber<'error, 'value>>

Verification Examples

loadPreview document |> Flow.forkReplacingKey document.Id previews
kind:membertask:concurrency

zipPar

zipPar left right
Member
Combines two flows into a tuple of their values, running them concurrently.

Parameters

NameTypeDescription
leftFlow<'env, 'error, 'left>The first flow to combine.
rightFlow<'env, 'error, 'right>The second flow to combine.

Returns

Flow<'env, 'error, ('left * 'right)>

Verification Examples

let combined = Flow.zipPar (Flow.succeed 1) (Flow.succeed 2)
combined |> Flow.run ()
kind:membertask:concurrency

sequencePar

sequencePar flows
Member
Runs all flows concurrently and returns their values in input order.

Parameters

NameTypeDescription
flowsFlow<'env, 'error, 'value> list

Returns

Flow<'env, 'error, 'value list>

Verification Examples

let after (ms: float) (name: string) =
    flow {
        printfn "start %s" name
        do! Flow.sleep (TimeSpan.FromMilliseconds ms)
        printfn "done %s" name
        return name
    }

[ after 400.0 "a"; after 100.0 "b"; after 200.0 "c" ]
|> Flow.sequencePar
|> Flow.run ()
// prints: start a, start b, start c, done b, done c, done a (all at once, with no limit)
// result = Success ["a"; "b"; "c"] (input order, though a finished last)

[ after 400.0 "a"; Flow.fail "b failed"; after 200.0 "c" ]
|> Flow.sequencePar
|> Flow.run ()
// prints: start a, start c (b fails, so a and c are interrupted before they are done)
// result = Failure (Cause.Fail "b failed")
kind:membertask:concurrency

race

race left right
Member
Runs two flows concurrently and returns the result of the first one to complete.

Parameters

NameTypeDescription
leftFlow<'env, 'error, 'value>The first flow to run.
rightFlow<'env, 'error, 'value>The second flow to run.

Returns

Flow<'env, 'error, 'value>

Verification Examples

let fastOrSlow = Flow.race (Flow.succeed "cached") (Flow.succeed "loaded")
fastOrSlow |> Flow.run ()
kind:membertask:concurrency

sequenceParWith

sequenceParWith parallelism flows
Member
Runs flows with bounded concurrency and the placement carried by parallelism.

Parameters

NameTypeDescription
parallelismParallelism
flowsFlow<'env, 'error, 'value> seq

Returns

Flow<'env, 'error, 'value list>

Verification Examples

let after (ms: float) (name: string) =
    flow {
        printfn "start %s" name
        do! Flow.sleep (TimeSpan.FromMilliseconds ms)
        printfn "done %s" name
        return name
    }

[ after 400.0 "a"; after 100.0 "b"; after 100.0 "c" ]
|> Flow.sequenceParWith (Parallelism.bounded 2)
|> Flow.run ()
// prints: start a, start b, done b, start c, done c, done a (at most 2 at once)
// result = Success ["a"; "b"; "c"] (input order)

Manage resources

kind:membertask:resources

scopeDisposable

scopeDisposable resource
Member
Registers a disposable resource with the current runtime scope.

Parameters

NameTypeDescription
resourceIDisposableThe disposable resource to close when the current scope closes.

Returns

Flow<'env, 'error, unit>
kind:membertask:resources

scopeAsyncDisposable

scopeAsyncDisposable resource
Member
Registers an asynchronously disposable resource with the current runtime scope.

Parameters

NameTypeDescription
resourceIAsyncDisposableThe async disposable resource to close when the current scope closes.

Returns

Flow<'env, 'error, unit>
kind:membertask:resources

scopeResource

scopeResource (Resource(acquire, release)
Member
Acquires a described resource and registers its release with the current runtime scope.

Parameters

NameTypeDescription
Resource(acquire, releaseResource<'env, 'error, 'value>

Returns

Flow<'env, 'error, 'value>
kind:membertask:resources

scopeAcquireRelease

scopeAcquireRelease acquire release
Member
Acquires a value and registers its release with the current runtime scope.

Parameters

NameTypeDescription
acquireFlow<'env, 'error, 'resource>The flow that acquires the value.
release'resource -> Flow<'env, Never, unit>The release flow run when the current scope closes.

Returns

Flow<'env, 'error, 'resource>
kind:membertask:resources

scopeFinalizer

scopeFinalizer release
Member
Registers a release flow with the current runtime scope.

Parameters

NameTypeDescription
releaseFlow<'env, Never, unit>The release flow run when the current scope closes.

Returns

Flow<'env, 'error, unit>
kind:membertask:resources

scoped

scoped flow
Member
Runs a flow in a child scope and closes that scope before returning.

Parameters

NameTypeDescription
flowFlow<'env, 'error, 'value>

Returns

Flow<'env, 'error, 'value>
kind:membertask:resources

onExit

onExit handler flow
Member
Runs a handler with the flow's final outcome, whether it succeeded, failed, or was interrupted.

Parameters

NameTypeDescription
handlerExit<'value, 'error> -> Flow<'env, Never, unit>Receives the flow's Exit; it cannot fail with a typed error.
flowFlow<'env, 'error, 'value>The source flow.

Returns

Flow<'env, 'error, 'value>

Verification Examples

transfer
|> Flow.onExit (fun exit ->
    match exit with
    | Exit.Success _ -> audit "transfer committed"
    | Exit.Failure _ -> audit "transfer rolled back")
kind:membertask:resources

ensuring

ensuring finalizer flow
Member
Runs a finalizer after the flow, however it ends.

Parameters

NameTypeDescription
finalizerFlow<'env, Never, unit>The cleanup to run; it cannot fail with a typed error.
flowFlow<'env, 'error, 'value>The source flow.

Returns

Flow<'env, 'error, 'value>

Verification Examples

render frame
|> Flow.ensuring (Flow.delay (fun () -> canvas.Unlock(); Flow.ok ()))
kind:membertask:resources

onInterrupt

onInterrupt handler flow
Member
Runs a handler only if the flow is interrupted.

Parameters

NameTypeDescription
handlerFlow<'env, Never, unit>The cleanup to run on interruption; it cannot fail with a typed error.
flowFlow<'env, 'error, 'value>The source flow.

Returns

Flow<'env, 'error, 'value>

Verification Examples

upload |> Flow.onInterrupt (deletePartialFile path)

Environment and time

kind:membertask:environment-time

withFiberObserver

withFiberObserver observer flow
Member
Installs runtime fiber-lifecycle hooks for diagnostics and telemetry.

Parameters

NameTypeDescription
observerFiberObserverThe lifecycle hooks. Start from FiberObserver.none and override what you need.
flowFlow<'env, 'error, 'value>The source flow.

Returns

Flow<'env, 'error, 'value>
kind:membertask:environment-time

addFiberObserver

addFiberObserver observer flow
Member
Adds runtime fiber-lifecycle hooks, composing with any observer already installed.

Parameters

NameTypeDescription
observerFiberObserverThe lifecycle hooks to add.
flowFlow<'env, 'error, 'value>The source flow.

Returns

Flow<'env, 'error, 'value>
kind:membertask:environment-time

withFiberRegistry

withFiberRegistry registry flow
Member
Tracks every fiber forked inside the flow in registry.

Parameters

NameTypeDescription
registryFiberRegistryThe registry that receives fiber lifecycle events.
flowFlow<'env, 'error, 'value>The source flow.

Returns

Flow<'env, 'error, 'value>
kind:membertask:environment-time

withAnnotationSink

withAnnotationSink sink flow
Member
Installs a runtime annotation sink for integration packages.

Parameters

NameTypeDescription
sinkstring -> string -> unit
flowFlow<'env, 'error, 'value>

Returns

Flow<'env, 'error, 'value>
kind:membertask:environment-time

addAnnotationSink

addAnnotationSink sink flow
Member
Adds a runtime annotation sink, composing with any sink already installed.

Parameters

NameTypeDescription
sinkstring -> string -> unit
flowFlow<'env, 'error, 'value>

Returns

Flow<'env, 'error, 'value>
kind:membertask:environment-time

annotate

annotate name value flow
Member
Adds a runtime annotation for the duration of the supplied flow.

Parameters

NameTypeDescription
namestringThe annotation key.
valuestringThe annotation value.
flowFlow<'env, 'error, 'value>The source flow.

Returns

Flow<'env, 'error, 'value>
kind:membertask:environment-time

withTraceId

withTraceId traceId flow
Member
Adds the standard trace_id runtime annotation for the duration of the supplied flow.

Parameters

NameTypeDescription
traceIdstringThe trace identifier.
flowFlow<'env, 'error, 'value>The source flow.

Returns

Flow<'env, 'error, 'value>
kind:membertask:environment-time

cancellationToken

cancellationToken
Member
Reads the current runtime cancellation token.

Returns

Flow<'env, 'error, CancellationToken>
kind:membertask:environment-time

ensureNotCanceled

ensureNotCanceled
Member
Stops with Cause.Interrupt if the runtime's cancellation token has been cancelled.

Returns

Flow<'env, 'error, unit>

Verification Examples

let sumSquares (values: int list) : Flow<unit, string, int> =
    flow {
        let mutable total = 0
        for value in values do
            do! Flow.ensureNotCanceled
            total <- total + value * value
        return total
    }
kind:membertask:environment-time

sleep

sleep delay
Member
Suspends the flow for the specified duration, observing cancellation.

Parameters

NameTypeDescription
delayTimeSpanThe duration to sleep.

Returns

Flow<'env, 'error, unit>
kind:membertask:environment-time

scope

scope
Member
Reads the current runtime scope.

Returns

Flow<'env, 'error, Scope>
kind:membertask:environment-time

annotations

annotations
Member
Reads the current runtime annotations.

Returns

Flow<'env, 'error, Map<string, string>>
kind:membertask:environment-time

traceId

traceId
Member
Reads the current trace id annotation, if one is present.

Returns

Flow<'env, 'error, string option>
kind:membertask:environment-time

fiberId

fiberId
Member
Reads the current fiber id from the ambient runtime context.

Returns

Flow<'env, 'error, FiberId>
kind:membertask:environment-time

timeout

timeout after timeoutError flow
Member
Fails with the supplied typed error when the flow does not complete before the timeout.

Parameters

NameTypeDescription
afterTimeSpanThe timeout duration.
timeoutError'errorThe typed error returned when the timeout wins.
flowFlow<'env, 'error, 'value>The source flow.

Returns

Flow<'env, 'error, 'value>
kind:membertask:environment-time

timeoutToOk

timeoutToOk after value flow
Member
Returns the supplied success value when the flow does not complete before the timeout.

Parameters

NameTypeDescription
afterTimeSpanThe timeout duration.
value'valueThe success value returned when the timeout wins.
flowFlow<'env, 'error, 'value>The source flow.

Returns

Flow<'env, 'error, 'value>
kind:membertask:environment-time

timeoutToError

timeoutToError after error flow
Member
Same as timeout; named to pair with timeoutToOk.

Parameters

NameTypeDescription
afterTimeSpan
error'error
flowFlow<'env, 'error, 'value>

Returns

Flow<'env, 'error, 'value>
kind:membertask:environment-time

timeoutWith

timeoutWith after fallback flow
Member
Runs a fallback flow when the source flow does not complete before the timeout.

Parameters

NameTypeDescription
afterTimeSpanThe timeout duration.
fallbackunit -> Flow<'env, 'error, 'value>Creates the fallback flow when the timeout wins.
flowFlow<'env, 'error, 'value>The source flow.

Returns

Flow<'env, 'error, 'value>
kind:membertask:environment-time

retry

retry schedule flow
Member
Retries a flow's typed failures according to a schedule.

Parameters

NameTypeDescription
scheduleSchedule<'env, 'error, 'output>Decides, from each typed error, whether to retry and after what delay.
flowFlow<'env, 'error, 'value>The flow to retry.

Returns

Flow<'env, 'error, 'value>

Verification Examples

fetch |> Flow.retry (Schedule.recurs 3)

let transientOnly = { Retry.defaults with When = HttpError.isTransient }
fetch |> Flow.retry (Retry.schedule transientOnly)
kind:membertask:environment-time

repeat

repeat schedule flow
Member
Repeats a successful flow according to a schedule.

Parameters

NameTypeDescription
scheduleSchedule<'env, 'value, 'output>Decides, from each value, whether to repeat and after what delay.
flowFlow<'env, 'error, 'value>The flow to repeat.

Returns

Flow<'env, 'error, 'value>

Verification Examples

heartbeat |> Flow.repeat (Schedule.spaced (TimeSpan.FromSeconds 5.0))
kind:membertask:environment-time

env

env
Member
Reads the current environment as the successful flow value.

Returns

Flow<'env, 'error, 'env>

Verification Examples

let myFlow = Flow.env |> Flow.map (fun env -> env)
kind:membertask:environment-time

envWith

envWith projection
Member
Projects one value from the current environment.

Parameters

NameTypeDescription
projection'env -> 'valueA function that extracts a value from the environment.

Returns

Flow<'env, 'error, 'value>

Verification Examples

let region () =
    Flow.envWith (fun (environment: {| Region: string |}) -> environment.Region)
kind:membertask:environment-time

localEnv

localEnv mapping flow
Member
Runs a flow against an environment derived from the outer environment.

Parameters

NameTypeDescription
mapping'outerEnvironment -> 'innerEnvironmentA function that maps the outer environment to the inner environment.
flowFlow<'innerEnvironment, 'error, 'value>The flow to run with the inner environment.

Returns

Flow<'outerEnvironment, 'error, 'value>

Verification Examples

let flow = Flow.succeed 1 |> Flow.localEnv (fun outer -> outer)

Run and interop

kind:membertask:run-interop

fromAsync

fromAsync operation
Member
Creates a flow from a raw async operation.

Parameters

NameTypeDescription
operationAsync<'value>

Returns

Flow<'env, 'error, 'value>
kind:membertask:run-interop

fromAsyncResult

fromAsyncResult operation
Member
Creates a flow from an async operation whose Error enters the typed error channel.

Parameters

NameTypeDescription
operationAsync<Result<'value, 'error>>

Returns

Flow<'env, 'error, 'value>
kind:membertask:run-interop

attemptAsync

attemptAsync operation
Member
Creates a flow from an async operation and treats thrown exceptions as recoverable typed errors.

Parameters

NameTypeDescription
operationAsync<'value>

Returns

Flow<'env, exn, 'value>
kind:membertask:run-interop

fromBlocking

fromBlocking operation
Member
Creates a flow from synchronous, blocking work, such as a database driver or native library call.

Parameters

NameTypeDescription
operationCancellationToken -> 'valueThe blocking operation, observing the supplied cancellation token where it can.

Returns

Flow<'env, 'error, 'value>

Verification Examples

let commits =
    Flow.fromBlocking (fun _ ->
        repository.Commits
        |> Seq.truncate 50
        |> List.ofSeq)
kind:membertask:run-interop

fromBlockingResult

fromBlockingResult operation
Member
Creates a flow from blocking work whose Error enters the typed error channel.

Parameters

NameTypeDescription
operationCancellationToken -> Result<'value, 'error>The blocking operation, observing the supplied cancellation token where it can.

Returns

Flow<'env, 'error, 'value>
kind:membertask:run-interop

attemptBlocking

attemptBlocking operation
Member
Creates a flow from blocking work and treats thrown exceptions as recoverable typed errors.

Parameters

NameTypeDescription
operationCancellationToken -> 'valueThe blocking operation, observing the supplied cancellation token where it can.

Returns

Flow<'env, exn, 'value>
kind:membertask:run-interop

fromTask

fromTask factory
Member
Creates a flow from a cancellable task factory.

Parameters

NameTypeDescription
factoryCancellationToken -> Task<'value>Starts the operation, observing the supplied cancellation token.

Returns

Flow<'env, 'error, 'value>

Verification Examples

let flow = Flow.fromTask (fun token -> client.GetStringAsync(url, token))
kind:membertask:run-interop

fromTaskResult

fromTaskResult factory
Member
Creates a flow from a cold task factory whose Error enters the typed error channel.

Parameters

NameTypeDescription
factoryCancellationToken -> Task<Result<'value, 'error>>

Returns

Flow<'env, 'error, 'value>
kind:membertask:run-interop

attemptTask

attemptTask factory
Member
Creates a flow from a cancellable task factory and treats thrown exceptions as recoverable typed errors.

Parameters

NameTypeDescription
factoryCancellationToken -> Task<'value>Starts the operation, observing the supplied cancellation token.

Returns

Flow<'env, exn, 'value>
kind:membertask:run-interop

fromValueTask

fromValueTask factory
Member
Creates a flow from a cancellable value-task factory.

Parameters

NameTypeDescription
factoryCancellationToken -> ValueTask<'value>Starts the operation, observing the supplied cancellation token.

Returns

Flow<'env, 'error, 'value>
kind:membertask:run-interop

fromValueTaskResult

fromValueTaskResult factory
Member
Creates a flow from a cold value-task factory whose Error enters the typed error channel.

Parameters

NameTypeDescription
factoryCancellationToken -> ValueTask<Result<'value, 'error>>

Returns

Flow<'env, 'error, 'value>
kind:membertask:run-interop

attemptValueTask

attemptValueTask factory
Member
Creates a flow from a cancellable value-task factory and treats thrown exceptions as recoverable typed errors.

Parameters

NameTypeDescription
factoryCancellationToken -> ValueTask<'value>Starts the operation, observing the supplied cancellation token.

Returns

Flow<'env, exn, 'value>
kind:membertask:run-interop

fromUnitTask

fromUnitTask factory
Member
Creates a flow from a cancellable factory for a Task with no result, such as a write, connect or copy.

Parameters

NameTypeDescription
factoryCancellationToken -> TaskStarts the operation, observing the supplied cancellation token.

Returns

Flow<'env, 'error, unit>

Verification Examples

let send = Flow.fromUnitTask (fun token -> stream.FlushAsync token)
kind:membertask:run-interop

attemptUnitTask

attemptUnitTask factory
Member
Creates a flow from a cancellable factory for a Task with no result and treats thrown exceptions as recoverable typed errors.

Parameters

NameTypeDescription
factoryCancellationToken -> TaskStarts the operation, observing the supplied cancellation token.

Returns

Flow<'env, exn, unit>

Verification Examples

let connect =
    Flow.attemptUnitTask (fun token -> socket.ConnectAsync(host, port, token).AsTask())
kind:membertask:run-interop

fromUnitValueTask

fromUnitValueTask factory
Member
Creates a flow from a cancellable factory for a ValueTask with no result.

Parameters

NameTypeDescription
factoryCancellationToken -> ValueTaskStarts the operation, observing the supplied cancellation token.

Returns

Flow<'env, 'error, unit>

Verification Examples

let write = Flow.fromUnitValueTask (fun token -> stream.WriteAsync(bytes, token))
kind:membertask:run-interop

attemptUnitValueTask

attemptUnitValueTask factory
Member
Creates a flow from a cancellable factory for a ValueTask with no result and treats thrown exceptions as recoverable typed errors.

Parameters

NameTypeDescription
factoryCancellationToken -> ValueTaskStarts the operation, observing the supplied cancellation token.

Returns

Flow<'env, exn, unit>

Verification Examples

let write = Flow.attemptUnitValueTask (fun token -> stream.WriteAsync(bytes, token))
kind:membertask:run-interop

awaitStartedTask

awaitStartedTask startedTask
Member
Observes a task that has already been started.

Parameters

NameTypeDescription
startedTaskTask<'value>A task that is already running.

Returns

Flow<'env, 'error, 'value>
kind:membertask:run-interop

awaitStartedTaskResult

awaitStartedTaskResult startedTask
Member
Observes an already-started task whose Error enters the typed error channel.

Parameters

NameTypeDescription
startedTaskTask<Result<'value, 'error>>

Returns

Flow<'env, 'error, 'value>
kind:membertask:run-interop

attemptStartedTask

attemptStartedTask startedTask
Member
Observes a task that has already been started and treats thrown exceptions as recoverable typed errors.

Parameters

NameTypeDescription
startedTaskTask<'value>A task that is already running.

Returns

Flow<'env, exn, 'value>
kind:membertask:run-interop

awaitStartedValueTask

awaitStartedValueTask startedValueTask
Member
Observes a value task that has already been started.

Parameters

NameTypeDescription
startedValueTaskValueTask<'value>A value task that is already running.

Returns

Flow<'env, 'error, 'value>
kind:membertask:run-interop

awaitStartedValueTaskResult

awaitStartedValueTaskResult startedValueTask
Member
Observes an already-started value task whose Error enters the typed error channel.

Parameters

NameTypeDescription
startedValueTaskValueTask<Result<'value, 'error>>

Returns

Flow<'env, 'error, 'value>
kind:membertask:run-interop

attemptStartedValueTask

attemptStartedValueTask startedValueTask
Member
Observes a value task that has already been started and treats thrown exceptions as recoverable typed errors.

Parameters

NameTypeDescription
startedValueTaskValueTask<'value>A value task that is already running.

Returns

Flow<'env, exn, 'value>
kind:membertask:run-interop

toAsync

toAsync environment flow
Member
Builds a cold async that runs the workflow when it is started.

Parameters

NameTypeDescription
environment'envThe environment used by the workflow.
flowFlow<'env, 'error, 'value>The workflow to describe.

Returns

Async<Exit<'value, 'error>>

Verification Examples

let handle = workflow |> Flow.toAsync environment
kind:membertask:run-interop

startTask

startTask environment flow
Member
Starts the workflow immediately and returns a task handle for its final exit.

Parameters

NameTypeDescription
environment'envThe environment used by the workflow.
flowFlow<'env, 'error, 'value>The workflow to start.

Returns

Task<Exit<'value, 'error>>

Verification Examples

let running = workflow |> Flow.startTask environment
kind:membertask:run-interop

run

run environment flow
Member
Runs the workflow and blocks until the final exit is available.

Parameters

NameTypeDescription
environment'envThe environment used by the workflow.
flowFlow<'env, 'error, 'value>The workflow to run.

Returns

Exit<'value, 'error>

Verification Examples

let exit = workflow |> Flow.run environment
kind:membertask:run-interop

RunSynchronously

this.RunSynchronously
Member
Starts the workflow and blocks until the final exit is available.

Parameters

NameTypeDescription
environment'envThe environment used by the workflow.
cancellationTokenCancellationToken

Returns

Exit<'value, 'error>
kind:membertask:run-interop

StartAsTask

this.StartAsTask
Member
Starts the workflow immediately and returns a task handle for its final exit.

Parameters

NameTypeDescription
environment'envThe environment used by the workflow.
cancellationTokenCancellationToken

Returns

Task<Exit<'value, 'error>>
kind:membertask:run-interop

StartAsValueTask

this.StartAsValueTask
Member
Starts the workflow immediately and returns a value-task handle for its final exit.

Parameters

NameTypeDescription
environment'envThe environment used by the workflow.
cancellationTokenCancellationToken

Returns

ValueTask<Exit<'value, 'error>>
kind:membertask:run-interop

ToAsync

this.ToAsync
Member
Builds a cold async that runs the workflow when it is started.

Parameters

NameTypeDescription
environment'envThe environment used by the workflow.
cancellationTokenCancellationToken

Returns

Async<Exit<'value, 'error>>