Skip to content

Commit

Permalink
Add cooldown timer, pass wrapRun context (#29)
Browse files Browse the repository at this point in the history
  • Loading branch information
ForNeVeR committed Jun 12, 2019
1 parent 90046a4 commit 7daaddf
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 7 deletions.
15 changes: 12 additions & 3 deletions Emulsion.Tests/MessageSystem.fs
Original file line number Diff line number Diff line change
@@ -1,18 +1,26 @@
module Emulsion.Tests.MessageSystem

open Xunit

open System
open System.Threading

open Xunit

open Emulsion
open Emulsion.MessageSystem

let private performTest expectedStage runBody =
use cts = new CancellationTokenSource()
let mutable stage = 0
let run ct =
stage <- stage + 1
runBody cts ct stage
MessageSystem.wrapRun cts.Token run ignore
let context = {
token = cts.Token
cooldown = TimeSpan.Zero
logError = ignore
logMessage = ignore
}
MessageSystem.wrapRun context run
Assert.Equal(expectedStage, stage)

[<Fact>]
Expand All @@ -21,6 +29,7 @@ let ``wrapRun should restart the activity on error``() =
match stage with
| 1 -> raise <| Exception()
| 2 -> cts.Cancel()
| _ -> failwith "Impossible"
)

[<Fact>]
Expand Down
18 changes: 14 additions & 4 deletions Emulsion/MessageSystem.fs
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,20 @@ type IMessageSystem =
/// Queues the message to be sent to the IM system when possible.
abstract member PutMessage : OutgoingMessage -> unit

let internal wrapRun (token: CancellationToken) (run: CancellationToken -> unit) (log: Exception -> unit) : unit =
while not token.IsCancellationRequested do
type RestartContext = {
token: CancellationToken
cooldown: TimeSpan
logError: Exception -> unit
logMessage: string -> unit
}

let wrapRun (ctx: RestartContext) (run: CancellationToken -> unit) : unit =
while not ctx.token.IsCancellationRequested do
try
run token
run ctx.token
with
| :? OperationCanceledException -> ()
| ex -> log ex
| ex ->
ctx.logError ex
ctx.logMessage <| sprintf "Waiting for %A to restart" ctx.cooldown
Thread.Sleep ctx.cooldown

0 comments on commit 7daaddf

Please sign in to comment.