7 people like it.

MailboxProcessor with exception handling and restarting

An extension of MailboxProcessor that catches all unhandled exceptions, and ensures that the user-provided function is run repeatedly until it returns normally. Based on the HandlingMailbox defined by Tomas Petricek: fssnip.net/cj

Definition of ResilientMailbox

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
21: 
22: 
23: 
24: 
25: 
26: 
27: 
28: 
29: 
30: 
31: 
/// A wrapper for MailboxProcessor that catches all unhandled
/// exceptions and reports them via the 'OnError' event, repeatedly
/// running the provided function until it returns normally.
type ResilientMailbox<'T> private(f:ResilientMailbox<'T> -> Async<unit>) as self =
    // Create an event for reporting errors
    let event = Event<_>()
    // Start the standard MailboxProcessor
    let inbox = new MailboxProcessor<_>(fun _inbox ->
        // Recursivly run the user-provided function until it returns
        // normally; handle any exceptions it throws
        let rec loop() = async {
            // Run the user-provided function and handle exceptions
            try return! f self
            with e ->
                event.Trigger(e)
                return! loop()
            }
        loop())
    /// Triggered when an unhandled exception occurs
    member __.OnError = event.Publish
    /// Starts the mailbox processor
    member __.Start() = inbox.Start()
    /// Receive a message from the mailbox processor
    member __.Receive() = inbox.Receive()
    /// Post a message to the mailbox processor
    member __.Post(v:'T) = inbox.Post(v)
    /// Start the mailbox processor
    static member Start(f) =
        let mbox = new ResilientMailbox<_>(f)
        mbox.Start()
        mbox

Example of use

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
// The usage is the same as with standard MailboxProcessor
let counter =
    ResilientMailbox<_>.Start(
        fun inbox ->
            async {
                while true do
                    printfn "waiting for data..."
                    let! data = inbox.Receive()
                    // Simulate an exception
                    failwith "fail!"
            })

// Specify callback for unhandled errors and send a test message
counter.OnError.Add(printfn "Exception: %A")
counter.Post(42)
Multiple items
type ResilientMailbox<'T> =
  private new : f:(ResilientMailbox<'T> -> Async<unit>) -> ResilientMailbox<'T>
  member Post : v:'T -> unit
  member Receive : unit -> Async<'T>
  member Start : unit -> unit
  member OnError : IEvent<exn>
  static member Start : f:(ResilientMailbox<'a> -> Async<unit>) -> ResilientMailbox<'a>

Full name: Script.ResilientMailbox<_>


 A wrapper for MailboxProcessor that catches all unhandled
 exceptions and reports them via the 'OnError' event, repeatedly
 running the provided function until it returns normally.


--------------------
private new : f:(ResilientMailbox<'T> -> Async<unit>) -> ResilientMailbox<'T>
val f : (ResilientMailbox<'T> -> Async<unit>)
Multiple items
type Async
static member AsBeginEnd : computation:('Arg -> Async<'T>) -> ('Arg * AsyncCallback * obj -> IAsyncResult) * (IAsyncResult -> 'T) * (IAsyncResult -> unit)
static member AwaitEvent : event:IEvent<'Del,'T> * ?cancelAction:(unit -> unit) -> Async<'T> (requires delegate and 'Del :> Delegate)
static member AwaitIAsyncResult : iar:IAsyncResult * ?millisecondsTimeout:int -> Async<bool>
static member AwaitTask : task:Task<'T> -> Async<'T>
static member AwaitWaitHandle : waitHandle:WaitHandle * ?millisecondsTimeout:int -> Async<bool>
static member CancelDefaultToken : unit -> unit
static member Catch : computation:Async<'T> -> Async<Choice<'T,exn>>
static member FromBeginEnd : beginAction:(AsyncCallback * obj -> IAsyncResult) * endAction:(IAsyncResult -> 'T) * ?cancelAction:(unit -> unit) -> Async<'T>
static member FromBeginEnd : arg:'Arg1 * beginAction:('Arg1 * AsyncCallback * obj -> IAsyncResult) * endAction:(IAsyncResult -> 'T) * ?cancelAction:(unit -> unit) -> Async<'T>
static member FromBeginEnd : arg1:'Arg1 * arg2:'Arg2 * beginAction:('Arg1 * 'Arg2 * AsyncCallback * obj -> IAsyncResult) * endAction:(IAsyncResult -> 'T) * ?cancelAction:(unit -> unit) -> Async<'T>
static member FromBeginEnd : arg1:'Arg1 * arg2:'Arg2 * arg3:'Arg3 * beginAction:('Arg1 * 'Arg2 * 'Arg3 * AsyncCallback * obj -> IAsyncResult) * endAction:(IAsyncResult -> 'T) * ?cancelAction:(unit -> unit) -> Async<'T>
static member FromContinuations : callback:(('T -> unit) * (exn -> unit) * (OperationCanceledException -> unit) -> unit) -> Async<'T>
static member Ignore : computation:Async<'T> -> Async<unit>
static member OnCancel : interruption:(unit -> unit) -> Async<IDisposable>
static member Parallel : computations:seq<Async<'T>> -> Async<'T []>
static member RunSynchronously : computation:Async<'T> * ?timeout:int * ?cancellationToken:CancellationToken -> 'T
static member Sleep : millisecondsDueTime:int -> Async<unit>
static member Start : computation:Async<unit> * ?cancellationToken:CancellationToken -> unit
static member StartAsTask : computation:Async<'T> * ?taskCreationOptions:TaskCreationOptions * ?cancellationToken:CancellationToken -> Task<'T>
static member StartChild : computation:Async<'T> * ?millisecondsTimeout:int -> Async<Async<'T>>
static member StartChildAsTask : computation:Async<'T> * ?taskCreationOptions:TaskCreationOptions -> Async<Task<'T>>
static member StartImmediate : computation:Async<unit> * ?cancellationToken:CancellationToken -> unit
static member StartWithContinuations : computation:Async<'T> * continuation:('T -> unit) * exceptionContinuation:(exn -> unit) * cancellationContinuation:(OperationCanceledException -> unit) * ?cancellationToken:CancellationToken -> unit
static member SwitchToContext : syncContext:SynchronizationContext -> Async<unit>
static member SwitchToNewThread : unit -> Async<unit>
static member SwitchToThreadPool : unit -> Async<unit>
static member TryCancelled : computation:Async<'T> * compensation:(OperationCanceledException -> unit) -> Async<'T>
static member CancellationToken : Async<CancellationToken>
static member DefaultCancellationToken : CancellationToken

Full name: Microsoft.FSharp.Control.Async

--------------------
type Async<'T>

Full name: Microsoft.FSharp.Control.Async<_>
type unit = Unit

Full name: Microsoft.FSharp.Core.unit
val self : ResilientMailbox<'T>
val event : Event<exn>
Multiple items
module Event

from Microsoft.FSharp.Control

--------------------
type Event<'T> =
  new : unit -> Event<'T>
  member Trigger : arg:'T -> unit
  member Publish : IEvent<'T>

Full name: Microsoft.FSharp.Control.Event<_>

--------------------
type Event<'Delegate,'Args (requires delegate and 'Delegate :> Delegate)> =
  new : unit -> Event<'Delegate,'Args>
  member Trigger : sender:obj * args:'Args -> unit
  member Publish : IEvent<'Delegate,'Args>

Full name: Microsoft.FSharp.Control.Event<_,_>

--------------------
new : unit -> Event<'T>

--------------------
new : unit -> Event<'Delegate,'Args>
val inbox : MailboxProcessor<'T>
Multiple items
type MailboxProcessor<'Msg> =
  interface IDisposable
  new : body:(MailboxProcessor<'Msg> -> Async<unit>) * ?cancellationToken:CancellationToken -> MailboxProcessor<'Msg>
  member Post : message:'Msg -> unit
  member PostAndAsyncReply : buildMessage:(AsyncReplyChannel<'Reply> -> 'Msg) * ?timeout:int -> Async<'Reply>
  member PostAndReply : buildMessage:(AsyncReplyChannel<'Reply> -> 'Msg) * ?timeout:int -> 'Reply
  member PostAndTryAsyncReply : buildMessage:(AsyncReplyChannel<'Reply> -> 'Msg) * ?timeout:int -> Async<'Reply option>
  member Receive : ?timeout:int -> Async<'Msg>
  member Scan : scanner:('Msg -> Async<'T> option) * ?timeout:int -> Async<'T>
  member Start : unit -> unit
  member TryPostAndReply : buildMessage:(AsyncReplyChannel<'Reply> -> 'Msg) * ?timeout:int -> 'Reply option
  ...

Full name: Microsoft.FSharp.Control.MailboxProcessor<_>

--------------------
new : body:(MailboxProcessor<'Msg> -> Async<unit>) * ?cancellationToken:System.Threading.CancellationToken -> MailboxProcessor<'Msg>
val _inbox : MailboxProcessor<'T>
val loop : (unit -> Async<unit>)
val async : AsyncBuilder

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.async
val e : exn
member Event.Trigger : arg:'T -> unit
member ResilientMailbox.OnError : IEvent<exn>

Full name: Script.ResilientMailbox`1.OnError


 Triggered when an unhandled exception occurs
property Event.Publish: IEvent<exn>
val __ : ResilientMailbox<'T>
member ResilientMailbox.Start : unit -> unit

Full name: Script.ResilientMailbox`1.Start


 Starts the mailbox processor
member MailboxProcessor.Start : unit -> unit
member ResilientMailbox.Receive : unit -> Async<'T>

Full name: Script.ResilientMailbox`1.Receive


 Receive a message from the mailbox processor
member MailboxProcessor.Receive : ?timeout:int -> Async<'Msg>
member ResilientMailbox.Post : v:'T -> unit

Full name: Script.ResilientMailbox`1.Post


 Post a message to the mailbox processor
val v : 'T
member MailboxProcessor.Post : message:'Msg -> unit
static member ResilientMailbox.Start : f:(ResilientMailbox<'a> -> Async<unit>) -> ResilientMailbox<'a>

Full name: Script.ResilientMailbox`1.Start


 Start the mailbox processor
val f : (ResilientMailbox<'a> -> Async<unit>)
val mbox : ResilientMailbox<'a>
member ResilientMailbox.Start : unit -> unit


 Starts the mailbox processor
val counter : ResilientMailbox<int>

Full name: Script.counter
type ResilientMailbox<'T> =
  private new : f:(ResilientMailbox<'T> -> Async<unit>) -> ResilientMailbox<'T>
  member Post : v:'T -> unit
  member Receive : unit -> Async<'T>
  member Start : unit -> unit
  member OnError : IEvent<exn>
  static member Start : f:(ResilientMailbox<'a> -> Async<unit>) -> ResilientMailbox<'a>

Full name: Script.ResilientMailbox<_>


 A wrapper for MailboxProcessor that catches all unhandled
 exceptions and reports them via the 'OnError' event, repeatedly
 running the provided function until it returns normally.
val inbox : ResilientMailbox<int>
val printfn : format:Printf.TextWriterFormat<'T> -> 'T

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.printfn
val data : int
member ResilientMailbox.Receive : unit -> Async<'T>


 Receive a message from the mailbox processor
val failwith : message:string -> 'T

Full name: Microsoft.FSharp.Core.Operators.failwith
property ResilientMailbox.OnError: IEvent<exn>


 Triggered when an unhandled exception occurs
member System.IObservable.Add : callback:('T -> unit) -> unit
member ResilientMailbox.Post : v:'T -> unit


 Post a message to the mailbox processor
Raw view Test code New version

More information

Link:http://fssnip.net/p2
Posted:9 years ago
Author:Anthony Perez
Tags: mailboxprocessor , agent , async , exception