Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: Fix intermittent test failures #52

Open
wants to merge 16 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 12 additions & 6 deletions Sources/CircuitBreaker/CircuitBreaker.swift
Original file line number Diff line number Diff line change
Expand Up @@ -77,13 +77,19 @@ public class CircuitBreaker<A, B> {
/// The Circuit Breaker's current state.
public private(set) var breakerState: State {
get {
return state
breakerStateSemaphore.wait()
let tempState = state
breakerStateSemaphore.signal()
return tempState
}
set {
breakerStateSemaphore.wait()
state = newValue
breakerStateSemaphore.signal()
}
}

// This the backing store for the state and must be accessed via breakerState
private(set) var state = State.closed
private let failures: FailureQueue
//fallback function is invoked ONLY when failing fast OR when timing out OR when application
Expand All @@ -93,9 +99,11 @@ public class CircuitBreaker<A, B> {
private let bulkhead: Bulkhead?

/// Dispatch
// resetTimer should be started via startResetTimer
private var resetTimer: DispatchSourceTimer?
private let semaphoreCircuit = DispatchSemaphore(value: 1)

private let timerSemaphore = DispatchSemaphore(value: 1)
private let breakerStateSemaphore = DispatchSemaphore(value: 1)
private let queue = DispatchQueue(label: "Circuit Breaker Queue", attributes: .concurrent)

// MARK: Initializers
Expand Down Expand Up @@ -215,16 +223,12 @@ public class CircuitBreaker<A, B> {

/// Method to force the circuit open.
public func forceOpen() {
semaphoreCircuit.wait()
open()
semaphoreCircuit.signal()
}

/// Method to force the circuit closed.
public func forceClosed() {
semaphoreCircuit.wait()
close()
semaphoreCircuit.signal()
}

/// Method to force the circuit half open.
Expand Down Expand Up @@ -340,6 +344,7 @@ public class CircuitBreaker<A, B> {

/// Reset timer setup
private func startResetTimer(delay: DispatchTimeInterval) {
timerSemaphore.wait()
// Cancel previous timer if any
resetTimer?.cancel()

Expand All @@ -352,6 +357,7 @@ public class CircuitBreaker<A, B> {
resetTimer?.schedule(deadline: .now() + delay)

resetTimer?.resume()
timerSemaphore.signal()
}
}

Expand Down
Loading