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.ElmishFlowsElmish programs
The Axial.ElmishFlows package exposes the Axial.ElmishFlows namespace and connects an Elmish 5 program to Axial
workflows. Create one runtime per program, passing an environment and a Post function that delivers callbacks on the
host's dispatch thread. When already on that thread, Post should run inline; otherwise it should post to it. Do not
call Elmish's dispatch directly from workers. Connect OnDefect to the host's crash reporting path; typed failures
are messages, but defects are not.
Install
dotnet add package Axial.ElmishFlows
Axial.ElmishFlows brings Elmish 5 with it. Reference Elmish directly when your program uses Program.mkProgram and
dispatch. Open Axial.ElmishFlows for the Axial API, and Axial when you override the runtime clock.
A minimal runtime supplies an environment, a Post function, a defect handler, a history capacity, and optional
clock and log-sink overrides (Clock = None and LogSink = None keep the runtime's live defaults; Some installs
that clock or sink for commands, subscriptions and layer provisioning):
open Axial
open Axial.ElmishFlows
open Axial
// In an Elmish host, `Post` is usually the program's dispatch, so callbacks run on the host's dispatch thread.
// Here the code is already on that thread, so it runs the callback inline.
let runtime =
ElmishRuntime.start
{ Post = (fun callback -> callback ())
OnDefect = (fun defect -> failwith defect.Rendered)
HistoryCapacity = 32
Clock = None
LogSink = None }
()When Post is not already on the dispatch thread it must post to it (for example Application.Post in WPF or
dispatching back to a UI loop); never call Elmish's dispatch directly from a worker.
First-use lifecycle
ElmishRuntime takes any environment, with no clock interface required: time comes from the runtime, and
ElmishRuntimeOptions.Clock overrides it, and ElmishRuntimeOptions.LogSink replaces the default
Information-and-above console sink. Keep the runtime's environment stable, and
supply a command's current dependencies with Flow.localEnv. For example, a git client can open another repository
without recreating its Elmish runtime:
open Axial
open Axial.ElmishFlows
open Axial
type RepositoryEnvironment = { Repository: string }
let runtime =
ElmishRuntime.start
{ Post = (fun callback -> callback ())
OnDefect = (fun defect -> failwith defect.Rendered)
HistoryCapacity = 32
Clock = None
LogSink = None }
()
let currentEnv = { Repository = "/repos/new" }
let repositoryName : Flow<RepositoryEnvironment, string, string> =
Flow.envWith (fun env -> env.Repository)
let command =
Cmd.OfFlow.either "repository" runtime
(repositoryName |> Flow.localEnv (fun _ -> currentEnv))
id
(fun _ -> "unavailable")Flow.localEnv selects the environment when the command runs; capture the selected environment for each command when
constructing it so later repository switches do not change already-issued requests.
Provisioning with startLayer
When a runtime needs resources that must live for the whole program — a Cache.make* cache, queues, hubs, or a
Layer.fromFlow resource — build them with a layer and start the runtime with ElmishRuntime.startLayer. The layer
is provisioned inside the runtime's root scope, so Stop/StopAndWait releases what the layer acquired. A typed
provisioning failure returns Error and leaves nothing running.
open Axial
open Axial.ElmishFlows
open Axial
type CacheEnvironment = { Cache: Cache<int, Never, string> }
let layer : Layer<unit, string, CacheEnvironment> =
Layer.fromFlow (flow {
let! cache =
Cache.make (fun key -> Flow.succeed $"value-{key}" : Flow<unit, Never, string>)
return { Cache = cache }
})
let runtime =
match
ElmishRuntime.startLayer
{ Post = (fun callback -> callback ())
OnDefect = (fun defect -> failwith defect.Rendered)
HistoryCapacity = 32
Clock = None
LogSink = None }
layer
()
|> Async.RunSynchronously
with
| Ok runtime -> runtime
| Error error -> failwith errorSynchronous desktop startup
A desktop host often starts before an Elmish loop exists. Keep provisioning asynchronous, and put the one blocking wait at the host boundary:
Show page setup
open System
open Axial
open Axial
let shouldEqual expected actual =
if actual <> expected then failwithf "Expected %A but got %A" expected actualopen Axial.ElmishFlows
let startDesktop
(options: ElmishRuntimeOptions)
(layer: Layer<'arg, string, 'env>)
(input: 'arg)
: Result<ElmishRuntime<'env>, string> =
ElmishRuntime.startLayer options layer input
|> Async.RunSynchronously
AxialElmishFlowsstartDesktop: ElmishRuntimeOptions -> Layer<'arg,string,'env> -> 'arg -> Result<ElmishRuntime<'env>,string>options: ElmishRuntimeOptionsAxial.ElmishFlows.ElmishRuntimeOptionsHost delivery and diagnostic policy.
layer: Layer<'arg,string,'env>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.
argstringAn abbreviation for the CLI type . Basic Types
envinput: 'argMicrosoft.FSharp.Core.FSharpResult`2Helper type for error handling without exceptions. Choices and Results
Axial.ElmishFlows.ElmishRuntime`1Owns the root scope for all commands in one Elmish program.
Axial.ElmishFlows.ElmishRuntimestartLayer: ElmishRuntimeOptions -> Layer<'input,'error,'env> -> 'input -> Async<Result<ElmishRuntime<'env>,'error>>Starts a runtime by provisioning a layer inside the runtime's root scope. The layer is built with Layer.provide around the runtime pump, so every resource the layer acquires (a Cache.make* cache, queues, hubs, or a Layer.fromFlow resource) stays open until Stop/StopAndWait closes the runtime. A typed provisioning failure returns Error and leaves no runtime running; a defect or interruption during provisioning raises from the returned Async. Host delivery and diagnostic policy. The layer that builds the runtime's environment. The input environment required to build the layer. A result whose Ok case is the running runtime.
(|>): '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
Microsoft.FSharp.Control.FSharpAsyncHolds static members for creating and manipulating asynchronous computations. See also F# Language Guide - Async Workflows. Async Programming
RunSynchronously: Async<'T> * int option * CancellationToken option -> 'TRuns the asynchronous computation and await its result. If an exception occurs in the asynchronous computation then an exception is re-raised by this function. If no cancellation token is provided then the default cancellation token is used. The computation is started on the current thread if is null, has of true, and no timeout is specified. Otherwise the computation is started by queueing a new work item in the thread pool, and the current thread is blocked awaiting the completion of the computation. The timeout parameter is given in milliseconds. A value of -1 is equivalent to . The computation to run. The amount of time in milliseconds to wait for the result of the computation before raising a . If no value is provided for timeout then a default of -1 is used to correspond to . The cancellation token to be associated with the computation. If one is not supplied, the default cancellation token is used. The result of the computation. Starting Async Computations printfn "A" let result = async { printfn "B" do! Async.Sleep(1000) printfn "C" 17 } |> Async.RunSynchronously printfn "D" Prints "A", "B" immediately, then "C", "D" in 1 second. result is set to 17.
Requires & types
Requires: open Axial; open Axial.ElmishFlows (packages: Axial, Axial.ElmishFlows)val startDesktop: ElmishRuntimeOptions -> Layer<'arg,string,'env> -> 'arg -> Result<ElmishRuntime<'env>,string>Declare that function's exact file in [boundaries].files and add a rule-specific
// axial-allow-AXG001: synchronous desktop host boundary with the reason. Startup must not require the blocked UI
dispatcher: provision asynchronously first, or supply a prebuilt environment with ElmishRuntime.start when
initialization is UI-affine. If provisioning posts work back to the dispatcher and waits for it, that is a dependency
cycle the runner cannot repair. Keep the successful runtime alive until shutdown and call its documented Stop or
StopAndWait exactly once; a synchronous stop is safe only when cleanup does not need the dispatcher.
Long-lived services and fire-and-forget
A service that lives as long as the program — a search pipeline, a poller, a cache warmer — belongs to the runtime,
not to a never-completing command. Cmd.OfFlow.perform needs a success message, so running Flow.never through it
forces an unreachable onSuccess. Start the service with ElmishRuntime.startService after the runtime starts and
before the Elmish program does. It runs as a named fiber in the runtime's root scope with the runtime's environment;
Stop/StopAndWait interrupts it and runs its finalizers. A defect goes to OnDefect under the service name, and so
does a service that completes while the runtime is still running, since a service should last as long as the runtime.
startService returns Error ServiceStartError.DuplicateName if a service with that name is still running, and
Error ServiceStartError.RuntimeStopping once the runtime is stopping. Unlike Cmd.OfFlow.start, which update runs
and which is expected to finish, a service is started by the host, one per name, and reports whether it started:
open Axial
open Axial.ElmishFlows
type SearchEnvironment = { Requests: Queue<string>; Results: Hub<string> }
let searchPipeline : Flow<SearchEnvironment, Never, unit> =
flow {
let! env = Flow.env
return!
FlowStream.fromDequeue env.Requests
|> FlowStream.mapFlow (fun query -> Hub.publish $"result:{query}" env.Results |> Flow.map ignore)
|> FlowStream.runDrain
}
let startServices (runtime: ElmishRuntime<SearchEnvironment>) : Result<unit, string> =
runtime
|> ElmishRuntime.startService "search-pipeline" searchPipeline
|> Result.mapError (function
| ServiceStartError.DuplicateName -> "the search pipeline is already running"
| ServiceStartError.RuntimeStopping -> "the runtime is stopping")The program then talks to the service through what the environment holds: it offers requests to the queue and
subscribes to the hub with Sub.OfFlowStream.subscribe. A service whose lifetime follows the model instead — running
only while a panel is open — is a subscription: Elmish disposes it (interrupting the stream and releasing its
resources) when the model no longer asks for it:
open Axial
open Axial.ElmishFlows
open Axial
// A search pipeline backed by an inbox: post queries, subscribe to results for the program's lifetime.
let searchPipeline (runtime: ElmishRuntime<unit>) =
let inbox = Inbox.create 8 runtime
let queries : FlowStream<unit, string, string> =
Inbox.stream inbox |> FlowStream.map (fun query -> $"result:{query}")
inbox, Sub.OfFlowStream.subscribe [ "search" ] runtime queries (fun error -> $"search-error:{error}")When the service also needs resources provisioned once for the whole program, ElmishRuntime.startLayer
above is the alternative: it builds the cache, queue, or hub inside the runtime's root scope and releases it on
Stop/StopAndWait.
Cmd.OfFlow.start is the right tool for fire-and-forget work, but it accepts only Flow<'env, Never, unit>. A flow
with a typed failure channel must handle that failure first — log it, then recover to unit:
let indexDocument (query: string) : Flow<unit, string, unit> =
flow {
if String.IsNullOrWhiteSpace query then
return! Flow.fail "empty query"
}
// Handle the typed failure before Cmd.OfFlow.start, which accepts only Flow<'env, Never, unit>.
let indexSafely (query: string) : Flow<unit, Never, unit> =
indexDocument query
|> Flow.recover (fun error ->
flow {
do! Log.error $"indexing skipped: {error}"
})
indexDocument: string -> Flow<unit,string,unit>query: stringstringAn abbreviation for the CLI type . Basic Types
Axial.Flow`3unitThe 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.
System.StringRepresents text as a sequence of UTF-16 code units.
IsNullOrWhiteSpace: string -> boolIndicates whether a specified string is , empty, or consists only of white-space characters. The string to test. if the parameter is or , or if consists exclusively of white-space characters.
Axial.Flowfail: '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")
indexSafely: string -> Flow<unit,Never,unit>Axial.NeverRepresents an error channel that cannot occur.
(|>): '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
recover: ('error -> Flow<'env,'nextError,'value>) -> Flow<'env,'error,'value> -> Flow<'env,'nextError,'value>error: stringAxial.LogHelpers for the logging service.
error: string -> Flow<'env,'error,unit>Writes an error message to the installed log sink.
Requires & types
Requires: open Axial; open System (packages: Axial)val indexDocument: string -> Flow<unit,string,unit>val indexSafely: string -> Flow<unit,Never,unit>let log = Log.memory ()
indexSafely "" |> Flow.withLogSink log |> Flow.run () |> shouldEqual (Exit.Success ())
log.Entries |> Seq.map _.Message |> Seq.toList |> shouldEqual [ "indexing skipped: empty query" ]
log: TestLogAxial.LogHelpers for the logging service.
memory: unit -> TestLogindexSafely: string -> Flow<unit,Never,unit>(|>): '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.FlowwithLogSink: ILogSink -> Flow<'env,'error,'value> -> Flow<'env,'error,'value>Replaces the log destination within this flow and its descendants.
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.
Entries: Collections.Generic.IReadOnlyList<LogEntry>The recorded entries, in the order they were written.
Microsoft.FSharp.Collections.SeqModuleContains operations for working with values of type .
map: ('T -> 'U) -> 'T seq -> 'U seqBuilds a new collection whose elements are the results of applying the given function to each of the elements of the collection. The given function will be applied as elements are demanded using the MoveNext method on enumerators retrieved from the object. The returned sequence may be passed between threads safely. However, individual IEnumerator values generated from the returned sequence should not be accessed concurrently. Sequence construction is O(1). Enumeration is O(n), where n is the length of the sequence. A function to transform items from the input sequence. The input sequence. The result sequence. Thrown when the input sequence is null. let inputs = ["a"; "bbb"; "cc"] inputs |> Seq.map (fun x -> x.Length) Evaluates to a sequence yielding the same results as seq { 1; 3; 2 }
_arg1: LogEntryMessage: stringtoList: 'T seq -> 'T listBuilds a list from the given collection. The input sequence. The result list. Thrown when the input sequence is null. let inputs = seq { 1; 2; 5 } inputs |> Seq.toList 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 log: TestLogopen Axial
open Axial.ElmishFlows
// indexSafely already handled its typed failure, so its type is Flow<'env, Never, unit>.
let backgroundIndex runtime query =
Cmd.OfFlow.start "index" runtime (indexSafely query)Streaming results into update
Cmd.OfFlowStream.latest key runtime stream onElement onError runs a FlowStream as a command and dispatches each
element as a message, in stream order, through Post. Starting another stream or Cmd.OfFlow.Latest command with the
same key interrupts the running one, and elements it already posted that update has not yet seen are dropped, so a
search-as-you-type command never mixes results from two queries. A typed failure dispatches onError after the
elements before it; completion dispatches nothing, so append a final element when update needs to know the stream
finished. Cmd.OfFlow.Latest.cancel key runtime stops it without a message.
open Axial
open Axial.ElmishFlows
type SearchMsg =
| Found of string list
| SearchDone
| SearchFailed of string
let search (runtime: ElmishRuntime<unit>) (files: FlowStream<unit, string, string>) (query: string) =
let batches =
files
|> FlowStream.filter (fun path -> path.Contains query)
|> FlowStream.groupedWithin 64 (System.TimeSpan.FromMilliseconds 100.0)
|> FlowStream.map Found
|> FlowStream.append (FlowStream.singleton SearchDone)
Cmd.OfFlowStream.latest "search" runtime batches id SearchFailedEach element costs one Post, so batch a fast stream with FlowStream.groupedWithin before dispatching it.
Command parameter order
Axial's commands keep Elmish's "work first" idea, but the runtime owns the command's root scope, so it precedes the flow. Pass the flow positionally, not piped:
let command =
Cmd.OfFlow.either "increment" runtime
(Flow.succeed 2)
id
(fun (_: string) -> 0)The order is name runtime workflow onSuccess onError for either; perform drops onError, attempt drops
onSuccess, and Cmd.OfFlow.start name runtime workflow is fire-and-forget: it runs a
Flow<'env, Never, unit> as a named fiber in the root scope, dispatches nothing, and reports defects to OnDefect.
Operation reference
The exhaustive operation inventory lives in the API reference:
- Cmd:
Cmd.OfFlow.either/perform/attempt/start, the latest-winsCmd.OfFlow.Latestvariants, and the streamingCmd.OfFlowStream.latest. - Sub:
Sub.OfFlowStream.subscribefor running a stream under a subscription id. - Inbox:
Inbox.create/offer/post/dropped/streamfor synchronous UI input and search-as-you-type. - ElmishRuntime:
start,startLayer,startService,test, and theStop/StopAndWaitshutdown methods. - TestRuntime:
run,settle,drain,dispatched, anddefectsfor tests with a manual clock.

