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.JavaScript
open Axial.ElmishFlowsAvalonia desktop application
This recipe wires one Elmish program to Axial in an Avalonia desktop application, from startup to exit. The view
binding is yours to choose (Avalonia.FuncUI, an Elmish.Avalonia binding, or your own view model); the examples use
FuncUI's Program.withHost, and the Axial parts are the same for every binding.
Axial.Hosting is for Generic Host, ASP.NET Core, systemd services and console exit codes; a GUI does not need it,
except for the --self-test path below, which is a console run.
The Axial parts of this recipe are compiled and run as part of the documentation; only the blocks that touch Avalonia are not.
The environment
Everything the program's commands and services need lives in one record, built by a layer. The queue and hub are created inside the runtime's root scope, so they live until the runtime stops:
Show page setup
open System
open Axial
open Axial.ElmishFlows
open Axial.Process
open Elmish
let shouldEqual expected actual =
if actual <> expected then failwithf "Expected %A but got %A" expected actualtype SearchRequest = { Id: int64; Query: string }
type SearchEvent =
| Matches of id: int64 * paths: string list
| Finished of id: int64
type AppEnv =
{ Process: IProcess
Requests: Queue<SearchRequest>
Events: Hub<SearchEvent> }
interface IHasProcess with
member this.Process = this.Process
let makeEnvironment (processes: IProcess) : Flow<unit, Never, AppEnv> =
flow {
let! requests = Queue.sliding 1
let! events = Hub.make ()
return { Process = processes; Requests = requests; Events = events }
}
let layer (processes: IProcess) : Layer<unit, Never, AppEnv> = Layer.fromFlow (makeEnvironment processes)
FsLiveDocsGeneratedPage1_312F8285B19D.SearchRequestId: int64int64An abbreviation for the CLI type . Basic Types
Query: stringstringAn abbreviation for the CLI type . Basic Types
FsLiveDocsGeneratedPage1_312F8285B19D.SearchEventMatchesid: int64paths: string listlistThe type of immutable singly-linked lists. See the module for further operations related to lists. Use the constructors [] and :: (infix) to create values of this type, or the notation [1; 2; 3]. Use the values in the List module to manipulate values of this type, or pattern match against the values directly. See also F# Language Guide - Lists.
FinishedFsLiveDocsGeneratedPage1_312F8285B19D.AppEnvProcess: IProcessAxial.Process.IProcessExecutes lazily, awaiting each observation with backpressure.
Requests: Queue<SearchRequest>Axial.Queue`1An asynchronous FIFO queue for handing values between fibers, with an overflow strategy chosen at creation. Create one with Queue.make or a shorthand such as Queue.bounded, offer with Queue.offer, and take with the Dequeue functions. A queue is meant for one logical consumer; use Hub when zero or many consumers each need every value. The type of the queued values.
Events: Hub<SearchEvent>Axial.Hub`1Broadcasts every published value to every current subscription. Create one with Hub.make. Use a hub when there can be zero or many consumers. The type of the published values.
Axial.Process.IHasProcessthis: AppEnvProcess: AppEnv -> unit -> IProcessmakeEnvironment: IProcess -> Flow<unit,Never,AppEnv>processes: IProcessAxial.Flow`3unitThe 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.
flow: FlowBuilderThe universal flow { } computation expression.
requests: Queue<SearchRequest>Axial.QueueModuleCreates queues and offers values to them. Take values, inspect, and shut a queue down with the Dequeue functions.
sliding: int -> Flow<'env,'error,Queue<'a>>Creates a queue whose offer evicts the oldest value when full and returns true. Shorthand for Queue.make (QueueStrategy.Sliding capacity).
events: Hub<SearchEvent>Axial.HubModuleCreates hubs, publishes to them, and subscribes to them. A publish reaches every subscription that exists when it starts; a subscriber sees only values published after its subscribe completes, so a late joiner that needs current state must get it elsewhere, for example from a SubscriptionRef. Publishes are serialized, so every subscriber observes values in the same order even with concurrent publishers. Dropping, Sliding, and Unbounded subscriptions never delay the publisher. A BackPressure subscription with a full buffer suspends publish until it has room or its subscription ends. While the publisher waits, no later value reaches any subscriber, lossy ones included: keeping one order for every subscriber means a stalled lossless subscriber stalls the feed. Size a lossless subscriber's buffer for the bursts you expect, watch Dequeue.size to raise an alarm before it fills, and use Hub.tryPublish where the publisher must never wait. Shutting a hub down shuts every subscription down with Dequeue.shutdown semantics: subscribers drain their backlog, streams over subscriptions end normally, and later publishes are interrupted.
make: unit -> Flow<'env,'error,Hub<'a>>Creates a hub with no subscriptions.
layer: IProcess -> Layer<unit,Never,AppEnv>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.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)
Requires & types
Requires: open Axial; open Axial.Process (packages: Axial, Axial.Process)val makeEnvironment: IProcess -> Flow<unit,Never,AppEnv>val layer: IProcess -> Layer<unit,Never,AppEnv>Run a service for the program's lifetime
The search pipeline reads requests from the queue and publishes events to the hub. It belongs to the runtime, not to
init: ElmishRuntime.startService forks it once in the root scope, and stopping the runtime interrupts it.
FlowStream.switchMapFlow interrupts the running search when a newer request arrives:
module Search =
let private runOne (request: SearchRequest) : Flow<AppEnv, Never, unit> =
flow {
let! env = Flow.env
let publish event = Hub.publish event env.Events |> Flow.map ignore
do! publish (Matches(request.Id, [ $"{request.Query}.log" ]))
do! publish (Finished request.Id)
}
let pipeline : Flow<AppEnv, Never, unit> =
flow {
let! env = Flow.env
return!
FlowStream.fromDequeue env.Requests
|> FlowStream.switchMapFlow runOne
|> FlowStream.runDrain
}
FsLiveDocsGeneratedPage1_312F8285B19D.SearchrunOne: SearchRequest -> Flow<AppEnv,Never,unit>request: SearchRequestFsLiveDocsGeneratedPage1_312F8285B19D.SearchRequestAxial.Flow`3FsLiveDocsGeneratedPage1_312F8285B19D.AppEnvAxial.NeverRepresents an error channel that cannot occur.
unitThe type 'unit', which has only one value "()". This value is special and always uses the representation 'null'. Basic Types
flow: FlowBuilderThe universal flow { } computation expression.
env: AppEnvAxial.Flowenv: Flow<'env,'error,'env>Reads the current environment as the successful flow value. Use this when the next step genuinely needs the whole environment value, for example when passing a request context to another helper. For a single dependency or configuration value, prefer Flow.envWith; it keeps the dependency local and makes the workflow easier to scan. A whose successful value is the current environment. let myFlow = Flow.env |> Flow.map (fun env -> env)
publish: SearchEvent -> Flow<'a,'b,unit>event: SearchEventAxial.HubModuleCreates hubs, publishes to them, and subscribes to them. A publish reaches every subscription that exists when it starts; a subscriber sees only values published after its subscribe completes, so a late joiner that needs current state must get it elsewhere, for example from a SubscriptionRef. Publishes are serialized, so every subscriber observes values in the same order even with concurrent publishers. Dropping, Sliding, and Unbounded subscriptions never delay the publisher. A BackPressure subscription with a full buffer suspends publish until it has room or its subscription ends. While the publisher waits, no later value reaches any subscriber, lossy ones included: keeping one order for every subscriber means a stalled lossless subscriber stalls the feed. Size a lossless subscriber's buffer for the bursts you expect, watch Dequeue.size to raise an alarm before it fills, and use Hub.tryPublish where the publisher must never wait. Shutting a hub down shuts every subscription down with Dequeue.shutdown semantics: subscribers drain their backlog, streams over subscriptions end normally, and later publishes are interrupted.
publish: 'a -> Hub<'a> -> Flow<'env,'error,PublishResult>Delivers a value to every current subscription. Suspends while a BackPressure subscription is full, and is interrupted if the hub is or becomes shut down. If the publisher is interrupted part way, the subscriptions already reached keep the value, so publishing the same value again would deliver it twice to them; bound the wait with Hub.tryPublish instead of a timeout when duplicates matter. flow { let! (readings: Hub<float>) = Hub.make () return! readings |> Hub.publish 21.5 }
Events: Hub<SearchEvent>(|>): '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: ('value -> 'next) -> Flow<'env,'error,'value> -> Flow<'env,'error,'next>Transforms the successful value of a flow. If the source fails, the is not executed. The original failure cause is preserved, including typed failures, interruption, and defects. Use map for pure value transformations after an effect has succeeded. A function of type 'value -> 'next to transform the successful value. The source flow of type to transform. A new with the transformed success value of type 'next. let flow = Flow.succeed 1 |> Flow.map (fun x -> x + 1)
ignore: 'T -> unitIgnore the passed value. This is often used to throw away results of a computation. The value to ignore. ignore 55555 // Evaluates to ()
MatchesId: int64Finishedpipeline: Flow<AppEnv,Never,unit>Axial.FlowStreamModulefromDequeue: Dequeue<'value> -> FlowStream<'env,'error,'value>Creates a stream that takes values from a queue or hub subscription until it is shut down and drained. Shutdown is the normal end of the stream, not a failure: after Dequeue.shutdown or Hub.shutdown the stream emits the remaining backlog and then completes. Each pull suspends while the queue is empty. Interrupting a pull leaves any value it would have received in the queue. flow { let! (jobs: Queue<string>) = Queue.bounded 8 do! jobs |> Queue.offerAll [ "a"; "b" ] |> Flow.ignore do! Dequeue.shutdown jobs return! jobs |> FlowStream.fromDequeue |> FlowStream.runCollect }
Requests: Queue<SearchRequest>switchMapFlow: ('a -> Flow<'b,'c,'d>) -> FlowStream<'b,'c,'a> -> FlowStream<'b,'c,'d>runDrain: FlowStream<'a,'b,'c> -> Flow<'a,'b,unit>Consumes a stream and ignores its values. stream |> FlowStream.runDrain
Requires & types
Requires: open Axial (packages: Axial)val runOne: SearchRequest -> Flow<AppEnv,Never,unit>val pipeline: Flow<AppEnv,Never,unit>The program sees the hub through a subscription, Sub.OfFlowStream.subscribe [ "search-events" ] runtime (FlowStream.fromHub (QueueStrategy.Sliding 64) runtime.Environment.Events) Never.absurd, so every event reaches
update through Post.
UI input, debounce and a window that can change
A text box posts into an Inbox from update with Inbox.offer, which returns a command, so update stays pure.
A subscription debounces the inbox. Put the debounce window in the subscription id: when the user changes the window
in settings, the id changes, Elmish disposes the old subscription and starts a new one on the same inbox, and later
input settles with the new window.
type Model = { Query: string; Debounce: TimeSpan; Results: string list; Status: string }
type Msg =
| QueryChanged of string
| QuerySettled of string
| DebounceChanged of TimeSpan
| Found of string list
| SearchDone
| SearchFailed of string
| RevealFolder of string
| RevealFailed of ProcessError
let init () : Model * Cmd<Msg> =
{ Query = ""; Debounce = TimeSpan.FromMilliseconds 300.0; Results = []; Status = "" }, Cmd.none
let subscriptions runtime (inbox: Inbox<string>) (model: Model) : Sub<Msg> =
let window = model.Debounce
let settled : FlowStream<AppEnv, Never, Msg> =
Inbox.stream inbox |> FlowStream.debounce window |> FlowStream.map QuerySettled
Sub.OfFlowStream.subscribe [ "query"; string window.TotalMilliseconds ] runtime settled Never.absurd
FsLiveDocsGeneratedPage1_312F8285B19D.ModelQuery: stringstringAn abbreviation for the CLI type . Basic Types
Debounce: TimeSpanSystem.TimeSpanRepresents a time interval.
Results: string listlistThe type of immutable singly-linked lists. See the module for further operations related to lists. Use the constructors [] and :: (infix) to create values of this type, or the notation [1; 2; 3]. Use the values in the List module to manipulate values of this type, or pattern match against the values directly. See also F# Language Guide - Lists.
Status: stringFsLiveDocsGeneratedPage1_312F8285B19D.MsgQueryChangedQuerySettledDebounceChangedFoundSearchDoneSearchFailedRevealFolderRevealFailedAxial.Process.ProcessErrorExpected process errors. Runtime cancellation remains Cause.Interrupt.
init: unit -> Model * Cmd<Msg>CmdCmd - container for effects that may produce messages
FromMilliseconds: float -> TimeSpanReturns a that represents a specified number of milliseconds. A number of milliseconds. An object that represents . is less than or greater than . -or- is . -or- is . is equal to .
Elmish.CmdCmd module for creating and manipulating commands
none: Cmd<'msg>None - no commands, also known as `[]`
subscriptions: ElmishRuntime<AppEnv> -> Inbox<string> -> Model -> Sub<Msg>runtime: ElmishRuntime<AppEnv>inbox: Inbox<string>Axial.ElmishFlows.Inbox`1One-way, drop-visible mail into an Elmish program: one queue, one reader, owned by a scope. An inbox is a Queue with the doors that must not be opened at an update boundary closed: there is one consumer, nothing can drain or shut it down from outside, and offers that never become messages are counted. Use it for values that arrive from outside the program (callbacks, hosts, other libraries' events). Use Queue directly for work distribution, fan-in or back-pressure between fibers.
model: ModelSubSubscription - Generates new messages when running
window: TimeSpansettled: FlowStream<AppEnv,Never,Msg>Axial.FlowStream`3Represents a cold stream of values that requires an environment, can fail with a typed error, and supports backpressure. The type of the environment dependency. The type of the failure value. The type of the success values in the stream.
FsLiveDocsGeneratedPage1_312F8285B19D.AppEnvAxial.NeverRepresents an error channel that cannot occur.
Axial.ElmishFlows.InboxConstructs, fills and reads an .
stream: Inbox<'value> -> FlowStream<'env,'error,'value>The mailbox as a stream: every accepted value, in the order it was offered. Read it once: two readers split the mail between them, which is a queue, not a mailbox.
(|>): '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.FlowStreamModuledebounce: TimeSpan -> FlowStream<'env,'error,'value> -> FlowStream<'env,'error,'value>Emits a value only once passes without a newer one. Each value replaces the pending one and restarts the wait, so a burst produces only its last value. The pending value is emitted when upstream ends, and before a failure is propagated. Use it for search-as-you-type input. keystrokes |> FlowStream.debounce (TimeSpan.FromMilliseconds 300.0)
map: ('v -> 'w) -> FlowStream<'env,'error,'v> -> FlowStream<'env,'error,'w>Transforms the successful values of a stream using the provided function. The function to transform each value. The stream whose values should be transformed. A new stream that yields transformed values. let stream = FlowStream.fromSeq [1; 2; 3] |> FlowStream.map (fun n -> n * 2)
Axial.ElmishFlows.Subsubscribe: SubId -> ElmishRuntime<'env> -> FlowStream<'env,'error,'msg> -> ('error -> 'msg) -> Sub<'msg>Disposal requests interruption without blocking; scoped finalizers finish in the background.
Axial.ElmishFlows.Sub.OfFlowStreamstring: 'T -> stringConverts the argument to a string using ToString. For standard integer and floating point values and any type that implements IFormattableToString conversion uses CultureInfo.InvariantCulture. The input value. The converted string. string 'A' // evaluates to "A" string 0xff // evaluates to "255" string -10 // evaluates to "-10"
TotalMilliseconds: floatGets the value of the current structure expressed in whole and fractional milliseconds. The total number of milliseconds represented by this instance.
Axial.NeverModuleUses the fact that a value cannot exist.
absurd: Never -> 'aConverts a Never to any type. No Never value exists, so this function is never called with one. Pass it where a mapping from the error channel is required, to widen a flow, layer, cause, or exit that cannot fail into one with a real error type: Exit.mapError Never.absurd. Flow.widenError and Layer.widenError cover the common cases. let exit : Exit<int, string> = Exit.Success 1 |> Exit.mapError Never.absurd
Requires & types
Requires: open Axial; open Axial.ElmishFlows; open Axial.Process; open Elmish; open System (packages: Axial, Axial.ElmishFlows, Axial.Process)val init: unit -> Model * Cmd<Msg>val subscriptions: ElmishRuntime<AppEnv> -> Inbox<string> -> Model -> Sub<Msg>Values still in the inbox survive the switch. The value the old debounce was holding for its quiet period is dropped, because that subscription is interrupted; the next keystroke settles normally.
Stream results into update
When a query settles, Cmd.OfFlowStream.latest runs the search as a stream of batches and dispatches each batch as a
message. A newer query with the same key interrupts the older stream, and the batch it left waiting in Post is
dropped. The stream waits for update to see each batch before it pulls the next, so a fast search cannot flood the UI
dispatcher. Process.shellOpen opens a folder in the file manager without waiting for it. Cmd.OfFlow.attempt
dispatches nothing when it succeeds and turns its typed failure into a message:
let private searchFiles (query: string) : FlowStream<AppEnv, string, string> =
FlowStream.fromSeq [ $"{query}-1.log"; $"{query}-2.log" ]
let update runtime inbox (msg: Msg) (model: Model) : Model * Cmd<Msg> =
match msg with
| QueryChanged text -> { model with Query = text }, Inbox.offer text inbox
| QuerySettled text ->
let batches =
searchFiles text
|> FlowStream.groupedWithin 64 (TimeSpan.FromMilliseconds 100.0)
|> FlowStream.map Found
|> FlowStream.append (FlowStream.singleton SearchDone)
{ model with Results = []; Status = "searching" },
Cmd.OfFlowStream.latest "search" runtime batches id SearchFailed
| Found paths -> { model with Results = model.Results @ paths }, Cmd.none
| SearchDone -> { model with Status = "done" }, Cmd.none
| SearchFailed error -> { model with Status = error }, Cmd.none
| DebounceChanged window -> { model with Debounce = window }, Cmd.none
| RevealFolder folder ->
model, Cmd.OfFlow.attempt "reveal" runtime (Process.shellOpen folder) RevealFailed
| RevealFailed error -> { model with Status = ProcessError.describe error }, Cmd.none
searchFiles: string -> FlowStream<AppEnv,string,string>query: stringstringAn abbreviation for the CLI type . Basic Types
Axial.FlowStream`3Represents a cold stream of values that requires an environment, can fail with a typed error, and supports backpressure. The type of the environment dependency. The type of the failure value. The type of the success values in the stream.
FsLiveDocsGeneratedPage1_312F8285B19D.AppEnvAxial.FlowStreamModulefromSeq: 'value seq -> FlowStream<'env,'error,'value>Creates a stream from a synchronous sequence of values. The sequence of values to be emitted by the stream. A that yields each value from the sequence. FlowStream.fromSeq [1..10] |> FlowStream.runCollect |> Flow.run ()
update: ElmishRuntime<AppEnv> -> Inbox<string> -> Msg -> Model -> Model * Cmd<Msg>runtime: ElmishRuntime<AppEnv>inbox: Inbox<string>msg: MsgFsLiveDocsGeneratedPage1_312F8285B19D.Msgmodel: ModelFsLiveDocsGeneratedPage1_312F8285B19D.ModelCmdCmd - container for effects that may produce messages
QueryChangedtext: stringQuery: stringAxial.ElmishFlows.InboxConstructs, fills and reads an .
offer: 'value -> Inbox<'value> -> Cmd<'msg>The same offer, as a command for update to return.
QuerySettledbatches: FlowStream<AppEnv,string,Msg>(|>): '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
groupedWithin: int -> TimeSpan -> FlowStream<'env,'error,'value> -> FlowStream<'env,'error,'value list>Groups values into lists of at most , emitting early when passes. A group starts with the next value and is emitted when it holds values or when has passed since its first value, whichever comes first. No empty group is emitted. When upstream ends or fails, the partial group is emitted first. Use it to batch writes or progress updates without waiting indefinitely for a full batch. events |> FlowStream.groupedWithin 100 (TimeSpan.FromSeconds 1.0)
System.TimeSpanRepresents a time interval.
FromMilliseconds: float -> TimeSpanReturns a that represents a specified number of milliseconds. A number of milliseconds. An object that represents . is less than or greater than . -or- is . -or- is . is equal to .
map: ('v -> 'w) -> FlowStream<'env,'error,'v> -> FlowStream<'env,'error,'w>Transforms the successful values of a stream using the provided function. The function to transform each value. The stream whose values should be transformed. A new stream that yields transformed values. let stream = FlowStream.fromSeq [1; 2; 3] |> FlowStream.map (fun n -> n * 2)
Foundappend: FlowStream<'a,'b,'c> -> FlowStream<'a,'b,'c> -> FlowStream<'a,'b,'c>Concatenates two streams, evaluating the second only after the first ends. first |> FlowStream.append second
singleton: 'value -> FlowStream<'env,'error,'value>Creates a stream containing one value. FlowStream.singleton 42
SearchDoneResults: string listStatus: stringAxial.ElmishFlows.CmdElmish commands backed by Axial workflows. Every command follows Elmish's Cmd.OfAsync.either shape of work first, then callbacks, but uses the parameter order name runtime workflow onSuccess onError: the runtime owns the command's root scope, so it precedes the workflow. Pass the workflow positionally, not piped.
latest: string -> ElmishRuntime<'env> -> FlowStream<'env,'error,'value> -> ('value -> 'msg) -> ('error -> 'msg) -> Cmd<'msg>Runs a stream keyed by and dispatches each element as a message; starting another stream or Cmd.OfFlow.Latest command for the same key interrupts this one. Every element and the final typed failure go through the runtime's Post in stream order, so update sees them on the host's dispatch thread. The stream has at most one element waiting in Post: it pulls the next element only after update has seen the previous one, so a fast stream is slowed to the pace of the dispatcher instead of flooding it, and no element is dropped or merged. Batch a fast stream with FlowStream.groupedWithin so that one dispatch carries many elements. The element still waiting in Post when the stream is replaced, cancelled or stopped is dropped, and so is a typed failure still waiting there when the runtime stops. Keys are shared with Cmd.OfFlow.Latest, so Cmd.OfFlow.Latest.cancel key interrupts the stream without dispatching. A stream that completes dispatches nothing more; append a final element when update needs to know it finished. An exception from is reported to OnDefect and that element is skipped; the stream continues. A defect is reported to OnDefect and interruption is silent. The latest-wins key, also the diagnostic name of the stream fiber. The runtime that owns the stream's root scope. The stream to run, passed positionally. Maps each element to a message. Maps the stream's typed failure to a message. An Elmish command. Parameter order is key runtime stream onElement onError.
Axial.ElmishFlows.Cmd.OfFlowStreamElmish commands that dispatch every element of an Axial stream.
id: 'T -> 'TThe identity function The input value. The same value. id 12 // Evaulates to 12 id "abc" // Evaulates to "abc"
SearchFailedpaths: string listElmish.CmdCmd module for creating and manipulating commands
none: Cmd<'msg>None - no commands, also known as `[]`
error: stringDebounceChangedwindow: TimeSpanDebounce: TimeSpanRevealFolderfolder: stringattempt: string -> ElmishRuntime<'a> -> Flow<'a,'b,unit> -> ('b -> 'c) -> Cmd<'c>Runs a workflow that succeeds only with unit and dispatches only its typed failure. Success dispatches nothing; a defect is reported to OnDefect and interruption is silent. The diagnostic name for the command fiber. The runtime that owns the command's root scope. The flow to run, passed positionally. Maps a typed failure to a message. An Elmish command. Parameter order is name runtime workflow onError.
Axial.ElmishFlows.Cmd.OfFlowAxial.Process.ProcessshellOpen: string -> Flow<'env,ProcessError,unit>Opens a file, folder or URL with the operating system's default handler. The live service uses ShellExecute on Windows, open on macOS and xdg-open elsewhere, and does not wait for the handler. The flow succeeds once the opener has started, so a target that no handler accepts is not reported. To reveal a file in the file manager, open its folder. The launch goes through IProcess.Launch, so Process.test () records it in Launches. Opening a target can run a program. ShellExecute runs an .exe, .bat or .cmd file, open runs an .app bundle or an executable script, and xdg-open hands the target to whatever the desktop associates with it. Do not pass a path or URL from an untrusted source without checking it, for example that it is an https: URL or a folder the application owns. An empty target, or one starting with - (which an opener reads as an option), fails with ProcessError.ShellOpenRejected and starts nothing; prefix a relative path with ./. A path or URL. A flow that fails with ProcessError.ShellOpenRejected for a refused target and ProcessError.StartFailed when the opener cannot be started.
RevealFailederror: ProcessErrorRequires & types
Requires: open Axial; open Axial.ElmishFlows; open Axial.Process; open Elmish; open System (packages: Axial, Axial.ElmishFlows, Axial.Process)val searchFiles: string -> FlowStream<AppEnv,string,string>val update: ElmishRuntime<AppEnv> -> Inbox<string> -> Msg -> Model -> Model * Cmd<Msg>Test update with the test runtime
ElmishRuntime.test runs the commands update returns against a ManualClock and the test process service, and
records what they dispatch. The same update drives the real program:
let processes = Process.test ()
let environment =
match makeEnvironment processes |> Flow.run () with
| Exit.Success environment -> environment
| _ -> failwith "environment failed"
let test = ElmishRuntime.test (ManualClock(DateTimeOffset.UnixEpoch)) environment
let inbox = Inbox.create 64 test.Runtime
let model, _ = init ()
let runUpdate msg =
let _, command = update test.Runtime inbox msg model
TestRuntime.run command test
TestRuntime.settle (TimeSpan.FromSeconds 5.0) test |> shouldEqual true
runUpdate (QuerySettled "app")
TestRuntime.dispatched test |> shouldEqual [ box (Found [ "app-1.log"; "app-2.log" ]); box SearchDone ]
// A reveal that succeeds dispatches nothing; the launch is recorded instead of started.
runUpdate (RevealFolder "/var/log")
TestRuntime.dispatched test |> List.length |> shouldEqual 2
match List.ofSeq processes.Launches with
| [ ProcessLaunch.ShellOpen folder ] -> folder |> shouldEqual "/var/log"
| _ -> failwith "expected one shell open"
let notInstalled = ProcessError.StartFailed { Command = "xdg-open"; Message = "not installed" }
processes.LaunchHandler <- Some(fun _ -> Flow.fail notInstalled)
runUpdate (RevealFolder "/var/log")
TestRuntime.dispatched test |> List.last |> shouldEqual (box (RevealFailed notInstalled))
TestRuntime.defects test |> shouldEqual []
(test :> IDisposable).Dispose()
processes: TestProcessAxial.Process.Processtest: unit -> TestProcessenvironment: AppEnvmakeEnvironment: IProcess -> Flow<unit,Never,AppEnv>(|>): '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
Axial.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.
failwith: string -> 'TThrow a exception. The exception message. Never returns. let failingFunction() = failwith "Oh no" // Throws an exception true // Never reaches this failingFunction() // Throws a System.Exception
test: TestRuntime<AppEnv>Axial.ElmishFlows.ElmishRuntimetest: ManualClock -> 'env -> TestRuntime<'env>Creates a runtime with queued dispatch and captured defects for tests.
``.ctor``: DateTimeOffset -> ManualClockSystem.DateTimeOffsetRepresents a point in time, typically expressed as a date and time of day, relative to Coordinated Universal Time (UTC).
UnixEpoch: DateTimeOffsetinbox: Inbox<string>Axial.ElmishFlows.InboxConstructs, fills and reads an .
create: int -> ElmishRuntime<'env> -> Inbox<'value>An inbox shut down by the runtime instead of a scope, for a host that already holds the runtime. Prefer scopedWith inside a layer or the root scope. Drops the newest offer with QueueStrategy.Dropping.
Runtime: ElmishRuntime<AppEnv>model: Modelinit: unit -> Model * Cmd<Msg>runUpdate: Msg -> unitmsg: Msgcommand: Cmd<Msg>update: ElmishRuntime<AppEnv> -> Inbox<string> -> Msg -> Model -> Model * Cmd<Msg>Axial.ElmishFlows.TestRuntimerun: Cmd<'a> -> TestRuntime<'env> -> unitsettle: TimeSpan -> TestRuntime<'env> -> boolSystem.TimeSpanRepresents a time interval.
FromSeconds: float -> TimeSpanReturns a that represents a specified number of seconds, where the specification is accurate to the nearest millisecond. A number of seconds, accurate to the nearest millisecond. An object that represents . is less than or greater than . -or- is . -or- is . is equal to .
shouldEqual: 'a -> 'a -> unitQuerySettleddispatched: TestRuntime<'env> -> obj listbox: 'T -> objBoxes a strongly typed value. The value to box. The boxed object. let x: int = 123 let obj1 = box x // obj1 is a generic object type unbox<int> obj1 // Evaluates to 123 (int) unbox<double> obj1 // Throws System.InvalidCastException
FoundSearchDoneRevealFolderMicrosoft.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.
length: 'T list -> intReturns the length of the list. The input list. The length of the list. The notation array.Length is preferred. let inputs = [ "a"; "b"; "c" ] inputs |> List.length Evaluates to 3
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 ].
Launches: Collections.Generic.IReadOnlyList<ProcessLaunch>Every detached launch requested, in order. Launches never call <c>RunHandler</c>.
Axial.Process.ProcessLaunchA start-and-forget launch: the caller does not wait for the child, capture its output, or own its lifetime.
ShellOpenOpens a file, folder or URL with the operating system's default handler.
folder: stringnotInstalled: ProcessErrorAxial.Process.ProcessErrorExpected process errors. Runtime cancellation remains Cause.Interrupt.
StartFailedCommand: stringMessage: stringLaunchHandler: (ProcessLaunch -> Flow<unit,ProcessError,unit>) optionReplaces the default launch result (success) — for example, to return <c>ProcessError.StartFailed</c>.
SomeThe representation of "Value of type 'T" The input value. An option representing the value.
fail: 'error -> Flow<'env,'error,'value>Same as error. The error value to wrap in a failing flow. A flow that always fails with the provided error. let result = Flow.fail "error" |> Flow.run () // result = Failure (Cause.Fail "error")
last: 'T list -> 'TReturns the last element of the list. The input list. The last element of the list. Thrown when the input does not have any elements. [ "pear"; "banana" ] |> List.last Evaluates to banana [ ] |> List.last Throws ArgumentException
RevealFaileddefects: TestRuntime<'env> -> CommandDefect listDispose: unit -> unitPerforms application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
System.IDisposableProvides a mechanism for releasing unmanaged resources.
Requires & types
Requires: open Axial; open Axial.ElmishFlows; open Axial.Process; open System (packages: Axial, Axial.ElmishFlows, Axial.Process)val processes: TestProcessval environment: AppEnvval test: TestRuntime<AppEnv>val inbox: Inbox<string>val model: Modelval runUpdate: Msg -> unitval notInstalled: ProcessErrorStart the runtime when Avalonia is ready
Create the runtime in OnFrameworkInitializationCompleted, then the program, and pass the runtime to init, update
and subscriptions. Post needs only Avalonia's UI dispatcher, which exists by then; it does not need the Elmish
program or the view binding, because each command captures Elmish's dispatch itself. So there is nothing to attach
later: do not create the runtime as a module-level value with a placeholder Post that is patched once the UI starts.
open Avalonia
open Avalonia.Controls.ApplicationLifetimes
open Avalonia.FuncUI.Elmish
open Avalonia.Threading
open Axial.Console
open Axial.FileSystem
/// Runs inline when already on the UI thread, so a keystroke dispatches, updates and renders in one pass.
let postToUi (callback: unit -> unit) =
if Dispatcher.UIThread.CheckAccess() then callback ()
else Dispatcher.UIThread.Post(fun () -> callback ())
let startRuntime () : ElmishRuntime<AppEnv> =
let options =
{ Post = postToUi
OnDefect = fun defect -> eprintfn "defect in %s: %s" defect.Name defect.Rendered
HistoryCapacity = 128
Clock = None
LogSink = None }
let processes = Process.live FileSystem.live Console.live
// The one blocking wait, at the desktop host boundary.
match ElmishRuntime.startLayer options (layer processes) () |> Async.RunSynchronously with
| Ok runtime -> runtime
| Error never -> Never.absurd never
type App() =
inherit Application()
override this.OnFrameworkInitializationCompleted() =
match this.ApplicationLifetime with
| :? IClassicDesktopStyleApplicationLifetime as desktop ->
let runtime = startRuntime ()
// A fresh runtime runs no services and is not stopping, so neither error occurs here.
match runtime |> ElmishRuntime.startService "search-pipeline" Search.pipeline with
| Ok () -> ()
| Error ServiceStartError.DuplicateName -> eprintfn "search pipeline already running"
| Error ServiceStartError.RuntimeStopping -> eprintfn "runtime stopped during startup"
let inbox = Inbox.create 64 runtime
let window = MainWindow()
Program.mkProgram init (update runtime inbox) view
|> Program.withSubscription (subscriptions runtime inbox)
|> Program.withHost window
|> Program.run
// Closing the window stops services, commands and subscriptions and runs their finalizers.
desktop.ShutdownRequested.Add(fun _ -> runtime.StopAndWait(TimeSpan.FromSeconds 5.0) |> ignore)
desktop.MainWindow <- window
| _ -> ()
base.OnFrameworkInitializationCompleted()startLayer is asynchronous; the one blocking wait sits at the host boundary, as in
synchronous desktop startup, and provisioning must not wait for the
UI dispatcher it is blocking. StopAndWait on the UI thread is safe while the finalizers do not need the dispatcher.
Keep update pure when results need time
update must not read the clock. Measure inside the flow, and let the message carry the timing: Clock.timed
returns the value and the monotonic duration, and Clock.now the wall-clock instant, both from the runtime's clock.
update stores what it is given, and a test can install a deterministic clock:
type Loaded = { Lines: string list; Took: TimeSpan; At: DateTimeOffset }
let loadLog : Flow<unit, string, string list> = Flow.succeed [ "started"; "ready" ]
// What Cmd.OfFlow.either runs; update receives the Loaded record and never touches a clock.
let loadTimed : Flow<unit, string, Loaded> =
flow {
let! lines, took = loadLog |> Clock.timed
let! at = Clock.now
return { Lines = lines; Took = took; At = at }
}
let describe (loaded: Loaded) =
$"{loaded.Lines.Length} lines in {loaded.Took.TotalMilliseconds} ms"
/// A clock whose monotonic timer advances 40 ms per reading.
let steppingClock () =
let mutable readings = 0
{ new IClock with
member _.UtcNow() = DateTimeOffset(2026, 1, 1, 9, 0, 0, TimeSpan.Zero)
member _.Elapsed() =
readings <- readings + 1
TimeSpan.FromMilliseconds(40.0 * float readings)
member _.Sleep(_, _) = System.Threading.Tasks.Task.CompletedTask }
FsLiveDocsGeneratedPage1_312F8285B19D.LoadedLines: string liststringAn abbreviation for the CLI type . Basic Types
listThe type of immutable singly-linked lists. See the module for further operations related to lists. Use the constructors [] and :: (infix) to create values of this type, or the notation [1; 2; 3]. Use the values in the List module to manipulate values of this type, or pattern match against the values directly. See also F# Language Guide - Lists.
Took: TimeSpanSystem.TimeSpanRepresents a time interval.
At: DateTimeOffsetSystem.DateTimeOffsetRepresents a point in time, typically expressed as a date and time of day, relative to Coordinated Universal Time (UTC).
loadLog: Flow<unit,string,string list>Axial.Flow`3unitThe type 'unit', which has only one value "()". This value is special and always uses the representation 'null'. Basic Types
Axial.Flowsucceed: 'value -> Flow<'env,'error,'value>Same as ok. The value to wrap in a successful flow. A flow that always succeeds with the provided value. let result = Flow.succeed 42 |> Flow.run () // result = Success 42
loadTimed: Flow<unit,string,Loaded>flow: FlowBuilderThe universal flow { } computation expression.
lines: string listtook: TimeSpan(|>): '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.ClockHelpers for the clock service.
timed: Flow<'env,'error,'value> -> Flow<'env,'error,('value * TimeSpan)>Runs a flow and returns its value together with how long it took. Measured with the clock's monotonic timer, so the duration is unaffected by system clock adjustments and is deterministic under a test clock. Failures propagate unchanged and are not timed. The flow to measure. let! report, took = buildReport |> Clock.timed
at: DateTimeOffsetnow: Flow<'env,'error,DateTimeOffset>Reads the current UTC timestamp from an explicit clock service.
describe: Loaded -> stringloaded: LoadedsteppingClock: unit -> IClockreadings: intAxial.IClockSupplies wall time, monotonic time, and cancellable delays from one source. Wall time is for timestamps. Use differences between Elapsed readings for durations.
_: IClockUtcNow: unit -> DateTimeOffset``.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 .
Zero: TimeSpanRepresents the zero value. This field is read-only.
Elapsed: unit -> TimeSpan(+): ^T1 -> ^T2 -> ^T3Overloaded addition operator The first parameter. The second parameter. The result of the operation. 2 + 2 // Evaluates to 4 "Hello " + "Word" // Evaluates to "Hello World"
FromMilliseconds: float -> TimeSpanReturns a that represents a specified number of milliseconds. A number of milliseconds. An object that represents . is less than or greater than . -or- is . -or- is . is equal to .
(*): ^T1 -> ^T2 -> ^T3Overloaded multiplication operator The first parameter. The second parameter. The result of the operation. 8 * 6 // Evaluates to 48
float: ^T -> floatConverts the argument to 64-bit float. This is a direct conversion for all primitive numeric types. For strings, the input is converted using Double.Parse() with InvariantCulture settings. Otherwise the operation requires an appropriate static conversion method on the input type. The input value. The converted float float 'A' // evaluates to 65.0 float 0xff // evaluates to 255.0 float -10 // evaluates to -10.0
Sleep: TimeSpan * CancellationToken -> TaskSystemCompletedTask: TaskGets a task that has already completed successfully. The successfully completed task.
ThreadingTasksSystem.Threading.Tasks.TaskRepresents an asynchronous operation.
Requires & types
Requires: open Axial; open System (packages: Axial)val loadLog: Flow<unit,string,string list>val loadTimed: Flow<unit,string,Loaded>val describe: Loaded -> stringval steppingClock: unit -> IClockmatch loadTimed |> Flow.withClock (steppingClock ()) |> Flow.run () with
| Exit.Success loaded ->
describe loaded |> shouldEqual "2 lines in 40 ms"
loaded.At |> shouldEqual (DateTimeOffset(2026, 1, 1, 9, 0, 0, TimeSpan.Zero))
| _ -> failwith "load failed"
loadTimed: Flow<unit,string,Loaded>(|>): '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.
steppingClock: unit -> IClockrun: '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
Axial.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.
loaded: Loadeddescribe: Loaded -> stringshouldEqual: 'a -> 'a -> unitAt: DateTimeOffset``.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.
failwith: string -> 'TThrow a exception. The exception message. Never returns. let failingFunction() = failwith "Oh no" // Throws an exception true // Never reaches this failingFunction() // Throws a System.Exception
Requires & types
Requires: open Axial; open System (packages: Axial)A --self-test command-line path
A --self-test argument runs the same layer and services without a window, and reports a process exit code, so CI
can smoke-test the packaged application. DotNetApp.exitCode from Axial.Hosting maps the final Exit to 0
(success), 1 (typed failure), 2 (defect) or 130 (interruption):
open Axial.Hosting
module SelfTest =
let private check : Flow<AppEnv, string, unit> =
flow {
let! env = Flow.env
let! subscription = env.Events |> Hub.subscribe QueueStrategy.Unbounded
let! _ = env.Requests |> Queue.offer { Id = 1L; Query = "self-test" }
let! first = Dequeue.take subscription
match first with
| Matches(1L, _ :: _) -> ()
| _ -> return! Flow.fail "search returned no matches"
}
let runWith (processes: IProcess) : int =
let application =
flow {
let! _ = Flow.fork Search.pipeline
return! check |> Flow.timeout (TimeSpan.FromSeconds 10.0) "self-test timed out"
}
|> Layer.provide (layer processes |> Layer.widenError)
let exit = application |> Flow.run ()
match exit with
| Exit.Failure cause -> eprintfn "%s" (Cause.prettyPrint id cause)
| Exit.Success () -> ()
DotNetApp.exitCode exit
AxialHostingFsLiveDocsGeneratedPage1_312F8285B19D.SelfTestcheck: Flow<AppEnv,string,unit>Axial.Flow`3FsLiveDocsGeneratedPage1_312F8285B19D.AppEnvstringAn abbreviation for the CLI type . Basic Types
unitThe type 'unit', which has only one value "()". This value is special and always uses the representation 'null'. Basic Types
flow: FlowBuilderThe universal flow { } computation expression.
env: AppEnvAxial.Flowenv: Flow<'env,'error,'env>Reads the current environment as the successful flow value. Use this when the next step genuinely needs the whole environment value, for example when passing a request context to another helper. For a single dependency or configuration value, prefer Flow.envWith; it keeps the dependency local and makes the workflow easier to scan. A whose successful value is the current environment. let myFlow = Flow.env |> Flow.map (fun env -> env)
subscription: Dequeue<SearchEvent>Events: Hub<SearchEvent>(|>): '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.HubModuleCreates hubs, publishes to them, and subscribes to them. A publish reaches every subscription that exists when it starts; a subscriber sees only values published after its subscribe completes, so a late joiner that needs current state must get it elsewhere, for example from a SubscriptionRef. Publishes are serialized, so every subscriber observes values in the same order even with concurrent publishers. Dropping, Sliding, and Unbounded subscriptions never delay the publisher. A BackPressure subscription with a full buffer suspends publish until it has room or its subscription ends. While the publisher waits, no later value reaches any subscriber, lossy ones included: keeping one order for every subscriber means a stalled lossless subscriber stalls the feed. Size a lossless subscriber's buffer for the bursts you expect, watch Dequeue.size to raise an alarm before it fills, and use Hub.tryPublish where the publisher must never wait. Shutting a hub down shuts every subscription down with Dequeue.shutdown semantics: subscribers drain their backlog, streams over subscriptions end normally, and later publishes are interrupted.
subscribe: QueueStrategy -> Hub<'a> -> Flow<'env,'error,Dequeue<'a>>Subscribes to the hub with a buffering strategy. The subscription ends when the current scope closes. Run subscribe inside Flow.scoped, a forked fiber, or an application root: a forked fiber's subscription ends with the fiber. Ending the subscription, by closing its scope or with Dequeue.shutdown, removes it from the hub and releases a publisher waiting on it. To subscribe for the life of a stream, use FlowStream.fromHub. flow { let! (readings: Hub<float>) = Hub.make () let! latest = readings |> Hub.subscribe (QueueStrategy.Sliding 1) do! readings |> Hub.publishAll [ 20.0; 21.5 ] |> Flow.ignore return! Dequeue.takeAll latest } |> Flow.scoped
Axial.QueueStrategyWhat a queue, or a hub subscription, does with a value offered while it is full. Lossless delivery needs either back-pressure or unbounded memory. BackPressure keeps every value by making the producer wait; Unbounded keeps every value by growing without limit; Dropping and Sliding never make the producer wait and lose values instead. A non-positive capacity fails the flow that uses the strategy with a defect.
UnboundedLossless and never suspends the producer; memory grows with the backlog.
Requests: Queue<SearchRequest>Axial.QueueModuleCreates queues and offers values to them. Take values, inspect, and shut a queue down with the Dequeue functions.
offer: 'a -> Queue<'a> -> Flow<'env,'error,bool>Adds a value according to the queue's strategy. true when the value was accepted, or false when a dropping queue discarded it. A bounded queue suspends until space exists. The flow is interrupted if the queue is or becomes shut down first. flow { let! (jobs: Queue<string>) = Queue.bounded 8 return! jobs |> Queue.offer "job" }
Id: int64Query: stringfirst: SearchEventAxial.DequeueModuleTakes values from a , inspects it, and shuts it down. Every function here also accepts a .
take: Dequeue<'a> -> Flow<'env,'error,'a>Removes the oldest value, suspending until one is available. After shutdown this returns the remaining values, then is interrupted. flow { let! (jobs: Queue<string>) = Queue.bounded 8 do! jobs |> Queue.offer "job" |> Flow.ignore return! Dequeue.take jobs }
Matches(::)fail: 'error -> Flow<'env,'error,'value>Same as error. The error value to wrap in a failing flow. A flow that always fails with the provided error. let result = Flow.fail "error" |> Flow.run () // result = Failure (Cause.Fail "error")
runWith: IProcess -> intprocesses: IProcessAxial.Process.IProcessExecutes lazily, awaiting each observation with backpressure.
intAn abbreviation for the CLI type . Basic Types
application: Flow<unit,string,unit>fork: Flow<'env,'error,'value> -> Flow<'env,'none,Fiber<'error,'value>>Starts a flow in a new fiber without waiting for it to complete. Forking turns a cold flow description into hot child work and returns a handle that can later be joined or interrupted. Prefer zipPar or race when the caller only needs a simple parallel composition. Wait for the handle with Fiber.join or Fiber.awaitExit, and stop it with Fiber.interrupt. The fiber runs in its own scope and releases its scoped resources (anything registered with a scope, such as scopeResource, scopeFinalizer, or a hub subscription) when it settles, whether or not anyone joins it. A value the fiber returns therefore outlives the scoped resources the fiber acquired: a resource returned through Fiber.join has already been released. Use forkResource to acquire a resource in the background and keep it, or zipPar and sequencePar to acquire several in parallel. The flow to fork. A flow that produces a handle.
FsLiveDocsGeneratedPage1_312F8285B19D.Searchpipeline: Flow<AppEnv,Never,unit>timeout: TimeSpan -> 'error -> Flow<'env,'error,'value> -> Flow<'env,'error,'value>Fails with the supplied typed error when the flow does not complete before the timeout. The timed-out flow is interrupted. The timeout owns that interruption, so it may report it as a typed error. The flow runs in its own scope: its scoped resources move to the caller's scope when it succeeds in time, and are released when it fails or times out. timeoutToOk and timeoutWith treat scoped resources the same way. As in race, a defect the interrupted flow or its cleanup (an onInterrupt or ensuring handler) settles with is not dropped: it becomes the failure in place of the timeout value, or is combined with a failing timeout error or fallback; its typed failures and the requested interruption are not. The timeout duration. The typed error returned when the timeout wins. The source flow. A flow that returns the source outcome or the timeout error.
System.TimeSpanRepresents a time interval.
FromSeconds: float -> TimeSpanReturns a that represents a specified number of seconds, where the specification is accurate to the nearest millisecond. A number of seconds, accurate to the nearest millisecond. An object that represents . is less than or greater than . -or- is . -or- is . is equal to .
Axial.LayerModuleprovide: 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
layer: IProcess -> Layer<unit,Never,AppEnv>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
exit: Exit<unit,string>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
Axial.Exit`2Represents the final outcome of a workflow execution. The type of the success value. The type of the domain-specific failure value.
FailureThe workflow failed due to a specific cause.
cause: Cause<string>eprintfn: Printf.TextWriterFormat<'T> -> 'TPrint to stderr using the given format, and add a newline. The formatter. The formatted result. See Printf.eprintfn (link: ) for examples.
Axial.CauseprettyPrint: ('error -> string) -> Cause<'error> -> stringPretty prints a cause tree for diagnostics.
id: 'T -> 'TThe identity function The input value. The same value. id 12 // Evaulates to 12 id "abc" // Evaulates to "abc"
SuccessThe workflow completed successfully.
Axial.Hosting.DotNetAppStandalone .NET process integration for Flow applications that do not use Generic Host.
exitCode: Exit<'value,'error> -> intMaps a final application exit to the conventional standalone process exit codes.
Requires & types
Requires: open Axial; open Axial.Hosting; open Axial.Process; open System (packages: Axial, Axial.Hosting, Axial.Process)val check: Flow<AppEnv,string,unit>val runWith: IProcess -> intSelfTest.runWith (Process.test ()) |> shouldEqual 0
FsLiveDocsGeneratedPage1_312F8285B19D.SelfTestrunWith: IProcess -> intAxial.Process.Processtest: unit -> TestProcess(|>): '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
shouldEqual: 'a -> 'a -> unitRequires & types
Requires: open Axial.Process (packages: Axial.Process)The entry point picks the path; only this part needs Avalonia:
[<EntryPoint>]
let main args =
if Array.contains "--self-test" args then
SelfTest.runWith (Process.live FileSystem.live Console.live)
else AppBuilder.Configure<App>().UsePlatformDetect().StartWithClassicDesktopLifetime(args)For the program's own logic, drive init and update with ElmishRuntime.test and a ManualClock, as in
Test update with the test runtime; the self-test proves the packaged services
start.

