### F# "Hello World" Example with Akkling Source: https://github.com/horusiath/akkling/blob/master/README.md Demonstrates a basic "hello world" example using Akkling. It initializes an actor system, spawns an anonymous actor that prints received messages, and sends a string message. It also shows an error when attempting to send an incorrect message type due to statically typed actors. ```fsharp open Akkling use system = System.create "my-system" <| Configuration.defaultConfig() let aref = spawnAnonymous system <| props(actorOf (fun m -> printfn "%s" m |> ignored)) aref printfn "Who sent Hi? %s?" lastKnown |> ignored | Greet(who) -> printfn "%s sends greetings" become (greeter who) let aref = spawn system "greeter" <| props(actorOf (greeter "Unknown")) aref printfn "Processing: %d" n ignored() | CrashWork -> failwith "Worker crashed!" ignored() // Supervisor with custom strategy let supervisor = spawn system "supervisor" <| { props(fun mailbox -> // Spawn supervised children let worker1 = spawn mailbox "worker1" <| props(actorOf workerBehavior) let worker2 = spawn mailbox "worker2" <| props(actorOf workerBehavior) let rec loop () = actor { let! (target: string, msg: WorkerMsg) = mailbox.Receive() let worker = if target = "w1" then worker1 else worker2 worker match ex with | :? InvalidOperationException -> Directive.Stop | _ -> Directive.Restart), retries = 3, timeout = TimeSpan.FromSeconds 10.0 )) } supervisor with SupervisorStrategy = (Strategy.OneForOne <@ fun error -> match error with | :? ArithmeticException -> Directive.Escalate | _ -> SupervisorStrategy.DefaultDecider error ) @>); Deploy = Deploy (RemoteScope remoteNodeAddr) } ``` -------------------------------- ### Create F#-Aware Actor System with Akkling Source: https://github.com/horusiath/akkling/wiki/Bootstrapping-an-actor-system Initializes an F#-aware actor system using the `Akkling.System.create` function. This method provides F#-specific features, such as serializers for F# quotations, which are beneficial for remote deployment. It requires a system name and an Akka configuration. The example demonstrates loading configuration from a project's .config file. ```fsharp open Akkling use system = System.create "my-system" (Configuration.load()) ``` -------------------------------- ### Spawn Named Actors in Akkling Source: https://context7.com/horusiath/akkling/llms.txt Shows how to spawn named actors in Akkling, allowing for explicit referencing through actor selection and integration into supervision hierarchies. This example demonstrates a counter actor with Increment, Decrement, and GetCount messages. ```fsharp open Akkling let system = System.create "my-system" <| Configuration.defaultConfig() type CounterMsg = | Increment | Decrement | GetCount // Named actor for easier reference let counter = spawn system "counter" <| props(actorOf (fun mailbox -> let rec loop count = actor { let! msg = mailbox.Receive() match msg with | Increment -> return! loop (count + 1) | Decrement -> return! loop (count - 1) | GetCount -> mailbox.Sender() Async.RunSynchronously ``` -------------------------------- ### Handling Persistent Lifecycle Events Source: https://github.com/horusiath/akkling/wiki/Persisting-events Provides an example of how to use dedicated event hooks, `ReplaySucceed` and `ReplayFailed`, to determine the outcome of the actor's recovery cycle. These events are useful for transitioning actor behavior or handling recovery failures. ```fsharp let! msg = ctx.Receive() match msg with | PersistentLifecycleEvent e -> match e with | ReplayFailed -> // actor failed to recover | ReplaySucceed -> // actor recovered successfully | _ -> ... ``` -------------------------------- ### Utilize Ask Pattern and Request-Reply in F# Source: https://context7.com/horusiath/akkling/llms.txt Shows how to implement request-reply communication with F# actors using the ask pattern. The `` representing the reply. This example also demonstrates how to set timeouts for these asynchronous requests, handling potential `TimeoutException` or other errors. ```fsharp open Akkling open System let system = System.create "ask-sys" <| Configuration.defaultConfig() type QueryMsg = | GetValue of key: string | SetValue of key: string * value: int // Actor with request-reply let kvStore = spawn system "kv-store" <| props(fun mailbox -> let rec loop (store: Map) = actor { let! msg = mailbox.Receive() match msg with | GetValue key -> let value = store.TryFind key mailbox.Sender() mailbox.Sender() Async.Ignore let! result = kvStore Async.RunSynchronously // Ask with timeout async { try let! value = kvStore.Ask(GetValue "y", Some (TimeSpan.FromSeconds 5.0)) printfn "Got: %A" value with | ex -> printfn "Timeout or error: %s" ex.Message } |> Async.RunSynchronously ``` -------------------------------- ### F# Akka OneForOne Supervisor Strategy Example Source: https://github.com/horusiath/akkling/wiki/Supervision-strategies Demonstrates how to configure the `Strategy.OneForOne` supervisor strategy in F# for a local actor. This strategy applies a specific decision to the child actor that faulted. It includes a decider function to handle different exception types, escalating `ArithmeticException` and using the default decider for others. ```fsharp let aref = spawnOpt system "my-actor" { props (actorOf myFunc) with SupervisorStrategy = Strategy.OneForOne (fun error -> match error with | :? ArithmeticException -> Directive.Escalate | _ -> SupervisorStrategy.DefaultDecider error ) } ``` -------------------------------- ### Akkling Actor Behavior with Effects (F#) Source: https://github.com/horusiath/akkling/wiki/Effects Demonstrates how to define an actor's behavior in Akkling using effects. The actor processes incoming messages and returns specific effects like 'Stop', 'Unhandled', or continues its loop. This example utilizes F# computation expressions for actor logic. ```fsharp let helloRef = spawn system "hello-actor" <| props(fun m -> let rec loop () = actor { let! msg = m.Receive () match msg with | "stop" -> return Stop | "unhandle" -> return Unhandled | x -> printfn "%s" x return! loop () } loop ()) ``` -------------------------------- ### Initialize Akkling Actor System Source: https://context7.com/horusiath/akkling/llms.txt Demonstrates how to initialize an Akkling actor system using default configurations, custom HOCON configurations, or by loading configurations from app.config. This is the foundational step for using the Akkling library. ```fsharp open Akkling // Create system with default configuration let system = System.create "my-system" <| Configuration.defaultConfig() // Create system with custom HOCON configuration let customConfig = Configuration.parse """ akka { actor { provider = \"Akka.Remote.RemoteActorRefProvider, Akka.Remote\" } remote { helios.tcp { hostname = \"127.0.0.1\" port = 8080 } } }" let remoteSystem = System.create "remote-system" customConfig // Load configuration from app.config let loadedSystem = System.create "loaded-system" <| Configuration.load() ``` -------------------------------- ### Creating an Actor System Source: https://context7.com/horusiath/akkling/llms.txt Initialize an actor system with default or custom configuration. Supports default configuration, custom HOCON configuration, and loading configuration from app.config. ```APIDOC ## Creating an Actor System ### Description Initialize an actor system with default or custom configuration. ### Method N/A (F# code examples) ### Endpoint N/A (F# code examples) ### Parameters N/A (F# code examples) ### Request Example ```fsharp open Akkling // Create system with default configuration let system = System.create "my-system" <| Configuration.defaultConfig() // Create system with custom HOCON configuration let customConfig = Configuration.parse """ akka { actor { provider = \"Akka.Remote.RemoteActorRefProvider, Akka.Remote\" } remote { helios.tcp { hostname = \"127.0.0.1\" port = 8080 } } }"" let remoteSystem = System.create "remote-system" customConfig // Load configuration from app.config let loadedSystem = System.create "loaded-system" <| Configuration.load() ``` ### Response #### Success Response (200) N/A (F# code examples) #### Response Example N/A (F# code examples) ``` -------------------------------- ### Handling Actor Phases with Pattern Matching Source: https://github.com/horusiath/akkling/wiki/Persisting-events Demonstrates how to handle different actor phases (recovery, persisted event, deferred) using pattern matching on received messages and context properties. This is crucial for ensuring correct logic execution based on the actor's current state. ```fsharp let! msg = ctx.Receive() match msg with | event when ctx.IsRecovering () -> // actor is in recovery phase | Persisted ctx event -> // actor has persisted an event | Deffered ctx event -> // actor has persisted events batch and invoked deffered phase | _ -> ... ``` -------------------------------- ### F# Akka Configuration Utilities Source: https://github.com/horusiath/akkling/wiki/Bootstrapping-an-actor-system Provides utility functions for managing Akka configurations within an F# environment. These functions allow for obtaining default configurations, parsing HOCON strings, and loading configurations from project files. These utilities are part of the F# actor system's Configuration module. ```fsharp // Returns default F# Akka configuration. defaultConfig() : Config // Parses a provided Akka configuration string. parse(hoconString : string) : Config // Loads an Akka configuration found inside current project's .config file. load() : Config ``` -------------------------------- ### Spawning Actors with spawn and spawnAnonymous Source: https://github.com/horusiath/akkling/wiki/Creating-an-actor Shows how to spawn actors using `spawn` for named actors and `spawnAnonymous` for unnamed actors. Both functions require an actor system or context and `Props` to define the actor's behavior and configuration. ```fsharp spawn system "my-actor" (props (actorOf2 (handleMessage []))) spawnAnonymous system (props Behaviors.ignore) ``` -------------------------------- ### F# Actor Lifecycle Hooks with Akkling Source: https://context7.com/horusiath/akkling/llms.txt Demonstrates handling actor lifecycle events such as PreStart, PostStop, and restarts using F# and Akkling. This involves defining custom messages and an actor behavior that reacts to lifecycle events. ```fsharp open Akkling let system = System.create "lifecycle-sys" <| Configuration.defaultConfig() type LifecycleMsg = | DoWork of string | Crash // Actor with lifecycle management let lifecycleActor = spawn system "lifecycle-actor" <| props(fun mailbox -> let rec loop () = actor { let! msg = mailbox.Receive() match msg with | :? LifecycleEvent as lifecycle -> match lifecycle with | PreStart -> printfn "Actor starting - initializing resources" | PostStop -> printfn "Actor stopping - cleaning up resources" | PreRestart (cause, msg) -> printfn "Actor restarting due to: %s" cause.Message | PostRestart cause -> printfn "Actor restarted after: %s" cause.Message return! loop() | DoWork content -> printfn "Working on: %s" content return! loop() | Crash -> failwith "Simulated crash" return! loop() } loop()) lifecycleActor printfn "Selected actor received: %s" msg ignored() )) // Select by relative path let selection1: TypedActorSelection = select system "user/my-actor" selection1 = select system "akka://selection-sys/user/my-actor" selection2 = select system "user/*" allUserActors Async.RunSynchronously ``` -------------------------------- ### Handle Actor Lifecycle Events in F# Source: https://github.com/horusiath/akkling/wiki/Managing-actor's-lifecycle This F# snippet demonstrates how to handle actor lifecycle events like PostStop to manage disposable resources. It initializes a resource and disposes of it when the actor receives the PostStop event. ```fsharp let ref = spawnAnonymous system (props <| fun ctx -> let resource = initDisposableResource() let rec loop () = actor { let! msg = ctx.Receive () match msg with | LifecycleEvent e -> match e with | PostStop -> resource.Dispose() return! loop () | _ -> return Unhandled | other -> ... } loop ()) ``` -------------------------------- ### Stateful Actors with Become in Akkling Source: https://context7.com/horusiath/akkling/llms.txt Demonstrates how to implement stateful actors in Akkling using the 'become' pattern. This allows actors to dynamically change their behavior over time, managing internal state by switching behavior functions. It's suitable for actors that transition through different operational phases. ```fsharp open Akkling let system = System.create "stateful-sys" <| Configuration.defaultConfig() type StateMsg = | Add of string | PrintAll | Clear // Stateful actor using become pattern let rec stateHandler state = function | Add item -> printfn "Adding: %s" item become (stateHandler (item :: state)) | PrintAll -> printfn "State: %A" state ignored() | Clear -> printfn "Clearing state" become (stateHandler []) let statefulActor = spawnAnonymous system <| props (actorOf (stateHandler [])) statefulActor let rec loop state = actor { let! msg = ctx.Receive() match msg with | SnapshotOffer snapshot -> return! loop snapshot | _ -> ... } loop initialState ``` -------------------------------- ### Implement Persistent Actors with Event Sourcing in F# Source: https://context7.com/horusiath/akkling/llms.txt Illustrates the creation of event-sourced F# actors that can recover their state from persisted events. This is achieved using the `propsPersist` function, which allows defining how to handle events for state updates and commands that trigger event persistence. State is automatically replayed on actor recovery. ```fsharp open Akkling open Akkling.Persistence let system = System.create "persist-sys" <| Configuration.defaultConfig() type CounterEvent = { Delta: int } type CounterCmd = | Inc | Dec | GetState type CounterMsg = | Command of CounterCmd | Event of CounterEvent // Persistent actor with event sourcing let counter = spawn system "persistent-counter-1" <| propsPersist (fun mailbox -> let rec loop state = actor { let! msg = mailbox.Receive() match msg with | Event changed -> // Replay persisted event return! loop (state + changed.Delta) | Command cmd -> match cmd with | GetState -> mailbox.Sender() // Persist event, then update state return Persist(Event { Delta = 1 }) | Dec -> return Persist(Event { Delta = -1 }) } loop 0) counter Async.RunSynchronously // Counter state persists across actor restarts ``` -------------------------------- ### Stateful Actors with Become Source: https://context7.com/horusiath/akkling/llms.txt Manage actor state by switching behavior functions using the 'become' pattern. Allows actors to change their internal logic dynamically. ```APIDOC ## Stateful Actors with Become ### Description Manage actor state by switching behavior functions. ### Method N/A (F# code examples) ### Endpoint N/A (F# code examples) ### Parameters N/A (F# code examples) ### Request Example ```fsharp open Akkling let system = System.create "stateful-sys" <| Configuration.defaultConfig() type StateMsg = | Add of string | PrintAll | Clear // Stateful actor using become pattern let rec stateHandler state = function | Add item -> printfn "Adding: %s" item become (stateHandler (item :: state)) | PrintAll -> printfn "State: %A" state ignored() | Clear -> printfn "Clearing state" become (stateHandler []) let statefulActor = spawnAnonymous system <| props (actorOf (stateHandler [])) statefulActor let rec loop count = actor { let! msg = mailbox.Receive() match msg with | Increment -> return! loop (count + 1) | Decrement -> return! loop (count - 1) | GetCount -> mailbox.Sender() Async.RunSynchronously ``` ### Response #### Success Response (200) N/A (F# code examples) #### Response Example N/A (F# code examples) ``` -------------------------------- ### F# Akkling Logging Methods Source: https://github.com/horusiath/akkling/wiki/Logging This section outlines the F# API for logging in Akkling, including methods for different log levels (Debug, Info, Warning, Error) and specialized functions like `log` and `logf` for explicit level control, as well as `logException` for error handling. ```fsharp // Log with explicit level log (level : LogLevel) (mailbox : Actor<'Message>) (msg : string) : unit logf (level : LogLevel) (mailbox : Actor<'Message>) (format:StringFormat<'T, 'Result>) : 'T // Log at Debug level logDebug (mailbox : Actor<'Message>) (msg : string) : unit logDebugf (mailbox : Actor<'Message>) (format:StringFormat<'T, 'Result>) : 'T // Log at Info level logInfo (mailbox : Actor<'Message>) (msg : string) : unit logInfof (mailbox : Actor<'Message>) (format:StringFormat<'T, 'Result>) : 'T // Log at Warning level logWarning (mailbox : Actor<'Message>) (msg : string) : unit logWarningf (mailbox : Actor<'Message>) (format:StringFormat<'T, 'Result>) : 'T // Log at Error level logError (mailbox : Actor<'Message>) (msg : string) : unit logErrorf (mailbox : Actor<'Message>) (format:StringFormat<'T, 'Result>) : 'T // Log an exception at Error level logException (mailbox: Actor<'a>) (e : exn) : unit ``` -------------------------------- ### Spawn Anonymous Actors in Akkling Source: https://context7.com/horusiath/akkling/llms.txt Illustrates spawning anonymous actors in Akkling, which are actors created without explicit names. This includes creating simple stateless actors and actors that utilize pattern matching for message handling. Useful for simple, self-contained behaviors. ```fsharp open Akkling let system = System.create "basic-sys" <| Configuration.defaultConfig() // Simple stateless actor let simpleActor = spawnAnonymous system <| props(actorOf (fun msg -> printfn "Received: %s" msg ignored() )) simpleActor printfn "Message: %s" msg ignored() | Stop -> printfn "Stopping actor" stop() )) patternActor and <&> Operators in F# Source: https://context7.com/horusiath/akkling/llms.txt Demonstrates combining multiple F# behavior functions using the 'or' (<|>) and 'and' (<&>) operators. The 'or' operator executes the right behavior only if the left is unhandled, while the 'and' operator executes the right behavior after the left is handled. This allows for flexible and modular actor logic. ```fsharp open Akkling let system = System.create "composition-sys" <| Configuration.defaultConfig() type CommandMsg = | CommandA of string | CommandB of int | Unknown // Primary behavior let primaryBehavior _ = function | CommandA msg -> printfn "Handling CommandA: %s" msg ignored() | _ -> unhandled() // Fallback behavior for unhandled messages let fallbackBehavior _ = function | CommandB num -> printfn "Fallback handling CommandB: %d" num ignored() | Unknown -> printfn "Unknown command received" ignored() | _ -> unhandled() // OR combinator: right executes only when left is unhandled let orActor = spawn system "or-actor" <| props (actorOf2 (primaryBehavior <|> fallbackBehavior)) orActor loggingBehavior)) andActor printfn "Received: %s" msg ignored() )) simpleActor printfn "Message: %s" msg ignored() | Stop -> printfn "Stopping actor" stop() )) patternActor -> Effect<'Message>) : Props<'Message>` #### Description Creates `Props<'Message>` for a persistent actor. This function cannot be used with `spawnAnonymous`. ### Function: `propsPersiste` #### Signature `propsPersiste(expr: Expr<(Eventsourced<'Message> -> Effect<'Message>)>) : Props<'Message>` #### Description Similar to `propsPersist`, but works with F# quotations. ``` -------------------------------- ### F# Akka.NET Typed Actor Selection and Communication Source: https://github.com/horusiath/akkling/wiki/Static-type-safety Demonstrates how to use Akkling's `select` function to create a typed actor selection from a given path and then communicate with the actor using the 'ask' (` ref () } ``` -------------------------------- ### Schedule Messages with Akkling Actor Source: https://context7.com/horusiath/akkling/llms.txt Schedules one-time and recurring messages to be delivered to an actor's mailbox after specified delays or intervals. It utilizes `mailbox.Schedule` for one-time messages and `mailbox.ScheduleRepeatedly` for recurring ones, allowing cancellation of recurring schedules. ```fsharp open Akkling open System let system = System.create "schedule-sys" <| Configuration.defaultConfig() type ScheduledMsg = | Tick | OneTime of string let scheduledActor = spawn system "scheduler" <| props(fun mailbox -> // Schedule one-time message let cancellable1 = mailbox.Schedule (TimeSpan.FromSeconds 2.0) mailbox.Self (OneTime "delayed message") // Schedule recurring messages let cancellable2 = mailbox.ScheduleRepeatedly (TimeSpan.FromSeconds 1.0) // initial delay (TimeSpan.FromSeconds 3.0) // interval mailbox.Self Tick let rec loop tickCount = actor { let! msg = mailbox.Receive() match msg with | Tick -> let newCount = tickCount + 1 printfn "Tick #%d at %A" newCount DateTime.Now if newCount >= 5 then cancellable2.Cancel() // Stop recurring printfn "Cancelled recurring ticks" return! loop newCount | OneTime content -> printfn "One-time message: %s" content return! loop tickCount } loop 0) System.Threading.Thread.Sleep(20000) // Let scheduler run ``` -------------------------------- ### F# Actor Message Handling with actorOf2 Source: https://github.com/horusiath/akkling/wiki/Creating-an-actor Illustrates defining an F# actor's message handler using the `actorOf2` shorthand. This function takes a state and context, allowing for behaviors like printing the state or updating it using `become`. ```fsharp let rec handleMessage state (context: Actor<'a>) = function | "print" -> printf "%A" state |> ignored // returned effect - stay the same | x -> become (handleMessage (x::state) context) // returned effect - update the actor's state let aref = spawn system "my-actor" (props (actorOf2 (handleMessage []))) // init actor state with empty list ``` -------------------------------- ### Akkling Behaviors: Ignore and Echo Source: https://github.com/horusiath/akkling/wiki/Creating-an-actor Demonstrates the use of pre-defined behaviors in Akkling. `Behaviors.ignore` creates an actor that discards all messages, while `Behaviors.echo` resends each received message back to its sender. ```fsharp let blackhole = spawnAnonymous system (props Behaviors.ignore) let echoRef = spawnAnonymous system (props Behaviors.echo) ``` -------------------------------- ### Persistent Views Source: https://github.com/horusiath/akkling/wiki/Persistent-actors Functions for creating persistent views connected to a persistent actor's event stream. ```APIDOC ## Persistent Views ### Description Functions for defining persistent views. A view is connected to a persistent actor's event stream and operates in read-only mode, allowing multiple views to replay different read models from the same event stream. ### Function: `propsView` #### Signature `propsView(persistentId: string) (receive: View<'Message> -> Effect<'Message>) : Props<'Message>` #### Description Creates `Props<'Message>` for a persistent view. `persistentId` is the event stream identifier of the correlated persistent actor. ### Function: `propsViewe` #### Signature `propsViewe(persistentId: string) (expr: Expr<(View<'Message> -> Effect<'Message>)>) : Props<'Message>` #### Description Similar to `propsView`, but takes an F# quotation as input. ``` -------------------------------- ### Akka Event Streams F# API Source: https://github.com/horusiath/akkling/wiki/Event-buses This section details the F# functions available for interacting with Akka's event streams. ```APIDOC ## Akka Event Streams F# API ### Description This section details the F# functions available for interacting with Akka's event streams. ### Subscribe #### Method `subscribe` #### Endpoint N/A (F# function) #### Parameters ##### Function Parameters - **ref** (`IActorRef<'Message>`) - Required - An actor reference to subscribe. - **eventStream** (`Akka.Event.EventStream`) - Required - The event stream to subscribe to. ### Publish #### Method `publish` #### Endpoint N/A (F# function) #### Parameters ##### Function Parameters - **event** (`'Event`) - Required - The event to publish. - **eventStream** (`Akka.Event.EventStream`) - Required - The event stream to publish on. ### Unsubscribe #### Method `unsubscribe` #### Endpoint N/A (F# function) #### Parameters ##### Function Parameters - **ref** (`IActorRef<'Message>`) - Required - An actor reference to unsubscribe. - **eventStream** (`Akka.Event.EventStream`) - Required - The event stream to unsubscribe from. ``` -------------------------------- ### Monitor Actor Termination in F# Source: https://github.com/horusiath/akkling/wiki/Managing-actor's-lifecycle This F# code illustrates how to monitor another actor's lifecycle using the `monitor` function. The watcher actor receives a `Terminated` message when the monitored actor dies permanently. ```fsharp let watcher = spawnAnonymous client (props <| fun context -> monitor context actorRef |> ignore let rec loop() = actor { let! msg = context.Receive() match msg with | Terminated(ref, existenceConfirmed, addressTerminated) -> return! loop() | _ -> return Unhandled } loop ()) ``` -------------------------------- ### Configure Akkling Logging Level Source: https://github.com/horusiath/akkling/wiki/Logging This snippet demonstrates how to configure the logging level for the Akkling actor system using HOCON. It specifies which loggers to use and the desired log level, affecting the verbosity of log output. ```hocon akka { actor { # collection of loggers used inside actor system, specified by fully-qualified type name loggers = [ "Akka.Event.DefaultLogger, Akka" ] # Options: OFF, ERROR, WARNING, INFO, DEBUG logLevel = "DEBUG" } } ``` -------------------------------- ### Pipe Async Results to Akkling Actor Source: https://context7.com/horusiath/akkling/llms.txt Pipes the results of asynchronous computations directly to an actor's mailbox using the `|!>` and ` printfn "Received result: %d" value ignored() | Error msg -> printfn "Received error: %s" msg ignored() )) // Long-running async computation let expensiveComputation () = async { do! Async.Sleep 1000 return Result 42 } // Pipe result to actor expensiveComputation() |!> resultHandler // Alternative syntax resultHandler return Error ex.Message }) System.Threading.Thread.Sleep(2000) ``` -------------------------------- ### Actor Selection Source: https://github.com/horusiath/akkling/wiki/Static-type-safety Allows communicating with actors via a logical path when an actor reference is not directly available. ```APIDOC ## Actor Selections ### Description When you don't have a direct actor reference, you can use `select` to obtain a `TypedActorSelection` based on a logical path. This selection can then be used with the same message-sending operators as actor references. ### Function - `select (selector : IActorRefFactory) (path : string) : TypedActorSelection<'Message>` - **Description:** Creates a typed actor selection for the specified path. The result is type-safe and can be used with message-sending operators. - **Parameters:** - `selector` (IActorRefFactory): The factory to create the selection from (e.g., the Akka `ActorSystem`). - `path` (string): The logical path to the target actor. ### Example Usage ```fsharp let selection = select system "akka.tcp://remote-system@localhost:4000/user/parent/child" let! reply = selection ref () // Actor not found ``` **Note:** Actor selection operations may also time out if the target actor or system does not respond. ``` -------------------------------- ### Retyping Actor References Source: https://github.com/horusiath/akkling/wiki/Static-type-safety Provides a mechanism to convert actor references between different message types. ```APIDOC ## Retyping Actor References ### Description The `retype` function allows you to convert an `IActorRef<'A>` to an `IActorRef<'B>`. This is useful when you need to combine custom message types with Akka system messages, or when you want to narrow or widen the message types that can be sent through an actor reference. ### Function - `retype (actorRef : IActorRef<'A>) : IActorRef<'B>` - **Description:** Converts an actor reference from handling messages of type `'A` to handling messages of type `'B`. - **Type Safety:** This operation is safe as long as the underlying actor can handle the new message type. ### Use Cases - Combining user-defined message hierarchies with Akka system messages. - Adjusting the message types an actor reference can communicate with for specific purposes. ``` -------------------------------- ### Stash Messages with Akkling Actor Source: https://context7.com/horusiath/akkling/llms.txt Temporarily stashes messages when an actor is not ready to process them, allowing for later processing using `mailbox.Stash` and `mailbox.UnstashAll`. This is useful for handling initialization or state-dependent message processing. ```fsharp open Akkling let system = System.create "stash-sys" <| Configuration.defaultConfig() type StashMsg = | Initialize of config: string | Process of data: string | Ready let stashingActor = spawn system "stasher" <| props(fun mailbox -> let rec uninitialized () = actor { let! msg = mailbox.Receive() match msg with | Initialize config -> printfn "Initializing with: %s" config mailbox.UnstashAll() // Process stashed messages return! ready() | Ready -> return! uninitialized() | Process _ -> printfn "Not ready, stashing message" mailbox.Stash() return! uninitialized() } and ready () = actor { let! msg = mailbox.Receive() match msg with | Process data -> printfn "Processing: %s" data return! ready() | _ -> return! ready() } uninitialized()) stashingActor let rec loop () = actor { let! msg = context.Receive () match msg with | "stop" -> return Stop // effect - stops current actor | "unhandle" -> return Unhandled // effect - marks message as unhandled | x -> printfn "%s" x return! loop () } loop ()) ``` -------------------------------- ### Message Sending Operators Source: https://github.com/horusiath/akkling/wiki/Static-type-safety Akkling provides type-safe operators for communicating with actors. ```APIDOC ## Message Sending Operators ### Description These operators allow for type-safe message passing to actors using their `IActorRef`. ### Operators - `() (msg : 'Message) : unit` - **Description:** Sends a message to the target actor. - **Type Safety:** Compile-time checked. - `(<) (msg : 'Message) : unit` - **Description:** Forwards a message to the target actor without overriding the message sender. - **Type Safety:** Compile-time checked. - `() (msg : 'Message) : Async>` - **Description:** Sends a message and asynchronously waits for a response. The response is returned as an F# `Async` computation. A timeout can be configured via HOCON (`akka.actor.ask-timeout`), with an infinite default. - **Type Safety:** Compile-time checked. - `(|!>) (computation : Async<'Message>) (recipient : ICanTell<'Message>)` - **Description:** Asynchronously waits for an `Async` operation to complete and sends its result as a message to the target actor. This operator has left-side (``) versions. - **Type Safety:** Compile-time checked. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.