Repository F# setup
open System
open System.IO
open System.Threading
open System.Threading.Tasks
open Axial
open Axial.Console
open Axial.FileSystem
open Axial.Hosting
open Axial.Hosting.Browser
open Axial.Hosting.Node
open Axial.State
open Axial.Telemetry
open Axial.Telemetry.JavaScriptLayers are not required: when every service can be built synchronously, a record built in code is enough. Once building the environment means awaiting a connection, reading configuration, failing with a typed startup error, or acquiring something that must be released (a database pool, a socket), a layer does that work and releases it in reverse order on shutdown. It is a small set of combinators over Flow and Scope for exactly those needs, and it ships in the core Axial package.
Use a record when you can. Construct the environment directly and hand it to the workflow:
Show page setup
// Setup for the checked examples on this page.
open System
open Axial
open Axial.Console
open Axial
/// Fails the docs test when an example's result differs from the value shown.
let shouldEqual expected actual =
if actual <> expected then failwithf "Expected %A but got %A" expected actualtype RegionEnv = { Region: string }
let describeRegion : Flow<RegionEnv, Never, string> =
flow {
let! now = Clock.now
let! region = Flow.envWith _.Region
return $"{region} at {now.Year}"
}
FsLiveDocsGeneratedPage6_4232598D5E1C.RegionEnvRegion: stringstringAn abbreviation for the CLI type . Basic Types
describeRegion: Flow<RegionEnv,Never,string>Axial.Flow`3Axial.NeverRepresents an error channel that cannot occur.
flow: FlowBuilderThe universal flow { } computation expression.
now: DateTimeOffsetAxial.ClockHelpers for the clock service.
now: Flow<'env,'error,DateTimeOffset>Reads the current UTC timestamp from an explicit clock service.
region: stringAxial.FlowenvWith: ('env -> 'value) -> Flow<'env,'error,'value>Projects one value from the current environment. This is the primary way to access app dependencies, configuration, or request metadata stored in env. The projection runs only when the flow is executed, so constructing the flow is still pure and side-effect free. Prefer small projections over passing a large environment deeper into reusable helpers. A function that extracts a value from the environment. A containing the projected value. let region () = Flow.envWith (fun (environment: {| Region: string |}) -> environment.Region)
_arg2: RegionEnvRequires & types
Requires: open Axial (packages: Axial)val describeRegion: Flow<RegionEnv,Never,string>let env = { Region = "eu" }
describeRegion |> Flow.withClock (Clock.fromValue (DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero))) |> Flow.run env |> shouldEqual (Exit.Success "eu at 2026")
env: RegionEnvRegion: stringdescribeRegion: Flow<RegionEnv,Never,string>(|>): 'T1 -> ('T1 -> 'U) -> 'UApply a function to a value, the value being on the left, the function on the right The argument. The function. The function result. let doubleIt x = x * 2 3 |> doubleIt // Evaluates to 6
Axial.FlowwithClock: IClock -> Flow<'env,'error,'value> -> Flow<'env,'error,'value>Overrides the clock within this flow and its descendants.
Axial.ClockHelpers for the clock service.
fromValue: DateTimeOffset -> ManualClockCreates a manual clock starting at the supplied instant. Sleeps require explicit advancement.
``.ctor``: int * int * int * int * int * int * TimeSpan -> unitInitializes a new instance of the structure using the specified year, month, day, hour, minute, second, and offset. The year (1 through 9999). The month (1 through 12). The day (1 through the number of days in ). The hours (0 through 23). The minutes (0 through 59). The seconds (0 through 59). The time's offset from Coordinated Universal Time (UTC). does not represent whole minutes. is less than one or greater than 9999. -or- is less than one or greater than 12. -or- is less than one or greater than the number of days in . -or- is less than zero or greater than 23. -or- is less than 0 or greater than 59. -or- is less than 0 or greater than 59. -or- is less than -14 hours or greater than 14 hours. -or- The property is earlier than or later than .
System.TimeSpanRepresents a time interval.
Zero: TimeSpanRepresents the zero value. This field is read-only.
run: 'env -> Flow<'env,'error,'value> -> Exit<'value,'error>Runs the workflow and blocks until the final exit is available. The environment used by the workflow. The workflow to run. The final workflow exit. let exit = workflow |> Flow.run environment
shouldEqual: 'a -> 'a -> unitAxial.Exit`2Represents the final outcome of a workflow execution. The type of the success value. The type of the domain-specific failure value.
SuccessThe workflow completed successfully.
Requires & types
Requires: open Axial; open System (packages: Axial)val env: RegionEnvDirect construction needs no layer. See dependencies.
Use a layer when construction is itself effectful:
- provisioning can fail, and the failure should be a typed startup error rather than an exception
- a service must be acquired and released for the duration of the flow
Layer.provideruns: acquired during provisioning and released when that flow ends, whether it succeeds, fails, or is interrupted - independent parts of the environment should be built in parallel
- a service needs another service in order to be constructed
type Connection(name: string, closed: ResizeArray<string>) =
member _.Name = name
member _.Close() = closed.Add name
type AppEnv = { Region: string; Connection: Connection }
type AppError = QueryFailed of string
let connectionLayer (closed: ResizeArray<string>) : Layer<unit, Never, Connection> =
Layer.acquireRelease
(Layer.succeed (Connection("orders-db", closed)))
(fun connection ->
Flow.delay (fun () ->
connection.Close()
Flow.ok ()))
let runtime (closed: ResizeArray<string>) : Layer<unit, Never, AppEnv> =
Layer.merge (Layer.succeed "eu") (connectionLayer closed)
|> Layer.map (fun (region, connection) -> { Region = region; Connection = connection })
let query : Flow<AppEnv, AppError, string> =
Flow.envWith (fun env -> env.Connection.Name)
let program (closed: ResizeArray<string>) : Flow<unit, AppError, string> =
Layer.provide (Layer.widenError (runtime closed)) query
FsLiveDocsGeneratedPage6_4232598D5E1C.Connectionname: stringstringAn abbreviation for the CLI type . Basic Types
closed: ResizeArray<string>ResizeArrayAn abbreviation for the CLI type
_: ConnectionName: Connection -> unit -> stringClose: Connection -> unit -> unitAdd: string -> unitAdds an object to the end of the . The object to be added to the end of the . The value can be for reference types.
FsLiveDocsGeneratedPage6_4232598D5E1C.AppEnvRegion: stringConnection: ConnectionFsLiveDocsGeneratedPage6_4232598D5E1C.AppErrorQueryFailedconnectionLayer: ResizeArray<string> -> Layer<unit,Never,Connection>Axial.Layer`3Represents a provisioning step that builds an explicit environment inside a scope. The input environment required to build the layer. The typed failure produced during provisioning. The environment or service bundle produced by the layer.
unitThe type 'unit', which has only one value "()". This value is special and always uses the representation 'null'. Basic Types
Axial.NeverRepresents an error channel that cannot occur.
Axial.LayerModuleacquireRelease: Layer<'input,'error,'resource> -> ('resource -> Flow<'input,Never,unit>) -> Layer<'input,'error,'resource>Acquires a resource and registers its release with the layer scope. The layer that acquires the resource. The release flow run, with the layer's input as its environment, when the layer scope closes. A layer that succeeds with the acquired resource. Use this for service implementations or provisioned resources that must live for the full Flow.provide boundary rather than only for the construction expression. The release runs without interruption; a defect it raises becomes a defect of the provided flow. To acquire with a flow, use Layer.fromFlow (Flow.scopeAcquireRelease acquire release).
succeed: 'output -> Layer<'input,'error,'output>Creates a layer that succeeds with a fixed output value.
``.ctor``: string * ResizeArray<string> -> Connectionconnection: ConnectionAxial.Flowdelay: (unit -> Flow<'env,'error,'value>) -> Flow<'env,'error,'value>Defers flow construction until execution time. A function that returns the flow to execute. Recursive calls deferred here are consumed by the executor without growing a chain of parent tasks. Work that must run after the recursive call still needs storage until that call finishes. A flow that lazily evaluates the factory when executed. let flow = Flow.delay (fun () -> Flow.succeed 42)
Close: unit -> unitok: 'value -> Flow<'env,'error,'value>Creates a successful synchronous flow. The value to wrap in a successful flow. A flow that always succeeds with the provided value.
runtime: ResizeArray<string> -> Layer<unit,Never,AppEnv>merge: Layer<'input,'error,'left> -> Layer<'input,'error,'right> -> Layer<'input,'error,('left * 'right)>Merges two independent service layers in parallel. merge is the layer-domain name for zipPar. Use it when combining service bundles or environment fragments that do not depend on each other.
(|>): 'T1 -> ('T1 -> 'U) -> 'UApply a function to a value, the value being on the left, the function on the right The argument. The function. The function result. let doubleIt x = x * 2 3 |> doubleIt // Evaluates to 6
map: ('output -> 'next) -> Layer<'input,'error,'output> -> Layer<'input,'error,'next>Maps the successful output of a layer.
region: stringquery: Flow<AppEnv,AppError,string>Axial.Flow`3envWith: ('env -> 'value) -> Flow<'env,'error,'value>Projects one value from the current environment. This is the primary way to access app dependencies, configuration, or request metadata stored in env. The projection runs only when the flow is executed, so constructing the flow is still pure and side-effect free. Prefer small projections over passing a large environment deeper into reusable helpers. A function that extracts a value from the environment. A containing the projected value. let region () = Flow.envWith (fun (environment: {| Region: string |}) -> environment.Region)
env: AppEnvName: stringprogram: ResizeArray<string> -> Flow<unit,AppError,string>provide: Layer<'input,'error,'environment> -> Flow<'environment,'error,'value> -> Flow<'input,'error,'value>Builds an environment with a layer, runs a downstream flow, and always closes the layer scope. This is the provisioning boundary. It creates a fresh scope, builds the supplied layer inside that scope, runs the downstream flow with the built environment, and finalizes all acquired resources when the downstream flow completes or fails. The layer that builds the downstream environment. The flow to run with the provided environment. A flow that requires only the input environment of the layer. let program () = let runtimeLayer = Layer.succeed "production" let workflow = Flow.envWith String.length Layer.provide runtimeLayer workflow
widenError: Layer<'input,Never,'output> -> Layer<'input,'error,'output>Gives a layer that cannot fail with a typed error any error type. Layer.provide and the layer combinators require one error type. Widen a layer that cannot fail, such as Layer.succeed value, to combine it with layers or workflows that can. let runtime : Layer<unit, string, int> = Layer.succeed 1 |> Layer.widenError
Requires & types
Requires: open Axial (packages: Axial)val connectionLayer: ResizeArray<string> -> Layer<unit,Never,Connection>val runtime: ResizeArray<string> -> Layer<unit,Never,AppEnv>val query: Flow<AppEnv,AppError,string>val program: ResizeArray<string> -> Flow<unit,AppError,string>runtime cannot fail, so its error type is Never; Layer.widenError lets it provide a workflow that fails with
AppError. The connection is closed when program ends:
let closed = ResizeArray<string>()
program closed |> Flow.run () |> shouldEqual (Exit.Success "orders-db")
List.ofSeq closed |> shouldEqual [ "orders-db" ]
closed: ResizeArray<string>``.ctor``: unit -> unitInitializes a new instance of the class that is empty and has the default initial capacity.
stringAn abbreviation for the CLI type . Basic Types
program: ResizeArray<string> -> Flow<unit,AppError,string>(|>): 'T1 -> ('T1 -> 'U) -> 'UApply a function to a value, the value being on the left, the function on the right The argument. The function. The function result. let doubleIt x = x * 2 3 |> doubleIt // Evaluates to 6
Axial.Flowrun: 'env -> Flow<'env,'error,'value> -> Exit<'value,'error>Runs the workflow and blocks until the final exit is available. The environment used by the workflow. The workflow to run. The final workflow exit. let exit = workflow |> Flow.run environment
shouldEqual: 'a -> 'a -> unitAxial.Exit`2Represents the final outcome of a workflow execution. The type of the success value. The type of the domain-specific failure value.
SuccessThe workflow completed successfully.
Microsoft.FSharp.Collections.ListModuleContains operations for working with values of type . Operations for collections such as lists, arrays, sets, maps and sequences. See also F# Collection Types in the F# Language Guide.
ofSeq: 'T seq -> 'T listBuilds a new list from the given enumerable object. The input sequence. The list of elements from the sequence. let inputs = seq { 1; 2; 5 } inputs |> List.ofSeq Evaluates to [ 1; 2; 5 ]. This is an O(n) operation, where n is the length of the sequence.
Requires & types
Requires: open Axial (packages: Axial)val closed: ResizeArray<string>Layer.provide is the boundary: it opens a scope, builds the layer inside it, runs the downstream
flow with the result, and closes the scope afterwards whether the flow succeeds, fails, or is
interrupted.
Two provisioning shapes
Typed startup failure. A layer can validate configuration before constructing application services:
open Axial.Configuration
let connectionString : Layer<IHasConfig, ConfigError, string> =
Layer.fromFlow (Config.required "ConnectionString")
AxialConfigurationconnectionString: Layer<IHasConfig,ConfigError,string>Axial.Layer`3Represents a provisioning step that builds an explicit environment inside a scope. The input environment required to build the layer. The typed failure produced during provisioning. The environment or service bundle produced by the layer.
Axial.Configuration.IHasConfigAn application environment that carries a merged configuration snapshot.
Axial.Configuration.ConfigErrorEvery configuration failure is a value; loading and reading never throw.
stringAn abbreviation for the CLI type . Basic Types
Axial.LayerModulefromFlow: Flow<'input,'error,'output> -> Layer<'input,'error,'output>Creates a layer that builds its output by running a flow with the layer's input as its environment. The flow runs in the layer's scope, so what it registers with Flow.scopeAcquireRelease, Flow.scopeFinalizer, or Flow.scopeResource stays open until the Layer.provide boundary closes, and is released in reverse acquisition order. A typed failure fails provisioning; whatever was acquired before it is released. The flow that builds the layer output. A layer that succeeds with the flow's value. let database : Layer<AppConfig, DbError, Database> = Layer.fromFlow (Flow.scopeAcquireRelease (Database.connect ()) Database.close)
Axial.Configuration.ConfigLoads, decodes and watches layered configuration. Axial 0.12 requires Reified 0.12.1 or later; its Fable schema builder supports typed schema construction and Config.load decoding on Fable.
required: string -> Flow<'env,ConfigError,string>Reads a required text value at a Reified data path, comparing keys ordinal-ignore-case.
Requires & types
Requires: open Axial; open Axial.Configuration (packages: Axial, Axial.Configuration)val connectionString: Layer<IHasConfig,ConfigError,string>The error channel is ConfigError, not Never. Layer.provide runs the downstream workflow only
after provisioning succeeds, releases resources acquired by earlier steps when a later step fails, and lets
independent steps build in parallel with merge. A direct factory returning Result can model the error too;
the layer additionally owns acquisition and release.
A service built from another service. An HTTP adapter needs an application-owned client and an explicit clock at its live boundary:
let httpLayer : Layer<System.Net.Http.HttpClient, Never, Axial.HttpClient.IHttp> =
Layer.envWith (Axial.HttpClient.Http.live)
httpLayer: Layer<Net.Http.HttpClient,Never,HttpClient.IHttp>Axial.Layer`3Represents a provisioning step that builds an explicit environment inside a scope. The input environment required to build the layer. The typed failure produced during provisioning. The environment or service bundle produced by the layer.
SystemSystem.Net.Http.HttpClientProvides a base class for sending HTTP requests and receiving HTTP responses from a resource identified by a URI.
NetHttpAxial.NeverRepresents an error channel that cannot occur.
AxialAxial.HttpClient.IHttpSends fully described HTTP requests for a concrete host platform.
HttpClientAxial.LayerModuleenvWith: ('input -> 'output) -> Layer<'input,'error,'output>Projects part of the input environment into the layer output.
live: Net.Http.HttpClient -> HttpClient.IHttpCreates a live HTTP service backed by the caller's <see cref="T:System.Net.Http.HttpClient" />. <remarks>Timestamps and request deadlines read the clock installed in the flow that executes the request. Set the supplied client's <c>Timeout</c> to <c>Timeout.InfiniteTimeSpan</c> when every deadline should be driven by <c>Request.timeout</c> and a test clock. Malformed URLs fail with <c>HttpError.InvalidRequest</c>. Response and request-message disposal run independently; disposal exceptions remain defects.</remarks> <example><code>Http.live (new HttpClient())</code></example>
Axial.HttpClient.HttpModuleRequires & types
Requires: open Axial (packages: Axial, Axial.HttpClient)val httpLayer: Layer<Net.Http.HttpClient,Never,HttpClient.IHttp>The layer consumes the client and constructs an explicit HTTP capability. It does not install a runtime clock or
log sink. Runtime overrides belong around the flow (Flow.withClock, Flow.withLogSink), not in an environment
layer. The same adaptation can be performed directly when a host constructs its record.
An already-built value that cannot fail needs no provisioning. Layer.succeed wraps it:
Layer.succeed Console.live
Axial.LayerModulesucceed: 'output -> Layer<'input,'error,'output>Creates a layer that succeeds with a fixed output value.
Axial.Console.ConsoleModulelive: IConsoleCreates a live console service backed by .
Requires & types
Requires: open Axial; open Axial.Console (packages: Axial, Axial.Console)Console, FileSystem, HttpClient and Process are all of this shape, which is why none of them needs a layer to provide it.
Scopes work without layers
Scopes and acquireRelease do not need a layer. See
scopes and resources.

