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

Fallback #3151

Open
wants to merge 4 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
Binary file added fallback/etc/fallback.urm.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
173 changes: 173 additions & 0 deletions fallback/etc/fallback.urm.puml
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
@startuml
package fallback {
class App {
- TIMEOUT : int {static}
- MAX_ATTEMPTS : int {static}
- RETRY_DELAY : int {static}
- DEFAULT_API_URL : String {static}
- circuitBreaker : CircuitBreaker
- executor : ExecutorService
- fallbackService : Service
- primaryService : Service
- state : ExecutionState
- LOGGER : Logger {static}
+ App()
+ App(primaryService : Service, fallbackService : Service, circuitBreaker : CircuitBreaker)
+ executeWithFallback() : String
- getFallbackData() : String
- updateFallbackCache(result : String)
+ shutdown()
+ main(args : String[]) {static}
}

interface Service {
+ getData() : String
}

interface CircuitBreaker {
+ isOpen() : boolean
+ allowRequest() : boolean
+ recordFailure()
+ recordSuccess()
+ reset()
+ getState() : CircuitState
}

class DefaultCircuitBreaker {
- RESET_TIMEOUT : long {static}
- MIN_HALF_OPEN_DURATION : Duration {static}
- state : State
- failureThreshold : int
- lastFailureTime : long
- failureTimestamps : Queue<Long>
- windowSize : Duration
- halfOpenStartTime : Instant
+ DefaultCircuitBreaker(failureThreshold : int)
+ isOpen() : boolean
+ allowRequest() : boolean
+ recordFailure()
+ recordSuccess()
+ reset()
+ getState() : CircuitState
- transitionToHalfOpen()
- enum State { CLOSED, OPEN, HALF_OPEN }
}

class FallbackService {
- {static} MAX_RETRIES : int = 3
- {static} RETRY_DELAY_MS : long = 1000
- {static} TIMEOUT : int = 2
- {static} MIN_SUCCESS_RATE : double = 0.6
- {static} MAX_REQUESTS_PER_MINUTE : int = 60
- {static} LOGGER : Logger
- primaryService : Service
- fallbackService : Service
- circuitBreaker : CircuitBreaker
- executor : ExecutorService
- healthChecker : ScheduledExecutorService
- monitor : ServiceMonitor
- rateLimiter : RateLimiter
- state : ServiceState
+ FallbackService(primaryService : Service, fallbackService : Service, circuitBreaker : CircuitBreaker)
+ getData() : String
- executeWithTimeout(task : Callable<String>) : String
- executeFallback() : String
- updateFallbackCache(result : String)
- startHealthChecker()
+ close()
+ getMonitor() : ServiceMonitor
+ getState() : ServiceState
- enum ServiceState { STARTING, RUNNING, DEGRADED, CLOSED }
}

class LocalCacheService {
- cache : Cache<String, String>
- refreshExecutor : ScheduledExecutorService
- {static} CACHE_EXPIRY_MS : long = 300000
- {static} CACHE_REFRESH_INTERVAL : Duration = Duration.ofMinutes(5)
- {static} LOGGER : Logger
+ LocalCacheService()
+ getData() : String
+ updateCache(key : String, value : String)
+ close() : void
- initializeDefaultCache()
- scheduleMaintenanceTasks()
- cleanupExpiredEntries()
- enum FallbackLevel { PRIMARY, SECONDARY, TERTIARY }
- class Cache<K, V> {
- map : ConcurrentHashMap<K, CacheEntry<V>>
- expiryMs : long
+ Cache(expiryMs : long)
+ get(key : K) : V
+ put(key : K, value : V)
+ cleanup()
- record CacheEntry<V>(value : V, expiryTime : long) { + isExpired() : boolean }
}


class RemoteService {
- apiUrl : String
- httpClient : HttpClient
- {static} TIMEOUT_SECONDS : int = 2
+ RemoteService(apiUrl : String, httpClient : HttpClient)
+ getData() : String
}

class ServiceMonitor {
- successCount : AtomicInteger
- fallbackCount : AtomicInteger
- errorCount : AtomicInteger
- lastSuccessTime : AtomicReference<Instant>
- lastFailureTime : AtomicReference<Instant>
- lastResponseTime : AtomicReference<Duration>
- metrics : Queue<ServiceMetric>
- fallbackWeight : double
- metricWindow : Duration
+ ServiceMonitor()
+ ServiceMonitor(fallbackWeight : double, metricWindow : Duration)
+ recordSuccess(responseTime : Duration)
+ recordFallback()
+ recordError()
+ getSuccessCount() : int
+ getFallbackCount() : int
+ getErrorCount() : int
+ getLastSuccessTime() : Instant
+ getLastFailureTime() : Instant
+ getLastResponseTime() : Duration
+ getSuccessRate() : double
+ reset()
- pruneOldMetrics()
- record ServiceMetric(timestamp : Instant, type : MetricType, responseTime : Duration)
- enum MetricType { SUCCESS, FALLBACK, ERROR }
}

class RateLimiter {
- maxRequests : int
- window : Duration
- requestTimestamps : Queue<Long>
+ RateLimiter(maxRequests : int, window : Duration)
+ tryAcquire() : boolean
}

class ServiceException {
+ ServiceException(message : String)
+ ServiceException(message : String, cause : Throwable)
}
}
' Relationships
App --> CircuitBreaker
App --> Service : primaryService
App --> Service : fallbackService
DefaultCircuitBreaker ..|> CircuitBreaker
LocalCacheService ..|> Service
RemoteService ..|> Service
FallbackService ..|> Service
FallbackService ..|> AutoCloseable
FallbackService --> Service : primaryService
FallbackService --> Service : fallbackService
FallbackService --> CircuitBreaker
FallbackService --> ServiceMonitor
FallbackService --> RateLimiter
ServiceException --|> Exception
}
@enduml
72 changes: 72 additions & 0 deletions fallback/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
<?xml version="1.0" encoding="UTF-8"?>
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not related to this file, but I noticed that README.md is missing. It has a very specific format described here: https://github.com/iluwatar/java-design-patterns/wiki/01.-How-to-contribute You can also check the other patterns for examples.

<!--

This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).

The MIT License
Copyright © 2014-2022 Ilkka Seppälä

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.iluwatar</groupId>
<artifactId>java-design-patterns</artifactId>
<version>1.26.0-SNAPSHOT</version>
</parent>

<artifactId>fallback</artifactId>

<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
Comment on lines +40 to +44
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not needed, comes from parent pom.xml

<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.8.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.8.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.8.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>4.5.1</version>
<scope>test</scope>
</dependency>

</dependencies>
</project>
Loading