diff --git a/build.gradle.kts b/build.gradle.kts index ee37c04729..4242853426 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -112,6 +112,7 @@ val allModules = mapOf( Pair("here-naksha-lib-auth", Pair(CleanAndTest.KOTLIN, PublishModule.YES)), Pair("here-naksha-lib-base", Pair(CleanAndTest.KOTLIN, PublishModule.YES)), Pair("here-naksha-lib-core", Pair(CleanAndTest.OFF, PublishModule.YES)), + Pair("here-naksha-lib-circuit-breaker", Pair(CleanAndTest.KOTLIN, PublishModule.YES)), Pair("here-naksha-lib-diff", Pair(CleanAndTest.KOTLIN, PublishModule.YES)), Pair("here-naksha-lib-ext-manager", Pair(CleanAndTest.KOTLIN, PublishModule.YES)), Pair("here-naksha-lib-geo", Pair(CleanAndTest.KOTLIN, PublishModule.YES)), diff --git a/buildSrc/src/main/kotlin/Descriptions.kt b/buildSrc/src/main/kotlin/Descriptions.kt index 9ef74ab046..355d2ed0a0 100644 --- a/buildSrc/src/main/kotlin/Descriptions.kt +++ b/buildSrc/src/main/kotlin/Descriptions.kt @@ -13,6 +13,7 @@ private val Descriptions = mapOf( //"here-naksha-lib-auth-naksha" to "TBD", "here-naksha-lib-base" to "Naksha library, providing basic cross-platform capabilities (extending the raw Kotlin features).", "here-naksha-lib-core" to "Naksha library, core parts of Naksha-Hub.", + "here-naksha-lib-circuit-breaker" to "Naksha Circuit Breaker Library", "here-naksha-lib-diff" to "Naksha library, provide tools to calculate differences, patched, and to apply them.", "here-naksha-lib-ext-manager" to "Naksha library, the Extension-Manager library to be included in applications to load extensions.", //"here-naksha-lib-extension" to "TBD", diff --git a/docs/HTTP_STORAGE_CIRCUIT_BREAKER.md b/docs/HTTP_STORAGE_CIRCUIT_BREAKER.md new file mode 100644 index 0000000000..a30de41a52 --- /dev/null +++ b/docs/HTTP_STORAGE_CIRCUIT_BREAKER.md @@ -0,0 +1,73 @@ +# HTTP Storage Circuit Breaker + +This document describes how circuit breaker works for [`com.here.naksha.storage.http.HttpStorage`](../here-naksha-storage-http/src/jvmMain/java/com/here/naksha/storage/http/HttpStorage.java). + +## Where it is applied + +The CircuitBreaker is applied whenever Naksha wants to forward a request to HttpStorage. + +**Key Points:** +- The CB config is read from the individual HTTP Storage definition. +- At runtime, the CB logic is executed against individual `storageId`. +- Different Storage definitions can imply different CB behavior based on their respective configurations. +- Whenever a Storage definition changes (via storage `updatedAt` value), the internal CB cache for that `storageId` is invalidated and a new CB is created with the updated configuration. +- This ensures that configuration changes are immediately reflected in the CB behavior without requiring an application restart. + +## Why it exists + +The goal is to isolate slow or failing requests by `storageId`. +If one storage starts timing out or responding slowly, only that storage's traffic should be throttled. +Requests for other storages should not be affected. + + +## HTTP Storage Configuration + +For detailed configuration properties and their validation rules, refer to: +- [HttpStorageProperties](../here-naksha-storage-http/src/jvmMain/java/com/here/naksha/storage/http/HttpStorageProperties.java) - HTTP storage-specific settings (URL, timeouts, headers, etc.) +- [CircuitBreakerProps](../here-naksha-lib-circuit-breaker/src/jvmMain/java/com/here/naksha/lib/circuitbreaker/models/CircuitBreakerProps.java) - Circuit breaker configuration + +### Example Storage JSON + +```json +{ + "id": "my_storage", + "type": "Storage", + "className": "com.here.naksha.storage.http.HttpStorage", + "properties": { + "url": "https://example.com/api", + "connectTimeout": 10, + "socketTimeout": 30, + "httpInterface": "ffwAdapter", + "maxRetries": 3, + "headers": { + "Authorization": "Bearer token123" + }, + "circuitBreakerConfig": { + "slidingWindowSize": 20, + "minimumNumberOfCalls": 10, + "slowCallDurationThresholdMs": 29000, + "slowCallRateThreshold": 50, + "waitDurationInOpenStateMs": 120000, + "permittedNumberOfCallsInHalfOpenState": 4 + } + } +} +``` + +**Note:** The `circuitBreakerConfig` configuration is optional. If omitted, HTTP requests are sent without circuit breaking. + + +## CircuitBreaker Behavior + +- **CLOSED**: This is default state during start of application where requests flow normally. +- **OPEN**: Requests are rejected immediately when circuit is in OPEN state. Circuit moves to or remains in OPEN state whenever the slow call rate exceeds `slowCallRateThreshold` (after minimum `minimumNumberOfCalls` have been observed). +- **HALF_OPEN**: Circuit transitions from OPEN to HALF_OPEN after waiting `waitDurationInOpenStateMs`. Limited number of probe calls (`permittedNumberOfCallsInHalfOpenState`) are allowed. It moves back to OPEN state if slow call rate exceeds `slowCallRateThreshold`. It moves to CLOSED state if slow call rate drops below `slowCallRateThreshold`. +- If probe calls are fast enough, the breaker closes. +- If probe calls are still slow, the breaker opens again. + +## Notes + +- The breaker is configured per `storageId`. +- Storage updates are detected through `updatedAt`. +- The storage JSON validation happens when storages are created or updated through the storage API. + diff --git a/gradle.properties b/gradle.properties index a170bad96e..6d4c7f99df 100644 --- a/gradle.properties +++ b/gradle.properties @@ -15,6 +15,9 @@ jvm.here_naksha_lib_hub=23 jvm.here_naksha_lib_ext_manager=23 jvm.here_naksha_handler_activitylog=23 +jvm.here_naksha_lib_circuit_breaker=17 +jvm.here_naksha_storage_http=17 +jvm.here_naksha_lib_handlers=17 # In Linux: ~/.gradle/gradle.properties # If publishing to maven central, use: https://mvnrepository.com/artifact/io.github.naksha-oss/ mavenUrl=some_maven_repo_publish_url diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index f88b6c2f49..fa582c7d9f 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -18,6 +18,7 @@ gson = "2.14.0" # https://github.com/google/gson jsonio = "4.108.0" # https://github.com/jdereg/json-io fastjson = "2.0.57" # https://github.com/alibaba/fastjson simdjson = "0.4.0" # https://github.com/simdjson/simdjson-java +resilience4j = "2.4.0" [libraries] jetbrains_annotations = { module = "org.jetbrains:annotations", version = "26.1.0" } @@ -106,7 +107,6 @@ test_containers_postgres = { module = "org.testcontainers:postgresql", versio flipkart_zjsonpatch = "com.flipkart.zjsonpatch:zjsonpatch:0.4.16" json_assert = "org.skyscreamer:jsonassert:1.5.3" -resillience4j_retry = "io.github.resilience4j:resilience4j-retry:2.3.0" otel = "io.opentelemetry:opentelemetry-api:1.51.0" cytodynamics = "com.linkedin.cytodynamics:cytodynamics-nucleus:0.2.0" kotlinx_datetime = "org.jetbrains.kotlinx:kotlinx-datetime:0.7.0" @@ -120,6 +120,7 @@ gson = { module = "com.google.code.gson:gson", version.re jsonio = { module = "com.cedarsoftware:json-io", version.ref = "jsonio" } fastjson = { module = "com.alibaba:fastjson", version.ref="fastjson" } simdjson = { module = "org.simdjson:simdjson-java", version.ref = "simdjson" } +resilience4j_circuitbreaker = { module = "io.github.resilience4j:resilience4j-circuitbreaker", version.ref = "resilience4j" } [plugins] kotlin_multiplatform = { id = "org.jetbrains.kotlin.multiplatform", version.ref = "kotlin" } diff --git a/here-naksha-app-service/build.gradle.kts b/here-naksha-app-service/build.gradle.kts index abfaaba608..57b11ee0b4 100644 --- a/here-naksha-app-service/build.gradle.kts +++ b/here-naksha-app-service/build.gradle.kts @@ -40,7 +40,7 @@ kotlin { jvmTest { dependencies { implementation(libs.bundles.testing) - implementation(libs.resillience4j.retry) + implementation(libs.resilience4j.circuitbreaker) implementation(libs.test.containers) runtimeOnly(libs.junit.platform.launcher) // https://github.com/gradle/gradle/issues/34512 } diff --git a/here-naksha-app-service/src/jvmTest/java/com/here/naksha/app/service/CircuitBreakerHttpStorageApiTest.java b/here-naksha-app-service/src/jvmTest/java/com/here/naksha/app/service/CircuitBreakerHttpStorageApiTest.java new file mode 100644 index 0000000000..8fd7ed49db --- /dev/null +++ b/here-naksha-app-service/src/jvmTest/java/com/here/naksha/app/service/CircuitBreakerHttpStorageApiTest.java @@ -0,0 +1,310 @@ +/* + * Copyright (C) 2017-2024 HERE Europe B.V. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * License-Filename: LICENSE + */ +package com.here.naksha.app.service; + +import static com.github.tomakehurst.wiremock.client.WireMock.get; +import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor; +import static com.github.tomakehurst.wiremock.client.WireMock.okJson; +import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; +import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; +import static com.github.tomakehurst.wiremock.client.WireMock.verify; +import static com.here.naksha.app.common.TestUtil.loadFileOrFail; +import static com.here.naksha.app.common.assertions.ResponseAssertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; + +import com.github.tomakehurst.wiremock.junit5.WireMockTest; +import com.github.tomakehurst.wiremock.matching.UrlPattern; +import com.here.naksha.app.common.ApiTest; +import java.net.http.HttpResponse; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; + +import org.junit.jupiter.api.Test; + +@WireMockTest(httpPort = CircuitBreakerHttpStorageApiTest.MOCK_PORT) +class CircuitBreakerHttpStorageApiTest extends ApiTest { + public static final int MOCK_PORT = 9094; + private static final String ENDPOINT = "/my_env/my_storage/my_feat_type/features"; + private static final String TEST_DIR_PATH = "CircuitBreaker/"; + private static final String SETUP_DIR_PATH = TEST_DIR_PATH + "setup/"; + private static final String FEATURE_RESPONSE_FIXTURE = SETUP_DIR_PATH + "feature_response.json"; + + @Test + void tc1000_testWorksWithoutCircuitBreakerConfigInStorage() throws Exception { + // Test API: GET /hub/spaces/{spaceId}/features/{featureId} + // Validate requests pass through when circuit breaker config is not present on storage. + // Given: Space setup with HTTP storage that has no circuit breaker configuration + SetupIds ids = createStorageHandlerSpace("cb_no_config", loadFileOrFail(TEST_DIR_PATH + "TC1000_noCircuitBreaker/no_cb_storage_properties.json")); + String streamId = UUID.randomUUID().toString(); + + // Given: downstream storage returns feature response + UrlPattern endpointPath = urlPathEqualTo(ENDPOINT + "/1"); + stubFor(get(endpointPath).willReturn(okJson(loadFileOrFail(FEATURE_RESPONSE_FIXTURE)))); + + // When: feature read request is submitted to NakshaHub + HttpResponse response = getNakshaClient().get("hub/spaces/" + ids.spaceId + "/features/1", streamId); + + // Then: request succeeds and is forwarded to storage + assertThat(response).hasStatus(200).hasStreamIdHeader(streamId); + verify(1, getRequestedFor(endpointPath)); + } + + @Test + void tc1100_testThrowsValidationErrorForPartialCircuitBreakerConfig() throws Exception { + // Test API: POST /hub/storages + // Validate storage creation fails when circuit breaker config is partially defined. + HttpResponse response = createStorage( + "cb_partial_config", loadFileOrFail(TEST_DIR_PATH + "TC1100_partialCircuitBreakerConfig/partial_cb_storage_properties.json")); + assertThat(response).hasStatus(400); + assertTrue(response.body().contains("IllegalArgument")); + } + + @Test + void tc1200_testThrowsValidationErrorWhenSlowDurationIsGreaterThanOrEqualSocketTimeout() throws Exception { + // Test API: POST /hub/storages + // Validate slowCallDurationThresholdMs must be lower than socketTimeout. + HttpResponse response = createStorage( + "cb_invalid_slow_duration", loadFileOrFail(TEST_DIR_PATH + "TC1200_invalidSlowDuration/invalid_slow_duration_storage_properties.json")); + assertTrue(response.body().contains("slowCallDurationThresholdMs must be lower than socketTimeout")); + } + + @Test + void tc1300_testThrowsValidationErrorWhenMinimumCallsExceedSlidingWindow() throws Exception { + // Test API: POST /hub/storages + // Validate minimumNumberOfCalls cannot exceed slidingWindowSize. + HttpResponse response = createStorage( + "cb_invalid_minimum_calls", loadFileOrFail(TEST_DIR_PATH + "TC1300_invalidMinimumCalls/invalid_minimum_calls_storage_properties.json")); + assertTrue(response.body().contains("minimumNumberOfCalls must be <= slidingWindowSize")); + } + + @Test + void tc1400_testThrowsValidationErrorWhenSlowCallRateThresholdIsGreaterThan100() throws Exception { + // Test API: POST /hub/storages + // Validate slowCallRateThreshold must stay within 1..100. + HttpResponse response = createStorage( + "cb_invalid_slow_rate_threshold", loadFileOrFail(TEST_DIR_PATH + "TC1400_invalidSlowRateThreshold/invalid_slow_rate_threshold_storage_properties.json")); + assertTrue(response.body().contains("slowCallRateThreshold must be in range 1..100")); + } + + @Test + void tc2000_testTransitionsClosedToOpenToHalfOpenToClosed() throws Exception { + // Test API: GET /hub/spaces/{spaceId}/features/{featureId} + // Validate circuit breaker transitions CLOSED -> OPEN -> HALF_OPEN -> CLOSED using timings. + // CbConfig: "slidingWindowSize": 10, "minimumNumberOfCalls": 5, "slowCallDurationThresholdMs": 500, "slowCallRateThreshold": 50, "waitDurationInOpenStateMs": 5000, "permittedNumberOfCallsInHalfOpenState": 4 + SetupIds ids = createStorageHandlerSpace( + "cb_transition_to_closed", loadFileOrFail(TEST_DIR_PATH + "TC2000_validCircuitBreaker/with_valid_cb_storage_properties.json")); + UrlPattern endpointPath = urlPathEqualTo(ENDPOINT + "/1"); + + // Given: storage responses are slow enough to count toward slow-call threshold. + stubFor(get(endpointPath).willReturn(okJson(loadFileOrFail(FEATURE_RESPONSE_FIXTURE)).withFixedDelay(600))); + + // When: 6 requests are issued sequentially, the first 5 succeed and the sixth is blocked. + for (int i = 0; i < 5; i++) { + assertThat(callFeatureById(ids.spaceId)).hasStatus(200); + } + HttpResponse openResponse = callFeatureById(ids.spaceId); + + // Then: the breaker opens and further requests are rejected immediately. + assertTrue(containsCallNotPermitted(openResponse)); + for (int i = 0; i < 20; i++) { + assertTrue(containsCallNotPermitted(callFeatureById(ids.spaceId))); + } + verify(5, getRequestedFor(endpointPath)); + + // Given: OPEN wait duration elapsed and probes are now fast. + Thread.sleep(5100); + // Add 250ms response delay to ensure all concurrent requests arrive in parallel + // This is high enough for synchronization but lower than slowCallDurationThresholdMs (500ms) + stubFor(get(endpointPath).willReturn(okJson(loadFileOrFail(FEATURE_RESPONSE_FIXTURE)).withFixedDelay(250))); + + // When: 6 concurrent probes are sent in HALF_OPEN, only 4 are permitted. + List> halfOpenResponses = callFeatureConcurrently(ids.spaceId, 6); + assertEquals(4, countSuccessfulResponses(halfOpenResponses)); + assertEquals(2, countCallNotPermittedResponses(halfOpenResponses)); + + // Then: after successful probes, the breaker closes and the next calls pass through. + verify(9, getRequestedFor(endpointPath)); + for (int i = 0; i < 10; i++) { + assertThat(callFeatureById(ids.spaceId)).hasStatus(200); + } + } + + @Test + void tc2100_testTransitionsClosedToOpenToHalfOpenToOpen() throws Exception { + // Test API: GET /hub/spaces/{spaceId}/features/{featureId} + // Validate circuit breaker transitions CLOSED -> OPEN -> HALF_OPEN -> OPEN using timings. + // CbConfig: "slidingWindowSize": 8, "minimumNumberOfCalls": 4, "slowCallDurationThresholdMs": 400, "slowCallRateThreshold": 50, "waitDurationInOpenStateMs": 4000, "permittedNumberOfCallsInHalfOpenState": 3 + SetupIds ids = createStorageHandlerSpace( + "cb_transition_to_open", + loadFileOrFail(TEST_DIR_PATH + "TC2100_validCircuitBreaker/with_valid_cb_storage_properties.json")); + UrlPattern endpointPath = urlPathEqualTo(ENDPOINT + "/1"); + + // Given: downstream responses are slow enough to trip the breaker. + stubFor(get(endpointPath).willReturn(okJson(loadFileOrFail(FEATURE_RESPONSE_FIXTURE)).withFixedDelay(500))); + + // When: 6 requests are issued sequentially, the first 4 succeed and the next 2 are blocked. + for (int i = 0; i < 4; i++) { + assertThat(callFeatureById(ids.spaceId)).hasStatus(200); + } + HttpResponse openResponse = callFeatureById(ids.spaceId); + HttpResponse openResponse2 = callFeatureById(ids.spaceId); + + // Then: the breaker is OPEN and blocks the remaining requests immediately. + assertTrue(containsCallNotPermitted(openResponse)); + assertTrue(containsCallNotPermitted(openResponse2)); + for (int i = 0; i < 10; i++) { + assertTrue(containsCallNotPermitted(callFeatureById(ids.spaceId))); + } + verify(4, getRequestedFor(endpointPath)); + + // Given: OPEN wait duration elapsed and HALF_OPEN probes are still slow. + Thread.sleep(4200); + List> halfOpenResponses = callFeatureConcurrently(ids.spaceId, 5); + + // Then: only 3 probes are permitted and the breaker opens again after slow responses. + assertEquals(3, countSuccessfulResponses(halfOpenResponses)); + assertEquals(2, countCallNotPermittedResponses(halfOpenResponses)); + for (int i = 0; i < 5; i++) { + assertTrue(containsCallNotPermitted(callFeatureById(ids.spaceId))); + } + verify(7, getRequestedFor(endpointPath)); + } + + @Test + void tc2200_testFast5xxResponsesDoNotOpenCircuitBreaker() throws Exception { + // Test API: GET /hub/spaces/{spaceId}/features/{featureId} + // Validate fast 5xx responses do not trip the circuit breaker counters. + SetupIds ids = createStorageHandlerSpace( + "cb_fast_5xx", + loadFileOrFail(TEST_DIR_PATH + "TC2000_validCircuitBreaker/with_valid_cb_storage_properties.json")); + UrlPattern endpointPath = urlPathEqualTo(ENDPOINT + "/1"); + + // Given: storage responds quickly with 5xx errors. + stubFor(get(endpointPath).willReturn(com.github.tomakehurst.wiremock.client.WireMock.serverError())); + + // When: multiple fast 5xx responses are returned. + for (int i = 0; i < 10; i++) { + HttpResponse response = callFeatureById(ids.spaceId); + assertThat(response).hasStatus(500); + assertFalse(containsCallNotPermitted(response)); + } + verify(10, getRequestedFor(endpointPath)); + + // Given: downstream recovers. + stubFor(get(endpointPath).willReturn(okJson(loadFileOrFail(FEATURE_RESPONSE_FIXTURE)))); + + // Then: the breaker is still closed and traffic continues to flow. + assertThat(callFeatureById(ids.spaceId)).hasStatus(200); + verify(11, getRequestedFor(endpointPath)); + } + + private HttpResponse callFeatureById(String spaceId) throws Exception { + return getNakshaClient().get("hub/spaces/" + spaceId + "/features/1", UUID.randomUUID().toString()); + } + + private List> callFeatureConcurrently(String spaceId, int requestCount) throws Exception { + ExecutorService executor = Executors.newFixedThreadPool(requestCount); + CountDownLatch ready = new CountDownLatch(requestCount); + CountDownLatch start = new CountDownLatch(1); + try { + List>> futures = new ArrayList<>(); + for (int i = 0; i < requestCount; i++) { + futures.add(executor.submit(() -> { + ready.countDown(); + start.await(5, TimeUnit.SECONDS); + return callFeatureById(spaceId); + })); + } + assertTrue(ready.await(5, TimeUnit.SECONDS)); + start.countDown(); + List> responses = new ArrayList<>(requestCount); + for (Future> future : futures) { + responses.add(future.get(10, TimeUnit.SECONDS)); + } + return responses; + } finally { + executor.shutdownNow(); + } + } + + private int countSuccessfulResponses(List> responses) { + int count = 0; + for (HttpResponse response : responses) { + if (response.statusCode() == 200) { + count++; + } + } + return count; + } + + private int countCallNotPermittedResponses(List> responses) { + int count = 0; + for (HttpResponse response : responses) { + if (containsCallNotPermitted(response)) { + count++; + } + } + return count; + } + + private boolean containsCallNotPermitted(HttpResponse response) { + if (response.statusCode() != 500) { + return false; + } + final String body = response.body(); + return body.contains("Service temporarily unavailable"); + } + + private SetupIds createStorageHandlerSpace(String prefix, String storagePropertiesJson) throws Exception { + String storageId = prefix + "_storage"; + String handlerId = prefix + "_handler"; + String spaceId = prefix + "_space"; + assertThat(createStorage(prefix, storagePropertiesJson)).hasStatus(200); + String handlerJson = applyTokens(loadFileOrFail(SETUP_DIR_PATH + "create_event_handler_template.json"), "{{handlerId}}", handlerId, "{{storageId}}", storageId); + String spaceJson = applyTokens(loadFileOrFail(SETUP_DIR_PATH + "create_space_template.json"), "{{spaceId}}", spaceId, "{{handlerId}}", handlerId); + + assertThat(getNakshaClient().post("hub/handlers", handlerJson, UUID.randomUUID().toString())).hasStatus(200); + assertThat(getNakshaClient().post("hub/spaces", spaceJson, UUID.randomUUID().toString())).hasStatus(200); + return new SetupIds(storageId, handlerId, spaceId); + } + + private HttpResponse createStorage(String prefix, String storagePropertiesJson) throws Exception { + String storageId = prefix + "_storage"; + String storageJson = applyTokens(loadFileOrFail(SETUP_DIR_PATH + "create_storage_template.json"), "{{storageId}}", storageId, "{{storageProperties}}", storagePropertiesJson); + return getNakshaClient().post("hub/storages", storageJson, UUID.randomUUID().toString()); + } + + private String applyTokens(String template, String... keyValuePairs) { + String result = template; + for (int i = 0; i < keyValuePairs.length; i += 2) { + result = result.replace(keyValuePairs[i], keyValuePairs[i + 1]); + } + return result; + } + + private record SetupIds(String storageId, String handlerId, String spaceId) {} +} diff --git a/here-naksha-app-service/src/jvmTest/resources/unit_test_data/CircuitBreaker/TC1000_noCircuitBreaker/no_cb_storage_properties.json b/here-naksha-app-service/src/jvmTest/resources/unit_test_data/CircuitBreaker/TC1000_noCircuitBreaker/no_cb_storage_properties.json new file mode 100644 index 0000000000..e20d1253a0 --- /dev/null +++ b/here-naksha-app-service/src/jvmTest/resources/unit_test_data/CircuitBreaker/TC1000_noCircuitBreaker/no_cb_storage_properties.json @@ -0,0 +1,9 @@ +{ + "connectTimeout": 1, + "socketTimeout": 2, + "url": "http://localhost:9094", + "headers": { + "Authorization": "Bearer ", + "Content-Type": "application/json" + } +} diff --git a/here-naksha-app-service/src/jvmTest/resources/unit_test_data/CircuitBreaker/TC1100_partialCircuitBreakerConfig/partial_cb_storage_properties.json b/here-naksha-app-service/src/jvmTest/resources/unit_test_data/CircuitBreaker/TC1100_partialCircuitBreakerConfig/partial_cb_storage_properties.json new file mode 100644 index 0000000000..597e847259 --- /dev/null +++ b/here-naksha-app-service/src/jvmTest/resources/unit_test_data/CircuitBreaker/TC1100_partialCircuitBreakerConfig/partial_cb_storage_properties.json @@ -0,0 +1,12 @@ +{ + "connectTimeout": 1, + "socketTimeout": 2, + "url": "http://localhost:9094", + "headers": { + "Authorization": "Bearer ", + "Content-Type": "application/json" + }, + "circuitBreakerConfig": { + "slidingWindowSize": 2 + } +} diff --git a/here-naksha-app-service/src/jvmTest/resources/unit_test_data/CircuitBreaker/TC1200_invalidSlowDuration/invalid_slow_duration_storage_properties.json b/here-naksha-app-service/src/jvmTest/resources/unit_test_data/CircuitBreaker/TC1200_invalidSlowDuration/invalid_slow_duration_storage_properties.json new file mode 100644 index 0000000000..02ed57ee5d --- /dev/null +++ b/here-naksha-app-service/src/jvmTest/resources/unit_test_data/CircuitBreaker/TC1200_invalidSlowDuration/invalid_slow_duration_storage_properties.json @@ -0,0 +1,17 @@ +{ + "connectTimeout": 1, + "socketTimeout": 2, + "url": "http://localhost:9094", + "headers": { + "Authorization": "Bearer ", + "Content-Type": "application/json" + }, + "circuitBreakerConfig": { + "slidingWindowSize": 2, + "minimumNumberOfCalls": 2, + "slowCallDurationThresholdMs": 2000, + "slowCallRateThreshold": 50, + "waitDurationInOpenStateMs": 300, + "permittedNumberOfCallsInHalfOpenState": 1 + } +} diff --git a/here-naksha-app-service/src/jvmTest/resources/unit_test_data/CircuitBreaker/TC1300_invalidMinimumCalls/invalid_minimum_calls_storage_properties.json b/here-naksha-app-service/src/jvmTest/resources/unit_test_data/CircuitBreaker/TC1300_invalidMinimumCalls/invalid_minimum_calls_storage_properties.json new file mode 100644 index 0000000000..9c8f19b7c6 --- /dev/null +++ b/here-naksha-app-service/src/jvmTest/resources/unit_test_data/CircuitBreaker/TC1300_invalidMinimumCalls/invalid_minimum_calls_storage_properties.json @@ -0,0 +1,17 @@ +{ + "connectTimeout": 1, + "socketTimeout": 2, + "url": "http://localhost:9094", + "headers": { + "Authorization": "Bearer ", + "Content-Type": "application/json" + }, + "circuitBreakerConfig": { + "slidingWindowSize": 2, + "minimumNumberOfCalls": 3, + "slowCallDurationThresholdMs": 250, + "slowCallRateThreshold": 50, + "waitDurationInOpenStateMs": 300, + "permittedNumberOfCallsInHalfOpenState": 1 + } +} diff --git a/here-naksha-app-service/src/jvmTest/resources/unit_test_data/CircuitBreaker/TC1400_invalidSlowRateThreshold/invalid_slow_rate_threshold_storage_properties.json b/here-naksha-app-service/src/jvmTest/resources/unit_test_data/CircuitBreaker/TC1400_invalidSlowRateThreshold/invalid_slow_rate_threshold_storage_properties.json new file mode 100644 index 0000000000..36977fb93e --- /dev/null +++ b/here-naksha-app-service/src/jvmTest/resources/unit_test_data/CircuitBreaker/TC1400_invalidSlowRateThreshold/invalid_slow_rate_threshold_storage_properties.json @@ -0,0 +1,17 @@ +{ + "connectTimeout": 1, + "socketTimeout": 2, + "url": "http://localhost:9094", + "headers": { + "Authorization": "Bearer ", + "Content-Type": "application/json" + }, + "circuitBreakerConfig": { + "slidingWindowSize": 2, + "minimumNumberOfCalls": 2, + "slowCallDurationThresholdMs": 250, + "slowCallRateThreshold": 101, + "waitDurationInOpenStateMs": 300, + "permittedNumberOfCallsInHalfOpenState": 1 + } +} diff --git a/here-naksha-app-service/src/jvmTest/resources/unit_test_data/CircuitBreaker/TC2000_validCircuitBreaker/with_valid_cb_storage_properties.json b/here-naksha-app-service/src/jvmTest/resources/unit_test_data/CircuitBreaker/TC2000_validCircuitBreaker/with_valid_cb_storage_properties.json new file mode 100644 index 0000000000..05c9f285d7 --- /dev/null +++ b/here-naksha-app-service/src/jvmTest/resources/unit_test_data/CircuitBreaker/TC2000_validCircuitBreaker/with_valid_cb_storage_properties.json @@ -0,0 +1,17 @@ +{ + "connectTimeout": 1, + "socketTimeout": 2, + "url": "http://localhost:9094", + "headers": { + "Authorization": "Bearer ", + "Content-Type": "application/json" + }, + "circuitBreakerConfig": { + "slidingWindowSize": 10, + "minimumNumberOfCalls": 5, + "slowCallDurationThresholdMs": 500, + "slowCallRateThreshold": 50, + "waitDurationInOpenStateMs": 5000, + "permittedNumberOfCallsInHalfOpenState": 4 + } +} diff --git a/here-naksha-app-service/src/jvmTest/resources/unit_test_data/CircuitBreaker/TC2100_validCircuitBreaker/with_valid_cb_storage_properties.json b/here-naksha-app-service/src/jvmTest/resources/unit_test_data/CircuitBreaker/TC2100_validCircuitBreaker/with_valid_cb_storage_properties.json new file mode 100644 index 0000000000..883c81747b --- /dev/null +++ b/here-naksha-app-service/src/jvmTest/resources/unit_test_data/CircuitBreaker/TC2100_validCircuitBreaker/with_valid_cb_storage_properties.json @@ -0,0 +1,17 @@ +{ + "connectTimeout": 1, + "socketTimeout": 2, + "url": "http://localhost:9094", + "headers": { + "Authorization": "Bearer ", + "Content-Type": "application/json" + }, + "circuitBreakerConfig": { + "slidingWindowSize": 8, + "minimumNumberOfCalls": 4, + "slowCallDurationThresholdMs": 400, + "slowCallRateThreshold": 50, + "waitDurationInOpenStateMs": 4000, + "permittedNumberOfCallsInHalfOpenState": 3 + } +} diff --git a/here-naksha-app-service/src/jvmTest/resources/unit_test_data/CircuitBreaker/setup/create_event_handler_template.json b/here-naksha-app-service/src/jvmTest/resources/unit_test_data/CircuitBreaker/setup/create_event_handler_template.json new file mode 100644 index 0000000000..8920cf195a --- /dev/null +++ b/here-naksha-app-service/src/jvmTest/resources/unit_test_data/CircuitBreaker/setup/create_event_handler_template.json @@ -0,0 +1,12 @@ +{ + "id": "{{handlerId}}", + "type": "EventHandler", + "title": "Circuit breaker test handler", + "description": "Storage handler for circuit breaker API tests", + "className": "com.here.naksha.lib.handlers.DefaultStorageHandler", + "active": true, + "extensionId": null, + "properties": { + "storageId": "{{storageId}}" + } +} diff --git a/here-naksha-app-service/src/jvmTest/resources/unit_test_data/CircuitBreaker/setup/create_space_template.json b/here-naksha-app-service/src/jvmTest/resources/unit_test_data/CircuitBreaker/setup/create_space_template.json new file mode 100644 index 0000000000..ac3f69ad0d --- /dev/null +++ b/here-naksha-app-service/src/jvmTest/resources/unit_test_data/CircuitBreaker/setup/create_space_template.json @@ -0,0 +1,15 @@ +{ + "id": "{{spaceId}}", + "type": "Space", + "title": "Circuit breaker test space", + "description": "Space for circuit breaker API tests", + "eventHandlerIds": [ + "{{handlerId}}" + ], + "properties": { + "collection": { + "id": "my_env/my_storage/my_feat_type", + "type": "NakshaCollection" + } + } +} diff --git a/here-naksha-app-service/src/jvmTest/resources/unit_test_data/CircuitBreaker/setup/create_storage_template.json b/here-naksha-app-service/src/jvmTest/resources/unit_test_data/CircuitBreaker/setup/create_storage_template.json new file mode 100644 index 0000000000..3f86e30274 --- /dev/null +++ b/here-naksha-app-service/src/jvmTest/resources/unit_test_data/CircuitBreaker/setup/create_storage_template.json @@ -0,0 +1,8 @@ +{ + "id": "{{storageId}}", + "type": "Storage", + "title": "Circuit breaker test storage", + "description": "Http storage for circuit breaker API tests", + "className": "com.here.naksha.storage.http.HttpStorage", + "properties": {{storageProperties}} +} diff --git a/here-naksha-app-service/src/jvmTest/resources/unit_test_data/CircuitBreaker/setup/feature_response.json b/here-naksha-app-service/src/jvmTest/resources/unit_test_data/CircuitBreaker/setup/feature_response.json new file mode 100644 index 0000000000..2792a05182 --- /dev/null +++ b/here-naksha-app-service/src/jvmTest/resources/unit_test_data/CircuitBreaker/setup/feature_response.json @@ -0,0 +1,12 @@ +{ + "type": "Feature", + "id": "1", + "geometry": { + "type": "Point", + "coordinates": [ + 8.67, + 50.11 + ] + }, + "properties": {} +} diff --git a/here-naksha-lib-circuit-breaker/LICENSE b/here-naksha-lib-circuit-breaker/LICENSE new file mode 100644 index 0000000000..d645695673 --- /dev/null +++ b/here-naksha-lib-circuit-breaker/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/here-naksha-lib-circuit-breaker/build.gradle.kts b/here-naksha-lib-circuit-breaker/build.gradle.kts new file mode 100644 index 0000000000..2acdd521a3 --- /dev/null +++ b/here-naksha-lib-circuit-breaker/build.gradle.kts @@ -0,0 +1,33 @@ +plugins { + alias(libs.plugins.kotlin.multiplatform) +} + +description = gatherDescription() + +kotlin { + jvm { } + sourceSets { + jvmMain { + dependencies { + api(project(":here-naksha-lib-model")) + api(libs.resilience4j.circuitbreaker) + implementation(libs.slf4j.api) + implementation(libs.jetbrains.annotations) + } + } + jvmTest { + dependencies { + implementation(kotlin("test-junit5")) + implementation(libs.bundles.testing) + runtimeOnly(libs.junit.platform.launcher) + } + } + } +} + +tasks { + getByName("jvmJar") { dependsOn("jvmProcessResources") } + getByName("jvmTestProcessResources") { dependsOn("jvmProcessResources") } + getByName("jvmTest") { useJUnitPlatform() } +} +setOverallCoverage(0.0) diff --git a/here-naksha-lib-circuit-breaker/src/jvmMain/java/com/here/naksha/lib/circuitbreaker/CircuitBreakerOpenException.java b/here-naksha-lib-circuit-breaker/src/jvmMain/java/com/here/naksha/lib/circuitbreaker/CircuitBreakerOpenException.java new file mode 100644 index 0000000000..4add50b887 --- /dev/null +++ b/here-naksha-lib-circuit-breaker/src/jvmMain/java/com/here/naksha/lib/circuitbreaker/CircuitBreakerOpenException.java @@ -0,0 +1,54 @@ +/* + * Copyright (C) 2017-2024 HERE Europe B.V. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * License-Filename: LICENSE + */ +package com.here.naksha.lib.circuitbreaker; + +/** + * Exception thrown when a CircuitBreaker is OPEN or HALF_OPEN (exceeding permitted number of operations). + * + *

This exception indicates that a request was rejected by the circuit breaker because: + *

    + *
  • OPEN state: The underlying service is considered unhealthy, so the breaker is + * rejecting all requests to protect it. + *
  • HALF_OPEN state: The breaker is probing for recovery, but the maximum number of + * concurrent probe requests has been reached. + *
+ * + *

Clients should retry the request after some delay, or use alternative services. + */ +public class CircuitBreakerOpenException extends Exception { + + /** + * Constructs a new CircuitBreakerOpenException with the specified detail message. + * + * @param message the detail message + */ + public CircuitBreakerOpenException(String message) { + super(message); + } + + /** + * Constructs a new CircuitBreakerOpenException with the specified detail message and cause. + * + * @param message the detail message + * @param cause the cause (which is saved for later retrieval) + */ + public CircuitBreakerOpenException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/here-naksha-lib-circuit-breaker/src/jvmMain/java/com/here/naksha/lib/circuitbreaker/CircuitBreakerProvider.java b/here-naksha-lib-circuit-breaker/src/jvmMain/java/com/here/naksha/lib/circuitbreaker/CircuitBreakerProvider.java new file mode 100644 index 0000000000..7ea55cdf58 --- /dev/null +++ b/here-naksha-lib-circuit-breaker/src/jvmMain/java/com/here/naksha/lib/circuitbreaker/CircuitBreakerProvider.java @@ -0,0 +1,58 @@ +/* + * Copyright (C) 2017-2024 HERE Europe B.V. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * License-Filename: LICENSE + */ +package com.here.naksha.lib.circuitbreaker; + +import org.jetbrains.annotations.NotNull; + +/** + * Factory for obtaining circuit breaker implementations. Provides singleton instances based on + * selected implementation type. + */ +public class CircuitBreakerProvider { + + private CircuitBreakerProvider() { + // Prevent instantiation + } + + /** + * Get the default circuit breaker instance (Resilience4j). + * + * @return singleton instance of ICircuitBreaker + */ + @NotNull + public static ICircuitBreaker getInstance() { + return getInstance(ECircuitBreakerImpl.RESILIENCE4J); + } + + /** + * Get a circuit breaker instance for the specified implementation. + * + * @param cbImpl the desired implementation + * @return singleton instance of ICircuitBreaker + */ + @NotNull + public static ICircuitBreaker getInstance(@NotNull ECircuitBreakerImpl cbImpl) { + switch (cbImpl) { + case RESILIENCE4J: + return Resilience4jCircuitBreaker.getInstance(); + default: + throw new IllegalArgumentException("Unknown circuit breaker implementation: " + cbImpl); + } + } +} diff --git a/here-naksha-lib-circuit-breaker/src/jvmMain/java/com/here/naksha/lib/circuitbreaker/ECircuitBreakerImpl.java b/here-naksha-lib-circuit-breaker/src/jvmMain/java/com/here/naksha/lib/circuitbreaker/ECircuitBreakerImpl.java new file mode 100644 index 0000000000..128f9829be --- /dev/null +++ b/here-naksha-lib-circuit-breaker/src/jvmMain/java/com/here/naksha/lib/circuitbreaker/ECircuitBreakerImpl.java @@ -0,0 +1,26 @@ +/* + * Copyright (C) 2017-2024 HERE Europe B.V. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * License-Filename: LICENSE + */ +package com.here.naksha.lib.circuitbreaker; + +/** + * Enumeration of available circuit breaker implementations. + */ +public enum ECircuitBreakerImpl { + RESILIENCE4J; +} diff --git a/here-naksha-lib-circuit-breaker/src/jvmMain/java/com/here/naksha/lib/circuitbreaker/ICircuitBreaker.java b/here-naksha-lib-circuit-breaker/src/jvmMain/java/com/here/naksha/lib/circuitbreaker/ICircuitBreaker.java new file mode 100644 index 0000000000..6c3127e05a --- /dev/null +++ b/here-naksha-lib-circuit-breaker/src/jvmMain/java/com/here/naksha/lib/circuitbreaker/ICircuitBreaker.java @@ -0,0 +1,103 @@ +/* + * Copyright (C) 2017-2024 HERE Europe B.V. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * License-Filename: LICENSE + */ +package com.here.naksha.lib.circuitbreaker; + +import com.here.naksha.lib.circuitbreaker.models.CircuitBreakerProps; +import java.util.concurrent.Callable; +import org.jetbrains.annotations.NotNull; + +/** + * Circuit breaker interface. Manages per-resourceId circuit breaker instances with thread-safe + * operations. + */ +public interface ICircuitBreaker { + + /** + * Execute a callable operation with circuit breaker protection scoped to resourceId. + * + *

Operation callback conditions based on CircuitBreaker state associated with a resourceId: + *

    + *
  • when in CLOSED state: Operation invoked immediately as normal + *
  • when in HALF_OPEN state: Only N Operations invoked, where "N" is `permittedNumberOfCallsInHalfOpenState` configuration, else CircuitBreakerOpenException thrown + *
  • when in OPEN state: Operation NOT invoked, instead CircuitBreakerOpenException thrown immediately + *
+ * + *

CircuitBreakerOpenException thrown when in OPEN/HALF_OPEN (outside permitted limits) state: Throws {@code CircuitBreakerOpenException}. + * + * @param resourceId Unique resource identifier (e.g. some storageId, Http endpoint) against which the CircuitBreaker protection is to be applied. + * @param operation The callable operation to be executed under CircuitBreaker protection + * @param Return type of the operation + * @return Result of the operation if executed successfully + * @throws CircuitBreakerOpenException If circuit breaker is OPEN or HALF_OPEN (exceeding permitted limits) + * @throws Exception If operation fails or other errors occur + */ + T execute(@NotNull String resourceId, @NotNull Callable operation) throws Exception; + + /** + * Get or create the circuit breaker for the given resourceId. It is implementation's responsibility to provide thread-safety for this function. + * + *

Important Note on Configuration Changes: + * This function does NOT compare or detect changes in the CircuitBreaker configuration between invocations. + * It is the caller's responsibility to detect configuration changes and handle them by: + *

    + *
  1. Calling {@link #remove(String)} to invalidate the existing circuit breaker instance + *
  2. Then invoking this method with the new configuration to ensure the circuit breaker is (re)created with updated settings + *
+ * If the configuration changes but {@code remove()} is not called first, the old circuit breaker instance + * (with its previous state and configuration) will continue to be used. + * + * @param resourceId Unique resource identifier (e.g. some storageId, Http endpoint) against which the CircuitBreaker protection is to be applied. + * @param config Circuit Breaker configuration to be applied for all future operations against the given resourceId + * @return the CircuitBreaker provider implementation + */ + @NotNull + ICircuitBreaker getOrCreateCircuitBreaker(@NotNull String resourceId, @NotNull CircuitBreakerProps config); + + /** + * Remove circuit breaker for the given resourceId. + * + * @param resourceId Unique identifier for circuit breaker instance to remove + */ + void remove(@NotNull String resourceId); + + /** + * Clear all circuit breakers. + */ + void clear(); + + /** + * Check if the circuit breaker for the given resourceId is in CLOSED state. + * + *

This is a READ-ONLY operation: Only reads state, does not modify anything. + * + * @param resourceId Unique identifier for circuit breaker instance + * @return true if circuit breaker is in CLOSED state, false otherwise (OPEN, HALF_OPEN, or not found) + */ + boolean isClosed(@NotNull String resourceId); + + /** + * Check if a circuit breaker exists for the given resourceId. + * + *

This is a READ-ONLY operation: Only checks existence, does not modify anything. + * + * @param resourceId Unique identifier for circuit breaker instance + * @return true if circuit breaker exists for this resourceId, false otherwise + */ + boolean exists(@NotNull String resourceId); +} diff --git a/here-naksha-lib-circuit-breaker/src/jvmMain/java/com/here/naksha/lib/circuitbreaker/Resilience4jCircuitBreaker.java b/here-naksha-lib-circuit-breaker/src/jvmMain/java/com/here/naksha/lib/circuitbreaker/Resilience4jCircuitBreaker.java new file mode 100644 index 0000000000..2a5250bf8c --- /dev/null +++ b/here-naksha-lib-circuit-breaker/src/jvmMain/java/com/here/naksha/lib/circuitbreaker/Resilience4jCircuitBreaker.java @@ -0,0 +1,134 @@ +/* + * Copyright (C) 2017-2024 HERE Europe B.V. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * License-Filename: LICENSE + */ +package com.here.naksha.lib.circuitbreaker; + +import com.here.naksha.lib.circuitbreaker.models.CircuitBreakerProps; +import io.github.resilience4j.circuitbreaker.CallNotPermittedException; +import io.github.resilience4j.circuitbreaker.CircuitBreaker; +import io.github.resilience4j.circuitbreaker.CircuitBreakerConfig; +import io.github.resilience4j.circuitbreaker.CircuitBreakerConfig.SlidingWindowType; +import io.github.resilience4j.circuitbreaker.CircuitBreakerRegistry; +import java.util.concurrent.Callable; +import org.jetbrains.annotations.NotNull; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Resilience4j-based implementation of {@link ICircuitBreaker}. Manages per-resourceId circuit + * breaker instances with slow-call-based state transitions. + * + *

Singleton pattern enforced through {@link #getInstance()} factory method. Direct instantiation + * is prevented via private constructor to ensure only one instance exists application-wide. + */ +class Resilience4jCircuitBreaker implements ICircuitBreaker { + + private static final Logger log = LoggerFactory.getLogger(Resilience4jCircuitBreaker.class); + private static Resilience4jCircuitBreaker instance = null; + + private final CircuitBreakerRegistry registry; + + private Resilience4jCircuitBreaker() { + this.registry = CircuitBreakerRegistry.ofDefaults(); + } + + /** + * Get the singleton instance of Resilience4jCircuitBreaker. + * + * @return singleton instance + */ + @NotNull + static Resilience4jCircuitBreaker getInstance() { + if (instance == null) { + synchronized (Resilience4jCircuitBreaker.class) { + if (instance == null) { + instance = new Resilience4jCircuitBreaker(); + } + } + } + return instance; + } + + @Override + public T execute(@NotNull String resourceId, @NotNull Callable operation) throws Exception { + CircuitBreaker cb = registry.find(resourceId).orElse(null); + if (cb == null) { + log.warn( + "CircuitBreaker not found for resourceId: {}. Executing operation without CircuitBreaker protection.", + resourceId); + return operation.call(); + } + try { + return cb.executeCallable(operation); + } catch (CallNotPermittedException e) { + // Wrap Resilience4j exception with abstraction + throw new CircuitBreakerOpenException( + "Circuit breaker '" + resourceId + "' is " + cb.getState() + " and does not permit further calls", + e); + } + } + + @Override + public @NotNull ICircuitBreaker getOrCreateCircuitBreaker( + @NotNull String resourceId, @NotNull CircuitBreakerProps config) { + if (!exists(resourceId)) { + log.info("Creating CircuitBreaker for resourceId: {} with config: {}", resourceId, config); + registry.circuitBreaker(resourceId, buildCircuitBreakerConfig(config)); + } + return this; + } + + @Override + public void remove(@NotNull String resourceId) { + log.info("Removing CircuitBreaker for resourceId: {}", resourceId); + registry.remove(resourceId); + } + + @Override + public void clear() { + int count = registry.getAllCircuitBreakers().size(); + log.info("Clearing entire CircuitBreaker registry ({} entries)", count); + registry.getAllCircuitBreakers().forEach(cb -> registry.remove(cb.getName())); + } + + @Override + public boolean isClosed(@NotNull String resourceId) { + return registry.find(resourceId) + .map(cb -> cb.getState() == CircuitBreaker.State.CLOSED) + .orElse(false); + } + + @Override + public boolean exists(@NotNull String resourceId) { + return registry.find(resourceId).isPresent(); + } + + private @NotNull CircuitBreakerConfig buildCircuitBreakerConfig(@NotNull CircuitBreakerProps config) { + return CircuitBreakerConfig.custom() + .slidingWindowType(SlidingWindowType.COUNT_BASED) + .slidingWindowSize(config.getSlidingWindowSize()) + .minimumNumberOfCalls(config.getMinimumNumberOfCalls()) + .slowCallDurationThreshold(java.time.Duration.ofMillis(config.getSlowCallDurationThresholdMs())) + .slowCallRateThreshold(config.getSlowCallRateThreshold()) + .waitDurationInOpenState(java.time.Duration.ofMillis(config.getWaitDurationInOpenStateMs())) + .permittedNumberOfCallsInHalfOpenState(config.getPermittedNumberOfCallsInHalfOpenState()) + .ignoreExceptions(Throwable.class) + .automaticTransitionFromOpenToHalfOpenEnabled(true) + .build(); + } +} diff --git a/here-naksha-lib-circuit-breaker/src/jvmMain/java/com/here/naksha/lib/circuitbreaker/models/CircuitBreakerProps.java b/here-naksha-lib-circuit-breaker/src/jvmMain/java/com/here/naksha/lib/circuitbreaker/models/CircuitBreakerProps.java new file mode 100644 index 0000000000..3b67b54a36 --- /dev/null +++ b/here-naksha-lib-circuit-breaker/src/jvmMain/java/com/here/naksha/lib/circuitbreaker/models/CircuitBreakerProps.java @@ -0,0 +1,197 @@ +/* + * Copyright (C) 2017-2024 HERE Europe B.V. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * License-Filename: LICENSE + */ +package com.here.naksha.lib.circuitbreaker.models; + +import naksha.base.JvmAnyObjectUtil; +import naksha.model.objects.NakshaProperties; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +/** + * Configuration properties for the sliding-window circuit breaker pattern. Controls how the + * circuit breaker monitors and manages the state transitions based on slow request rates. + */ +public class CircuitBreakerProps extends NakshaProperties { + + public static final String SLIDING_WINDOW_SIZE = "slidingWindowSize"; + public static final String MINIMUM_NUMBER_OF_CALLS = "minimumNumberOfCalls"; + public static final String SLOW_CALL_DURATION_THRESHOLD_MS = "slowCallDurationThresholdMs"; + public static final String SLOW_CALL_RATE_THRESHOLD = "slowCallRateThreshold"; + public static final String WAIT_DURATION_IN_OPEN_STATE_MS = "waitDurationInOpenStateMs"; + public static final String PERMITTED_NUMBER_OF_CALLS_IN_HALF_OPEN_STATE = "permittedNumberOfCallsInHalfOpenState"; + + public CircuitBreakerProps() {} + + /** + * The total number of most recent requests that should be measured to make a decision on + * opening/closing the circuit breaker. + * + *

Example: A slidingWindowSize of 20 means the circuit breaker evaluates the last 20 + * requests. + * + *

Unit: Number of requests (count-based sliding window) + */ + public Integer getSlidingWindowSize() { + final Integer value = JvmAnyObjectUtil.getProperty(this, SLIDING_WINDOW_SIZE, Integer.class); + return value != null ? value : parseIntOrNull(getRaw(SLIDING_WINDOW_SIZE)); + } + + public void setSlidingWindowSize(final @Nullable Integer slidingWindowSize) { + setRaw(SLIDING_WINDOW_SIZE, slidingWindowSize); + } + + /** + * The minimum number of requests that must be observed before the circuit breaker checks + * against slow-call threshold values. + * + *

When starting from zero, the circuit breaker will not make any state transition decisions + * until at least this many requests have been observed. + * + *

Example: A minimumNumberOfCalls of 10 means the circuit breaker needs at least 10 + * requests before evaluating if it should open. + * + *

Unit: Number of requests (count) + */ + public Integer getMinimumNumberOfCalls() { + final Integer value = JvmAnyObjectUtil.getProperty(this, MINIMUM_NUMBER_OF_CALLS, Integer.class); + return value != null ? value : parseIntOrNull(getRaw(MINIMUM_NUMBER_OF_CALLS)); + } + + public void setMinimumNumberOfCalls(final @Nullable Integer minimumNumberOfCalls) { + setRaw(MINIMUM_NUMBER_OF_CALLS, minimumNumberOfCalls); + } + + /** + * The duration threshold above which a request is considered "slow". + * + *

Any request that takes longer than this threshold will be counted as a slow call. The + * circuit breaker uses the percentage of slow calls against the slow call rate threshold to + * determine state transitions. + * + *

Example: A slowCallDurationThresholdMs of 10000 means any request taking more than 10 + * seconds is considered slow. + * + *

Unit: Milliseconds (ms) + */ + public Long getSlowCallDurationThresholdMs() { + final Long value = JvmAnyObjectUtil.getProperty(this, SLOW_CALL_DURATION_THRESHOLD_MS, Long.class); + return value != null ? value : parseLongOrNull(getRaw(SLOW_CALL_DURATION_THRESHOLD_MS)); + } + + public void setSlowCallDurationThresholdMs(final @Nullable Long slowCallDurationThresholdMs) { + setRaw(SLOW_CALL_DURATION_THRESHOLD_MS, slowCallDurationThresholdMs); + } + + /** + * The percentage threshold of slow calls that triggers the circuit breaker to open. + * + *

When the percentage of slow calls (out of the sliding window) exceeds this threshold, the + * circuit breaker transitions to OPEN state and starts rejecting requests. If the slow rate + * remains above this threshold during HALF_OPEN state, the circuit breaker reopens. + * + *

Example: A slowCallRateThreshold of 50 means if 50% or more of the requests in the + * sliding window are slow, the circuit breaker opens. + * + *

Unit: Percentage (1-100) + */ + public Integer getSlowCallRateThreshold() { + final Integer value = JvmAnyObjectUtil.getProperty(this, SLOW_CALL_RATE_THRESHOLD, Integer.class); + return value != null ? value : parseIntOrNull(getRaw(SLOW_CALL_RATE_THRESHOLD)); + } + + public void setSlowCallRateThreshold(final @Nullable Integer slowCallRateThreshold) { + setRaw(SLOW_CALL_RATE_THRESHOLD, slowCallRateThreshold); + } + + /** + * The duration the circuit breaker waits in OPEN state before transitioning to HALF_OPEN. + * + *

During the OPEN state, the circuit breaker rejects all requests. After this wait duration + * expires, it automatically transitions to HALF_OPEN to probe if the underlying service has + * recovered. + * + *

Example: A waitDurationInOpenStateMs of 60000 means the circuit breaker will wait 60 + * seconds in OPEN state before attempting to probe recovery via HALF_OPEN. + * + *

Unit: Milliseconds (ms) + */ + public Long getWaitDurationInOpenStateMs() { + final Long value = JvmAnyObjectUtil.getProperty(this, WAIT_DURATION_IN_OPEN_STATE_MS, Long.class); + return value != null ? value : parseLongOrNull(getRaw(WAIT_DURATION_IN_OPEN_STATE_MS)); + } + + public void setWaitDurationInOpenStateMs(final @Nullable Long waitDurationInOpenStateMs) { + setRaw(WAIT_DURATION_IN_OPEN_STATE_MS, waitDurationInOpenStateMs); + } + + /** + * The maximum number of requests allowed when the circuit breaker is in HALF_OPEN + * state. + * + *

During HALF_OPEN, the circuit breaker allows a small number of test requests through to + * determine if the underlying service has recovered. If these test requests result in a slow + * rate below the threshold, the circuit closes. Otherwise, it reopens. + * + *

Example: A permittedNumberOfCallsInHalfOpenState of 5 means only 5 requests are allowed + * during the HALF_OPEN probe phase. + * + *

Unit: Number of requests (count) + */ + public Integer getPermittedNumberOfCallsInHalfOpenState() { + final Integer value = JvmAnyObjectUtil.getProperty(this, PERMITTED_NUMBER_OF_CALLS_IN_HALF_OPEN_STATE, Integer.class); + return value != null ? value : parseIntOrNull(getRaw(PERMITTED_NUMBER_OF_CALLS_IN_HALF_OPEN_STATE)); + } + + public void setPermittedNumberOfCallsInHalfOpenState(final @Nullable Integer permittedNumberOfCallsInHalfOpenState) { + setRaw(PERMITTED_NUMBER_OF_CALLS_IN_HALF_OPEN_STATE, permittedNumberOfCallsInHalfOpenState); + } + + private static @Nullable Integer parseIntOrNull(final @Nullable Object raw) { + if (!(raw instanceof String)) { + return null; + } + try { + return Integer.parseInt(((String) raw).trim()); + } catch (NumberFormatException e) { + return null; + } + } + + private static @Nullable Long parseLongOrNull(final @Nullable Object raw) { + if (!(raw instanceof String)) { + return null; + } + try { + return Long.parseLong(((String) raw).trim()); + } catch (NumberFormatException e) { + return null; + } + } + + @Override + public @NotNull String toString() { + return "CircuitBreakerProps{" + "slidingWindowSize=" + + getSlidingWindowSize() + ", minimumNumberOfCalls=" + + getMinimumNumberOfCalls() + ", slowCallDurationThresholdMs=" + + getSlowCallDurationThresholdMs() + ", slowCallRateThreshold=" + + getSlowCallRateThreshold() + "%" + ", waitDurationInOpenStateMs=" + + getWaitDurationInOpenStateMs() + ", permittedNumberOfCallsInHalfOpenState=" + + getPermittedNumberOfCallsInHalfOpenState() + '}'; + } +} diff --git a/here-naksha-lib-handlers/build.gradle.kts b/here-naksha-lib-handlers/build.gradle.kts index d35fe1f580..c8d301e35a 100644 --- a/here-naksha-lib-handlers/build.gradle.kts +++ b/here-naksha-lib-handlers/build.gradle.kts @@ -13,6 +13,7 @@ kotlin { api(project(":here-naksha-lib-model")) api(project(":here-naksha-lib-view")) api(project(":here-naksha-storage-http")) + implementation(project(":here-naksha-lib-circuit-breaker")) implementation(libs.commons.lang3) implementation(libs.commons.dbutils) diff --git a/here-naksha-lib-handlers/src/jvmMain/java/com/here/naksha/lib/handlers/internal/HttpStorageValidation.java b/here-naksha-lib-handlers/src/jvmMain/java/com/here/naksha/lib/handlers/internal/HttpStorageValidation.java index f49051add6..37262f9a57 100644 --- a/here-naksha-lib-handlers/src/jvmMain/java/com/here/naksha/lib/handlers/internal/HttpStorageValidation.java +++ b/here-naksha-lib-handlers/src/jvmMain/java/com/here/naksha/lib/handlers/internal/HttpStorageValidation.java @@ -1,6 +1,7 @@ package com.here.naksha.lib.handlers.internal; import com.here.naksha.storage.http.HttpStorageProperties; +import com.here.naksha.lib.circuitbreaker.models.CircuitBreakerProps; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; @@ -45,6 +46,12 @@ private static Response httpStoragePropertiesValidation(HttpStorageProperties ht boolean isSocketTimeoutValid = isBetween( httpStorageProperties.getSocketTimeout(), MIN_HTTP_SOCKET_TIMEOUT_SEC, MAX_HTTP_SOCKET_TIMEOUT_SEC); boolean isUrlValid = isUrlValid(httpStorageProperties.getUrl()); + + Response cbValidationResult = validateCircuitBreakerConfig(httpStorageProperties); + if (cbValidationResult instanceof ErrorResponse) { + return cbValidationResult; + } + if (isConnectionTimeoutValid && isSocketTimeoutValid && isUrlValid) { return new SuccessResponse(); } @@ -53,6 +60,54 @@ private static Response httpStoragePropertiesValidation(HttpStorageProperties ht return new ErrorResponse(NakshaError.ILLEGAL_ARGUMENT, errorMsg); } + private static Response validateCircuitBreakerConfig(HttpStorageProperties httpStorageProperties) { + try { + final CircuitBreakerProps cbConfig = httpStorageProperties.getCircuitBreakerConfig(); + if (cbConfig == null) { + return new SuccessResponse(); + } + if (cbConfig.getSlidingWindowSize() == null + || cbConfig.getMinimumNumberOfCalls() == null + || cbConfig.getSlowCallDurationThresholdMs() == null + || cbConfig.getSlowCallRateThreshold() == null + || cbConfig.getWaitDurationInOpenStateMs() == null + || cbConfig.getPermittedNumberOfCallsInHalfOpenState() == null) { + throw new IllegalArgumentException("circuitBreakerConfig is missing required properties"); + } + if (cbConfig.getSlidingWindowSize() <= 0) { + throw new IllegalArgumentException("circuitBreakerConfig.slidingWindowSize must be > 0"); + } + if (cbConfig.getMinimumNumberOfCalls() <= 0) { + throw new IllegalArgumentException("circuitBreakerConfig.minimumNumberOfCalls must be > 0"); + } + if (cbConfig.getMinimumNumberOfCalls() > cbConfig.getSlidingWindowSize()) { + throw new IllegalArgumentException("circuitBreakerConfig.minimumNumberOfCalls must be <= slidingWindowSize"); + } + if (cbConfig.getSlowCallDurationThresholdMs() <= 0) { + throw new IllegalArgumentException("circuitBreakerConfig.slowCallDurationThresholdMs must be > 0"); + } + if (cbConfig.getSlowCallRateThreshold() <= 0 || cbConfig.getSlowCallRateThreshold() > 100) { + throw new IllegalArgumentException("circuitBreakerConfig.slowCallRateThreshold must be in range 1..100"); + } + if (cbConfig.getWaitDurationInOpenStateMs() <= 0) { + throw new IllegalArgumentException("circuitBreakerConfig.waitDurationInOpenStateMs must be > 0"); + } + if (cbConfig.getPermittedNumberOfCallsInHalfOpenState() <= 0) { + throw new IllegalArgumentException("circuitBreakerConfig.permittedNumberOfCallsInHalfOpenState must be > 0"); + } + + long socketTimeoutMs = httpStorageProperties.getSocketTimeout() * 1000L; + if (cbConfig.getSlowCallDurationThresholdMs() >= socketTimeoutMs) { + throw new IllegalArgumentException( + "circuitBreakerConfig.slowCallDurationThresholdMs must be lower than socketTimeout in milliseconds"); + } + + return new SuccessResponse(); + } catch (IllegalArgumentException e) { + return new ErrorResponse(NakshaError.ILLEGAL_ARGUMENT, e.getMessage()); + } + } + @NotNull private static String getErrorMsg( HttpStorageProperties httpStorageProperties, diff --git a/here-naksha-lib-mm-util/build.gradle.kts b/here-naksha-lib-mm-util/build.gradle.kts index 157e17d032..b29f7227cc 100644 --- a/here-naksha-lib-mm-util/build.gradle.kts +++ b/here-naksha-lib-mm-util/build.gradle.kts @@ -10,7 +10,6 @@ kotlin { jvmMain { dependencies { api(project(":here-naksha-lib-model")) - api(project(":here-naksha-lib-handlers")) } } jvmTest { diff --git a/here-naksha-storage-http/build.gradle.kts b/here-naksha-storage-http/build.gradle.kts index 920a5aaab6..638edd6ee4 100644 --- a/here-naksha-storage-http/build.gradle.kts +++ b/here-naksha-storage-http/build.gradle.kts @@ -12,6 +12,7 @@ kotlin { api(project(":here-naksha-lib-jbon")) api(project(":here-naksha-lib-core")) api(project(":here-naksha-common-http")) + implementation(project(":here-naksha-lib-circuit-breaker")) implementation(libs.commons.lang3) implementation(libs.bundles.jackson) diff --git a/here-naksha-storage-http/src/jvmMain/java/com/here/naksha/storage/http/HttpStorage.java b/here-naksha-storage-http/src/jvmMain/java/com/here/naksha/storage/http/HttpStorage.java index 7fcef3ef1c..06600fc759 100644 --- a/here-naksha-storage-http/src/jvmMain/java/com/here/naksha/storage/http/HttpStorage.java +++ b/here-naksha-storage-http/src/jvmMain/java/com/here/naksha/storage/http/HttpStorage.java @@ -19,7 +19,10 @@ package com.here.naksha.storage.http; import com.here.naksha.storage.http.RequestSender.KeyProperties; +import com.here.naksha.storage.http.cache.CircuitBreakerCache; import com.here.naksha.storage.http.cache.RequestSenderCache; +import com.here.naksha.lib.circuitbreaker.CircuitBreakerProvider; +import com.here.naksha.lib.circuitbreaker.ICircuitBreaker; import kotlin.reflect.KClass; import naksha.base.Action; import naksha.base.JvmBoxingUtil; @@ -42,6 +45,7 @@ public class HttpStorage extends AbstractStorage { private NakshaStorage storageConfig; private HttpStorageProperties httpStorageProperties; + private @Nullable ICircuitBreaker circuitBreaker = null; public HttpStorage() { @@ -63,6 +67,11 @@ protected void initStorage(@NotNull NakshaStorage config, @Nullable Boolean crea throw new IllegalArgumentException("A HTTP storage must have properties containing a 'url'"); } this.defaultKeyProperties = KeyProperties.fromHttpStorageProperties(config.getId(), httpStorageProperties); + if (httpStorageProperties.getCircuitBreakerConfig() != null) { + circuitBreaker = CircuitBreakerProvider.getInstance(); + CircuitBreakerCache.checkOrInvalidateCircuitBreakerCache( + circuitBreaker, config.getId(), defaultKeyProperties.getStorageUpdatedAt()); + } } @NotNull @@ -80,10 +89,12 @@ public IReadSession newReadSession(@Nullable SessionOptions options) { defaultKeyProperties.getDefaultHeaders(), defaultKeyProperties.getConnectionTimeoutSec(), defaultKeyProperties.getSocketTimeoutSec(), - httpStorageProperties.getMaxRetries() + httpStorageProperties.getMaxRetries(), + defaultKeyProperties.getStorageUpdatedAt() )); return new HttpStorageReadSession( - NakshaContext.currentContext(), this, requestSender, httpStorageProperties.getProtocol()); + NakshaContext.currentContext(), this, requestSender, httpStorageProperties.getProtocol(), + circuitBreaker, getId(), httpStorageProperties.getCircuitBreakerConfig()); } @NotNull @@ -101,10 +112,12 @@ public IWriteSession newWriteSession(@Nullable SessionOptions options) { defaultKeyProperties.getDefaultHeaders(), defaultKeyProperties.getConnectionTimeoutSec(), defaultKeyProperties.getSocketTimeoutSec(), - httpStorageProperties.getMaxRetries() + httpStorageProperties.getMaxRetries(), + defaultKeyProperties.getStorageUpdatedAt() )); return new HttpStorageWriteSession( - NakshaContext.currentContext(), this, requestSender, httpStorageProperties.getProtocol()); + NakshaContext.currentContext(), this, requestSender, httpStorageProperties.getProtocol(), + circuitBreaker, getId(), httpStorageProperties.getCircuitBreakerConfig()); } @NotNull diff --git a/here-naksha-storage-http/src/jvmMain/java/com/here/naksha/storage/http/HttpStorageProperties.java b/here-naksha-storage-http/src/jvmMain/java/com/here/naksha/storage/http/HttpStorageProperties.java index a752a52945..1aa4ba6edb 100644 --- a/here-naksha-storage-http/src/jvmMain/java/com/here/naksha/storage/http/HttpStorageProperties.java +++ b/here-naksha-storage-http/src/jvmMain/java/com/here/naksha/storage/http/HttpStorageProperties.java @@ -18,6 +18,8 @@ */ package com.here.naksha.storage.http; +import com.here.naksha.lib.circuitbreaker.models.CircuitBreakerProps; +import naksha.base.JvmBoxingUtil; import naksha.base.JvmMapProxy; import naksha.base.NakshaError; import naksha.base.NakshaException; @@ -31,7 +33,7 @@ import java.util.Map; /** - * A Http storage configuration as used by the {@link HttpStorage}. + * Configuration properties for HTTP storage backends. */ @AvailableSince(NakshaVersion.v2_0_12) public class HttpStorageProperties extends NakshaProperties { @@ -60,12 +62,17 @@ private void putHeaders(@NotNull Map headers) { private static final String HEADERS = "headers"; private static final String HTTP_INTERFACE = "httpInterface"; + private static final String CIRCUIT_BREAKER = "circuitBreakerConfig"; private static final HttpInterface DEFAULT_XYZ_PROTOCOL = HttpInterface.ffwAdapter; public HttpStorageProperties() {} /** - * Points to the instance, not to an endpoint. + * The base URL of the remote HTTP storage backend. + * + *

Required: Yes + * + *

Points to the instance, not to an endpoint. */ public @NotNull String getUrl() { return (String) getRaw(URL); @@ -76,8 +83,12 @@ public void setUrl(final @Nullable String url) { } /** - * The connection timeout in seconds. - * By default: 20 + * Timeout for establishing an HTTP connection to the remote storage, in seconds. + * + *

Required: Yes + *

Unit: Seconds + * + *

By default: 20 */ public @NotNull Integer getConnectTimeout() { return getOrSet(CONNECTION_TIMEOUT, DEF_CONNECTION_TIMEOUT_SEC); @@ -88,8 +99,12 @@ public void setConnectTimeout(final @Nullable Integer connectTimeout) { } /** - * The socket timeout in seconds. - * By default: 90 + * Timeout for waiting on a response from the remote storage, in seconds. + * + *

Required: Yes + *

Unit: Seconds + * + *

By default: 90 */ public @NotNull Integer getSocketTimeout() { return getOrSet(SOCKET_TIMEOUT, DEF_SOCKET_TIMEOUT_SEC); @@ -100,8 +115,13 @@ public void setSocketTimeout(final @Nullable Integer socketTimeout) { } /** - * The max number of retries. - * By default: 1 + * Number of retry attempts for retryable transport failures. + * + *

When a request fails due to a retryable error (e.g., connection reset, timeout), Naksha + * will automatically retry up to this many times before giving up. Non-retryable errors are + * not retried. + * + *

By default: 1 */ public @NotNull Integer getMaxRetries() { return getOrSet(MAX_RETRIES, DEF_MAX_RETRIES); @@ -112,8 +132,12 @@ public void setMaxRetries(final @Nullable Integer maxRetries) { } /** - * The HTTP headers to be sent with each request. - * By default: 'Content-Type: application/json' and 'Accept-Encoding: gzip' + * Default HTTP headers added to every request sent to this storage. + * + *

These headers are merged with request-specific headers. Common use cases include + * Authorization tokens, API keys, or custom identifiers. + * + *

By default: 'Content-Type: application/json' and 'Accept-Encoding: gzip' */ public @NotNull Map getHeaders() { final Object raw = getPath(HEADERS); @@ -141,6 +165,13 @@ public void setHeaders(final @Nullable Map headers) { setRaw(HEADERS, headerMap); } + /** + * HTTP protocol interface mode for communication with the remote storage. + * + *

Determines how Naksha formats requests and parses responses from the storage backend. + * + *

See: HttpInterface enum for available modes + */ public @NotNull HttpInterface getProtocol() { final Object raw = getRaw(HTTP_INTERFACE); if (raw instanceof HttpInterface) { @@ -163,6 +194,36 @@ public void setHeaders(final @Nullable Map headers) { public void setProtocol(final HttpInterface protocol) {setRaw(HTTP_INTERFACE, protocol);} + /** + * Optional circuit breaker configuration for this storage. + * + *

If configured, the circuit breaker monitors requests triggered via this storage. + * When the slow request rate exceeds the configured threshold, the circuit breaker + * opens to throttle traffic. + * + *

This enables per-storage isolation: if one storage times out, only its traffic is + * throttled. Requests to other storages continue unaffected. + * + *

Default: null (no circuit breaking) + * + *

See: CircuitBreakerProps for configuration options + */ + public @Nullable CircuitBreakerProps getCircuitBreakerConfig() { + final Object raw = getRaw(CIRCUIT_BREAKER); + if (raw == null) { + return null; + } + // v2 (Jackson) rejected a non-object circuitBreaker value (e.g. a string or boolean) + if (!(raw instanceof naksha.base.PlatformMap)) { + throw new IllegalArgumentException("circuitBreaker must be an object"); + } + return JvmBoxingUtil.box(raw, CircuitBreakerProps.class); + } + + public void setCircuitBreakerConfig(@Nullable CircuitBreakerProps config) { + setRaw(CIRCUIT_BREAKER, config); + } + private @NotNull HeaderMap toHeaderMap(@NotNull Map rawHeaders) { HeaderMap headers = new HeaderMap(); rawHeaders.forEach((key, value) -> { diff --git a/here-naksha-storage-http/src/jvmMain/java/com/here/naksha/storage/http/HttpStorageReadSession.java b/here-naksha-storage-http/src/jvmMain/java/com/here/naksha/storage/http/HttpStorageReadSession.java index 98fcfa76f5..6bd320649b 100644 --- a/here-naksha-storage-http/src/jvmMain/java/com/here/naksha/storage/http/HttpStorageReadSession.java +++ b/here-naksha-storage-http/src/jvmMain/java/com/here/naksha/storage/http/HttpStorageReadSession.java @@ -19,6 +19,9 @@ package com.here.naksha.storage.http; import com.here.naksha.lib.core.models.storage.ReadFeaturesProxyWrapper; +import com.here.naksha.lib.circuitbreaker.CircuitBreakerOpenException; +import com.here.naksha.lib.circuitbreaker.ICircuitBreaker; +import com.here.naksha.lib.circuitbreaker.models.CircuitBreakerProps; import com.here.naksha.storage.http.connector.ConnectorInterfaceReadExecute; import com.here.naksha.storage.http.ffw.FfwInterfaceReadExecute; import naksha.base.*; @@ -38,6 +41,7 @@ import org.slf4j.LoggerFactory; import java.util.List; +import java.util.concurrent.Callable; import static java.util.Objects.requireNonNull; import static naksha.base.Platform.javaProxy; @@ -59,15 +63,30 @@ public class HttpStorageReadSession implements IReadSession { @NotNull private final HttpInterface httpInterface; + @Nullable + private final ICircuitBreaker circuitBreaker; + + @NotNull + protected final String storageId; + + @Nullable + private final CircuitBreakerProps circuitBreakerConfig; + HttpStorageReadSession( @Nullable NakshaContext context, @NotNull HttpStorage storage, @NotNull RequestSender requestSender, - @NotNull HttpInterface httpInterface) { + @NotNull HttpInterface httpInterface, + @Nullable ICircuitBreaker circuitBreaker, + @NotNull String storageId, + @Nullable CircuitBreakerProps circuitBreakerConfig) { this.context = context == null ? NakshaContext.currentContext() : context; this.storage = storage; this.requestSender = requestSender; this.httpInterface = httpInterface; + this.circuitBreaker = circuitBreaker; + this.circuitBreakerConfig = circuitBreakerConfig; + this.storageId = storageId; } public @NotNull NakshaContext getNakshaContext() { @@ -79,18 +98,14 @@ public class HttpStorageReadSession implements IReadSession { try { final ReadFeaturesProxyWrapper requestWrapper = request instanceof ReadFeaturesProxyWrapper ? (ReadFeaturesProxyWrapper) request : requireNonNull(javaProxy(request, ReadFeaturesProxyWrapper.class)); - final Response response; - switch (httpInterface) { - case ffwAdapter: - response = FfwInterfaceReadExecute.execute(context, requestWrapper, requestSender); - break; - case dataHubConnector: - response = ConnectorInterfaceReadExecute.execute(context, requestWrapper, requestSender); - break; - default: - throw new IllegalStateException("Unsupported HTTP interface: " + httpInterface); - } + final Response response = executeWithOptionalCircuitBreaker(() -> executeReadRequest(requestWrapper)); return attachVirtualTupleNumbers(response, requestWrapper); + } catch (CircuitBreakerOpenException e) { + log.warn( + "Circuit breaker is OPEN or HALF_OPEN (no permits) for storageId: {}. Request rejected.", + storageId, + e); + return new ErrorResponse(NakshaError.EXCEPTION, "Service temporarily unavailable", e); } catch (NakshaException exception) { log.info("Unexpected error while executing read", exception); return new ErrorResponse(exception.getError()); @@ -100,6 +115,22 @@ public class HttpStorageReadSession implements IReadSession { } } + protected @NotNull Response executeWithOptionalCircuitBreaker(@NotNull Callable operation) throws Exception { + if (circuitBreaker != null && circuitBreakerConfig != null) { + return circuitBreaker + .getOrCreateCircuitBreaker(storageId, circuitBreakerConfig) + .execute(storageId, operation); + } + return operation.call(); + } + + private @NotNull Response executeReadRequest(@NotNull ReadFeaturesProxyWrapper readRequest) { + return switch (httpInterface) { + case ffwAdapter -> FfwInterfaceReadExecute.execute(context, readRequest, requestSender); + case dataHubConnector -> ConnectorInterfaceReadExecute.execute(context, readRequest, requestSender); + }; + } + @Override public void close() {} diff --git a/here-naksha-storage-http/src/jvmMain/java/com/here/naksha/storage/http/HttpStorageWriteSession.java b/here-naksha-storage-http/src/jvmMain/java/com/here/naksha/storage/http/HttpStorageWriteSession.java index 147641d08c..8c0353efe4 100644 --- a/here-naksha-storage-http/src/jvmMain/java/com/here/naksha/storage/http/HttpStorageWriteSession.java +++ b/here-naksha-storage-http/src/jvmMain/java/com/here/naksha/storage/http/HttpStorageWriteSession.java @@ -1,5 +1,8 @@ package com.here.naksha.storage.http; +import com.here.naksha.lib.circuitbreaker.CircuitBreakerOpenException; +import com.here.naksha.lib.circuitbreaker.ICircuitBreaker; +import com.here.naksha.lib.circuitbreaker.models.CircuitBreakerProps; import com.here.naksha.storage.http.connector.ConnectorInterfaceWriteExecute; import naksha.model.ILock; import naksha.model.IWriteSession; @@ -23,22 +26,27 @@ public class HttpStorageWriteSession extends HttpStorageReadSession implements I private final HttpInterface httpInterface; public HttpStorageWriteSession( - NakshaContext context, HttpStorage storage, RequestSender requestSender, HttpInterface httpInterface) { - super(context, storage, requestSender, httpInterface); + @Nullable NakshaContext context, + @NotNull HttpStorage storage, + @NotNull RequestSender requestSender, + @NotNull HttpInterface httpInterface, + @Nullable ICircuitBreaker circuitBreaker, + @NotNull String storageId, + @Nullable CircuitBreakerProps circuitBreakerConfig) { + super(context, storage, requestSender, httpInterface, circuitBreaker, storageId, circuitBreakerConfig); this.httpInterface = httpInterface; } @Override public @NotNull Response executeWrite(@NotNull WriteRequest request) { try { - switch (httpInterface) { - case ffwAdapter: - return new ErrorResponse(NakshaError.NOT_IMPLEMENTED, "Writing not supported by underlying storage"); - case dataHubConnector: - return new ConnectorInterfaceWriteExecute(getNakshaContext(), request, getRequestSender()).execute(); - default: - throw new IllegalStateException("Unsupported HTTP interface: " + httpInterface); - } + return executeWithOptionalCircuitBreaker(() -> executeWriteRequest(request)); + } catch (CircuitBreakerOpenException e) { + log.warn( + "Circuit breaker is OPEN or HALF_OPEN (no permits) for storageId: {}. Request rejected.", + storageId, + e); + return new ErrorResponse(NakshaError.EXCEPTION, "Service temporarily unavailable", e); } catch (NakshaException e) { log.info("Unexpected error while executing write", e); return new ErrorResponse(e.getError()); @@ -50,6 +58,15 @@ public HttpStorageWriteSession( } } + private @NotNull Response executeWriteRequest(@NotNull WriteRequest request) { + return switch (httpInterface) { + case ffwAdapter -> + new ErrorResponse(NakshaError.NOT_IMPLEMENTED, "Writing not supported by underlying storage"); + case dataHubConnector -> + new ConnectorInterfaceWriteExecute(getNakshaContext(), request, getRequestSender()).execute(); + }; + } + @Override public @NotNull ILock acquireSessionLock(@NotNull String lockId) { return null; diff --git a/here-naksha-storage-http/src/jvmMain/java/com/here/naksha/storage/http/RequestSender.java b/here-naksha-storage-http/src/jvmMain/java/com/here/naksha/storage/http/RequestSender.java index 7b439dca93..2bac22e21e 100644 --- a/here-naksha-storage-http/src/jvmMain/java/com/here/naksha/storage/http/RequestSender.java +++ b/here-naksha-storage-http/src/jvmMain/java/com/here/naksha/storage/http/RequestSender.java @@ -32,6 +32,8 @@ import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; +import naksha.model.XyzNs; +import naksha.model.objects.NakshaProperties; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -138,8 +140,8 @@ private boolean isRetryEligibleException(@NotNull final Exception e) { return ioe.getMessage() != null && ioe.getMessage().contains("GOAWAY"); } - public boolean hasKeyProps(KeyProperties thatKeyProps) { - return this.keyProps.equals(thatKeyProps); + public boolean hasPropsChanged(KeyProperties thatKeyProps) { + return thatKeyProps.getStorageUpdatedAt() > this.keyProps.getStorageUpdatedAt(); } public static final class KeyProperties { @@ -149,6 +151,7 @@ public static final class KeyProperties { private final int connectionTimeoutSec; private final int socketTimeoutSec; private final int maxRetries; + private final long storageUpdatedAt; public KeyProperties( @NotNull String name, @@ -156,13 +159,15 @@ public KeyProperties( @NotNull Map defaultHeaders, int connectionTimeoutSec, int socketTimeoutSec, - int maxRetries) { + int maxRetries, + long storageUpdatedAt) { this.name = name; this.hostUrl = hostUrl; this.defaultHeaders = defaultHeaders; this.connectionTimeoutSec = connectionTimeoutSec; this.socketTimeoutSec = socketTimeoutSec; this.maxRetries = maxRetries; + this.storageUpdatedAt = storageUpdatedAt; } public static @NotNull KeyProperties fromHttpStorageProperties( @@ -174,10 +179,20 @@ public KeyProperties( properties.getHeaders(), properties.getConnectTimeout(), properties.getSocketTimeout(), - properties.getMaxRetries() + properties.getMaxRetries(), + getStorageUpdatedAt(properties) ); } + /** + * Reads {@code updatedAt} of the storage from the XYZ namespace of the properties (in v2: {@code getXyzNamespace().getUpdatedAt()}), + * without creating the namespace when it is missing. + */ + private static long getStorageUpdatedAt(@NotNull HttpStorageProperties properties) { + final Object updatedAt = properties.getPath(NakshaProperties.XYZ_KEY, XyzNs.UPDATED_AT); + return updatedAt instanceof Number ? ((Number) updatedAt).longValue() : 0L; + } + public @NotNull String getName() { return name; } @@ -202,6 +217,10 @@ public int getMaxRetries() { return maxRetries; } + public long getStorageUpdatedAt() { + return storageUpdatedAt; + } + @Override public boolean equals(Object o) { if (this == o) { @@ -214,6 +233,7 @@ public boolean equals(Object o) { return connectionTimeoutSec == that.connectionTimeoutSec && socketTimeoutSec == that.socketTimeoutSec && maxRetries == that.maxRetries + && storageUpdatedAt == that.storageUpdatedAt && name.equals(that.name) && hostUrl.equals(that.hostUrl) && defaultHeaders.equals(that.defaultHeaders); @@ -221,7 +241,7 @@ public boolean equals(Object o) { @Override public int hashCode() { - return Objects.hash(name, hostUrl, defaultHeaders, connectionTimeoutSec, socketTimeoutSec, maxRetries); + return Objects.hash(name, hostUrl, defaultHeaders, connectionTimeoutSec, socketTimeoutSec, maxRetries, storageUpdatedAt); } @Override @@ -233,6 +253,7 @@ public String toString() { + ", connectionTimeoutSec=" + connectionTimeoutSec + ", socketTimeoutSec=" + socketTimeoutSec + ", maxRetries=" + maxRetries + + ", storageUpdatedAt=" + storageUpdatedAt + ']'; } } diff --git a/here-naksha-storage-http/src/jvmMain/java/com/here/naksha/storage/http/cache/CircuitBreakerCache.java b/here-naksha-storage-http/src/jvmMain/java/com/here/naksha/storage/http/cache/CircuitBreakerCache.java new file mode 100644 index 0000000000..5d1daa99d1 --- /dev/null +++ b/here-naksha-storage-http/src/jvmMain/java/com/here/naksha/storage/http/cache/CircuitBreakerCache.java @@ -0,0 +1,156 @@ +/* + * Copyright (C) 2017-2024 HERE Europe B.V. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * License-Filename: LICENSE + */ +package com.here.naksha.storage.http.cache; + +import com.here.naksha.lib.circuitbreaker.ICircuitBreaker; +import com.here.naksha.lib.circuitbreaker.models.CircuitBreakerProps; +import java.util.ArrayList; +import java.util.List; +import java.util.Random; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.TestOnly; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Cache for circuit breaker lastUpdatedAt timestamps scoped to storageId. + * Tracks when each storageId's configuration was last updated to detect config changes. + * + *

Size-based Eviction: When cache exceeds {@link #MAX_SIZE} entries: + *

    + *
  • All circuit breakers in CLOSED state are removed from registry + *
  • If still full, arbitrary entries are evicted (with warnings) + *
+ */ +public class CircuitBreakerCache { + + private static final Logger logger = LoggerFactory.getLogger(CircuitBreakerCache.class); + private static final int MAX_SIZE = 1000; + private static final Random random = new Random(); + + private static final ConcurrentMap<@NotNull String, @NotNull Long> circuitBreakerMap = new ConcurrentHashMap<>(); + + /** + * Register or invalidate circuit breaker entry for a storageId in {@link #circuitBreakerMap}. + * If configuration changed (detected by lastUpdatedAt), removes old CB. + * Check or invalidate the cached timestamp for a storageId, recreating its circuit breaker if needed. + * + * Compares provided timestamp against cached value. If no cache entry exists or timestamp is newer, + * updates cache and removes any stale CB from provider (harmless no-op for new storageIds). + * Caller must call {@link ICircuitBreaker#getOrCreateCircuitBreaker(String, CircuitBreakerProps)} afterward. + * + * @param provider circuit breaker provider instance + * @param storageId unique storage identifier + * @param lastUpdatedAt timestamp when config was last updated + */ + public static void checkOrInvalidateCircuitBreakerCache( + @NotNull ICircuitBreaker provider, @NotNull String storageId, long lastUpdatedAt) { + final Long cached = circuitBreakerMap.get(storageId); + if (cached == null || lastUpdatedAt > cached) { + boolean updated = updateInternalCache(storageId, lastUpdatedAt, provider); + if (updated) { + // Remove old CB; harmless for new storageIds (no-op since CB doesn't exist yet) + provider.remove(storageId); + } + } + } + + /** + * Update cache with new timestamp, removing old entries if needed. + * + * @param storageId storage identifier + * @param lastUpdatedAt new timestamp value + * @param provider circuit breaker provider for cleanup + * @return true if the cache was updated, false otherwise + */ + private static synchronized boolean updateInternalCache( + @NotNull String storageId, long lastUpdatedAt, @NotNull ICircuitBreaker provider) { + // Double check to prevent concurrent threads from creating duplicate entries + final Long cached = circuitBreakerMap.get(storageId); + if (cached != null && lastUpdatedAt <= cached) { + return false; // Another thread already updated, nothing to do + } + + // Check if cache size exceeds max size + if (circuitBreakerMap.size() >= MAX_SIZE) { + removeClosedEntries(provider); + if (circuitBreakerMap.size() >= MAX_SIZE) { + removeFirstEntry(provider); + } + } + + // Add new or replace existing cache entry + circuitBreakerMap.put(storageId, lastUpdatedAt); + return true; + } + + /** + * Remove entries with CLOSED circuit breakers due to cache size limit. + * Iterates through all entries and removes those with CLOSED circuit breakers. + * + * @param provider circuit breaker provider to check CB state + */ + private static synchronized void removeClosedEntries(@NotNull ICircuitBreaker provider) { + List storageIds = new ArrayList<>(circuitBreakerMap.keySet()); + for (String storageId : storageIds) { + if (provider.isClosed(storageId)) { + circuitBreakerMap.remove(storageId); + provider.remove(storageId); + logger.info("Removed CLOSED CircuitBreaker for storageId: {} due to max cache size limit", storageId); + } + } + } + + /** + * Remove the first entry from cache due to size limit (oldest insertion). + * + * @param provider circuit breaker provider to remove the entry from + */ + private static synchronized void removeFirstEntry(@NotNull ICircuitBreaker provider) { + if (!circuitBreakerMap.isEmpty()) { + String storageId = (String) circuitBreakerMap.keySet().toArray()[0]; + circuitBreakerMap.remove(storageId); + provider.remove(storageId); + logger.info("Cache full ({}). Evicted circuit breaker for storageId={}", MAX_SIZE, storageId); + } + } + + /** + * Clear all cache entries. Intended for testing purposes. + */ + @TestOnly + public static void clearCache() { + circuitBreakerMap.clear(); + } + + /** + * Get cached timestamp for a storageId. Intended for testing purposes. + * + * @param storageId storage identifier + * @return cached timestamp or null if not found + */ + @TestOnly + @Nullable + public static Long getCachedTimestamp(@NotNull String storageId) { + return circuitBreakerMap.get(storageId); + } +} diff --git a/here-naksha-storage-http/src/jvmMain/java/com/here/naksha/storage/http/cache/RequestSenderCache.java b/here-naksha-storage-http/src/jvmMain/java/com/here/naksha/storage/http/cache/RequestSenderCache.java index b452d87cb8..eb057adac6 100644 --- a/here-naksha-storage-http/src/jvmMain/java/com/here/naksha/storage/http/cache/RequestSenderCache.java +++ b/here-naksha-storage-http/src/jvmMain/java/com/here/naksha/storage/http/cache/RequestSenderCache.java @@ -55,7 +55,7 @@ public RequestSender getSenderWith(KeyProperties keyProperties) { private @NotNull RequestSender getUpdated( @Nullable RequestSender cachedSender, @NotNull KeyProperties keyProperties) { - if (cachedSender != null && cachedSender.hasKeyProps(keyProperties)) return cachedSender; + if (cachedSender != null && !cachedSender.hasPropsChanged(keyProperties)) return cachedSender; else return new RequestSender(keyProperties); } diff --git a/here-naksha-storage-http/src/jvmTest/java/com/here/naksha/storage/http/HttpStorageReadSessionTest.java b/here-naksha-storage-http/src/jvmTest/java/com/here/naksha/storage/http/HttpStorageReadSessionTest.java index 8afbb56693..9f4ce5b43f 100644 --- a/here-naksha-storage-http/src/jvmTest/java/com/here/naksha/storage/http/HttpStorageReadSessionTest.java +++ b/here-naksha-storage-http/src/jvmTest/java/com/here/naksha/storage/http/HttpStorageReadSessionTest.java @@ -184,6 +184,7 @@ private static ReadFeaturesProxyWrapper request(String catalogId, String collect } private static HttpStorageReadSession session() { - return new HttpStorageReadSession(null, storage, mock(RequestSender.class), HttpInterface.ffwAdapter); + return new HttpStorageReadSession(null, storage, mock(RequestSender.class), HttpInterface.ffwAdapter, + null, STORAGE_ID, null); } } diff --git a/here-naksha-storage-http/src/jvmTest/java/com/here/naksha/storage/http/RequestSenderTest.java b/here-naksha-storage-http/src/jvmTest/java/com/here/naksha/storage/http/RequestSenderTest.java index 29e043bf19..d6160d6eb3 100644 --- a/here-naksha-storage-http/src/jvmTest/java/com/here/naksha/storage/http/RequestSenderTest.java +++ b/here-naksha-storage-http/src/jvmTest/java/com/here/naksha/storage/http/RequestSenderTest.java @@ -52,7 +52,8 @@ void t01_testGoAwayException() throws ExecutionException, InterruptedException, new HashMap<>(), 10, 10, - 1 + 1, + 1200 ); // Given: Mock setup for generating GOAWAY exception on first attempt diff --git a/here-naksha-storage-http/src/jvmTest/java/com/here/naksha/storage/http/cache/CircuitBreakerCacheTest.java b/here-naksha-storage-http/src/jvmTest/java/com/here/naksha/storage/http/cache/CircuitBreakerCacheTest.java new file mode 100644 index 0000000000..d4e99e866e --- /dev/null +++ b/here-naksha-storage-http/src/jvmTest/java/com/here/naksha/storage/http/cache/CircuitBreakerCacheTest.java @@ -0,0 +1,292 @@ +package com.here.naksha.storage.http.cache; + +import com.here.naksha.lib.circuitbreaker.CircuitBreakerProvider; +import com.here.naksha.lib.circuitbreaker.ICircuitBreaker; +import com.here.naksha.lib.circuitbreaker.models.CircuitBreakerProps; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.RepeatedTest; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.jupiter.api.Assertions.*; + +class CircuitBreakerCacheTest { + + private static final ICircuitBreaker provider = CircuitBreakerProvider.getInstance(); + + private static final CircuitBreakerProps CB_CONFIG = cbConfig(20, 10, 500L, 50, 30000L, 5); + + private static CircuitBreakerProps cbConfig( + int slidingWindowSize, int minimumNumberOfCalls, long slowCallDurationThresholdMs, + int slowCallRateThreshold, long waitDurationInOpenStateMs, int permittedNumberOfCallsInHalfOpenState) { + final CircuitBreakerProps config = new CircuitBreakerProps(); + config.setSlidingWindowSize(slidingWindowSize); + config.setMinimumNumberOfCalls(minimumNumberOfCalls); + config.setSlowCallDurationThresholdMs(slowCallDurationThresholdMs); + config.setSlowCallRateThreshold(slowCallRateThreshold); + config.setWaitDurationInOpenStateMs(waitDurationInOpenStateMs); + config.setPermittedNumberOfCallsInHalfOpenState(permittedNumberOfCallsInHalfOpenState); + return config; + } + + private static final String ID_1 = "test_storage_1"; + private static final String ID_2 = "test_storage_2"; + private static final String ID_3 = "test_storage_3"; + + @BeforeEach + void setUp() { + provider.clear(); + CircuitBreakerCache.clearCache(); + } + + /** + * Verifies that checking with same timestamp is idempotent. + */ + @Test + void testSameStorageIdSameTimestampIsIdempotent() { + long timestamp = 100L; + + // First check + CircuitBreakerCache.checkOrInvalidateCircuitBreakerCache(provider, ID_1, timestamp); + provider.getOrCreateCircuitBreaker(ID_1, CB_CONFIG); + assertTrue(provider.exists(ID_1), "CB should exist after first check"); + assertEquals(timestamp, CircuitBreakerCache.getCachedTimestamp(ID_1), "Timestamp should be cached"); + + // Second check with same timestamp should be no-op + CircuitBreakerCache.checkOrInvalidateCircuitBreakerCache(provider, ID_1, timestamp); + assertTrue(provider.exists(ID_1), "CB should still exist"); + assertEquals(timestamp, CircuitBreakerCache.getCachedTimestamp(ID_1), "Timestamp should remain the same"); + } + + /** + * Verifies that checking with a newer timestamp invalidates the circuit breaker. + */ + @Test + void testNewerTimestampRecreatesCircuitBreaker() { + long oldTimestamp = 100L; + long newTimestamp = 200L; + + // Register with old timestamp + CircuitBreakerCache.checkOrInvalidateCircuitBreakerCache(provider, ID_1, oldTimestamp); + provider.getOrCreateCircuitBreaker(ID_1, CB_CONFIG); + assertTrue(provider.exists(ID_1), "CB should exist after first check"); + assertEquals(oldTimestamp, CircuitBreakerCache.getCachedTimestamp(ID_1), "Old timestamp should be cached"); + + // Check with newer timestamp + CircuitBreakerCache.checkOrInvalidateCircuitBreakerCache(provider, ID_1, newTimestamp); + provider.getOrCreateCircuitBreaker(ID_1, CB_CONFIG); + assertTrue(provider.exists(ID_1), "CB should exist after second check"); + assertEquals(newTimestamp, CircuitBreakerCache.getCachedTimestamp(ID_1), "Timestamp should be updated to new value"); + } + + /** + * Verifies that checking with an older timestamp is ignored (no downgrade). + */ + @Test + void testOlderTimestampIsIgnored() { + long oldTimestamp = 100L; + long newerTimestamp = 200L; + + // Check with newer timestamp first + CircuitBreakerCache.checkOrInvalidateCircuitBreakerCache(provider, ID_1, newerTimestamp); + provider.getOrCreateCircuitBreaker(ID_1, CB_CONFIG); + assertEquals(newerTimestamp, CircuitBreakerCache.getCachedTimestamp(ID_1), "Newer timestamp should be cached"); + + // Try to check with older timestamp (should be ignored) + CircuitBreakerCache.checkOrInvalidateCircuitBreakerCache(provider, ID_1, oldTimestamp); + + // Timestamp should not be downgraded + assertEquals(newerTimestamp, CircuitBreakerCache.getCachedTimestamp(ID_1), "Timestamp should not be downgraded"); + } + + /** + * Verifies that different storageIds maintain independent cache entries. + */ + @Test + void testMultipleStorageIdsAreIndependent() { + long timestamp1 = 100L; + long timestamp2 = 200L; + long timestamp3 = 300L; + + CircuitBreakerCache.checkOrInvalidateCircuitBreakerCache(provider, ID_1, timestamp1); + provider.getOrCreateCircuitBreaker(ID_1, CB_CONFIG); + CircuitBreakerCache.checkOrInvalidateCircuitBreakerCache(provider, ID_2, timestamp2); + provider.getOrCreateCircuitBreaker(ID_2, CB_CONFIG); + CircuitBreakerCache.checkOrInvalidateCircuitBreakerCache(provider, ID_3, timestamp3); + provider.getOrCreateCircuitBreaker(ID_3, CB_CONFIG); + + assertTrue(provider.exists(ID_1), "CB for ID_1 should exist"); + assertTrue(provider.exists(ID_2), "CB for ID_2 should exist"); + assertTrue(provider.exists(ID_3), "CB for ID_3 should exist"); + + // Verify each has the correct timestamp + assertEquals(timestamp1, CircuitBreakerCache.getCachedTimestamp(ID_1)); + assertEquals(timestamp2, CircuitBreakerCache.getCachedTimestamp(ID_2)); + assertEquals(timestamp3, CircuitBreakerCache.getCachedTimestamp(ID_3)); + } + + /** + * Verifies that cache respects the 1000 entry limit via size-based cleanup. + * Fills cache to 1000 entries and verifies cleanup maintains limit. + */ + @Test + void testSizeBasedCleanupOnCachedClosedEntries() throws InterruptedException { + int maxCacheSize = 1000; + + // Fill cache to 1000 entries + for (int i = 0; i < maxCacheSize; i++) { + String storageId = "storage_" + i; + long timestamp = 100L + i; + CircuitBreakerCache.checkOrInvalidateCircuitBreakerCache(provider, storageId, timestamp); + provider.getOrCreateCircuitBreaker(storageId, CB_CONFIG); + } + + // Small delay to ensure all registrations complete + Thread.sleep(50); + + // Add one more entry which should trigger cleanup + CircuitBreakerCache.checkOrInvalidateCircuitBreakerCache(provider, "storage_extra", 200L); + provider.getOrCreateCircuitBreaker("storage_extra", CB_CONFIG); + + // After cleanup, verify cache size is still reasonable (≤ 1000 or close to it) + int finalCacheSize = 0; + for (int i = 0; i < maxCacheSize + 1; i++) { + String storageId = (i < maxCacheSize) ? "storage_" + i : "storage_extra"; + if (CircuitBreakerCache.getCachedTimestamp(storageId) != null) { + finalCacheSize++; + } + } + assertTrue(finalCacheSize <= 1000, "After cleanup, cache should be ≤ 1000 entries, but had: " + finalCacheSize); + } + + /** + * Verifies concurrent checks with same storageId converge correctly. + */ + @RepeatedTest(5) + void testConcurrentRegistrationsSameStorageId() throws InterruptedException { + int threadCount = 10; + CountDownLatch startLatch = new CountDownLatch(1); + CountDownLatch endLatch = new CountDownLatch(threadCount); + + for (int i = 0; i < threadCount; i++) { + new Thread(() -> { + try { + startLatch.await(); // Wait for all threads to be ready + CircuitBreakerCache.checkOrInvalidateCircuitBreakerCache(provider, ID_1, 100L); + provider.getOrCreateCircuitBreaker(ID_1, CB_CONFIG); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } finally { + endLatch.countDown(); + } + }).start(); + } + + startLatch.countDown(); // Release all threads at once + endLatch.await(); // Wait for all to complete + + assertTrue(provider.exists(ID_1), "CB should exist after concurrent registrations"); + } + + /** + * Verifies concurrent checks with different storageIds work correctly. + */ + @RepeatedTest(5) + void testConcurrentRegistrationsDifferentStorageIds() throws InterruptedException { + int threadCount = 10; + CountDownLatch startLatch = new CountDownLatch(1); + CountDownLatch endLatch = new CountDownLatch(threadCount); + + for (int i = 0; i < threadCount; i++) { + final int index = i; + new Thread(() -> { + try { + startLatch.await(); + String storageId = "storage_" + index; + CircuitBreakerCache.checkOrInvalidateCircuitBreakerCache(provider, storageId, 100L); + provider.getOrCreateCircuitBreaker(storageId, CB_CONFIG); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } finally { + endLatch.countDown(); + } + }).start(); + } + + startLatch.countDown(); + endLatch.await(); + + // Retry loop: wait for CBs to be created (with timeout) + int maxRetries = 50; + int retries = 0; + boolean allExist = false; + while (retries < maxRetries) { + allExist = true; + for (int i = 0; i < threadCount; i++) { + if (!provider.exists("storage_" + i)) { + allExist = false; + break; + } + } + if (allExist) break; + Thread.sleep(10); + retries++; + } + + // All 10 CBs should be registered + for (int i = 0; i < threadCount; i++) { + String storageId = "storage_" + i; + assertTrue(provider.exists(storageId), "CB should exist for storageId: " + storageId); + } + } + + /** + * Verifies concurrent updates to same storageId with different timestamps. + */ + @RepeatedTest(5) + void testConcurrentUpdatesWithDifferentTimestamps() throws InterruptedException { + int threadCount = 5; + CountDownLatch startLatch = new CountDownLatch(1); + CountDownLatch endLatch = new CountDownLatch(threadCount); + AtomicInteger updateCount = new AtomicInteger(0); + long maxExpectedTimestamp = 100L + (4 * 10); // Max timestamp: 140L + + for (int i = 0; i < threadCount; i++) { + final int index = i; + new Thread(() -> { + try { + startLatch.await(); + long timestamp = 100L + (index * 10); // Different timestamps + CircuitBreakerCache.checkOrInvalidateCircuitBreakerCache(provider, ID_1, timestamp); + provider.getOrCreateCircuitBreaker(ID_1, CB_CONFIG); + updateCount.incrementAndGet(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } finally { + endLatch.countDown(); + } + }).start(); + } + + startLatch.countDown(); + endLatch.await(); + + // Retry loop: wait for CB to be created (with timeout) + int maxRetries = 50; + int retries = 0; + while (!provider.exists(ID_1) && retries < maxRetries) { + Thread.sleep(10); + retries++; + } + + assertTrue(provider.exists(ID_1), "CB should exist after concurrent updates"); + assertEquals(threadCount, updateCount.get(), "All threads should complete"); + + // Verify the cached timestamp is the maximum one (140L) + Long cachedTimestamp = CircuitBreakerCache.getCachedTimestamp(ID_1); + assertNotNull(cachedTimestamp, "Timestamp should be cached"); + assertEquals(maxExpectedTimestamp, cachedTimestamp.longValue(),"Cached timestamp should be the maximum: " + maxExpectedTimestamp); + } +} diff --git a/here-naksha-storage-http/src/jvmTest/java/com/here/naksha/storage/http/cache/RequestSenderCacheTest.java b/here-naksha-storage-http/src/jvmTest/java/com/here/naksha/storage/http/cache/RequestSenderCacheTest.java index 701c326840..5c8c42d737 100644 --- a/here-naksha-storage-http/src/jvmTest/java/com/here/naksha/storage/http/cache/RequestSenderCacheTest.java +++ b/here-naksha-storage-http/src/jvmTest/java/com/here/naksha/storage/http/cache/RequestSenderCacheTest.java @@ -1,7 +1,9 @@ package com.here.naksha.storage.http.cache; +import com.here.naksha.lib.circuitbreaker.CircuitBreakerProvider; import com.here.naksha.storage.http.RequestSender; import com.here.naksha.storage.http.RequestSender.KeyProperties; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.RepeatedTest; import org.junit.jupiter.api.Test; @@ -12,173 +14,107 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertNotSame; + class RequestSenderCacheTest { - public static final String EXAMPLE_URL = "www.example.naksha.com"; + @BeforeEach + void clearProviderState() { + CircuitBreakerProvider.getInstance().clear(); + } + public static final String EXAMPLE_URL = "www.example.naksha.com"; public static final int EXAMPLE_CONNECTION_TIMEOUT = 1; - public static final int EXAMPLE_SOCKET_TIMEOUT = 1; - public static final int EXAMPLE_MAX_RETRIES = 1; - - public static final Map EXAMPLE_HEADERS = Map.of("Authorization", "Bearer exampleToken", "Content-Type", "application/json"); - public static final Map MODIFIED_HEADERS = Map.of("Authorization", "Bearer modifiedToken", "Content-Type", "application/json"); + public static final Map EXAMPLE_HEADERS = Map.of("Authorization", "******", "Content-Type", "application/json"); public static final String ID_1 = "id_1"; public static final String ID_2 = "id_2"; public static final String ID_3 = "id_3"; - public static final KeyProperties PROP_ID_1 = new KeyProperties( - ID_1, - EXAMPLE_URL, - EXAMPLE_HEADERS, - EXAMPLE_CONNECTION_TIMEOUT, - EXAMPLE_SOCKET_TIMEOUT, - EXAMPLE_MAX_RETRIES - ); - - public static final KeyProperties PROP_ID_1_COPY = new KeyProperties( - ID_1, - EXAMPLE_URL, - EXAMPLE_HEADERS, - EXAMPLE_CONNECTION_TIMEOUT, - EXAMPLE_SOCKET_TIMEOUT, - EXAMPLE_MAX_RETRIES - ); - - public static final KeyProperties PROP_ID_1_INT_CHANGED = new KeyProperties( - ID_1, - EXAMPLE_URL, - EXAMPLE_HEADERS, - EXAMPLE_CONNECTION_TIMEOUT, - 2, - EXAMPLE_MAX_RETRIES - ); - - public static final KeyProperties PROP_ID_1_MAP_COPIED = new KeyProperties( - ID_1, - EXAMPLE_URL, - Map.copyOf(EXAMPLE_HEADERS), - EXAMPLE_CONNECTION_TIMEOUT, - EXAMPLE_SOCKET_TIMEOUT, - EXAMPLE_MAX_RETRIES - ); - - public static final KeyProperties PROP_ID_1_MAP_CHANGED = new KeyProperties( - ID_1, - EXAMPLE_URL, - MODIFIED_HEADERS, - EXAMPLE_CONNECTION_TIMEOUT, - EXAMPLE_SOCKET_TIMEOUT, - EXAMPLE_MAX_RETRIES - ); - - public static final KeyProperties PROP_ID_2 = new KeyProperties( - ID_2, - EXAMPLE_URL, - EXAMPLE_HEADERS, - EXAMPLE_CONNECTION_TIMEOUT, - EXAMPLE_SOCKET_TIMEOUT, - EXAMPLE_MAX_RETRIES - ); - - public static final KeyProperties PROP_ID_3 = new KeyProperties( - ID_3, - EXAMPLE_URL, - EXAMPLE_HEADERS, - EXAMPLE_CONNECTION_TIMEOUT, - EXAMPLE_SOCKET_TIMEOUT, - EXAMPLE_MAX_RETRIES - ); + // Same storageId, same updatedAt → should reuse cached sender + public static final KeyProperties PROP_ID_1 = keyProps(ID_1, 100L); + public static final KeyProperties PROP_ID_1_COPY = keyProps(ID_1, 100L); + + // Same storageId, newer updatedAt → should create new sender + public static final KeyProperties PROP_ID_1_NEWER = keyProps(ID_1, 200L); + + // Different storageIds → independent cache entries + public static final KeyProperties PROP_ID_2 = keyProps(ID_2, 100L); + public static final KeyProperties PROP_ID_3 = keyProps(ID_3, 100L); + + private static KeyProperties keyProps(String storageId, long updatedAt) { + return new KeyProperties( + storageId, EXAMPLE_URL, EXAMPLE_HEADERS, EXAMPLE_CONNECTION_TIMEOUT, + EXAMPLE_SOCKET_TIMEOUT, EXAMPLE_MAX_RETRIES, updatedAt); + } @Test - void testOneId() { + void testOneIdSameUpdatedAtReusesCache() { // Setup ConcurrentMap senders = new ConcurrentHashMap<>(); - RequestSenderCache cache = new RequestSenderCache( - senders, - 8, - TimeUnit.HOURS - ); - - assertEquals(PROP_ID_1, PROP_ID_1_COPY); - assertNotSame(PROP_ID_1, PROP_ID_1_COPY); + RequestSenderCache cache = new RequestSenderCache(senders, 8, TimeUnit.HOURS); // Tests assertEquals(0, senders.size()); + // First lookup creates the sender RequestSender senderId1 = cache.getSenderWith(PROP_ID_1); assertEquals(1, senders.size()); + // Same storageId + same updatedAt reuses the cached sender RequestSender senderId1Copy = cache.getSenderWith(PROP_ID_1_COPY); assertEquals(1, senders.size()); - assertSame(senderId1, senderId1Copy); - - RequestSender senderId1IntChanged - = cache.getSenderWith(PROP_ID_1_INT_CHANGED); - assertEquals(1, senders.size()); - assertNotEquals(senderId1Copy, senderId1IntChanged); + assertSame(senderId1, senderId1Copy, "Should reuse sender when updatedAt is same"); } @Test - void testOneIdMapChange() { + void testOneIdNewerUpdatedAtRefreshesCache() { // Setup ConcurrentMap senders = new ConcurrentHashMap<>(); - RequestSenderCache cache = new RequestSenderCache( - senders, - 8, - TimeUnit.HOURS - ); - - assertEquals(PROP_ID_1, PROP_ID_1_MAP_COPIED); - assertNotSame(PROP_ID_1, PROP_ID_1_MAP_COPIED); + RequestSenderCache cache = new RequestSenderCache(senders, 8, TimeUnit.HOURS); // Tests assertEquals(0, senders.size()); + // First lookup creates the sender RequestSender senderId1 = cache.getSenderWith(PROP_ID_1); assertEquals(1, senders.size()); - RequestSender senderId1MapCopied = cache.getSenderWith(PROP_ID_1_MAP_COPIED); - assertEquals(1, senders.size()); - assertSame(senderId1, senderId1MapCopied); - - RequestSender senderId1MapChanged - = cache.getSenderWith(PROP_ID_1_MAP_CHANGED); - assertEquals(1, senders.size()); - assertNotEquals(senderId1MapCopied, senderId1MapChanged); + // Newer updatedAt replaces the cached sender + RequestSender senderId1Newer = cache.getSenderWith(PROP_ID_1_NEWER); + assertEquals(1, senders.size(), "Cache size should remain 1 (same storageId)"); + assertNotSame(senderId1, senderId1Newer, "Should create new sender when updatedAt is newer"); } @Test - void testMoreIds() { + void testMultipleIds() { // Setup ConcurrentMap senders = new ConcurrentHashMap<>(); - RequestSenderCache cache = new RequestSenderCache( - senders, - 8, - TimeUnit.HOURS - ); + RequestSenderCache cache = new RequestSenderCache(senders, 8, TimeUnit.HOURS); // Tests assertEquals(0, senders.size()); + // Different storageIds keep independent cache entries RequestSender senderId1 = cache.getSenderWith(PROP_ID_1); assertEquals(1, senders.size()); RequestSender senderId2 = cache.getSenderWith(PROP_ID_2); assertEquals(2, senders.size()); - assertNotEquals(senderId1, senderId2); + assertNotSame(senderId1, senderId2); RequestSender senderId3 = cache.getSenderWith(PROP_ID_3); assertEquals(3, senders.size()); - assertNotEquals(senderId1, senderId3); + assertNotSame(senderId1, senderId3); RequestSender newSenderId1 = cache.getSenderWith(PROP_ID_1); assertEquals(3, senders.size()); - assertSame(senderId1, newSenderId1); + assertSame(senderId1, newSenderId1, "Should reuse same storageId when updatedAt matches"); } @Test @@ -186,42 +122,40 @@ void testCleanup() throws InterruptedException { // Setup int cleanPeriodMs = 1000; ConcurrentMap senders = new ConcurrentHashMap<>(); - RequestSenderCache cache = new RequestSenderCache( - senders, - cleanPeriodMs, - TimeUnit.MILLISECONDS - ); + RequestSenderCache cache = new RequestSenderCache(senders, cleanPeriodMs, TimeUnit.MILLISECONDS); // Tests assertEquals(0, senders.size()); + + // Populate cache cache.getSenderWith(PROP_ID_1); cache.getSenderWith(PROP_ID_2); cache.getSenderWith(PROP_ID_3); assertEquals(3, senders.size()); + + // Wait for cleanup and verify cache is cleared Thread.sleep(cleanPeriodMs + 100); assertEquals(0, senders.size()); + + // Cache should work again after cleanup cache.getSenderWith(PROP_ID_1); assertEquals(1, senders.size()); } - @RepeatedTest(10) void testCleanupConcurrency() throws InterruptedException { // Setup int cleanPeriodMs = 1; ConcurrentMap senders = new ConcurrentHashMap<>(); - RequestSenderCache cache = new RequestSenderCache( - senders, - cleanPeriodMs, - TimeUnit.MILLISECONDS - ); + RequestSenderCache cache = new RequestSenderCache(senders, cleanPeriodMs, TimeUnit.MILLISECONDS); // Tests assertEquals(0, senders.size()); - assertTrue(cache.getSenderWith(PROP_ID_1).hasKeyProps(PROP_ID_1)); - assertTrue(cache.getSenderWith(PROP_ID_2).hasKeyProps(PROP_ID_2)); - assertTrue(cache.getSenderWith(PROP_ID_3).hasKeyProps(PROP_ID_3)); + // Rapid cache population should still be removed by cleanup + cache.getSenderWith(PROP_ID_1); + cache.getSenderWith(PROP_ID_2); + cache.getSenderWith(PROP_ID_3); Thread.sleep(cleanPeriodMs + 100); assertEquals(0, senders.size()); } @@ -230,31 +164,21 @@ void testCleanupConcurrency() throws InterruptedException { void testGetSenderConcurrency() throws InterruptedException { // Setup ConcurrentMap senders = new ConcurrentHashMap<>(); - RequestSenderCache cache = new RequestSenderCache( - senders, - 8, - TimeUnit.HOURS - ); + RequestSenderCache cache = new RequestSenderCache(senders, 8, TimeUnit.HOURS); AtomicReference senderId1 = new AtomicReference<>(); AtomicReference senderId1Copy = new AtomicReference<>(); - AtomicReference senderId1IntChanged = new AtomicReference<>(); - AtomicReference senderId1MapChanged = new AtomicReference<>(); // Tests + // Concurrent requests with the same version should converge to one cached sender List threads = List.of( - new Thread(() -> senderId1.set(cache.getSenderWith(PROP_ID_1))), - new Thread(() -> senderId1Copy.set(cache.getSenderWith(PROP_ID_1_COPY))), - new Thread(() -> senderId1IntChanged.set(cache.getSenderWith(PROP_ID_1_INT_CHANGED))), - new Thread(() -> senderId1MapChanged.set(cache.getSenderWith(PROP_ID_1_MAP_CHANGED))) + new Thread(() -> senderId1.set(cache.getSenderWith(PROP_ID_1))), + new Thread(() -> senderId1Copy.set(cache.getSenderWith(PROP_ID_1_COPY))) ); threads.forEach(Thread::start); for (Thread thread : threads) { thread.join(); } - assertTrue(senderId1.get().hasKeyProps(PROP_ID_1)); - assertTrue(senderId1Copy.get().hasKeyProps(PROP_ID_1_COPY)); - assertTrue(senderId1IntChanged.get().hasKeyProps(PROP_ID_1_INT_CHANGED)); - assertTrue(senderId1MapChanged.get().hasKeyProps(PROP_ID_1_MAP_CHANGED)); + assertEquals(senderId1.get(), senderId1Copy.get()); } } \ No newline at end of file diff --git a/settings.gradle.kts b/settings.gradle.kts index 598d234e87..29fcc44f21 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -42,6 +42,7 @@ include(":here-naksha-lib-handlers") include(":here-naksha-lib-hub") include(":here-naksha-lib-view") include(":here-naksha-common-http") +include(":here-naksha-lib-circuit-breaker") include(":here-naksha-storage-http") include(":here-naksha-app-service") include(":here-naksha-lib-ext-manager")