diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index c7dc2b1..591b2e6 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -6,7 +6,7 @@ labels: kind/bug assignees: '' --- -- [ ] I have searched the [issues](https://github.com/reactivegroup/capa/issues) of this repository and believe that this is not a duplicate. +- [ ] I have searched the [issues](https://github.com/capa-cloud/capa-java/issues) of this repository and believe that this is not a duplicate. ### Environment diff --git a/README.md b/README.md index 7bc5757..7771053 100644 --- a/README.md +++ b/README.md @@ -48,9 +48,9 @@ Capa API design follow community standards, please refer to the API definitions The API definition is placed in the following independent warehouse, unbound from the Capa project, and hopes to develop into the community's API standard definition: -+ java: [cloud-runtimes-jvm](https://github.com/reactivegroup/cloud-runtimes-jvm) -+ python(alpha): [cloud-runtimes-python](https://github.com/reactivegroup/cloud-runtimes-python) -+ golang(alpha): [cloud-runtimes-golang](https://github.com/reactivegroup/cloud-runtimes-golang) ++ java: [cloud-runtimes-jvm](https://github.com/capa-cloud/cloud-runtimes-jvm) ++ python(alpha): [cloud-runtimes-python](https://github.com/capa-cloud/cloud-runtimes-python) ++ golang(alpha): [cloud-runtimes-golang](https://github.com/capa-cloud/cloud-runtimes-golang) #### Why not use Dapr API directly? @@ -120,7 +120,7 @@ For a Maven project, add the following to your pom.xml file: group.rxcloud capa-sdk - 1.0.7.RELEASE + 2.12.1.RELEASE ... @@ -140,7 +140,7 @@ Sample implementation library: group.rxcloud capa-sdk-spi-demo - 1.0.7.RELEASE + 2.12.1.RELEASE ... @@ -152,9 +152,9 @@ Sample implementation library: Try the following examples to learn more about Capa's Java SDK: -* [capa-demo](https://github.com/reactivegroup/capa/tree/master/sdk-spi-demo) -* [capa-aws](https://github.com/reactivegroup/capa-aws) -* [capa-alibaba](https://github.com/reactivegroup/capa-alibaba) +* [capa-demo](https://github.com/capa-cloud/capa-java/tree/master/sdk-spi-demo) +* [capa-aws](https://github.com/capa-cloud/capa-java-aws) +* [capa-alibaba](https://github.com/capa-cloud/capa-java-alibaba) ### Low retrofit cost migration diff --git a/README_ZH.md b/README_ZH.md index a13a2ae..5bfa15d 100644 --- a/README_ZH.md +++ b/README_ZH.md @@ -46,9 +46,9 @@ Capa API设计follow社区标准,请参考 Dapr / Layotto 等开源项目的AP API定义放置于以下独立仓库中,与Capa项目解绑,希望发展成为社区的API标准定义: -+ java: [cloud-runtimes-jvm](https://github.com/reactivegroup/cloud-runtimes-jvm) -+ python(alpha): [cloud-runtimes-python](https://github.com/reactivegroup/cloud-runtimes-python) -+ golang(alpha): [cloud-runtimes-golang](https://github.com/reactivegroup/cloud-runtimes-golang) ++ java: [cloud-runtimes-jvm](https://github.com/capa-cloud/cloud-runtimes-jvm) ++ python(alpha): [cloud-runtimes-python](https://github.com/capa-cloud/cloud-runtimes-python) ++ golang(alpha): [cloud-runtimes-golang](https://github.com/capa-cloud/cloud-runtimes-golang) #### 为什么不直接使用Dapr API? @@ -118,7 +118,7 @@ For a Maven project, add the following to your pom.xml file: group.rxcloud capa-sdk - 1.0.7.RELEASE + 2.12.1.RELEASE ... @@ -138,7 +138,7 @@ Sample implementation library: group.rxcloud capa-sdk-spi-demo - 1.0.7.RELEASE + 2.12.1.RELEASE ... @@ -150,9 +150,9 @@ Sample implementation library: Try the following examples to learn more about Capa's Java SDK: -* [capa-demo](https://github.com/reactivegroup/capa/tree/master/sdk-spi-demo) -* [capa-aws](https://github.com/reactivegroup/capa-aws) -* [capa-alibaba](https://github.com/reactivegroup/capa-alibaba) +* [capa-demo](https://github.com/capa-cloud/capa-java/tree/master/sdk-spi-demo) +* [capa-aws](https://github.com/capa-cloud/capa-java-aws) +* [capa-alibaba](https://github.com/capa-cloud/capa-java-alibaba) ### 低改造成本迁移 diff --git a/examples/pom.xml b/examples/pom.xml index e07c6e9..a84989b 100644 --- a/examples/pom.xml +++ b/examples/pom.xml @@ -23,7 +23,7 @@ capa-parent group.rxcloud - 1.11.13.2.RELEASE + 2.12.1.RELEASE capa-examples @@ -33,6 +33,7 @@ 2.17.1 1.2.10 + 1.18.22 @@ -52,12 +53,6 @@ org.apache.logging.log4j log4j-core ${log4j.version} - - - log4j-api - org.apache.logging.log4j - - + org.projectlombok lombok - 1.18.2 + ${lombok.version} diff --git a/examples/src/main/java/group/rxcloud/capa/examples/log/DemoLog.java b/examples/src/main/java/group/rxcloud/capa/examples/log/DemoLog.java index b64ac9d..1fd03e1 100644 --- a/examples/src/main/java/group/rxcloud/capa/examples/log/DemoLog.java +++ b/examples/src/main/java/group/rxcloud/capa/examples/log/DemoLog.java @@ -32,9 +32,8 @@ public class DemoLog { public static void main(String[] args) { try { log.info("test"); - }catch (Exception e){ + } catch (Exception e) { System.out.println(); } - } } diff --git a/examples/src/main/java/group/rxcloud/capa/examples/telemetry/DemoTelemetryClient.java b/examples/src/main/java/group/rxcloud/capa/examples/telemetry/DemoTelemetryClient.java index 8ef4efd..58cd7ff 100644 --- a/examples/src/main/java/group/rxcloud/capa/examples/telemetry/DemoTelemetryClient.java +++ b/examples/src/main/java/group/rxcloud/capa/examples/telemetry/DemoTelemetryClient.java @@ -39,17 +39,18 @@ public static void main(String[] args) throws InterruptedException { // tracer Tracer tracer = capaTelemetryClient.buildTracer("tracer-test") - .block(); + .block(); LongCounter counter = capaTelemetryClient.buildMeter("meter-test") - .block() - .counterBuilder("counter-test") - .build(); + .block() + .counterBuilder("counter-test") + .build(); Span span = tracer.spanBuilder("span-test") - .setAttribute("key1", 1) - .setAttribute("key2", 2) - .startSpan(); + .setAttribute("key1", 1) + .setAttribute("key2", 2) + .startSpan(); + // working for (int i = 0; i < 50; i++) { Thread.sleep(200); diff --git a/examples/src/main/java/group/rxcloud/capa/examples/telemetry/TraceProcessor.java b/examples/src/main/java/group/rxcloud/capa/examples/telemetry/TraceProcessor.java index 63f5589..32609c9 100644 --- a/examples/src/main/java/group/rxcloud/capa/examples/telemetry/TraceProcessor.java +++ b/examples/src/main/java/group/rxcloud/capa/examples/telemetry/TraceProcessor.java @@ -25,7 +25,6 @@ public class TraceProcessor implements SpanProcessor { @Override public void onStart(Context context, ReadWriteSpan span) { - } @Override diff --git a/pom.xml b/pom.xml index 1e20552..4b630d2 100644 --- a/pom.xml +++ b/pom.xml @@ -23,10 +23,10 @@ group.rxcloud capa-parent pom - 1.11.13.2.RELEASE + 2.12.1.RELEASE capa-sdk-parent SDK for Capa. - https://github.com/reactivegroup + https://github.com/capa-cloud @@ -51,9 +51,9 @@ - scm:git:git@github.com:reactivegroup/capa.git - scm:git:git@github.com:reactivegroup/capa.git - git@github.com:reactivegroup/capa.git + scm:git:git@github.com:capa-cloud/capa.git + scm:git:git@github.com:capa-cloud/capa.git + git@github.com:capa-cloud/capa.git @@ -81,17 +81,29 @@ 8 UTF-8 3.8.1 - 1.11.RELEASE + + + 1.15.RELEASE 3.3.22.RELEASE - 1.7.21 - 1.39.0 - 2.12.4 + 1.7.36 + 0.10.4 + 1.0.8 1.9.0 1.9.0-alpha + 4.9.1 + 1.4.10 + 2.17.1 + 1.2.10 + 2.13.2.2 + 1.45.1 + 2.9.0 + + 5.3.1 3.6.0 2.0.2 + 3.1.2 0.13 2.7 @@ -137,46 +149,113 @@ group.rxcloud cloud-runtimes-api ${cloud-runtimes.version} + true - io.projectreactor reactor-core ${reactor-core.version} + true - org.slf4j slf4j-api ${slf4j.version} + true + + + + + org.apache.logging.log4j + log4j-core + ${log4j.version} + true + + + + + ch.qos.logback + logback-core + ${logback.version} + true + + + ch.qos.logback + logback-classic + ${logback.version} + true + + + + io.opentelemetry + opentelemetry-api + ${open.telemetry.version} + true + + + io.opentelemetry + opentelemetry-api-metrics + ${open.telemetry.version.alpha} + true + + + + group.rxcloud + vrml + ${vrml.version} + pom + import + true + + + + io.vavr + vavr + ${vavr.version} + true - com.fasterxml.jackson.core jackson-databind ${jackson.version} + true - io.grpc grpc-protobuf ${grpc.version} - - + + - io.opentelemetry - opentelemetry-api - ${open.telemetry.version} + com.google.code.gson + gson + ${gson.version} + true + - io.opentelemetry - opentelemetry-api-metrics - ${open.telemetry.version.alpha} + com.squareup.okhttp3 + okhttp + ${okhttp.version} + true + + + + org.jetbrains.kotlin + kotlin-stdlib + ${kotlin-stdlib.version} + true + + + org.jetbrains.kotlin + kotlin-stdlib-common + ${kotlin-stdlib.version} + true @@ -335,7 +414,7 @@ **/*.load **/*.flex **/*.fc - **/*.properties + **/*.constants **/*.sh **/*.bat **/*.md diff --git a/sdk-component/pom.xml b/sdk-component/pom.xml index 120a79b..16ccf63 100644 --- a/sdk-component/pom.xml +++ b/sdk-component/pom.xml @@ -23,7 +23,7 @@ group.rxcloud capa-parent - 1.11.13.2.RELEASE + 2.12.1.RELEASE capa-sdk-component @@ -31,11 +31,7 @@ SDK Component for Capa - 4.9.1 - 1.4.10 - 2.17.1 - 1.2.10 - + @@ -44,66 +40,114 @@ capa-sdk-infrastructure - + + + group.rxcloud + cloud-runtimes-api + true + + + + io.projectreactor + reactor-core + true + + + + org.slf4j + slf4j-api + true + + io.opentelemetry - opentelemetry-sdk - ${open.telemetry.version} + opentelemetry-api + true io.opentelemetry - opentelemetry-sdk-metrics - ${open.telemetry.version.alpha} + opentelemetry-api-metrics + true + + + + group.rxcloud + vrml-core + true + + + group.rxcloud + vrml-error + true + + + group.rxcloud + vrml-resource + true + + + group.rxcloud + vrml-spi + true + + + + io.vavr + vavr + true + + + + io.grpc + grpc-protobuf + true + + + + com.fasterxml.jackson.core + jackson-databind + true + + + + com.google.code.gson + gson + true - com.squareup.okhttp3 okhttp - ${okhttp.version} - - - kotlin-stdlib - org.jetbrains.kotlin - - - kotlin-stdlib-common - org.jetbrains.kotlin - - + true - org.jetbrains.kotlin kotlin-stdlib - ${kotlin-stdlib.version} + true org.jetbrains.kotlin kotlin-stdlib-common - ${kotlin-stdlib.version} + true - + org.apache.logging.log4j log4j-core - ${log4j.version} true + ch.qos.logback logback-core - ${logback.version} true ch.qos.logback logback-classic - ${logback.version} - true diff --git a/sdk-component/src/main/java/group/rxcloud/capa/component/CapaConfigurationProperties.java b/sdk-component/src/main/java/group/rxcloud/capa/component/CapaConfigurationProperties.java index e4bdf42..5e0db53 100644 --- a/sdk-component/src/main/java/group/rxcloud/capa/component/CapaConfigurationProperties.java +++ b/sdk-component/src/main/java/group/rxcloud/capa/component/CapaConfigurationProperties.java @@ -16,7 +16,7 @@ */ package group.rxcloud.capa.component; -import group.rxcloud.capa.infrastructure.CapaProperties; +import group.rxcloud.capa.infrastructure.loader.CapaProperties; import java.util.Arrays; import java.util.Collections; @@ -35,7 +35,7 @@ abstract class Settings { private static final String CONFIGURATION_COMPONENT_STORE_NAMES = "CONFIGURATION_COMPONENT_STORE_NAMES"; static { - Properties properties = CapaProperties.COMPONENT_PROPERTIES_SUPPLIER.apply("configuration-common"); + Properties properties = CapaProperties.loadComponentProperties("configuration-common"); String storeNames = properties.getProperty(CONFIGURATION_COMPONENT_STORE_NAMES, ""); if (storeNames != null) { diff --git a/sdk-component/src/main/java/group/rxcloud/capa/component/CapaLogProperties.java b/sdk-component/src/main/java/group/rxcloud/capa/component/CapaLogProperties.java index bdb6886..5abad9e 100644 --- a/sdk-component/src/main/java/group/rxcloud/capa/component/CapaLogProperties.java +++ b/sdk-component/src/main/java/group/rxcloud/capa/component/CapaLogProperties.java @@ -16,32 +16,8 @@ */ package group.rxcloud.capa.component; -import group.rxcloud.capa.infrastructure.CapaProperties; - -import java.util.Properties; - /** * Capa log component common properties. */ public interface CapaLogProperties { - - abstract class Settings { - - private static String centerConfigAppId = ""; - - private static final String LOG_COMPONENT_CENTER_CONFIG_APPID = "LOG_COMPONENT_CENTER_CONFIG_APPID"; - - static { - Properties properties = CapaProperties.COMPONENT_PROPERTIES_SUPPLIER.apply("log-common"); - - centerConfigAppId = properties.getProperty(LOG_COMPONENT_CENTER_CONFIG_APPID, centerConfigAppId); - } - - public static String getCenterConfigAppId() { - return centerConfigAppId; - } - - private Settings() { - } - } } diff --git a/sdk-component/src/main/java/group/rxcloud/capa/component/CapaRpcProperties.java b/sdk-component/src/main/java/group/rxcloud/capa/component/CapaRpcProperties.java index 9e1e1d8..74b5c8d 100644 --- a/sdk-component/src/main/java/group/rxcloud/capa/component/CapaRpcProperties.java +++ b/sdk-component/src/main/java/group/rxcloud/capa/component/CapaRpcProperties.java @@ -16,7 +16,7 @@ */ package group.rxcloud.capa.component; -import group.rxcloud.capa.infrastructure.CapaProperties; +import group.rxcloud.capa.infrastructure.loader.CapaProperties; import java.util.Properties; @@ -30,12 +30,12 @@ abstract class Settings { /** * Determines if Capa client will use HTTP or Other client. */ - public static String API_PROTOCOL; + private static final String API_PROTOCOL; /** * Capa's timeout in seconds for HTTP client reads. */ - public static Integer HTTP_CLIENT_READ_TIMEOUT_SECONDS; + private static final Integer HTTP_CLIENT_READ_TIMEOUT_SECONDS; /** * Capa's default use of HTTP. @@ -48,7 +48,7 @@ abstract class Settings { private static final Integer DEFAULT_HTTP_CLIENT_READTIMEOUTSECONDS = 60; static { - Properties properties = CapaProperties.COMPONENT_PROPERTIES_SUPPLIER.apply("rpc"); + Properties properties = CapaProperties.loadComponentProperties("rpc-common"); API_PROTOCOL = properties.getProperty("API_PROTOCOL", DEFAULT_API_PROTOCOL); diff --git a/sdk-component/src/main/java/group/rxcloud/capa/component/CapaTelemetryProperties.java b/sdk-component/src/main/java/group/rxcloud/capa/component/CapaTelemetryProperties.java index 9d4b695..d188b5b 100644 --- a/sdk-component/src/main/java/group/rxcloud/capa/component/CapaTelemetryProperties.java +++ b/sdk-component/src/main/java/group/rxcloud/capa/component/CapaTelemetryProperties.java @@ -16,32 +16,8 @@ */ package group.rxcloud.capa.component; -import group.rxcloud.capa.infrastructure.CapaProperties; - -import java.util.Properties; - /** * Capa telemetry component common properties. */ public interface CapaTelemetryProperties { - - abstract class Settings { - - private static String centerConfigAppId = ""; - - private static final String TELEMETRY_COMPONENT_CENTER_CONFIG_APPID = "TELEMETRY_COMPONENT_CENTER_CONFIG_APPID"; - - static { - Properties properties = CapaProperties.COMPONENT_PROPERTIES_SUPPLIER.apply("telemetry-common"); - - centerConfigAppId = properties.getProperty(TELEMETRY_COMPONENT_CENTER_CONFIG_APPID, centerConfigAppId); - } - - public static String getCenterConfigAppId() { - return centerConfigAppId; - } - - private Settings() { - } - } } diff --git a/sdk-component/src/main/java/group/rxcloud/capa/component/configstore/CapaConfigStore.java b/sdk-component/src/main/java/group/rxcloud/capa/component/configstore/CapaConfigStore.java index c4dd186..165aac4 100644 --- a/sdk-component/src/main/java/group/rxcloud/capa/component/configstore/CapaConfigStore.java +++ b/sdk-component/src/main/java/group/rxcloud/capa/component/configstore/CapaConfigStore.java @@ -29,11 +29,6 @@ */ public abstract class CapaConfigStore implements AutoCloseable { - /** - * Capa API used in this client. - */ - public static final String API_VERSION = "v1.0"; - /** * A utility class for serialize and deserialize the transient objects. */ diff --git a/sdk-component/src/main/java/group/rxcloud/capa/component/configstore/CapaConfigStoreBuilder.java b/sdk-component/src/main/java/group/rxcloud/capa/component/configstore/CapaConfigStoreBuilder.java index 3fd2c9e..1e235d0 100644 --- a/sdk-component/src/main/java/group/rxcloud/capa/component/configstore/CapaConfigStoreBuilder.java +++ b/sdk-component/src/main/java/group/rxcloud/capa/component/configstore/CapaConfigStoreBuilder.java @@ -17,7 +17,7 @@ package group.rxcloud.capa.component.configstore; -import group.rxcloud.capa.infrastructure.CapaClassLoader; +import group.rxcloud.capa.infrastructure.loader.CapaClassLoader; import group.rxcloud.capa.infrastructure.serializer.CapaObjectSerializer; import group.rxcloud.capa.infrastructure.serializer.DefaultObjectSerializer; diff --git a/sdk-component/src/main/java/group/rxcloud/capa/component/http/CapaHttpBuilder.java b/sdk-component/src/main/java/group/rxcloud/capa/component/http/CapaHttpBuilder.java index 2aca826..8b2649b 100644 --- a/sdk-component/src/main/java/group/rxcloud/capa/component/http/CapaHttpBuilder.java +++ b/sdk-component/src/main/java/group/rxcloud/capa/component/http/CapaHttpBuilder.java @@ -18,7 +18,7 @@ import group.rxcloud.capa.component.CapaRpcProperties; -import group.rxcloud.capa.infrastructure.CapaClassLoader; +import group.rxcloud.capa.infrastructure.loader.CapaClassLoader; import group.rxcloud.capa.infrastructure.serializer.CapaObjectSerializer; import group.rxcloud.capa.infrastructure.serializer.DefaultObjectSerializer; import okhttp3.OkHttpClient; diff --git a/sdk-component/src/main/java/group/rxcloud/capa/component/http/HttpResponse.java b/sdk-component/src/main/java/group/rxcloud/capa/component/http/HttpResponse.java index e0fc625..82537e1 100644 --- a/sdk-component/src/main/java/group/rxcloud/capa/component/http/HttpResponse.java +++ b/sdk-component/src/main/java/group/rxcloud/capa/component/http/HttpResponse.java @@ -45,8 +45,6 @@ public HttpResponse(T body, Map headers, int statusCode) { /** * Gets actual response data. - * - * @return */ public T getBody() { return body; @@ -54,8 +52,6 @@ public T getBody() { /** * Gets http headers. - * - * @return */ public Map getHeaders() { return headers; @@ -63,8 +59,6 @@ public Map getHeaders() { /** * Gets http invocation status code. - * - * @return */ public int getStatusCode() { return statusCode; diff --git a/sdk-component/src/main/java/group/rxcloud/capa/component/log/CapaLog4jAppenderAgent.java b/sdk-component/src/main/java/group/rxcloud/capa/component/log/CapaLog4jAppenderAgent.java index e2602ef..591b4b3 100644 --- a/sdk-component/src/main/java/group/rxcloud/capa/component/log/CapaLog4jAppenderAgent.java +++ b/sdk-component/src/main/java/group/rxcloud/capa/component/log/CapaLog4jAppenderAgent.java @@ -16,7 +16,7 @@ */ package group.rxcloud.capa.component.log; -import group.rxcloud.capa.infrastructure.CapaClassLoader; +import group.rxcloud.capa.infrastructure.loader.CapaClassLoader; import org.apache.logging.log4j.core.Appender; import org.apache.logging.log4j.core.Filter; import org.apache.logging.log4j.core.Layout; diff --git a/sdk-component/src/main/java/group/rxcloud/capa/component/log/CapaLogbackAppenderAgent.java b/sdk-component/src/main/java/group/rxcloud/capa/component/log/CapaLogbackAppenderAgent.java index bad5fd4..840b2ab 100644 --- a/sdk-component/src/main/java/group/rxcloud/capa/component/log/CapaLogbackAppenderAgent.java +++ b/sdk-component/src/main/java/group/rxcloud/capa/component/log/CapaLogbackAppenderAgent.java @@ -18,7 +18,7 @@ import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.UnsynchronizedAppenderBase; -import group.rxcloud.capa.infrastructure.CapaClassLoader; +import group.rxcloud.capa.infrastructure.loader.CapaClassLoader; /** * The agent of the logback impl. @@ -82,8 +82,7 @@ public interface CapaLogbackAppender { void append(ILoggingEvent event); /** - * - Do some initialization operations when the appender starts. + * Do some initialization operations when the appender starts. */ void doStart(); } diff --git a/sdk-component/src/main/java/group/rxcloud/capa/component/pubsub/CapaPubSubBuilder.java b/sdk-component/src/main/java/group/rxcloud/capa/component/pubsub/CapaPubSubBuilder.java index 3ed6f04..a028653 100644 --- a/sdk-component/src/main/java/group/rxcloud/capa/component/pubsub/CapaPubSubBuilder.java +++ b/sdk-component/src/main/java/group/rxcloud/capa/component/pubsub/CapaPubSubBuilder.java @@ -16,7 +16,7 @@ */ package group.rxcloud.capa.component.pubsub; -import group.rxcloud.capa.infrastructure.CapaClassLoader; +import group.rxcloud.capa.infrastructure.loader.CapaClassLoader; /** * A builder for the {@link CapaPubSub} implementor. diff --git a/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/context/CapaContext.java b/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/context/CapaContext.java deleted file mode 100644 index a00c310..0000000 --- a/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/context/CapaContext.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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. - */ -package group.rxcloud.capa.component.telemetry.context; - -import group.rxcloud.capa.infrastructure.utils.SpiUtils; - -import java.util.concurrent.Callable; -import java.util.concurrent.Executor; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.ScheduledExecutorService; - -/** - * Method for async context. - */ -public final class CapaContext { - - private static final CapaContextAsyncWrapper WRAPPER = getAsyncWrapper(); - - private CapaContext() { - } - - public static Runnable taskWrapping(Runnable runnable) { - return WRAPPER.wrap(runnable); - } - - public static Callable taskWrapping(Callable callable) { - return WRAPPER.wrap(callable); - } - - public static Executor taskWrapping(Executor executor) { - return WRAPPER.wrap(executor); - } - - public static ExecutorService taskWrapping(ExecutorService executor) { - return WRAPPER.wrap(executor); - } - - public static ScheduledExecutorService taskWrapping(ScheduledExecutorService executor) { - return WRAPPER.wrap(executor); - } - - public static String getTraceId() { - return WRAPPER.getTraceId(); - } - - private static CapaContextAsyncWrapper getAsyncWrapper() { - CapaContextAsyncWrapper WRAPPER = SpiUtils.loadFromSpiComponentFileNullable(CapaContextAsyncWrapper.class, "telemetry"); - if (WRAPPER == null) { - return new CapaContextAsyncWrapper() {}; - } - return WRAPPER; - } -} diff --git a/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/context/CapaContextAsyncWrapper.java b/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/context/CapaContextAsyncWrapper.java index 94fc790..6db2b7d 100644 --- a/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/context/CapaContextAsyncWrapper.java +++ b/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/context/CapaContextAsyncWrapper.java @@ -16,39 +16,78 @@ */ package group.rxcloud.capa.component.telemetry.context; -import io.opentelemetry.api.trace.Span; -import io.opentelemetry.context.Context; - import java.util.concurrent.Callable; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.ScheduledExecutorService; /** + * Method for async context. */ -public interface CapaContextAsyncWrapper { +public final class CapaContextAsyncWrapper { + + private static final CapaContextAsyncWrapperPlugin WRAPPER_PLUGIN = CapaContextAsyncWrapperPlugin.loadPlugin(); + + private CapaContextAsyncWrapper() { + } - default Runnable wrap(Runnable runnable) { - return Context.current().wrap(runnable); + /** + * Task wrapping runnable. + * + * @param runnable the runnable + * @return the runnable + */ + public static Runnable taskWrapping(Runnable runnable) { + return WRAPPER_PLUGIN.wrap(runnable); } - default Callable wrap(Callable callable) { - return Context.current().wrap(callable); + /** + * Task wrapping callable. + * + * @param the type parameter + * @param callable the callable + * @return the callable + */ + public static Callable taskWrapping(Callable callable) { + return WRAPPER_PLUGIN.wrap(callable); } - default Executor wrap(Executor executor) { - return Context.current().wrap(executor); + /** + * Task wrapping executor. + * + * @param executor the executor + * @return the executor + */ + public static Executor taskWrapping(Executor executor) { + return WRAPPER_PLUGIN.wrap(executor); } - default ExecutorService wrap(ExecutorService executor) { - return Context.current().wrap(executor); + /** + * Task wrapping executor service. + * + * @param executor the executor + * @return the executor service + */ + public static ExecutorService taskWrapping(ExecutorService executor) { + return WRAPPER_PLUGIN.wrap(executor); } - default ScheduledExecutorService wrap(ScheduledExecutorService executor) { - return Context.current().wrap(executor); + /** + * Task wrapping scheduled executor service. + * + * @param executor the executor + * @return the scheduled executor service + */ + public static ScheduledExecutorService taskWrapping(ScheduledExecutorService executor) { + return WRAPPER_PLUGIN.wrap(executor); } - default String getTraceId() { - return Span.fromContext(Context.current()).getSpanContext().getTraceId(); + /** + * Gets trace id. + * + * @return the trace id + */ + public static String getTraceId() { + return WRAPPER_PLUGIN.getTraceId(); } } diff --git a/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/context/CapaContextAsyncWrapperPlugin.java b/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/context/CapaContextAsyncWrapperPlugin.java new file mode 100644 index 0000000..c621645 --- /dev/null +++ b/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/context/CapaContextAsyncWrapperPlugin.java @@ -0,0 +1,120 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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. + */ +package group.rxcloud.capa.component.telemetry.context; + +import group.rxcloud.capa.infrastructure.plugin.PluginLoader; +import io.opentelemetry.api.trace.Span; +import io.opentelemetry.context.Context; + +import java.util.concurrent.Callable; +import java.util.concurrent.Executor; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.ScheduledExecutorService; + +/** + * The Capa context async wrapper plugin. + */ +public interface CapaContextAsyncWrapperPlugin { + + static CapaContextAsyncWrapperPlugin loadPlugin() { + return PluginLoader.loadPluginImpl(CapaContextAsyncWrapperPlugin.class, CapaContextAsyncWrapperPlugin.CapaContextAsyncWrapperDefault::new); + } + + /** + * Wrap runnable. + * + * @param runnable the runnable + * @return the runnable + */ + Runnable wrap(Runnable runnable); + + /** + * Wrap callable. + * + * @param the type parameter + * @param callable the callable + * @return the callable + */ + Callable wrap(Callable callable); + + /** + * Wrap executor. + * + * @param executor the executor + * @return the executor + */ + Executor wrap(Executor executor); + + /** + * Wrap executor service. + * + * @param executor the executor + * @return the executor service + */ + ExecutorService wrap(ExecutorService executor); + + /** + * Wrap scheduled executor service. + * + * @param executor the executor + * @return the scheduled executor service + */ + ScheduledExecutorService wrap(ScheduledExecutorService executor); + + /** + * Gets trace id. + * + * @return the trace id + */ + String getTraceId(); + + /** + * The Capa context async wrapper default. + */ + class CapaContextAsyncWrapperDefault implements CapaContextAsyncWrapperPlugin { + + @Override + public Runnable wrap(Runnable runnable) { + return Context.current().wrap(runnable); + } + + @Override + public Callable wrap(Callable callable) { + return Context.current().wrap(callable); + } + + @Override + public Executor wrap(Executor executor) { + return Context.current().wrap(executor); + } + + @Override + public ExecutorService wrap(ExecutorService executor) { + return Context.current().wrap(executor); + } + + @Override + public ScheduledExecutorService wrap(ScheduledExecutorService executor) { + return Context.current().wrap(executor); + } + + @Override + public String getTraceId() { + return Span.fromContext(Context.current()).getSpanContext().getTraceId(); + } + } +} diff --git a/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/context/CapaContextPropagatorBuilder.java b/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/context/CapaContextPropagatorBuilder.java index c364272..6daab93 100644 --- a/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/context/CapaContextPropagatorBuilder.java +++ b/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/context/CapaContextPropagatorBuilder.java @@ -16,7 +16,7 @@ */ package group.rxcloud.capa.component.telemetry.context; -import group.rxcloud.capa.infrastructure.utils.SpiUtils; +import group.rxcloud.capa.infrastructure.loader.CapaClassLoader; import io.opentelemetry.context.propagation.ContextPropagators; import io.opentelemetry.context.propagation.TextMapPropagator; @@ -28,32 +28,7 @@ * Builder for capa context propagator. */ @NotThreadSafe -public class CapaContextPropagatorBuilder implements CapaContextPropagatorSettings { - - /** - * Context config. - */ - private ContextConfig contextConfig; - - /** - * Context propagator instances. - */ - private List contextPropagatorsInstance; - - @Override - public CapaContextPropagatorBuilder setContextConfig(ContextConfig config) { - contextConfig = config; - return this; - } - - @Override - public CapaContextPropagatorBuilder addContextPropagators(TextMapPropagator processor) { - if (contextPropagatorsInstance == null) { - contextPropagatorsInstance = new ArrayList<>(); - } - contextPropagatorsInstance.add(processor); - return this; - } +public class CapaContextPropagatorBuilder { /** * Build context propagators. @@ -61,38 +36,20 @@ public CapaContextPropagatorBuilder addContextPropagators(TextMapPropagator proc * @return context propagators. */ public ContextPropagators buildContextPropagators() { - List propagators = new ArrayList<>(); - initContextConfig(); - if (contextConfig != null) { - List types = contextConfig.getContextPropagators(); - if (types != null && !types.isEmpty()) { - types.stream() - .map(path -> SpiUtils.newInstanceWithConstructorCache(path, TextMapPropagator.class)) - .forEach(propagator -> propagators.add(propagator)); - } - } + List contextPropagatorsInstance = new ArrayList<>(); - if (contextPropagatorsInstance != null && !contextPropagatorsInstance.isEmpty()) { - propagators.addAll(contextPropagatorsInstance); + ContextPropagatorLoader loader = CapaClassLoader.loadComponentClassObj("telemetry-common", ContextPropagatorLoader.class); + List loaded = loader.load(); + if (loaded != null) { + contextPropagatorsInstance.addAll(loaded); } - ContextPropagatorLoader loader = SpiUtils.loadFromSpiComponentFileNullable(ContextPropagatorLoader.class, "telemetry"); - if (loader != null) { - List loaded = loader.load(); - if (loaded != null) { - propagators.addAll(loaded); - } - } - - if (propagators.isEmpty()) { + if (contextPropagatorsInstance.isEmpty()) { return ContextPropagators.noop(); } - return ContextPropagators.create(TextMapPropagator.composite(propagators.toArray(new TextMapPropagator[0]))); - } - private void initContextConfig() { - if (contextConfig == null) { - contextConfig = SpiUtils.loadConfigNullable(FILE_PATH, ContextConfig.class);; - } + TextMapPropagator[] textMapPropagators = contextPropagatorsInstance.toArray(new TextMapPropagator[0]); + TextMapPropagator textPropagator = TextMapPropagator.composite(textMapPropagators); + return ContextPropagators.create(textPropagator); } } diff --git a/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/context/CapaContextPropagatorSettings.java b/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/context/CapaContextPropagatorSettings.java deleted file mode 100644 index 93b2c68..0000000 --- a/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/context/CapaContextPropagatorSettings.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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. - */ -package group.rxcloud.capa.component.telemetry.context; - -import io.opentelemetry.context.propagation.TextMapPropagator; - -/** - * Settings for capa context propagator. - */ -public interface CapaContextPropagatorSettings { - - String FILE_PATH = "/capa-component-telemetry-context.json"; - - /** - * Replace the whole context config. - * - * @param config context config - * @return current settings. - */ - CapaContextPropagatorSettings setContextConfig(ContextConfig config); - - /** - * Add one more processor to current context config. - * - * @param processor processor config - * @return current settings. - */ - CapaContextPropagatorSettings addContextPropagators(TextMapPropagator processor); -} diff --git a/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/context/ContextConfig.java b/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/context/ContextConfig.java deleted file mode 100644 index 5b17317..0000000 --- a/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/context/ContextConfig.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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. - */ -package group.rxcloud.capa.component.telemetry.context; - -import java.io.Serializable; -import java.util.List; - -/** - * Config for context propagators. - */ -public class ContextConfig implements Serializable { - - private static final long serialVersionUID = 6587103489345563395L; - - private List contextPropagators; - - public List getContextPropagators() { - return contextPropagators; - } - - public void setContextPropagators(List contextPropagators) { - this.contextPropagators = contextPropagators; - } -} diff --git a/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/context/ContextPropagatorLoader.java b/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/context/ContextPropagatorLoader.java index ab69cff..fd99133 100644 --- a/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/context/ContextPropagatorLoader.java +++ b/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/context/ContextPropagatorLoader.java @@ -26,9 +26,6 @@ */ public interface ContextPropagatorLoader { - ContextPropagatorLoader DEFAULT = new ContextPropagatorLoader() { - }; - /** * Load default context propagator. * diff --git a/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/metrics/CapaDoubleHistogram.java b/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/metrics/CapaDoubleHistogram.java index 4828001..0ca2a65 100644 --- a/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/metrics/CapaDoubleHistogram.java +++ b/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/metrics/CapaDoubleHistogram.java @@ -18,8 +18,6 @@ import io.opentelemetry.api.metrics.DoubleHistogram; -/** - */ public abstract class CapaDoubleHistogram implements DoubleHistogram { protected final String meterName; diff --git a/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/metrics/CapaDoubleHistogramBuilder.java b/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/metrics/CapaDoubleHistogramBuilder.java index 6fafd87..d36c285 100644 --- a/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/metrics/CapaDoubleHistogramBuilder.java +++ b/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/metrics/CapaDoubleHistogramBuilder.java @@ -21,9 +21,6 @@ import io.opentelemetry.api.metrics.LongHistogramBuilder; import io.opentelemetry.api.metrics.internal.NoopMeter; -/** - * - */ public class CapaDoubleHistogramBuilder implements DoubleHistogramBuilder { protected final String meterName; diff --git a/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/metrics/CapaLongHistogram.java b/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/metrics/CapaLongHistogram.java index a3d750d..2daddfe 100644 --- a/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/metrics/CapaLongHistogram.java +++ b/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/metrics/CapaLongHistogram.java @@ -18,8 +18,6 @@ import io.opentelemetry.api.metrics.LongHistogram; -/** - */ public abstract class CapaLongHistogram implements LongHistogram { protected final String meterName; diff --git a/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/metrics/CapaLongHistogramBuilder.java b/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/metrics/CapaLongHistogramBuilder.java index 508c943..3bac0a2 100644 --- a/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/metrics/CapaLongHistogramBuilder.java +++ b/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/metrics/CapaLongHistogramBuilder.java @@ -21,9 +21,6 @@ import io.opentelemetry.api.metrics.LongHistogramBuilder; import io.opentelemetry.api.metrics.internal.NoopMeter; -/** - * - */ public class CapaLongHistogramBuilder implements LongHistogramBuilder { private final String meterName; @@ -60,7 +57,7 @@ public LongHistogramBuilder setUnit(String unit) { @Override public DoubleHistogramBuilder ofDoubles() { return new CapaDoubleHistogramBuilder(meterName, schemaUrl, version, name).setDescription(description) - .setUnit(unit); + .setUnit(unit); } @Override diff --git a/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/metrics/CapaMeter.java b/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/metrics/CapaMeter.java index b2201aa..275859e 100644 --- a/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/metrics/CapaMeter.java +++ b/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/metrics/CapaMeter.java @@ -24,8 +24,6 @@ import javax.annotation.concurrent.NotThreadSafe; -/** - */ @NotThreadSafe public class CapaMeter implements Meter { diff --git a/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/metrics/CapaMeterProviderBuilder.java b/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/metrics/CapaMeterProviderBuilder.java index 160bd28..b4dfb01 100644 --- a/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/metrics/CapaMeterProviderBuilder.java +++ b/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/metrics/CapaMeterProviderBuilder.java @@ -17,11 +17,11 @@ package group.rxcloud.capa.component.telemetry.metrics; import group.rxcloud.capa.component.telemetry.SamplerConfig; +import group.rxcloud.capa.infrastructure.loader.CapaClassLoader; import group.rxcloud.capa.infrastructure.utils.SpiUtils; import io.opentelemetry.api.metrics.MeterProvider; import io.opentelemetry.sdk.metrics.SdkMeterProvider; import io.opentelemetry.sdk.metrics.SdkMeterProviderBuilder; -import io.opentelemetry.sdk.metrics.export.MetricExporter; import io.opentelemetry.sdk.metrics.export.MetricReaderFactory; import io.opentelemetry.sdk.metrics.export.PeriodicMetricReader; import org.jetbrains.annotations.NotNull; @@ -32,28 +32,38 @@ import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; -import java.util.function.Supplier; /** * Builder for capa metric provider. */ @NotThreadSafe -public class CapaMeterProviderBuilder implements CapaMeterProviderSettings { +public class CapaMeterProviderBuilder { /** - * Config for capa metric provider. + * Build the meter provider with the config. + * In the following cases, a noop implementation will be returned and no new thread will be started. + * 1. No metrics reader was defined. + * + * @return the meter provider. */ - private MeterConfig meterConfigs; + public MeterProvider buildMeterProvider() { + MeterConfigLoader meterConfigsLoader = CapaClassLoader.loadComponentClassObj("telemetry-common", MeterConfigLoader.class); - /** - * Sampler config. - */ - private Supplier samplerConfig = SamplerConfig.DEFAULT_SUPPLIER; + List metricsReaderConfigs = meterConfigsLoader.getReaders(); + if (metricsReaderConfigs == null || metricsReaderConfigs.isEmpty()) { + return MeterProvider.noop(); + } - /** - * Readers manually set. - */ - private List metricsReaderConfigs; + SamplerConfig samplerConfig = meterConfigsLoader.getSamplerConfig(); + List factories = bulidReaderFactories(metricsReaderConfigs, samplerConfig); + + + SdkMeterProviderBuilder builder = SdkMeterProvider.builder() + .setExemplarFilter(new CapaMetricsSampler(samplerConfig)); + factories.forEach(f -> builder.registerMetricReader(f)); + SdkMeterProvider provider = builder.build(); + return new CapaMeterProvider(provider); + } /** * Build the reader factories with reader configs. @@ -62,93 +72,27 @@ public class CapaMeterProviderBuilder implements CapaMeterProviderSettings { * @param readerConfigs metrics reader configs. * @return metrics reader factories. */ - private static List bulidReaderFactories(List readerConfigs, - Supplier samplerConfig) { + private List bulidReaderFactories(List readerConfigs, + SamplerConfig samplerConfig) { List factories = new ArrayList<>(); - for (MetricsReaderConfig config : readerConfigs) { - MetricExporter exporter = SpiUtils - .newInstance(config.getExporterType(), CapaMetricsExporter.class, new Class[]{Supplier.class}, - new Object[]{samplerConfig}, false); - if (exporter == null) { - throw new IllegalArgumentException( - "Metric Exporter is not configured. readerName = " + config.getName() + '.'); - } + for (CapaMetricsExporter exporter : readerConfigs) { ScheduledThreadPoolExecutor worker = new ScheduledThreadPoolExecutor(1, new ThreadFactory() { @Override public Thread newThread(@NotNull Runnable r) { Thread thread = new Thread(r); thread.setDaemon(true); - thread.setName("capa-metric-reader-" + config.getName() + '-' + System + thread.setName("capa-metric-reader-" + exporter.getName() + '-' + System .currentTimeMillis()); return thread; } }); factories.add(PeriodicMetricReader.builder(exporter) - .setInterval(config.getExportIntervalMillis(), TimeUnit.MILLISECONDS) - .setExecutor(worker) - .newMetricReaderFactory()); + .setInterval(exporter.getExportIntervalMillis(), TimeUnit.MILLISECONDS) + .setExecutor(worker) + .newMetricReaderFactory()); } return factories; } - - @Override - public CapaMeterProviderBuilder setSamplerConfig(Supplier samplerConfig) { - this.samplerConfig = samplerConfig; - return this; - } - - @Override - public CapaMeterProviderBuilder setMeterConfig(MeterConfig config) { - meterConfigs = config; - return this; - } - - @Override - public CapaMeterProviderBuilder addMetricReaderConfig(MetricsReaderConfig config) { - if (metricsReaderConfigs == null) { - metricsReaderConfigs = new ArrayList<>(); - } - metricsReaderConfigs.add(config); - return this; - } - - /** - * Build the meter provider with the config. - * In the following cases, a noop implementation will be returned and no new thread will be started. - * 1. No metrics reader was defined. - * - * @return the meter provider. - */ - public MeterProvider buildMeterProvider() { - List metricsReaderConfigs = this.metricsReaderConfigs; - if (metricsReaderConfigs == null || metricsReaderConfigs.isEmpty()) { - // if config was not explicitly set, try loading the config from the config loader. - initMeterConfig(); - - if (meterConfigs != null) { - metricsReaderConfigs = meterConfigs.getReaders(); - } - } - - if (metricsReaderConfigs == null || metricsReaderConfigs.isEmpty()) { - return MeterProvider.noop(); - } - - List factories = bulidReaderFactories(metricsReaderConfigs, samplerConfig); - - - SdkMeterProviderBuilder builder = SdkMeterProvider.builder() - .setExemplarFilter(new CapaMetricsSampler(samplerConfig)); - factories.forEach(f -> builder.registerMetricReader(f)); - SdkMeterProvider provider = builder.build(); - return new CapaMeterProvider(provider); - } - - private void initMeterConfig() { - if (meterConfigs == null) { - meterConfigs = SpiUtils.loadConfigNullable(FILE_PATH, MeterConfig.class); - } - } } diff --git a/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/metrics/CapaMeterProviderSettings.java b/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/metrics/CapaMeterProviderSettings.java deleted file mode 100644 index 3b36b63..0000000 --- a/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/metrics/CapaMeterProviderSettings.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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. - */ -package group.rxcloud.capa.component.telemetry.metrics; - -import group.rxcloud.capa.component.telemetry.SamplerConfig; - -import java.util.function.Supplier; - -/** - * Settings for capa meter provider. - */ -public interface CapaMeterProviderSettings { - - String FILE_PATH ="/capa-component-telemetry-meter.json"; - - /** - * Replace the whole config for the meter. - * - * @param config meter config. - * @return current settings. - */ - CapaMeterProviderSettings setMeterConfig(MeterConfig config); - - /** - * Add one more reader to current meter config. - * - * @param config metrics reader config. - * @return current settings. - */ - CapaMeterProviderSettings addMetricReaderConfig(MetricsReaderConfig config); - - /** - * Set sample config. - * - * @param samplerConfig sample config. - * @return current settings. - */ - CapaMeterProviderSettings setSamplerConfig(Supplier samplerConfig); -} diff --git a/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/metrics/CapaMeterWrapper.java b/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/metrics/CapaMeterWrapper.java index 07b6e75..6b6b564 100644 --- a/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/metrics/CapaMeterWrapper.java +++ b/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/metrics/CapaMeterWrapper.java @@ -39,12 +39,7 @@ static CapaMeter wrap(String meterName, String schemaUrl, String version, Meter if (meter instanceof CapaMeter) { return (CapaMeter) meter; } - CapaMeter result = SpiUtils.loadFromSpiComponentFileNullable(CapaMeter.class, - new Class[]{String.class, String.class, String.class, Meter.class}, - new Object[]{meterName, schemaUrl, version, meter}, FILE_SUFFIX, CACHE); - if (result == null) { - result = new CapaMeter(meterName, schemaUrl, version, meter); - } + CapaMeter result = new CapaMeter(meterName, schemaUrl, version, meter); return result; } diff --git a/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/metrics/CapaMetricsExporter.java b/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/metrics/CapaMetricsExporter.java index 3ce214e..f0405f2 100644 --- a/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/metrics/CapaMetricsExporter.java +++ b/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/metrics/CapaMetricsExporter.java @@ -22,14 +22,14 @@ import io.opentelemetry.sdk.metrics.export.MetricExporter; import java.util.Collection; +import java.util.concurrent.TimeUnit; import java.util.function.Supplier; -/** - * - */ public abstract class CapaMetricsExporter implements MetricExporter { + private String name; private Supplier samplerConfig; + private long exportIntervalMillis = TimeUnit.MINUTES.toMillis(1L); public CapaMetricsExporter(Supplier samplerConfig) { this.samplerConfig = samplerConfig; @@ -58,4 +58,16 @@ public CompletableResultCode flush() { protected abstract CompletableResultCode doExport(Collection metrics); protected abstract CompletableResultCode doFlush(); + + public String getName() { + return name; + } + + public Supplier getSamplerConfig() { + return samplerConfig; + } + + public long getExportIntervalMillis() { + return exportIntervalMillis; + } } diff --git a/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/metrics/MeterConfig.java b/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/metrics/MeterConfigLoader.java similarity index 70% rename from sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/metrics/MeterConfig.java rename to sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/metrics/MeterConfigLoader.java index aa91b1f..9c3b876 100644 --- a/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/metrics/MeterConfig.java +++ b/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/metrics/MeterConfigLoader.java @@ -16,28 +16,21 @@ */ package group.rxcloud.capa.component.telemetry.metrics; -import java.io.Serializable; -import java.util.Collections; +import group.rxcloud.capa.component.telemetry.SamplerConfig; + import java.util.List; /** * Config for meters. */ -public class MeterConfig implements Serializable { - - private static final long serialVersionUID = 7090415828392034412L; +public interface MeterConfigLoader { /** * Configs for metrics readers. * Each reader related with a scheduled thread. */ - private List readers = Collections.emptyList(); - public List getReaders() { - return readers; - } + List getReaders(); - public void setReaders(List readers) { - this.readers = readers; - } + SamplerConfig getSamplerConfig(); } diff --git a/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/metrics/MetricsReaderConfig.java b/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/metrics/MetricsReaderConfig.java index aff868b..cdd62e1 100644 --- a/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/metrics/MetricsReaderConfig.java +++ b/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/metrics/MetricsReaderConfig.java @@ -43,10 +43,6 @@ public class MetricsReaderConfig implements Serializable { */ private String exporterType; - public String getExporterType() { - return exporterType; - } - public void setExporterType(String exporterType) { this.exporterType = exporterType; } diff --git a/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/trace/CapaReadWriteSpan.java b/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/trace/CapaReadWriteSpan.java index 5a9f137..af47f7c 100644 --- a/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/trace/CapaReadWriteSpan.java +++ b/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/trace/CapaReadWriteSpan.java @@ -35,11 +35,8 @@ public class CapaReadWriteSpan implements ReadWriteSpan { protected final ReadWriteSpan span; - protected final String tracerName; - protected final String version; - protected final String schemaUrl; public CapaReadWriteSpan(String tracerName, String version, String schemaUrl, ReadWriteSpan span) { diff --git a/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/trace/CapaSpanBuilder.java b/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/trace/CapaSpanBuilder.java index 9053817..a6c98af 100644 --- a/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/trace/CapaSpanBuilder.java +++ b/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/trace/CapaSpanBuilder.java @@ -33,17 +33,13 @@ public class CapaSpanBuilder implements SpanBuilder { protected final String tracerName; + protected final String spanName; + protected final SpanBuilder spanBuilder; protected String version; - protected String schemaUrl; - protected final String spanName; - - protected final SpanBuilder spanBuilder; - - public CapaSpanBuilder(String tracerName, String version, String schemaUrl, String spanName, - SpanBuilder spanBuilder) { + public CapaSpanBuilder(String tracerName, String version, String schemaUrl, String spanName, SpanBuilder spanBuilder) { this.tracerName = tracerName; this.version = version; this.schemaUrl = schemaUrl; @@ -51,14 +47,6 @@ public CapaSpanBuilder(String tracerName, String version, String schemaUrl, Stri this.spanBuilder = spanBuilder; } - public String getSchemaUrl() { - return schemaUrl; - } - - public String getVersion() { - return version; - } - @Override public SpanBuilder setParent(Context context) { spanBuilder.setParent(context); @@ -129,7 +117,8 @@ public SpanBuilder setStartTimestamp(long startTimestamp, TimeUnit unit) { public Span startSpan() { Span span = spanBuilder.startSpan(); if (span instanceof ReadWriteSpan) { - return CapaTracerWrapper.wrap(tracerName, version, schemaUrl, (ReadWriteSpan) span); + // plugin: wrap + return CapaTracerWrapperPlugin.loadPlugin().wrap(tracerName, version, schemaUrl, (ReadWriteSpan) span); } return span; } diff --git a/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/trace/CapaTraceSampler.java b/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/trace/CapaTraceSampler.java index 2fc563b..7984d6b 100644 --- a/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/trace/CapaTraceSampler.java +++ b/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/trace/CapaTraceSampler.java @@ -25,7 +25,6 @@ import io.opentelemetry.sdk.trace.samplers.SamplingResult; import java.util.List; -import java.util.function.Supplier; /** * Sampler for trace data. @@ -33,21 +32,17 @@ */ public class CapaTraceSampler implements Sampler { - private final Supplier samplerConfigSupplier; + private final SamplerConfig samplerConfig; - public CapaTraceSampler(Supplier samplerConfigSupplier) { - if (samplerConfigSupplier == null) { - samplerConfigSupplier = () -> SamplerConfig.DEFAULT_CONFIG; - } - this.samplerConfigSupplier = samplerConfigSupplier; + public CapaTraceSampler(SamplerConfig samplerConfig) { + this.samplerConfig = samplerConfig; } @Override public SamplingResult shouldSample(Context context, String traceId, String name, SpanKind kind, Attributes attributes, List list) { Sampler sampler = Sampler.alwaysOn(); - SamplerConfig config = samplerConfigSupplier.get(); - if (config != null && !config.isTraceEnable()) { + if (samplerConfig != null && !samplerConfig.isTraceEnable()) { sampler = Sampler.alwaysOff(); } return sampler.shouldSample(context, traceId, name, kind, attributes, list); diff --git a/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/trace/CapaTracer.java b/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/trace/CapaTracer.java index a048ee7..c78a99c 100644 --- a/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/trace/CapaTracer.java +++ b/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/trace/CapaTracer.java @@ -39,7 +39,8 @@ public CapaTracer(String tracerName, String version, String schemaUrl, Tracer tr @Override public SpanBuilder spanBuilder(String spanName) { SpanBuilder builder = tracer.spanBuilder(spanName); - return CapaTracerWrapper.wrap(tracerName, version, schemaUrl, spanName, builder); + // plugin: wrap + return CapaTracerWrapperPlugin.loadPlugin().wrap(tracerName, version, schemaUrl, spanName, builder); } public String getVersion() { diff --git a/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/trace/CapaTracerBuilder.java b/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/trace/CapaTracerBuilder.java index 6e46ea6..17d2410 100644 --- a/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/trace/CapaTracerBuilder.java +++ b/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/trace/CapaTracerBuilder.java @@ -25,11 +25,9 @@ public class CapaTracerBuilder implements TracerBuilder { protected final TracerBuilder tracerBuilder; - protected final String tracerName; protected String version; - protected String schemaUrl; public CapaTracerBuilder(String tracerName, TracerBuilder tracerBuilder) { @@ -53,6 +51,8 @@ public TracerBuilder setInstrumentationVersion(String instrumentationVersion) { @Override public Tracer build() { - return CapaTracerWrapper.wrap(tracerName, version, schemaUrl, tracerBuilder.build()); + Tracer tracer = tracerBuilder.build(); + // plugin: wrap + return CapaTracerWrapperPlugin.loadPlugin().wrap(tracerName, version, schemaUrl, tracer); } } diff --git a/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/trace/CapaTracerProvider.java b/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/trace/CapaTracerProvider.java index ad72469..b9b78f8 100644 --- a/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/trace/CapaTracerProvider.java +++ b/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/trace/CapaTracerProvider.java @@ -33,17 +33,21 @@ public CapaTracerProvider(TracerProvider provider) { @Override public Tracer get(String instrumentationName) { - return tracerBuilder(instrumentationName).build(); + return tracerBuilder(instrumentationName) + .build(); } @Override public Tracer get(String instrumentationName, String instrumentationVersion) { - return tracerBuilder(instrumentationName).setInstrumentationVersion(instrumentationVersion).build(); + return tracerBuilder(instrumentationName) + .setInstrumentationVersion(instrumentationVersion) + .build(); } @Override public TracerBuilder tracerBuilder(String instrumentationName) { TracerBuilder tracerBuilder = provider.tracerBuilder(instrumentationName); - return CapaTracerWrapper.wrap(instrumentationName, tracerBuilder); + // plugin: wrap + return CapaTracerWrapperPlugin.loadPlugin().wrap(instrumentationName, tracerBuilder); } } diff --git a/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/trace/CapaTracerProviderBuilder.java b/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/trace/CapaTracerProviderBuilder.java index 00a9530..ca9ed22 100644 --- a/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/trace/CapaTracerProviderBuilder.java +++ b/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/trace/CapaTracerProviderBuilder.java @@ -17,9 +17,9 @@ package group.rxcloud.capa.component.telemetry.trace; import group.rxcloud.capa.component.telemetry.SamplerConfig; +import group.rxcloud.capa.infrastructure.loader.CapaClassLoader; import group.rxcloud.capa.infrastructure.exceptions.CapaErrorContext; import group.rxcloud.capa.infrastructure.exceptions.CapaException; -import group.rxcloud.capa.infrastructure.utils.SpiUtils; import io.opentelemetry.api.trace.TracerProvider; import io.opentelemetry.sdk.trace.IdGenerator; import io.opentelemetry.sdk.trace.SdkTracerProvider; @@ -31,42 +31,83 @@ import javax.annotation.concurrent.NotThreadSafe; import java.lang.reflect.Field; -import java.util.ArrayList; import java.util.List; -import java.util.function.Supplier; /** * Builder for capa tracer provider. */ @NotThreadSafe -public class CapaTracerProviderBuilder implements CapaTracerProviderSettings { +public class CapaTracerProviderBuilder { /** - * Config for capa tracer provider. + * Build the tracer provider with the config. + * In the following cases, a noop implementation will be returned. + * 1. No processor config was defined. + * + * @return the meter provider. */ - private TracerConfig tracerConfig; + public CapaTracerProvider buildTracerProvider() { + TracerConfigLoader tracerConfigLoader = CapaClassLoader.loadComponentClassObj("telemetry-common", TracerConfigLoader.class); - /** - * Id generator instance. - */ - private IdGenerator idGenerator; + if (tracerConfigLoader.getProcessors() == null || tracerConfigLoader.getProcessors().isEmpty()) { + return new CapaTracerProvider(TracerProvider.noop()); + } - /** - * Span processor instances. - */ - private List processors; + SdkTracerProviderBuilder builder = SdkTracerProvider.builder(); + this.addSpanLimits(builder, tracerConfigLoader); + this.addIdGenerator(builder, tracerConfigLoader); + this.addSampler(builder, tracerConfigLoader); + this.addProcessors(builder, tracerConfigLoader); - /** - * Span limits. - */ - private SpanLimitsConfig spanLimitsConfig; + SdkTracerProvider provider = builder.build(); - /** - * Sampler config. - */ - private Supplier samplerConfig = SamplerConfig.DEFAULT_SUPPLIER; + if (tracerConfigLoader != null && !tracerConfigLoader.isEnableIdValidate()) { + InnerModule.skipIdValidate(provider); + } + + return new CapaTracerProvider(provider); + } + + private void addSpanLimits(SdkTracerProviderBuilder builder, TracerConfigLoader tracerConfigLoader) { + SpanLimitsBuilder limits = SpanLimits.builder(); + + SpanLimitsConfig spanLimits = tracerConfigLoader.getSpanLimits(); + if (spanLimits != null) { + boolean added = addSpanLimits(spanLimits, limits); + if (added) { + builder.setSpanLimits(limits.build()); + } + } + } - private static boolean addSpanLimits(SpanLimitsConfig spanLimits, SpanLimitsBuilder limits) { + private void addIdGenerator(SdkTracerProviderBuilder builder, TracerConfigLoader tracerConfigLoader) { + IdGenerator idGenerator = tracerConfigLoader.getIdGenerator(); + if (idGenerator != null) { + builder.setIdGenerator(idGenerator); + } + } + + private void addSampler(SdkTracerProviderBuilder builder, TracerConfigLoader tracerConfigLoader) { + SamplerConfig samplerConfig = tracerConfigLoader.getSamplerConfig(); + CapaTraceSampler root = new CapaTraceSampler(samplerConfig); + Sampler sampler = Sampler.parentBased(root); + builder.setSampler(sampler); + } + + private void addProcessors(SdkTracerProviderBuilder builder, TracerConfigLoader tracerConfigLoader) { + if (tracerConfigLoader != null) { + List processors = tracerConfigLoader.getProcessors(); + if (processors != null) { + processors.forEach(processor -> { + if (processor != null) { + builder.addSpanProcessor(processor); + } + }); + } + } + } + + private boolean addSpanLimits(SpanLimitsConfig spanLimits, SpanLimitsBuilder limits) { if (spanLimits == null) { return false; } @@ -97,13 +138,18 @@ private static boolean addSpanLimits(SpanLimitsConfig spanLimits, SpanLimitsBuil } return added; } +} + +interface InnerModule { - private static void skipIdValidate(SdkTracerProvider provider) { + static void skipIdValidate(SdkTracerProvider provider) { try { Field fieldTracerSharedState = SdkTracerProvider.class.getDeclaredField("sharedState"); fieldTracerSharedState.setAccessible(true); + Object sharedStatus = fieldTracerSharedState.get(provider); Class sharedStatusType = sharedStatus.getClass(); + Field fieldFlag = sharedStatusType.getDeclaredField("idGeneratorSafeToSkipIdValidation"); fieldFlag.setAccessible(true); fieldFlag.set(sharedStatus, true); @@ -111,121 +157,4 @@ private static void skipIdValidate(SdkTracerProvider provider) { throw new CapaException(CapaErrorContext.SYSTEM_ERROR, "Fail to skip id validation.", e); } } - - @Override - public CapaTracerProviderBuilder setSamplerConfig(Supplier samplerConfig) { - this.samplerConfig = samplerConfig; - return this; - } - - @Override - public CapaTracerProviderBuilder setTracerConfig(TracerConfig tracerConfig) { - this.tracerConfig = tracerConfig; - return this; - } - - @Override - public CapaTracerProviderBuilder setSpanLimits(SpanLimitsConfig spanLimits) { - spanLimitsConfig = spanLimits; - return this; - } - - @Override - public CapaTracerProviderBuilder setIdGenerator(IdGenerator idGenerator) { - this.idGenerator = idGenerator; - return this; - } - - @Override - public CapaTracerProviderBuilder addProcessor(SpanProcessor processor) { - if (processors == null) { - processors = new ArrayList<>(); - } - processors.add(processor); - return this; - } - - private void initTracerConfig() { - if (tracerConfig == null) { - tracerConfig = SpiUtils.loadConfigNullable(CapaTracerProviderSettings.FILE_PATH, TracerConfig.class); - } - } - - /** - * Build the tracer provider with the config. - * In the following cases, a noop implementation will be returned. - * 1. No processor config was defined. - * - * @return the meter provider. - */ - public CapaTracerProvider buildTracerProvider() { - // if config was not explicitly set, try loading the config from the config loader. - initTracerConfig(); - - if ((processors == null || processors.isEmpty()) && (tracerConfig == null - || tracerConfig.getProcessors() == null - || tracerConfig.getProcessors().isEmpty())) { - return new CapaTracerProvider(TracerProvider.noop()); - } - - SdkTracerProviderBuilder builder = SdkTracerProvider.builder(); - addSpanLimits(builder); - addIdGenerator(builder); - addSampler(builder); - addProcessors(builder); - - SdkTracerProvider provider = builder.build(); - - if (tracerConfig != null && !tracerConfig.isEnableIdValidate()) { - skipIdValidate(provider); - } - - return new CapaTracerProvider(provider); - } - - private void addIdGenerator(SdkTracerProviderBuilder builder) { - if (idGenerator != null) { - builder.setIdGenerator(idGenerator); - } else if (tracerConfig != null) { - IdGenerator generator = SpiUtils - .newInstanceWithConstructorCache(tracerConfig.getIdGenerator(), IdGenerator.class); - if (generator != null) { - builder.setIdGenerator(generator); - } - } - } - - private void addSpanLimits(SdkTracerProviderBuilder builder) { - SpanLimitsBuilder limits = SpanLimits.builder(); - boolean added = false; - if (tracerConfig != null && tracerConfig.getSpanLimits() != null) { - added |= addSpanLimits(tracerConfig.getSpanLimits(), limits); - } - if (spanLimitsConfig != null) { - added |= addSpanLimits(spanLimitsConfig, limits); - } - - if (added) { - builder.setSpanLimits(limits.build()); - } - } - - private void addSampler(SdkTracerProviderBuilder builder) { - builder.setSampler(Sampler.parentBased(new CapaTraceSampler(samplerConfig))); - } - - private void addProcessors(SdkTracerProviderBuilder builder) { - List processors = this.processors; - if (processors != null && !processors.isEmpty()) { - processors.forEach(p -> builder.addSpanProcessor(p)); - } else if (tracerConfig != null && tracerConfig.getProcessors() != null) { - tracerConfig.getProcessors().forEach(p -> { - SpanProcessor processor = SpiUtils.newInstanceWithConstructorCache(p, SpanProcessor.class); - if (processor != null) { - builder.addSpanProcessor(processor); - } - }); - } - } -} - +} \ No newline at end of file diff --git a/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/trace/CapaTracerProviderSettings.java b/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/trace/CapaTracerProviderSettings.java deleted file mode 100644 index a98cf06..0000000 --- a/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/trace/CapaTracerProviderSettings.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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. - */ -package group.rxcloud.capa.component.telemetry.trace; - -import group.rxcloud.capa.component.telemetry.SamplerConfig; -import io.opentelemetry.sdk.trace.IdGenerator; -import io.opentelemetry.sdk.trace.SpanProcessor; - -import java.util.function.Supplier; - -/** - * Settings for capa trace provider. - */ -public interface CapaTracerProviderSettings { - - String FILE_PATH = "/capa-component-telemetry-tracer.json"; - - /** - * Replace the whole config for the meter. - * - * @param tracerConfig tracer config - * @return current settings. - */ - CapaTracerProviderSettings setTracerConfig(TracerConfig tracerConfig); - - /** - * Set the span limits. - * - * @param spanLimits span limits config. - * @return current settings. - */ - CapaTracerProviderSettings setSpanLimits(SpanLimitsConfig spanLimits); - - /** - * Set the trace/span id generator. - * - * @param idGenerator trace/span id generator. - * @return current settings. - */ - CapaTracerProviderSettings setIdGenerator(IdGenerator idGenerator); - - /** - * Add one more span processor to current meter config. - * - * @param processor span processor. - * @return current settings. - */ - CapaTracerProviderSettings addProcessor(SpanProcessor processor); - - /** - * Set sample config. - * - * @param samplerConfig sample config. - * @return current settings. - */ - CapaTracerProviderSettings setSamplerConfig(Supplier samplerConfig); - -} diff --git a/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/trace/CapaTracerWrapper.java b/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/trace/CapaTracerWrapper.java deleted file mode 100644 index 04f87f6..0000000 --- a/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/trace/CapaTracerWrapper.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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. - */ -package group.rxcloud.capa.component.telemetry.trace; - -import group.rxcloud.capa.infrastructure.utils.SpiUtils; -import io.opentelemetry.api.trace.SpanBuilder; -import io.opentelemetry.api.trace.Tracer; -import io.opentelemetry.api.trace.TracerBuilder; -import io.opentelemetry.sdk.trace.ReadWriteSpan; - -import javax.annotation.Nullable; - -/** - * Load capa implementation. - */ -final class CapaTracerWrapper { - - static final String FILE_SUFFIX = "telemetry"; - - static final boolean CACHE = true; - - private CapaTracerWrapper() { - } - - @Nullable - static CapaSpanBuilder wrap(String tracerName, String version, String schemaUrl, String spanName, SpanBuilder builder) { - if (builder instanceof CapaSpanBuilder) { - return (CapaSpanBuilder) builder; - } - CapaSpanBuilder result = SpiUtils - .loadFromSpiComponentFileNullable(CapaSpanBuilder.class, new Class[]{String.class, String.class, String.class, String.class, SpanBuilder.class}, - new Object[]{tracerName, version, schemaUrl, spanName, builder}, FILE_SUFFIX, CACHE); - if (result == null) { - result = new CapaSpanBuilder(tracerName, version, schemaUrl, spanName, builder); - } - return result; - } - - @Nullable - static CapaReadWriteSpan wrap(String tracerName, String version, String schemaUrl, ReadWriteSpan span) { - if (span instanceof CapaReadWriteSpan) { - return (CapaReadWriteSpan) span; - } - CapaReadWriteSpan result = SpiUtils - .loadFromSpiComponentFileNullable(CapaReadWriteSpan.class, new Class[]{String.class, String.class, String.class, ReadWriteSpan.class}, new Object[]{tracerName, version, schemaUrl, span}, - FILE_SUFFIX, CACHE); - if (result == null) { - result = new CapaReadWriteSpan(tracerName, version, schemaUrl, span); - } - return result; - } - - @Nullable - static CapaTracer wrap(String tracerName, String version, String schemaUrl, Tracer tracer) { - if (tracer instanceof CapaTracer) { - return (CapaTracer) tracer; - } - CapaTracer result = SpiUtils.loadFromSpiComponentFileNullable(CapaTracer.class, new Class[]{String.class, String.class, String.class, Tracer.class}, - new Object[]{tracerName, version, schemaUrl, tracer}, FILE_SUFFIX, CACHE); - if (result == null) { - result = new CapaTracer(tracerName, version, schemaUrl, tracer); - } - return result; - } - - @Nullable - static CapaTracerBuilder wrap(String tracerName, TracerBuilder tracerBuilder) { - if (tracerBuilder instanceof CapaTracerBuilder) { - return (CapaTracerBuilder) tracerBuilder; - } - CapaTracerBuilder result = SpiUtils - .loadFromSpiComponentFileNullable(CapaTracerBuilder.class, new Class[]{String.class, TracerBuilder.class}, - new Object[]{tracerName, tracerBuilder}, FILE_SUFFIX, CACHE); - if (result == null) { - result = new CapaTracerBuilder(tracerName, tracerBuilder); - } - return result; - } -} diff --git a/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/trace/CapaTracerWrapperPlugin.java b/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/trace/CapaTracerWrapperPlugin.java new file mode 100644 index 0000000..6f10042 --- /dev/null +++ b/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/trace/CapaTracerWrapperPlugin.java @@ -0,0 +1,119 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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. + */ +package group.rxcloud.capa.component.telemetry.trace; + +import group.rxcloud.capa.infrastructure.plugin.PluginLoader; +import io.opentelemetry.api.trace.SpanBuilder; +import io.opentelemetry.api.trace.Tracer; +import io.opentelemetry.api.trace.TracerBuilder; +import io.opentelemetry.sdk.trace.ReadWriteSpan; + +/** + * Load capa implementation. + */ +public interface CapaTracerWrapperPlugin { + + /** + * Load plugin capa tracer wrapper plugin. + * + * @return the capa tracer wrapper plugin + */ + static CapaTracerWrapperPlugin loadPlugin() { + return PluginLoader.loadPluginImpl(CapaTracerWrapperPlugin.class, CapaTracerWrapperPlugin.CapaTracerWrapperDefault::new); + } + + /** + * Wrap capa span builder. + * + * @param tracerName the tracer name + * @param version the version + * @param schemaUrl the schema url + * @param spanName the span name + * @param builder the builder + * @return the capa span builder + */ + CapaSpanBuilder wrap(String tracerName, String version, String schemaUrl, String spanName, SpanBuilder builder); + + /** + * Wrap capa read write span. + * + * @param tracerName the tracer name + * @param version the version + * @param schemaUrl the schema url + * @param span the span + * @return the capa read write span + */ + CapaReadWriteSpan wrap(String tracerName, String version, String schemaUrl, ReadWriteSpan span); + + /** + * Wrap capa tracer. + * + * @param tracerName the tracer name + * @param version the version + * @param schemaUrl the schema url + * @param tracer the tracer + * @return the capa tracer + */ + CapaTracer wrap(String tracerName, String version, String schemaUrl, Tracer tracer); + + /** + * Wrap capa tracer builder. + * + * @param tracerName the tracer name + * @param tracerBuilder the tracer builder + * @return the capa tracer builder + */ + CapaTracerBuilder wrap(String tracerName, TracerBuilder tracerBuilder); + + /** + * The Capa tracer wrapper default. + */ + class CapaTracerWrapperDefault implements CapaTracerWrapperPlugin { + + @Override + public CapaSpanBuilder wrap(String tracerName, String version, String schemaUrl, String spanName, SpanBuilder builder) { + if (builder instanceof CapaSpanBuilder) { + return (CapaSpanBuilder) builder; + } + return new CapaSpanBuilder(tracerName, version, schemaUrl, spanName, builder); + } + + @Override + public CapaReadWriteSpan wrap(String tracerName, String version, String schemaUrl, ReadWriteSpan span) { + if (span instanceof CapaReadWriteSpan) { + return (CapaReadWriteSpan) span; + } + return new CapaReadWriteSpan(tracerName, version, schemaUrl, span); + } + + @Override + public CapaTracer wrap(String tracerName, String version, String schemaUrl, Tracer tracer) { + if (tracer instanceof CapaTracer) { + return (CapaTracer) tracer; + } + return new CapaTracer(tracerName, version, schemaUrl, tracer); + } + + @Override + public CapaTracerBuilder wrap(String tracerName, TracerBuilder tracerBuilder) { + if (tracerBuilder instanceof CapaTracerBuilder) { + return (CapaTracerBuilder) tracerBuilder; + } + return new CapaTracerBuilder(tracerName, tracerBuilder); + } + } +} diff --git a/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/trace/TracerConfig.java b/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/trace/TracerConfig.java deleted file mode 100644 index 19cc7ab..0000000 --- a/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/trace/TracerConfig.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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. - */ -package group.rxcloud.capa.component.telemetry.trace; - -import java.io.Serializable; -import java.util.List; - -/** - * Trace config. - */ -public class TracerConfig implements Serializable { - - private static final long serialVersionUID = 6587103489345563395L; - - /** - * Id generator class. - */ - private String idGenerator; - - /** - * Will trace/span id be validated with open telemetry restriction. - */ - private boolean enableIdValidate; - - /** - * Span limits. - */ - private SpanLimitsConfig spanLimits; - - /** - * Span processor classes. - */ - private List processors; - - public String getIdGenerator() { - return idGenerator; - } - - public void setIdGenerator(String className) { - this.idGenerator = className; - } - - public boolean isEnableIdValidate() { - return enableIdValidate; - } - - public void setEnableIdValidate(boolean enableIdValidate) { - this.enableIdValidate = enableIdValidate; - } - - public SpanLimitsConfig getSpanLimits() { - return spanLimits; - } - - public void setSpanLimits(SpanLimitsConfig spanLimits) { - this.spanLimits = spanLimits; - } - - public List getProcessors() { - return processors; - } - - public void setProcessors(List processors) { - this.processors = processors; - } -} diff --git a/sdk-spi/src/main/java/group/rxcloud/capa/spi/http/config/RpcServiceOptions.java b/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/trace/TracerConfigLoader.java similarity index 62% rename from sdk-spi/src/main/java/group/rxcloud/capa/spi/http/config/RpcServiceOptions.java rename to sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/trace/TracerConfigLoader.java index 23f1b9d..984b22e 100644 --- a/sdk-spi/src/main/java/group/rxcloud/capa/spi/http/config/RpcServiceOptions.java +++ b/sdk-component/src/main/java/group/rxcloud/capa/component/telemetry/trace/TracerConfigLoader.java @@ -14,12 +14,26 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +package group.rxcloud.capa.component.telemetry.trace; -package group.rxcloud.capa.spi.http.config; +import group.rxcloud.capa.component.telemetry.SamplerConfig; +import io.opentelemetry.sdk.trace.IdGenerator; +import io.opentelemetry.sdk.trace.SpanProcessor; +import java.util.List; /** - * RPC service options. Define for AppId. + * Trace config. */ -public interface RpcServiceOptions { +public interface TracerConfigLoader { + + IdGenerator getIdGenerator(); + + boolean isEnableIdValidate(); + + SpanLimitsConfig getSpanLimits(); + + List getProcessors(); + + SamplerConfig getSamplerConfig(); } diff --git a/sdk-component/src/main/resources/sample/capa-component-log-common.properties b/sdk-component/src/main/resources/sample/capa-component-log-common.properties deleted file mode 100644 index e8cf1c9..0000000 --- a/sdk-component/src/main/resources/sample/capa-component-log-common.properties +++ /dev/null @@ -1,2 +0,0 @@ -# log component center config appid -LOG_COMPONENT_CENTER_CONFIG_APPID=11111 \ No newline at end of file diff --git a/sdk-component/src/main/resources/sample/capa-component-rpc-common.properties b/sdk-component/src/main/resources/sample/capa-component-rpc-common.properties new file mode 100644 index 0000000..047531a --- /dev/null +++ b/sdk-component/src/main/resources/sample/capa-component-rpc-common.properties @@ -0,0 +1,4 @@ +# configuration component store names +API_PROTOCOL=HTTP + +HTTP_CLIENT_READ_TIMEOUT_SECONDS=60 \ No newline at end of file diff --git a/sdk-component/src/main/resources/sample/capa-component-telemetry-common.properties b/sdk-component/src/main/resources/sample/capa-component-telemetry-common.properties index b132abc..ca943c3 100644 --- a/sdk-component/src/main/resources/sample/capa-component-telemetry-common.properties +++ b/sdk-component/src/main/resources/sample/capa-component-telemetry-common.properties @@ -1,2 +1,2 @@ -# telemetry component center config appid -TELEMETRY_COMPONENT_CENTER_CONFIG_APPID=11111 \ No newline at end of file +# configuration component loader +group.rxcloud.capa.component.telemetry.context.ContextPropagatorLoader=your-spi-class-path \ No newline at end of file diff --git a/sdk-component/src/test/java/group/rxcloud/capa/component/CapaRpcPropertiesTest.java b/sdk-component/src/test/java/group/rxcloud/capa/component/CapaRpcConstantsTest.java similarity index 97% rename from sdk-component/src/test/java/group/rxcloud/capa/component/CapaRpcPropertiesTest.java rename to sdk-component/src/test/java/group/rxcloud/capa/component/CapaRpcConstantsTest.java index 9df292b..c14ca5d 100644 --- a/sdk-component/src/test/java/group/rxcloud/capa/component/CapaRpcPropertiesTest.java +++ b/sdk-component/src/test/java/group/rxcloud/capa/component/CapaRpcConstantsTest.java @@ -19,7 +19,7 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -public class CapaRpcPropertiesTest { +public class CapaRpcConstantsTest { @Test public void testGetApiProtocol_Success() { diff --git a/sdk-component/src/test/java/group/rxcloud/capa/component/telemetry/context/CapaContextPropagatorBuilderTest.java b/sdk-component/src/test/java/group/rxcloud/capa/component/telemetry/context/CapaContextAsyncWrapperPropagatorBuilderTest.java similarity index 98% rename from sdk-component/src/test/java/group/rxcloud/capa/component/telemetry/context/CapaContextPropagatorBuilderTest.java rename to sdk-component/src/test/java/group/rxcloud/capa/component/telemetry/context/CapaContextAsyncWrapperPropagatorBuilderTest.java index fd852a2..0bfba02 100644 --- a/sdk-component/src/test/java/group/rxcloud/capa/component/telemetry/context/CapaContextPropagatorBuilderTest.java +++ b/sdk-component/src/test/java/group/rxcloud/capa/component/telemetry/context/CapaContextAsyncWrapperPropagatorBuilderTest.java @@ -31,7 +31,7 @@ * @author: chenyijiang * @date: 2021/11/25 21:03 */ -public class CapaContextPropagatorBuilderTest { +public class CapaContextAsyncWrapperPropagatorBuilderTest { @Test public void setContextConfig() { diff --git a/sdk-component/src/test/java/group/rxcloud/capa/component/telemetry/context/CapaContextTest.java b/sdk-component/src/test/java/group/rxcloud/capa/component/telemetry/context/CapaContextAsyncWrapperTest.java similarity index 66% rename from sdk-component/src/test/java/group/rxcloud/capa/component/telemetry/context/CapaContextTest.java rename to sdk-component/src/test/java/group/rxcloud/capa/component/telemetry/context/CapaContextAsyncWrapperTest.java index b1493b4..87085f8 100644 --- a/sdk-component/src/test/java/group/rxcloud/capa/component/telemetry/context/CapaContextTest.java +++ b/sdk-component/src/test/java/group/rxcloud/capa/component/telemetry/context/CapaContextAsyncWrapperTest.java @@ -32,37 +32,37 @@ * @author: chenyijiang * @date: 2021/11/25 20:53 */ -public class CapaContextTest { +public class CapaContextAsyncWrapperTest { @Test public void taskWrapping() { - CapaContext.taskWrapping(new Runnable() { + CapaContextAsyncWrapper.taskWrapping(new Runnable() { @Override public void run() { } }); - assertTrue(TestCapaContextAsyncWrapper.called(Runnable.class)); - CapaContext.taskWrapping(new Callable() { + assertTrue(TestCapaContextAsyncWrapperPlugin.called(Runnable.class)); + CapaContextAsyncWrapper.taskWrapping(new Callable() { @Override public Boolean call() throws Exception { return true; } }); - assertTrue(TestCapaContextAsyncWrapper.called(Callable.class)); - CapaContext.taskWrapping(Executors.newSingleThreadExecutor()); - assertTrue(TestCapaContextAsyncWrapper.called(ExecutorService.class)); - CapaContext.taskWrapping(new Executor() { + assertTrue(TestCapaContextAsyncWrapperPlugin.called(Callable.class)); + CapaContextAsyncWrapper.taskWrapping(Executors.newSingleThreadExecutor()); + assertTrue(TestCapaContextAsyncWrapperPlugin.called(ExecutorService.class)); + CapaContextAsyncWrapper.taskWrapping(new Executor() { @Override public void execute(@NotNull Runnable command) { } }); - assertTrue(TestCapaContextAsyncWrapper.called(Executor.class)); - CapaContext.taskWrapping(Executors.newScheduledThreadPool(1)); - assertTrue(TestCapaContextAsyncWrapper.called(ScheduledExecutorService.class)); + assertTrue(TestCapaContextAsyncWrapperPlugin.called(Executor.class)); + CapaContextAsyncWrapper.taskWrapping(Executors.newScheduledThreadPool(1)); + assertTrue(TestCapaContextAsyncWrapperPlugin.called(ScheduledExecutorService.class)); - assertNotNull(CapaContext.getTraceId()); + assertNotNull(CapaContextAsyncWrapper.getTraceId()); } } \ No newline at end of file diff --git a/sdk-component/src/test/java/group/rxcloud/capa/component/telemetry/context/TestCapaContextAsyncWrapper.java b/sdk-component/src/test/java/group/rxcloud/capa/component/telemetry/context/TestCapaContextAsyncWrapperPlugin.java similarity index 81% rename from sdk-component/src/test/java/group/rxcloud/capa/component/telemetry/context/TestCapaContextAsyncWrapper.java rename to sdk-component/src/test/java/group/rxcloud/capa/component/telemetry/context/TestCapaContextAsyncWrapperPlugin.java index 8c114e1..5198595 100644 --- a/sdk-component/src/test/java/group/rxcloud/capa/component/telemetry/context/TestCapaContextAsyncWrapper.java +++ b/sdk-component/src/test/java/group/rxcloud/capa/component/telemetry/context/TestCapaContextAsyncWrapperPlugin.java @@ -27,43 +27,43 @@ * @author: chenyijiang * @date: 2021/11/25 20:55 */ -public class TestCapaContextAsyncWrapper implements CapaContextAsyncWrapper { +public class TestCapaContextAsyncWrapperPlugin extends CapaContextAsyncWrapperPlugin.CapaContextAsyncWrapperDefault { private static Set called = new HashSet<>(); @Override public Runnable wrap(Runnable runnable) { called.add(Runnable.class); - return CapaContextAsyncWrapper.super.wrap(runnable); + return super.wrap(runnable); } @Override public Callable wrap(Callable callable) { called.add(Callable.class); - return CapaContextAsyncWrapper.super.wrap(callable); + return super.wrap(callable); } @Override public Executor wrap(Executor executor) { called.add(Executor.class); - return CapaContextAsyncWrapper.super.wrap(executor); + return super.wrap(executor); } @Override public ExecutorService wrap(ExecutorService executor) { called.add(ExecutorService.class); - return CapaContextAsyncWrapper.super.wrap(executor); + return super.wrap(executor); } @Override public ScheduledExecutorService wrap(ScheduledExecutorService executor) { called.add(ScheduledExecutorService.class); - return CapaContextAsyncWrapper.super.wrap(executor); + return super.wrap(executor); } @Override public String getTraceId() { - return CapaContextAsyncWrapper.super.getTraceId(); + return super.getTraceId(); } public static boolean called(Class type) { diff --git a/sdk-component/src/test/java/group/rxcloud/capa/component/telemetry/metrics/CapaMeterProviderBuilderTest.java b/sdk-component/src/test/java/group/rxcloud/capa/component/telemetry/metrics/CapaMeterProviderBuilderTest.java index 56169e9..847ed28 100644 --- a/sdk-component/src/test/java/group/rxcloud/capa/component/telemetry/metrics/CapaMeterProviderBuilderTest.java +++ b/sdk-component/src/test/java/group/rxcloud/capa/component/telemetry/metrics/CapaMeterProviderBuilderTest.java @@ -54,7 +54,7 @@ public void buildWithConfigFile() { public void buildWithEmptyConfig() { MeterProvider meterProvider = new CapaMeterProviderBuilder() - .setMeterConfig(new MeterConfig()) + .setMeterConfig(new MeterConfigLoader()) .buildMeterProvider(); assertTrue(meterProvider instanceof NoopMeterProvider); @@ -105,12 +105,12 @@ public void addReaderConfig() { @Test public void setMeterConfig() { - MeterConfig meterConfig = new MeterConfig(); + MeterConfigLoader meterConfigLoader = new MeterConfigLoader(); MetricsReaderConfig readerConfigByInstance = new MetricsReaderConfig(); readerConfigByInstance.setName("reader_a3"); readerConfigByInstance.setExportInterval(2, TimeUnit.SECONDS); readerConfigByInstance.setExporterType(TestMetricsExporter.class.getName()); - meterConfig.setReaders(Lists.newArrayList(readerConfigByInstance)); + meterConfigLoader.setReaders(Lists.newArrayList(readerConfigByInstance)); MetricsReaderConfig readerConfigByPath = new MetricsReaderConfig(); readerConfigByPath.setName("reader_b3"); @@ -122,7 +122,7 @@ public void setMeterConfig() { MeterProvider meterProvider = new CapaMeterProviderBuilder() .addMetricReaderConfig(readerConfigByPath) - .setMeterConfig(meterConfig) + .setMeterConfig(meterConfigLoader) .setSamplerConfig(() -> samplerConfig) .buildMeterProvider(); diff --git a/sdk-component/src/test/java/group/rxcloud/capa/component/telemetry/trace/CapaTracerProviderBuilderTest.java b/sdk-component/src/test/java/group/rxcloud/capa/component/telemetry/trace/CapaTracerProviderBuilderTest.java index f4f2232..1389cad 100644 --- a/sdk-component/src/test/java/group/rxcloud/capa/component/telemetry/trace/CapaTracerProviderBuilderTest.java +++ b/sdk-component/src/test/java/group/rxcloud/capa/component/telemetry/trace/CapaTracerProviderBuilderTest.java @@ -46,7 +46,7 @@ public class CapaTracerProviderBuilderTest { @Test public void buildFromTraceConfg() { - TracerConfig config = new TracerConfig(); + TracerConfigLoader config = new TracerConfigLoader(); config.setEnableIdValidate(false); config.setSpanLimits(new SpanLimitsConfig()); config.getSpanLimits().setMaxAttributeValueLength(1); diff --git a/sdk-component/src/test/resources/META-INF/services/group.rxcloud.capa.component.telemetry.context.CapaContextAsyncWrapperPlugin b/sdk-component/src/test/resources/META-INF/services/group.rxcloud.capa.component.telemetry.context.CapaContextAsyncWrapperPlugin new file mode 100644 index 0000000..f737050 --- /dev/null +++ b/sdk-component/src/test/resources/META-INF/services/group.rxcloud.capa.component.telemetry.context.CapaContextAsyncWrapperPlugin @@ -0,0 +1 @@ +group.rxcloud.capa.component.telemetry.context.TestCapaContextAsyncWrapperPlugin \ No newline at end of file diff --git a/sdk-component/src/test/resources/capa-component-telemetry.properties b/sdk-component/src/test/resources/capa-component-telemetry.properties index f2e9505..3240350 100644 --- a/sdk-component/src/test/resources/capa-component-telemetry.properties +++ b/sdk-component/src/test/resources/capa-component-telemetry.properties @@ -1,2 +1,2 @@ -group.rxcloud.capa.component.telemetry.context.CapaContextAsyncWrapper=group.rxcloud.capa.component.telemetry.context.TestCapaContextAsyncWrapper +group.rxcloud.capa.component.telemetry.context.CapaContextAsyncWrapperPlugin=group.rxcloud.capa.component.telemetry.context.TestCapaContextAsyncWrapperPlugin group.rxcloud.capa.component.telemetry.metrics.CapaLongHistogram=group.rxcloud.capa.component.telemetry.metrics.TestLongHistogram \ No newline at end of file diff --git a/sdk-infrastructure/pom.xml b/sdk-infrastructure/pom.xml index 008a294..c92273b 100644 --- a/sdk-infrastructure/pom.xml +++ b/sdk-infrastructure/pom.xml @@ -23,7 +23,7 @@ capa-parent group.rxcloud - 1.11.13.2.RELEASE + 2.12.1.RELEASE capa-sdk-infrastructure @@ -31,8 +31,6 @@ SDK infrastructure for Capa - 0.10.4 - 1.0.1-RELEASE @@ -40,53 +38,75 @@ group.rxcloud cloud-runtimes-api + true - io.projectreactor reactor-core + true - org.slf4j slf4j-api + true - io.opentelemetry opentelemetry-api + true io.opentelemetry opentelemetry-api-metrics + true - - com.kevinten + group.rxcloud + vrml-core + true + + + group.rxcloud vrml-error - ${vrml.version} + true + + + group.rxcloud + vrml-resource + true + + + group.rxcloud + vrml-spi + true io.vavr vavr - ${vavr.version} + true - io.grpc grpc-protobuf + true - com.fasterxml.jackson.core jackson-databind + true + + + + com.google.code.gson + gson + true @@ -138,4 +158,5 @@ + \ No newline at end of file diff --git a/sdk-infrastructure/src/main/java/group/rxcloud/capa/infrastructure/CapaConstants.java b/sdk-infrastructure/src/main/java/group/rxcloud/capa/infrastructure/CapaConstants.java deleted file mode 100644 index 0fa36e1..0000000 --- a/sdk-infrastructure/src/main/java/group/rxcloud/capa/infrastructure/CapaConstants.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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. - */ -package group.rxcloud.capa.infrastructure; - -/** - * The Capa infrastructure constants. - */ -interface CapaConstants { - - /** - * The Properties constants. - */ - interface Properties { - - /** - * The {@code component} properties prefix. - */ - String CAPA_COMPONENT_PROPERTIES_PREFIX = "/capa-component-"; - /** - * The {@code infrastructure} properties prefix. - */ - String CAPA_INFRASTRUCTURE_PROPERTIES_PREFIX = "/capa-infrastructure-"; - - /** - * The properties suffix. - */ - String CAPA_PROPERTIES_SUFFIX = ".properties"; - /** - * The json suffix. - */ - String CAPA_JSON_SUFFIX = ".json"; - } -} diff --git a/sdk-infrastructure/src/main/java/group/rxcloud/capa/infrastructure/CapaInfrastructureProperties.java b/sdk-infrastructure/src/main/java/group/rxcloud/capa/infrastructure/CapaInfrastructureProperties.java new file mode 100644 index 0000000..4efbf90 --- /dev/null +++ b/sdk-infrastructure/src/main/java/group/rxcloud/capa/infrastructure/CapaInfrastructureProperties.java @@ -0,0 +1,55 @@ +package group.rxcloud.capa.infrastructure; + +import group.rxcloud.capa.infrastructure.loader.CapaClassLoader; +import group.rxcloud.capa.infrastructure.metainfo.CapaEnvironment; + +/** + * Capa infrastructure common properties. + */ +public interface CapaInfrastructureProperties { + + /** + * The Properties constants. + */ + interface Constants { + + /** + * The {@code component} properties prefix. + */ + String CAPA_COMPONENT_PROPERTIES_PREFIX = "/capa-component-"; + /** + * The {@code infrastructure} properties prefix. + */ + String CAPA_INFRASTRUCTURE_PROPERTIES_PREFIX = "/capa-infrastructure-"; + + /** + * The properties suffix. + */ + String CAPA_PROPERTIES_SUFFIX = ".properties"; + /** + * The json suffix. + */ + String CAPA_JSON_SUFFIX = ".json"; + } + + /** + * The Settings. + */ + abstract class Settings { + + private static final CapaEnvironment capaEnvironment; + + static { + capaEnvironment = CapaClassLoader.loadInfrastructureClassObj("cloud", CapaEnvironment.class); + } + + /** + * Gets capa environment. + * + * @return the capa environment + */ + public static CapaEnvironment getCapaEnvironment() { + return capaEnvironment; + } + } +} diff --git a/sdk-infrastructure/src/main/java/group/rxcloud/capa/infrastructure/CapaProperties.java b/sdk-infrastructure/src/main/java/group/rxcloud/capa/infrastructure/CapaProperties.java deleted file mode 100644 index 17ad9d8..0000000 --- a/sdk-infrastructure/src/main/java/group/rxcloud/capa/infrastructure/CapaProperties.java +++ /dev/null @@ -1,137 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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. - */ -package group.rxcloud.capa.infrastructure; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import io.vavr.Function2; - -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.nio.charset.StandardCharsets; -import java.util.Iterator; -import java.util.Map; -import java.util.Objects; -import java.util.Properties; -import java.util.ServiceLoader; -import java.util.concurrent.ConcurrentHashMap; -import java.util.function.Function; - -import static group.rxcloud.capa.infrastructure.CapaConstants.Properties.CAPA_COMPONENT_PROPERTIES_PREFIX; -import static group.rxcloud.capa.infrastructure.CapaConstants.Properties.CAPA_INFRASTRUCTURE_PROPERTIES_PREFIX; -import static group.rxcloud.capa.infrastructure.CapaConstants.Properties.CAPA_PROPERTIES_SUFFIX; -import static group.rxcloud.capa.infrastructure.InnerModule.FILE_CACHE_MAP; -import static group.rxcloud.capa.infrastructure.InnerModule.loadCapaConfig; -import static group.rxcloud.capa.infrastructure.InnerModule.loadCapaFileByJavaSpi; -import static group.rxcloud.capa.infrastructure.InnerModule.loadCapaProperties; - -/** - * Global properties for Capa's SDK, using Supplier so they are dynamically resolved. - */ -public abstract class CapaProperties { - - /** - * Capa's component properties supplier. - */ - public static final Function COMPONENT_PROPERTIES_SUPPLIER - = (componentDomain) -> (Properties) FILE_CACHE_MAP.computeIfAbsent(componentDomain, - s -> { - final String fileName = CAPA_COMPONENT_PROPERTIES_PREFIX - + componentDomain.toLowerCase() - + CAPA_PROPERTIES_SUFFIX; - return loadCapaProperties(fileName); - }); - - /** - * Capa's infrastructure properties supplier. - */ - public static final Function INFRASTRUCTURE_PROPERTIES_SUPPLIER - = (infrastructureDomain) -> (Properties) FILE_CACHE_MAP.computeIfAbsent(infrastructureDomain, - s -> { - final String fileName = CAPA_INFRASTRUCTURE_PROPERTIES_PREFIX - + infrastructureDomain.toLowerCase() - + CAPA_PROPERTIES_SUFFIX; - return loadCapaProperties(fileName); - }); - - /** - * Capa's plugin properties supplier. - */ - public static final Function PLUGIN_PROPERTIES_SUPPLIER - = (clazz) -> FILE_CACHE_MAP.computeIfAbsent(clazz.getName(), - s -> loadCapaFileByJavaSpi(clazz)); - - /** - * Capa's config file supplier. - */ - public static final Function2 CONFIG_FILE_SUPPLIER - = (fileName, clazz) -> FILE_CACHE_MAP.computeIfAbsent(fileName, - s -> loadCapaConfig(s, clazz)); -} - -interface InnerModule { - - /** - * Capa's file cache map. - */ - Map FILE_CACHE_MAP = new ConcurrentHashMap<>(); - - ObjectMapper OBJECT_MAPPER = new ObjectMapper() - .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) - .setSerializationInclusion(JsonInclude.Include.NON_NULL); - - static Properties loadCapaProperties(final String fileName) { - Objects.requireNonNull(fileName, "fileName not found."); - try (InputStream in = CapaProperties.class.getResourceAsStream(fileName)) { - InputStreamReader inputStreamReader = new InputStreamReader(in, StandardCharsets.UTF_8); - Properties properties = new Properties(); - properties.load(inputStreamReader); - return properties; - } catch (IOException e) { - throw new IllegalArgumentException(fileName + " file not found.", e); - } - } - - static T loadCapaConfig(final String fileName, Class configClazz) { - Objects.requireNonNull(fileName, "fileName not found."); - try (InputStream in = CapaProperties.class.getResourceAsStream(fileName)) { - InputStreamReader inputStreamReader = new InputStreamReader(in, StandardCharsets.UTF_8); - return OBJECT_MAPPER.readValue(inputStreamReader, configClazz); - } catch (JsonParseException | JsonMappingException e) { - throw new IllegalArgumentException(fileName + " file not load.", e); - } catch (IOException e) { - throw new IllegalArgumentException(fileName + " file not found.", e); - } - } - - static T loadCapaFileByJavaSpi(Class configClazz) { - try { - ServiceLoader loader = ServiceLoader.load(configClazz); - Iterator iterator = loader.iterator(); - if (!iterator.hasNext()) { - return null; - } - return iterator.next(); - } catch (Exception e) { - throw new IllegalArgumentException(configClazz.getName() + " spi file not found.", e); - } - } -} diff --git a/sdk-infrastructure/src/main/java/group/rxcloud/capa/infrastructure/exceptions/CapaErrorContext.java b/sdk-infrastructure/src/main/java/group/rxcloud/capa/infrastructure/exceptions/CapaErrorContext.java index 483eaa8..8460766 100644 --- a/sdk-infrastructure/src/main/java/group/rxcloud/capa/infrastructure/exceptions/CapaErrorContext.java +++ b/sdk-infrastructure/src/main/java/group/rxcloud/capa/infrastructure/exceptions/CapaErrorContext.java @@ -17,7 +17,7 @@ package group.rxcloud.capa.infrastructure.exceptions; -import com.kevinten.vrml.error.code.ErrorCodeContext; +import group.rxcloud.vrml.error.code.ErrorCodeContext; /** * Application error info context: diff --git a/sdk-infrastructure/src/main/java/group/rxcloud/capa/infrastructure/exceptions/CapaException.java b/sdk-infrastructure/src/main/java/group/rxcloud/capa/infrastructure/exceptions/CapaException.java index b6f0a3c..97dac2a 100644 --- a/sdk-infrastructure/src/main/java/group/rxcloud/capa/infrastructure/exceptions/CapaException.java +++ b/sdk-infrastructure/src/main/java/group/rxcloud/capa/infrastructure/exceptions/CapaException.java @@ -17,8 +17,8 @@ package group.rxcloud.capa.infrastructure.exceptions; -import com.kevinten.vrml.error.code.ErrorCodeContext; -import com.kevinten.vrml.error.exception.ErrorCodeException; +import group.rxcloud.vrml.error.code.ErrorCodeContext; +import group.rxcloud.vrml.error.exception.ErrorCodeException; /** * A Capa's specific exception. diff --git a/sdk-infrastructure/src/main/java/group/rxcloud/capa/infrastructure/hook/Mixer.java b/sdk-infrastructure/src/main/java/group/rxcloud/capa/infrastructure/hook/Mixer.java index c5c7b85..8ac6bb5 100644 --- a/sdk-infrastructure/src/main/java/group/rxcloud/capa/infrastructure/hook/Mixer.java +++ b/sdk-infrastructure/src/main/java/group/rxcloud/capa/infrastructure/hook/Mixer.java @@ -16,7 +16,7 @@ */ package group.rxcloud.capa.infrastructure.hook; -import group.rxcloud.capa.infrastructure.CapaClassLoader; +import group.rxcloud.capa.infrastructure.loader.CapaClassLoader; import io.vavr.Lazy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/sdk-infrastructure/src/main/java/group/rxcloud/capa/infrastructure/CapaClassLoader.java b/sdk-infrastructure/src/main/java/group/rxcloud/capa/infrastructure/loader/CapaClassLoader.java similarity index 63% rename from sdk-infrastructure/src/main/java/group/rxcloud/capa/infrastructure/CapaClassLoader.java rename to sdk-infrastructure/src/main/java/group/rxcloud/capa/infrastructure/loader/CapaClassLoader.java index 3ca5700..8f50358 100644 --- a/sdk-infrastructure/src/main/java/group/rxcloud/capa/infrastructure/CapaClassLoader.java +++ b/sdk-infrastructure/src/main/java/group/rxcloud/capa/infrastructure/loader/CapaClassLoader.java @@ -14,27 +14,33 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package group.rxcloud.capa.infrastructure; +package group.rxcloud.capa.infrastructure.loader; + +import group.rxcloud.vrml.core.serialization.Serialization; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.Properties; /** - * The Capa SPI Class loader. + * The Capa SPI Class obj loader. */ public final class CapaClassLoader { + private static final Logger logger = LoggerFactory.getLogger(CapaClassLoader.class); + /** * Load component class obj. * * @param the target class type * @param componentDomain the component domain - * @param superClazz the interface class type + * @param clazz the interface class type * @return the target spi class obj */ - public static T loadComponentClassObj(String componentDomain, Class superClazz) { - return loadComponentClassObj(componentDomain, superClazz, null, null); + public static T loadComponentClassObj(String componentDomain, Class clazz) { + return loadComponentClassObj(componentDomain, clazz, null, null); } /** @@ -42,14 +48,14 @@ public static T loadComponentClassObj(String componentDomain, Class super * * @param the target class type * @param componentDomain the component domain - * @param superClazz the interface class type + * @param clazz the interface class type * @param parameterTypes the constructor parameters * @param initargs the constructor initargs * @return the target spi class obj */ - public static T loadComponentClassObj(String componentDomain, Class superClazz, Class[] parameterTypes, Object[] initargs) { - Properties properties = CapaProperties.COMPONENT_PROPERTIES_SUPPLIER.apply(componentDomain); - String implClassPath = properties.getProperty(superClazz.getName()); + public static T loadComponentClassObj(String componentDomain, Class clazz, Class[] parameterTypes, Object[] initargs) { + Properties properties = CapaProperties.loadComponentProperties(componentDomain); + String implClassPath = properties.getProperty(clazz.getName()); return loadClassObj(implClassPath, parameterTypes, initargs); } @@ -58,11 +64,11 @@ public static T loadComponentClassObj(String componentDomain, Class super * * @param the target class type * @param infrastructureDomain the infrastructure domain - * @param superClazz the interface class type + * @param clazz the interface class type * @return the target spi class obj */ - public static T loadInfrastructureClassObj(String infrastructureDomain, Class superClazz) { - return loadInfrastructureClassObj(infrastructureDomain, superClazz, null, null); + public static T loadInfrastructureClassObj(String infrastructureDomain, Class clazz) { + return loadInfrastructureClassObj(infrastructureDomain, clazz, null, null); } /** @@ -70,39 +76,36 @@ public static T loadInfrastructureClassObj(String infrastructureDomain, Clas * * @param the target class type * @param infrastructureDomain the infrastructure domain - * @param superClazz the interface class type + * @param clazz the interface class type * @param parameterTypes the constructor parameters * @param initargs the constructor initargs * @return the target spi class obj */ - public static T loadInfrastructureClassObj(String infrastructureDomain, Class superClazz, Class[] parameterTypes, Object[] initargs) { - Properties properties = CapaProperties.INFRASTRUCTURE_PROPERTIES_SUPPLIER.apply(infrastructureDomain); - String implClassPath = properties.getProperty(superClazz.getName()); + public static T loadInfrastructureClassObj(String infrastructureDomain, Class clazz, Class[] parameterTypes, Object[] initargs) { + Properties properties = CapaProperties.loadInfrastructureProperties(infrastructureDomain); + String implClassPath = properties.getProperty(clazz.getName()); return loadClassObj(implClassPath, parameterTypes, initargs); } - /** - * Load plugin class obj. - * - * @param the target class type - * @param superClazz the interface class type - * @return the target plugin class obj - */ - public static T loadPluginClassObj(Class superClazz) { - Object pluginImpl = CapaProperties.PLUGIN_PROPERTIES_SUPPLIER.apply(superClazz); - return (T) pluginImpl; - } - - // -- Private + // -- Class loader private static T loadClassObj(String classPath, Class[] parameterTypes, Object[] initargs) { + Throwable throwable = null; try { Class aClass = (Class) Class.forName(classPath); Constructor constructor = aClass.getConstructor(parameterTypes); Object newInstance = constructor.newInstance(initargs); return (T) newInstance; } catch (ClassNotFoundException | NoSuchMethodException | InvocationTargetException | InstantiationException | IllegalAccessException e) { - throw new IllegalArgumentException("Capa load class error: [" + classPath + "] not found."); + throwable = e; + throw new IllegalArgumentException("Capa load class[" + classPath + "] not found error: " + e.getMessage()); + } finally { + if (throwable != null) { + if (logger.isWarnEnabled()) { + logger.warn("[Capa][CapaClassLoader.loadClassObj] classPath[{}] parameterTypes[{}] initargs[{}] load error!", + classPath, Serialization.GSON.toJson(parameterTypes), Serialization.GSON.toJson(initargs), throwable); + } + } } } } diff --git a/sdk-infrastructure/src/main/java/group/rxcloud/capa/infrastructure/loader/CapaProperties.java b/sdk-infrastructure/src/main/java/group/rxcloud/capa/infrastructure/loader/CapaProperties.java new file mode 100644 index 0000000..4a6c165 --- /dev/null +++ b/sdk-infrastructure/src/main/java/group/rxcloud/capa/infrastructure/loader/CapaProperties.java @@ -0,0 +1,89 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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. + */ +package group.rxcloud.capa.infrastructure.loader; + +import group.rxcloud.vrml.resource.Resources; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Properties; + +import static group.rxcloud.capa.infrastructure.CapaInfrastructureProperties.Constants.CAPA_COMPONENT_PROPERTIES_PREFIX; +import static group.rxcloud.capa.infrastructure.CapaInfrastructureProperties.Constants.CAPA_INFRASTRUCTURE_PROPERTIES_PREFIX; +import static group.rxcloud.capa.infrastructure.CapaInfrastructureProperties.Constants.CAPA_PROPERTIES_SUFFIX; + +/** + * Global properties for Capa's SDK, using Supplier so they are dynamically resolved. + */ +public abstract class CapaProperties { + + private static final Logger logger = LoggerFactory.getLogger(CapaProperties.class); + + /** + * Load Capa's component properties. + * + * @param componentDomain /capa-component-{componentDomain}.properties + */ + public static Properties loadComponentProperties(final String componentDomain) { + final String fileName = CAPA_COMPONENT_PROPERTIES_PREFIX + + componentDomain.toLowerCase() + + CAPA_PROPERTIES_SUFFIX; + return Resources.loadResourcesProperties(fileName) + .onFailure(throwable -> { + if (logger.isErrorEnabled()) { + logger.error("[Capa][CapaProperties.loadComponentProperties] fileName[{}] load error!", + fileName, throwable); + } + }) + .get(); + } + + /** + * Load Capa's infrastructure properties. + * + * @param infrastructureDomain /capa-infrastructure-{infrastructureDomain}.properties + */ + public static Properties loadInfrastructureProperties(final String infrastructureDomain) { + final String fileName = CAPA_INFRASTRUCTURE_PROPERTIES_PREFIX + + infrastructureDomain.toLowerCase() + + CAPA_PROPERTIES_SUFFIX; + return Resources.loadResourcesProperties(fileName) + .onFailure(throwable -> { + if (logger.isErrorEnabled()) { + logger.error("[Capa][CapaProperties.loadInfrastructureProperties] fileName[{}] load error!", + fileName, throwable); + } + }) + .get(); + } + + /** + * Load Capa's config file. + * + * @param fileName /{fileName}.xxx + */ + public static T loadConfigFile(final String fileName, final Class fileType) { + return Resources.loadResources(fileName, fileType) + .onFailure(throwable -> { + if (logger.isErrorEnabled()) { + logger.error("[Capa][CapaProperties.loadConfigFile] fileName[{}] fileType[{}] load error!", + fileName, fileType.getName(), throwable); + } + }) + .get(); + } +} \ No newline at end of file diff --git a/sdk-infrastructure/src/main/java/group/rxcloud/capa/infrastructure/CapaEnvironment.java b/sdk-infrastructure/src/main/java/group/rxcloud/capa/infrastructure/metainfo/CapaEnvironment.java similarity index 65% rename from sdk-infrastructure/src/main/java/group/rxcloud/capa/infrastructure/CapaEnvironment.java rename to sdk-infrastructure/src/main/java/group/rxcloud/capa/infrastructure/metainfo/CapaEnvironment.java index 2d47b49..8607b82 100644 --- a/sdk-infrastructure/src/main/java/group/rxcloud/capa/infrastructure/CapaEnvironment.java +++ b/sdk-infrastructure/src/main/java/group/rxcloud/capa/infrastructure/metainfo/CapaEnvironment.java @@ -14,7 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package group.rxcloud.capa.infrastructure; +package group.rxcloud.capa.infrastructure.metainfo; /** * Capa System Environment Properties. @@ -26,7 +26,6 @@ public interface CapaEnvironment { *
      * + AWS
      * + ALIBABA
-     * + CTRIP
      * 
* * @return the deploy cloud name @@ -56,29 +55,4 @@ public interface CapaEnvironment { * @return the deploy env name */ String getDeployEnv(); - - /** - * The {@code CapaEnvironment} SPI Class Provider. - */ - abstract class Provider { - - /** - * The {@code CapaEnvironment} SPI Class Obj. - */ - private volatile static CapaEnvironment INSTANCE; - - /** - * Gets {@code CapaEnvironment} instance. - */ - public static CapaEnvironment getInstance() { - if (INSTANCE == null) { - synchronized (Provider.class) { - if (INSTANCE == null) { - INSTANCE = CapaClassLoader.loadInfrastructureClassObj("cloud", CapaEnvironment.class); - } - } - } - return INSTANCE; - } - } } diff --git a/sdk-infrastructure/src/main/java/group/rxcloud/capa/infrastructure/plugin/PluginLoader.java b/sdk-infrastructure/src/main/java/group/rxcloud/capa/infrastructure/plugin/PluginLoader.java index de783be..90e447c 100644 --- a/sdk-infrastructure/src/main/java/group/rxcloud/capa/infrastructure/plugin/PluginLoader.java +++ b/sdk-infrastructure/src/main/java/group/rxcloud/capa/infrastructure/plugin/PluginLoader.java @@ -16,11 +16,10 @@ */ package group.rxcloud.capa.infrastructure.plugin; -import group.rxcloud.capa.infrastructure.CapaClassLoader; +import group.rxcloud.vrml.spi.SPI; -import java.util.Map; +import java.util.List; import java.util.Optional; -import java.util.concurrent.ConcurrentHashMap; import java.util.function.Supplier; /** @@ -28,16 +27,6 @@ */ public final class PluginLoader { - private static final Map pluginImplCache; - - static { - pluginImplCache = new ConcurrentHashMap<>(); - } - - public static Map getPluginImplCache() { - return pluginImplCache; - } - /** * Load plugin impl by java spi. * @@ -46,9 +35,18 @@ public static Map getPluginImplCache() { * @return the optional of plugin impl */ public static Optional loadPluginImpl(Class pluginSuperClazz) { - Object o = pluginImplCache.computeIfAbsent(pluginSuperClazz, - aClass -> CapaClassLoader.loadPluginClassObj(pluginSuperClazz)); - return Optional.ofNullable((T) o); + return SPI.loadSpiImpl(pluginSuperClazz); + } + + /** + * Load plugin impls by java spi. + * + * @param the plugin interface type + * @param pluginSuperClazz the plugin interface class + * @return the optional of plugin impls + */ + public static Optional> loadPluginImpls(Class pluginSuperClazz) { + return SPI.loadSpiImpls(pluginSuperClazz); } /** @@ -60,14 +58,6 @@ public static Optional loadPluginImpl(Class pluginSuperClazz) { * @return the plugin impl */ public static T loadPluginImpl(Class pluginSuperClazz, Supplier defaultPluginObj) { - Object o = pluginImplCache.computeIfAbsent(pluginSuperClazz, - aClass -> { - T pluginClassObj = CapaClassLoader.loadPluginClassObj(pluginSuperClazz); - if (pluginClassObj != null) { - return pluginClassObj; - } - return defaultPluginObj.get(); - }); - return (T) o; + return SPI.loadSpiImpl(pluginSuperClazz, defaultPluginObj); } } diff --git a/sdk-infrastructure/src/main/java/group/rxcloud/capa/infrastructure/plugin/PluginOrder.java b/sdk-infrastructure/src/main/java/group/rxcloud/capa/infrastructure/plugin/PluginOrder.java deleted file mode 100644 index 958dba6..0000000 --- a/sdk-infrastructure/src/main/java/group/rxcloud/capa/infrastructure/plugin/PluginOrder.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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. - */ -package group.rxcloud.capa.infrastructure.plugin; - -/** - * TODO: 2021/12/29 currently only support one plugin. - */ -public @interface PluginOrder { - - int order() default 0; -} diff --git a/sdk-infrastructure/src/main/java/group/rxcloud/capa/infrastructure/utils/SpiUtils.java b/sdk-infrastructure/src/main/java/group/rxcloud/capa/infrastructure/utils/SpiUtils.java deleted file mode 100644 index 0bf4b12..0000000 --- a/sdk-infrastructure/src/main/java/group/rxcloud/capa/infrastructure/utils/SpiUtils.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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. - */ - -package group.rxcloud.capa.infrastructure.utils; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.ObjectMapper; -import group.rxcloud.capa.infrastructure.CapaProperties; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.nio.charset.StandardCharsets; -import java.util.Map; -import java.util.Properties; -import java.util.concurrent.ConcurrentHashMap; - -/** - * Load class and create instance from config file. - * TODO move to {@link CapaProperties} - */ -@Deprecated -public final class SpiUtils { - - private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper() - .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) - .setSerializationInclusion(JsonInclude.Include.NON_NULL); - - private static final Map CACHE = new ConcurrentHashMap<>(); - - private SpiUtils() { - } - - public static T loadConfigNullable(String path, Class configType) { - try (InputStream in = configType.getResourceAsStream(path)) { - if (in != null) { - InputStreamReader inputStreamReader = new InputStreamReader(in, StandardCharsets.UTF_8); - return OBJECT_MAPPER.readValue(inputStreamReader, configType); - } - } catch (IOException e) { - } - return null; - } - - @Nullable - public static T loadFromSpiComponentFileNullable(Class type, String fileSuffix) { - return loadFromSpiComponentFileNullable(type, null, null, fileSuffix, false); - } - - @Nullable - public static T loadFromSpiComponentFileNullable(Class type, Class[] argTypes, Object[] args, - String fileSuffix, boolean cache) { - try { - Properties properties = CapaProperties.COMPONENT_PROPERTIES_SUPPLIER.apply(fileSuffix); - String path = properties.getProperty(type.getName()); - if (path != null) { - return doNewInstance(path, type, argTypes, args, cache); - } - return null; - } catch (Throwable e) { - } - return null; - } - - @Nullable - public static T newInstanceWithConstructorCache(String path, Class type) { - return newInstance(path, type, null, null, true); - } - - @Nullable - public static T newInstance(String path, Class type, Class[] argTypes, Object[] args, boolean cache) { - if (path == null) { - return null; - } - return doNewInstance(path, type, argTypes, args, cache); - } - - private static String keyOf(String path, Class type, Class[] argTypes) { - StringBuilder builder = new StringBuilder(type.getName()).append('=').append(path); - if (argTypes != null) { - for (Class arg : argTypes) { - builder.append('_').append(arg.getName()); - } - } - return builder.toString(); - } - - @Nonnull - private static T doNewInstance(String path, Class type, Class[] argTypes, Object[] args, boolean cache) { - String key = keyOf(path, type, argTypes); - Constructor targetCons = cache - ? CACHE.computeIfAbsent(key, k -> findConstructor(path, type, argTypes)) - : findConstructor(path, type, argTypes); - try { - return targetCons.getParameterCount() == 0 ? targetCons.newInstance() : targetCons.newInstance(args); - } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) { - throw new IllegalArgumentException("Fail to create component. targetType = " + type.getName(), e); - } - } - - private static Constructor findConstructor(String path, Class type, Class[] argTypes) { - try { - Class aClass = path == null ? type : (Class) Class.forName(path); - return aClass.getConstructor(argTypes); - } catch (ClassNotFoundException | NoSuchMethodException e) { - throw new IllegalArgumentException("Fail to find the constructor. path = " + path, e); - } - } -} diff --git a/sdk-infrastructure/src/main/resources/sample/capa-infrastructure-cloud.properties b/sdk-infrastructure/src/main/resources/sample/capa-infrastructure-cloud.properties index 55b95a1..07f4905 100644 --- a/sdk-infrastructure/src/main/resources/sample/capa-infrastructure-cloud.properties +++ b/sdk-infrastructure/src/main/resources/sample/capa-infrastructure-cloud.properties @@ -1,2 +1,2 @@ # {@code CapaEnvironment} spi class load -group.rxcloud.capa.infrastructure.CapaEnvironment=your-spi-class-path \ No newline at end of file +group.rxcloud.capa.infrastructure.metainfo.CapaEnvironment=your-spi-class-path \ No newline at end of file diff --git a/sdk-infrastructure/src/test/java/group/rxcloud/capa/infrastructure/CapaPropertiesTest.java b/sdk-infrastructure/src/test/java/group/rxcloud/capa/infrastructure/loader/CapaPropertiesTest.java similarity index 89% rename from sdk-infrastructure/src/test/java/group/rxcloud/capa/infrastructure/CapaPropertiesTest.java rename to sdk-infrastructure/src/test/java/group/rxcloud/capa/infrastructure/loader/CapaPropertiesTest.java index 11c803c..83f7b5d 100644 --- a/sdk-infrastructure/src/test/java/group/rxcloud/capa/infrastructure/CapaPropertiesTest.java +++ b/sdk-infrastructure/src/test/java/group/rxcloud/capa/infrastructure/loader/CapaPropertiesTest.java @@ -14,7 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package group.rxcloud.capa.infrastructure; +package group.rxcloud.capa.infrastructure.loader; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @@ -25,7 +25,7 @@ public class CapaPropertiesTest { @Test public void testGetComponentProperties_Success() { - Properties properties = CapaProperties.COMPONENT_PROPERTIES_SUPPLIER.apply("rpc"); + Properties properties = CapaProperties.loadComponentProperties("rpc"); String value = properties.getProperty("key"); Assertions.assertEquals("value", value); } diff --git a/sdk-infrastructure/src/test/java/group/rxcloud/capa/infrastructure/utils/MyImpl.java b/sdk-infrastructure/src/test/java/group/rxcloud/capa/infrastructure/utils/MyImpl.java deleted file mode 100644 index 1791222..0000000 --- a/sdk-infrastructure/src/test/java/group/rxcloud/capa/infrastructure/utils/MyImpl.java +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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. - */ - -package group.rxcloud.capa.infrastructure.utils; - -public class MyImpl implements MyInterface{ - -} diff --git a/sdk-infrastructure/src/test/java/group/rxcloud/capa/infrastructure/utils/MyImplWithArgs.java b/sdk-infrastructure/src/test/java/group/rxcloud/capa/infrastructure/utils/MyImplWithArgs.java deleted file mode 100644 index 5232dca..0000000 --- a/sdk-infrastructure/src/test/java/group/rxcloud/capa/infrastructure/utils/MyImplWithArgs.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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. - */ - -package group.rxcloud.capa.infrastructure.utils; - -public class MyImplWithArgs implements MyInterfaceWithArgs{ - - private MyImplWithArgs(Integer a) { - - } - public MyImplWithArgs(String a) { - - } - public MyImplWithArgs(Integer a, String b) { - - } - - public MyImplWithArgs(boolean a, short b, int c, long d, float e, double f, byte g, char h, String i) { - - } -} diff --git a/sdk-infrastructure/src/test/java/group/rxcloud/capa/infrastructure/utils/MyInterface.java b/sdk-infrastructure/src/test/java/group/rxcloud/capa/infrastructure/utils/MyInterface.java deleted file mode 100644 index 70fb329..0000000 --- a/sdk-infrastructure/src/test/java/group/rxcloud/capa/infrastructure/utils/MyInterface.java +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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. - */ - -package group.rxcloud.capa.infrastructure.utils; - -public interface MyInterface { - -} diff --git a/sdk-infrastructure/src/test/java/group/rxcloud/capa/infrastructure/utils/MyInterfaceWithArgs.java b/sdk-infrastructure/src/test/java/group/rxcloud/capa/infrastructure/utils/MyInterfaceWithArgs.java deleted file mode 100644 index fe69c4c..0000000 --- a/sdk-infrastructure/src/test/java/group/rxcloud/capa/infrastructure/utils/MyInterfaceWithArgs.java +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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. - */ - -package group.rxcloud.capa.infrastructure.utils; - -public interface MyInterfaceWithArgs { - -} diff --git a/sdk-infrastructure/src/test/java/group/rxcloud/capa/infrastructure/utils/SpiUtilsTest.java b/sdk-infrastructure/src/test/java/group/rxcloud/capa/infrastructure/utils/SpiUtilsTest.java deleted file mode 100644 index 9e0ab08..0000000 --- a/sdk-infrastructure/src/test/java/group/rxcloud/capa/infrastructure/utils/SpiUtilsTest.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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. - */ -package group.rxcloud.capa.infrastructure.utils; - -import org.junit.jupiter.api.Test; - -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -public class SpiUtilsTest { - - @Test - public void loadConfigNullable() { - Config config = SpiUtils.loadConfigNullable("/config.json", Config.class); - assertEquals("aaa", config.str); - assertEquals(2, config.getList().size()); - assertEquals("zzz", config.getList().get(0)); - - assertNull(SpiUtils.loadConfigNullable("aaa", Config.class)); - assertNull(SpiUtils.loadConfigNullable("/config.json", Integer.class)); - } - - @Test - public void loadFromSpiComponentFileNullable() { - MyInterface myInterface = SpiUtils.loadFromSpiComponentFileNullable(MyInterface.class, "test"); - assertTrue(myInterface instanceof MyImpl); - } - - @Test - public void loadFromSpiComponentFileNullable2() { - MyInterfaceWithArgs myInterfaceWithArgs = SpiUtils.loadFromSpiComponentFileNullable(MyInterfaceWithArgs.class, new Class[] {boolean.class, short.class, int.class, long.class, float.class, double.class, byte.class, char.class, String.class}, new Object[] {true, (short)1, 2, 3L, 4.0f, 5.0, (byte)0x1, 'x', "a"}, "test", true); - - assertTrue(myInterfaceWithArgs instanceof MyImplWithArgs); - - - } - - @Test - public void loadFromSpiComponentFileNullable2Fail() { - MyInterfaceWithArgs myInterfaceWithArgs = SpiUtils.loadFromSpiComponentFileNullable(MyInterfaceWithArgs.class, "test"); - assertNull(myInterfaceWithArgs); - - - assertNull(SpiUtils.loadFromSpiComponentFileNullable(MyImplWithArgs.class, new Class[] {String.class}, new Object[] {"a"}, "test", true)); - - assertNull(SpiUtils.loadFromSpiComponentFileNullable(MyInterfaceWithArgs.class, new Class[] {Long.class}, new Object[] {1L}, "test", false)); - - assertNull(SpiUtils.loadFromSpiComponentFileNullable(MyInterfaceWithArgs.class, new Class[] {Integer.class}, new Object[] {1}, "test", false)); - - assertNull(SpiUtils.loadFromSpiComponentFileNullable(MyInterfaceWithArgs.class, new Class[] {boolean.class, short.class, int.class, long.class, float.class, double.class, byte.class, char.class, String.class}, new Object[] {true, (short)1, 2, 3L, 4.0f, 5.0, null, 'x', "a"}, "test", true)); - - - } - - @Test - public void newInstance() { - assertNull(SpiUtils.newInstance(null, Config.class, null, null, false)); - - MyImpl my = SpiUtils.newInstanceWithConstructorCache(MyImpl.class.getCanonicalName(), MyImpl.class); - assertNotNull(my); - - MyImplWithArgs myImplWithArgs = SpiUtils.newInstance(MyImplWithArgs.class.getCanonicalName(),MyImplWithArgs.class, new Class[] {String.class}, new Object[] {"a"}, false); - assertNotNull(myImplWithArgs); - } - - @Test - public void newInstanceFail() { - Throwable t = null; - try { - Config my = SpiUtils.newInstanceWithConstructorCache(Config.class.getCanonicalName(), Config.class); - } catch (Throwable throwable) { - t = throwable; - } - assertNotNull(t); - } - - static class Config { - - private String str; - - private List list; - - public String getStr() { - return str; - } - - public Config setStr(String str) { - this.str = str; - return this; - } - - public List getList() { - return list; - } - - public Config setList(List list) { - this.list = list; - return this; - } - } -} \ No newline at end of file diff --git a/sdk-infrastructure/src/test/resources/capa-component-test.properties b/sdk-infrastructure/src/test/resources/capa-component-test.properties deleted file mode 100644 index dafd0e8..0000000 --- a/sdk-infrastructure/src/test/resources/capa-component-test.properties +++ /dev/null @@ -1,2 +0,0 @@ -group.rxcloud.capa.infrastructure.utils.MyInterface=group.rxcloud.capa.infrastructure.utils.MyImpl -group.rxcloud.capa.infrastructure.utils.MyInterfaceWithArgs=group.rxcloud.capa.infrastructure.utils.MyImplWithArgs \ No newline at end of file diff --git a/sdk-infrastructure/src/test/resources/config.json b/sdk-infrastructure/src/test/resources/config.json deleted file mode 100644 index 0de38f1..0000000 --- a/sdk-infrastructure/src/test/resources/config.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "str": "aaa", - "list": ["zzz", "yyy"] -} \ No newline at end of file diff --git a/sdk-infrastructure/src/test/resources/config.properties b/sdk-infrastructure/src/test/resources/config.properties deleted file mode 100644 index 2b9c2c9..0000000 --- a/sdk-infrastructure/src/test/resources/config.properties +++ /dev/null @@ -1 +0,0 @@ -str=aaa \ No newline at end of file diff --git a/sdk-spi-demo/pom.xml b/sdk-spi-demo/pom.xml index db60b90..2e4e9a0 100644 --- a/sdk-spi-demo/pom.xml +++ b/sdk-spi-demo/pom.xml @@ -23,7 +23,7 @@ capa-parent group.rxcloud - 1.11.13.2.RELEASE + 2.12.1.RELEASE capa-sdk-spi-demo diff --git a/sdk-spi-demo/src/main/java/group/rxcloud/capa/spi/demo/DemoCapaEnvironment.java b/sdk-spi-demo/src/main/java/group/rxcloud/capa/spi/demo/DemoCapaEnvironment.java index 2c5ad16..a74c679 100644 --- a/sdk-spi-demo/src/main/java/group/rxcloud/capa/spi/demo/DemoCapaEnvironment.java +++ b/sdk-spi-demo/src/main/java/group/rxcloud/capa/spi/demo/DemoCapaEnvironment.java @@ -16,7 +16,7 @@ */ package group.rxcloud.capa.spi.demo; -import group.rxcloud.capa.infrastructure.CapaEnvironment; +import group.rxcloud.capa.infrastructure.metainfo.CapaEnvironment; public class DemoCapaEnvironment implements CapaEnvironment { diff --git a/sdk-spi-demo/src/main/java/group/rxcloud/capa/spi/demo/http/DemoCapaHttp.java b/sdk-spi-demo/src/main/java/group/rxcloud/capa/spi/demo/http/DemoCapaHttp.java index 8e14a28..9308cb1 100644 --- a/sdk-spi-demo/src/main/java/group/rxcloud/capa/spi/demo/http/DemoCapaHttp.java +++ b/sdk-spi-demo/src/main/java/group/rxcloud/capa/spi/demo/http/DemoCapaHttp.java @@ -18,9 +18,7 @@ import group.rxcloud.capa.component.http.HttpResponse; import group.rxcloud.capa.infrastructure.serializer.CapaObjectSerializer; -import group.rxcloud.capa.spi.demo.http.config.DemoRpcServiceOptions; import group.rxcloud.capa.spi.http.CapaSerializeHttpSpi; -import group.rxcloud.capa.spi.http.config.RpcServiceOptions; import group.rxcloud.cloudruntimes.utils.TypeRef; import okhttp3.OkHttpClient; import org.slf4j.Logger; @@ -54,11 +52,7 @@ protected CompletableFuture> invokeSpiApi(String appId, String httpMethod, Map headers, Map> urlParameters, - TypeRef type, - RpcServiceOptions rpcServiceOptions) { - DemoRpcServiceOptions demoRpcServiceOptions = (DemoRpcServiceOptions) rpcServiceOptions; - logger.info("[DemoCapaHttp.invokeSpiApi] rpcServiceOptions[{}]", demoRpcServiceOptions); - + TypeRef type) { return CompletableFuture.supplyAsync( () -> { logger.info("[DemoCapaHttp.invokeSpiApi] supplyAsync[{}]", System.currentTimeMillis()); diff --git a/sdk-spi-demo/src/main/java/group/rxcloud/capa/spi/demo/http/config/DemoRpcServiceOptions.java b/sdk-spi-demo/src/main/java/group/rxcloud/capa/spi/demo/http/config/DemoRpcServiceOptions.java deleted file mode 100644 index a826018..0000000 --- a/sdk-spi-demo/src/main/java/group/rxcloud/capa/spi/demo/http/config/DemoRpcServiceOptions.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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. - */ -package group.rxcloud.capa.spi.demo.http.config; - -import group.rxcloud.capa.spi.http.config.RpcServiceOptions; - -/** - * RPC service options. Define for AppId. - */ -public class DemoRpcServiceOptions implements RpcServiceOptions { - - /** - * Unique rpc service ID - */ - private final String appId; - - /** - * Instantiates a new Capa rpc service options. - * - * @param appId the app id - */ - public DemoRpcServiceOptions(String appId) { - this.appId = appId; - } -} diff --git a/sdk-spi-demo/src/main/java/group/rxcloud/capa/spi/demo/http/config/DemoSpiOptionsLoader.java b/sdk-spi-demo/src/main/java/group/rxcloud/capa/spi/demo/http/config/DemoSpiOptionsLoader.java deleted file mode 100644 index 5d069fd..0000000 --- a/sdk-spi-demo/src/main/java/group/rxcloud/capa/spi/demo/http/config/DemoSpiOptionsLoader.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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. - */ -package group.rxcloud.capa.spi.demo.http.config; - -import group.rxcloud.capa.spi.http.config.CapaSpiOptionsLoader; - -import java.util.Objects; - -public class DemoSpiOptionsLoader implements CapaSpiOptionsLoader { - - @Override - public DemoRpcServiceOptions loadRpcServiceOptions(String appId) { - Objects.requireNonNull(appId, "appId"); - return new DemoRpcServiceOptions(appId); - } -} diff --git a/sdk-spi-demo/src/main/resources/capa-component-rpc-common.properties b/sdk-spi-demo/src/main/resources/capa-component-rpc-common.properties deleted file mode 100644 index 603ac10..0000000 --- a/sdk-spi-demo/src/main/resources/capa-component-rpc-common.properties +++ /dev/null @@ -1,2 +0,0 @@ -# rpc spi options class loader -group.rxcloud.capa.spi.http.config.CapaSpiOptionsLoader=group.rxcloud.capa.spi.demo.http.config.DemoSpiOptionsLoader \ No newline at end of file diff --git a/sdk-spi-demo/src/main/resources/capa-infrastructure-cloud.properties b/sdk-spi-demo/src/main/resources/capa-infrastructure-cloud.properties index 1ea1ff4..c2ce813 100644 --- a/sdk-spi-demo/src/main/resources/capa-infrastructure-cloud.properties +++ b/sdk-spi-demo/src/main/resources/capa-infrastructure-cloud.properties @@ -1,2 +1,2 @@ # {@code CapaEnvironment} spi class load -group.rxcloud.capa.infrastructure.CapaEnvironment=group.rxcloud.capa.spi.demo.DemoCapaEnvironment \ No newline at end of file +group.rxcloud.capa.infrastructure.metainfo.CapaEnvironment=group.rxcloud.capa.spi.demo.DemoCapaEnvironment \ No newline at end of file diff --git a/sdk-spi/pom.xml b/sdk-spi/pom.xml index 2537bf6..0193333 100644 --- a/sdk-spi/pom.xml +++ b/sdk-spi/pom.xml @@ -23,7 +23,7 @@ capa-parent group.rxcloud - 1.11.13.2.RELEASE + 2.12.1.RELEASE capa-sdk-spi diff --git a/sdk-spi/src/main/java/group/rxcloud/capa/spi/http/CapaHttpSpi.java b/sdk-spi/src/main/java/group/rxcloud/capa/spi/http/CapaHttpSpi.java index e2b3291..d27b720 100644 --- a/sdk-spi/src/main/java/group/rxcloud/capa/spi/http/CapaHttpSpi.java +++ b/sdk-spi/src/main/java/group/rxcloud/capa/spi/http/CapaHttpSpi.java @@ -21,9 +21,6 @@ import group.rxcloud.capa.infrastructure.exceptions.CapaErrorContext; import group.rxcloud.capa.infrastructure.exceptions.CapaException; import group.rxcloud.capa.infrastructure.serializer.CapaObjectSerializer; -import group.rxcloud.capa.spi.http.config.CapaSpiOptionsLoader; -import group.rxcloud.capa.spi.http.config.CapaSpiProperties; -import group.rxcloud.capa.spi.http.config.RpcServiceOptions; import group.rxcloud.cloudruntimes.utils.TypeRef; import okhttp3.OkHttpClient; import org.slf4j.Logger; @@ -90,18 +87,10 @@ protected CompletableFuture> doInvokeApi(String httpMethod, version, _invoke, appId, _method, method); } - // load spi service options - RpcServiceOptions rpcServiceOptions = getRpcServiceOptions(appId); - Objects.requireNonNull(rpcServiceOptions, "rpcServiceOptions"); - if (logger.isDebugEnabled()) { - logger.debug("[Capa.Rpc.Client.http] [CapaHttpSpi] invoke rpc options[{}]", - rpcServiceOptions); - } - try { // spi invoke CompletableFuture> invokeSpiApi = invokeSpiApi( - appId, method, requestData, httpMethod, headers, urlParameters, type, rpcServiceOptions); + appId, method, requestData, httpMethod, headers, urlParameters, type); invokeSpiApi.whenComplete(this::callbackLog); return invokeSpiApi; } catch (CapaException e) { @@ -114,17 +103,6 @@ protected CompletableFuture> doInvokeApi(String httpMethod, } } - /** - * Override to get the configuration of the corresponding appId. - * - * @param appId the app id - * @return the rpc service options - */ - protected RpcServiceOptions getRpcServiceOptions(String appId) { - CapaSpiOptionsLoader capaSpiOptionsLoader = CapaSpiProperties.getSpiOptionsLoader(); - return capaSpiOptionsLoader.loadRpcServiceOptions(appId); - } - private void callbackLog(HttpResponse tHttpResponse, Throwable throwable) { if (throwable != null) { if (throwable instanceof CapaException) { @@ -157,15 +135,14 @@ private void callbackLog(HttpResponse tHttpResponse, Throwable throwable) /** * Invoke spi api and then return async completable future. * - * @param the response type parameter - * @param appId the app id - * @param method the invoke method - * @param requestData the request data - * @param httpMethod the http method - * @param headers the headers - * @param urlParameters the url parameters - * @param type the response type - * @param rpcServiceOptions the rpc service options + * @param the response type parameter + * @param appId the app id + * @param method the invoke method + * @param requestData the request data + * @param httpMethod the http method + * @param headers the headers + * @param urlParameters the url parameters + * @param type the response type * @return the async completable future */ protected abstract CompletableFuture> invokeSpiApi(String appId, @@ -174,6 +151,5 @@ protected abstract CompletableFuture> invokeSpiApi(String ap String httpMethod, Map headers, Map> urlParameters, - TypeRef type, - RpcServiceOptions rpcServiceOptions); + TypeRef type); } diff --git a/sdk-spi/src/main/java/group/rxcloud/capa/spi/http/config/CapaSpiOptionsLoader.java b/sdk-spi/src/main/java/group/rxcloud/capa/spi/http/config/CapaSpiOptionsLoader.java deleted file mode 100644 index ed952e7..0000000 --- a/sdk-spi/src/main/java/group/rxcloud/capa/spi/http/config/CapaSpiOptionsLoader.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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. - */ -package group.rxcloud.capa.spi.http.config; - - -/** - * Read SPI configuration and generate corresponding configuration objects. - */ -public interface CapaSpiOptionsLoader { - - /** - * Load rpc service options. - * - * @param appId the appId - * @return the rpc service options - */ - T loadRpcServiceOptions(String appId); -} diff --git a/sdk-spi/src/main/java/group/rxcloud/capa/spi/http/config/CapaSpiProperties.java b/sdk-spi/src/main/java/group/rxcloud/capa/spi/http/config/CapaSpiProperties.java deleted file mode 100644 index 5a1550f..0000000 --- a/sdk-spi/src/main/java/group/rxcloud/capa/spi/http/config/CapaSpiProperties.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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. - */ -package group.rxcloud.capa.spi.http.config; - -import group.rxcloud.capa.infrastructure.CapaClassLoader; - -/** - * The Capa SPI environment. - */ -public abstract class CapaSpiProperties { - - /** - * Static lock object. - */ - private static final Object LOCK = new Object(); - - private static volatile CapaSpiOptionsLoader instance; - - /** - * Gets default options loader. - * - * @return the default options loader - */ - public static CapaSpiOptionsLoader getSpiOptionsLoader() { - if (instance == null) { - synchronized (LOCK) { - if (instance == null) { - instance = CapaClassLoader.loadComponentClassObj("rpc-common", CapaSpiOptionsLoader.class); - } - } - } - // load spi rpc impl - return instance; - } -} diff --git a/sdk-spi/src/main/java/group/rxcloud/capa/spi/telemetry/CapaContextAsyncWrapperSpi.java b/sdk-spi/src/main/java/group/rxcloud/capa/spi/telemetry/CapaContextAsyncWrapperPluginSpi.java similarity index 88% rename from sdk-spi/src/main/java/group/rxcloud/capa/spi/telemetry/CapaContextAsyncWrapperSpi.java rename to sdk-spi/src/main/java/group/rxcloud/capa/spi/telemetry/CapaContextAsyncWrapperPluginSpi.java index 55cf4c4..6419e87 100644 --- a/sdk-spi/src/main/java/group/rxcloud/capa/spi/telemetry/CapaContextAsyncWrapperSpi.java +++ b/sdk-spi/src/main/java/group/rxcloud/capa/spi/telemetry/CapaContextAsyncWrapperPluginSpi.java @@ -16,10 +16,10 @@ */ package group.rxcloud.capa.spi.telemetry; -import group.rxcloud.capa.component.telemetry.context.CapaContextAsyncWrapper; +import group.rxcloud.capa.component.telemetry.context.CapaContextAsyncWrapperPlugin; /** * SPI Capa context async wrapper. */ -public abstract class CapaContextAsyncWrapperSpi implements CapaContextAsyncWrapper { +public abstract class CapaContextAsyncWrapperPluginSpi implements CapaContextAsyncWrapperPlugin { } diff --git a/sdk-spi/src/main/resources/sample/capa-component-rpc-common.properties b/sdk-spi/src/main/resources/sample/capa-component-rpc-common.properties deleted file mode 100644 index 1e2ea0f..0000000 --- a/sdk-spi/src/main/resources/sample/capa-component-rpc-common.properties +++ /dev/null @@ -1,2 +0,0 @@ -# rpc spi options class loader -group.rxcloud.capa.spi.http.config.CapaSpiOptionsLoader=your-spi-class-path \ No newline at end of file diff --git a/sdk-spi/src/test/java/group/rxcloud/capa/spi/http/CapaSerializeHttpSpiTest.java b/sdk-spi/src/test/java/group/rxcloud/capa/spi/http/CapaSerializeHttpSpiTest.java index 3136b6e..b3b4487 100644 --- a/sdk-spi/src/test/java/group/rxcloud/capa/spi/http/CapaSerializeHttpSpiTest.java +++ b/sdk-spi/src/test/java/group/rxcloud/capa/spi/http/CapaSerializeHttpSpiTest.java @@ -22,7 +22,6 @@ import group.rxcloud.capa.infrastructure.serializer.CapaObjectSerializer; import group.rxcloud.capa.infrastructure.serializer.DefaultObjectSerializer; import group.rxcloud.capa.infrastructure.serializer.ExtensionObjectSerializer; -import group.rxcloud.capa.spi.http.config.RpcServiceOptions; import group.rxcloud.cloudruntimes.utils.TypeRef; import okhttp3.Headers; import okhttp3.MediaType; @@ -183,14 +182,6 @@ public void testOnResponseInSerializationResponseFutureCallback_Success() throws future.cancel(true); } - - @Test - public void testGetRpcServiceOptions_Success() { - RpcServiceOptions rpcServiceOptions = capaSerializeHttpSpi.getRpcServiceOptions("appId"); - String className = rpcServiceOptions.getClass().getName(); - Assertions.assertEquals("group.rxcloud.capa.spi.http.config.TestRpcServiceOptions", className); - } - @Test public void testDoInvokeApi_Success() throws ExecutionException, InterruptedException { String[] pathSegments = new String[]{ @@ -298,8 +289,7 @@ protected CompletableFuture> invokeSpiApi(String appId, String httpMethod, Map headers, Map> urlParameters, - TypeRef type, - RpcServiceOptions rpcServiceOptions) { + TypeRef type) { return CompletableFuture.supplyAsync( () -> { return new HttpResponse<>(null, null, 200); diff --git a/sdk-spi/src/test/java/group/rxcloud/capa/spi/http/config/TestRpcServiceOptions.java b/sdk-spi/src/test/java/group/rxcloud/capa/spi/http/config/TestRpcServiceOptions.java deleted file mode 100644 index 6f9f5ff..0000000 --- a/sdk-spi/src/test/java/group/rxcloud/capa/spi/http/config/TestRpcServiceOptions.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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. - */ -package group.rxcloud.capa.spi.http.config; - -/** - * RPC service options used in tests only. - */ -public class TestRpcServiceOptions implements RpcServiceOptions { - - /** - * Unique rpc service ID - */ - private final String appId; - - /** - * Instantiates a new Capa rpc service options. - * - * @param appId the app id - */ - public TestRpcServiceOptions(String appId) { - this.appId = appId; - } -} diff --git a/sdk-spi/src/test/java/group/rxcloud/capa/spi/http/config/TestSpiOptionsLoader.java b/sdk-spi/src/test/java/group/rxcloud/capa/spi/http/config/TestSpiOptionsLoader.java deleted file mode 100644 index 9d65cdd..0000000 --- a/sdk-spi/src/test/java/group/rxcloud/capa/spi/http/config/TestSpiOptionsLoader.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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. - */ -package group.rxcloud.capa.spi.http.config; - -import java.util.Objects; - -/** - * The spi options loader used in tests only. - */ -public class TestSpiOptionsLoader implements CapaSpiOptionsLoader { - - @Override - public TestRpcServiceOptions loadRpcServiceOptions(String appId) { - Objects.requireNonNull(appId, "appId"); - return new TestRpcServiceOptions(appId); - } -} \ No newline at end of file diff --git a/sdk-spi/src/test/resources/capa-component-rpc-common.properties b/sdk-spi/src/test/resources/capa-component-rpc-common.properties deleted file mode 100644 index d3f0e57..0000000 --- a/sdk-spi/src/test/resources/capa-component-rpc-common.properties +++ /dev/null @@ -1 +0,0 @@ -group.rxcloud.capa.spi.http.config.CapaSpiOptionsLoader=group.rxcloud.capa.spi.http.config.TestSpiOptionsLoader \ No newline at end of file diff --git a/sdk-springboot/pom.xml b/sdk-springboot/pom.xml index 921629f..cc37f2e 100644 --- a/sdk-springboot/pom.xml +++ b/sdk-springboot/pom.xml @@ -23,7 +23,7 @@ capa-parent group.rxcloud - 1.11.13.2.RELEASE + 2.12.1.RELEASE sdk-springboot @@ -31,7 +31,6 @@ 2.3.12.RELEASE - 1.0.1-RELEASE @@ -55,14 +54,28 @@ org.springframework.boot - spring-boot-starter + spring-boot-starter-web + true - - com.kevinten + group.rxcloud + cloud-runtimes-api + true + + + + + group.rxcloud vrml-core - ${vrml.version} + true + + + + + io.projectreactor + reactor-core + true
diff --git a/sdk-springboot/src/main/java/group/rxcloud/capa/springboot/pubsub/PubSubBeanPostProcessor.java b/sdk-springboot/src/main/java/group/rxcloud/capa/springboot/pubsub/PubSubBeanPostProcessor.java index 75f862a..b7bd5ab 100644 --- a/sdk-springboot/src/main/java/group/rxcloud/capa/springboot/pubsub/PubSubBeanPostProcessor.java +++ b/sdk-springboot/src/main/java/group/rxcloud/capa/springboot/pubsub/PubSubBeanPostProcessor.java @@ -16,15 +16,14 @@ */ package group.rxcloud.capa.springboot.pubsub; -import com.kevinten.vrml.core.beans.SpringContextConfigurator; -import com.kevinten.vrml.core.serialization.Serialization; import group.rxcloud.capa.infrastructure.exceptions.CapaException; import group.rxcloud.capa.infrastructure.serializer.CapaObjectSerializer; import group.rxcloud.capa.infrastructure.serializer.DefaultObjectSerializer; -import group.rxcloud.capa.pubsub.Topic; -import group.rxcloud.capa.pubsub.domain.TopicEventRequest; -import group.rxcloud.capa.pubsub.domain.TopicSubscription; +import group.rxcloud.cloudruntimes.domain.core.pubsub.TopicEventRequest; +import group.rxcloud.cloudruntimes.domain.core.pubsub.TopicSubscription; import group.rxcloud.cloudruntimes.utils.TypeRef; +import group.rxcloud.vrml.core.beans.SpringContextConfigurator; +import group.rxcloud.vrml.core.serialization.Serialization; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; diff --git a/sdk/src/main/java/group/rxcloud/capa/pubsub/Topic.java b/sdk-springboot/src/main/java/group/rxcloud/capa/springboot/pubsub/Topic.java similarity index 97% rename from sdk/src/main/java/group/rxcloud/capa/pubsub/Topic.java rename to sdk-springboot/src/main/java/group/rxcloud/capa/springboot/pubsub/Topic.java index b25a2aa..47df5fa 100644 --- a/sdk/src/main/java/group/rxcloud/capa/pubsub/Topic.java +++ b/sdk-springboot/src/main/java/group/rxcloud/capa/springboot/pubsub/Topic.java @@ -14,7 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package group.rxcloud.capa.pubsub; +package group.rxcloud.capa.springboot.pubsub; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; diff --git a/sdk-springboot/src/main/java/group/rxcloud/capa/springboot/pubsub/TopicSubscriber.java b/sdk-springboot/src/main/java/group/rxcloud/capa/springboot/pubsub/TopicSubscriber.java index 96b217f..5969f24 100644 --- a/sdk-springboot/src/main/java/group/rxcloud/capa/springboot/pubsub/TopicSubscriber.java +++ b/sdk-springboot/src/main/java/group/rxcloud/capa/springboot/pubsub/TopicSubscriber.java @@ -16,12 +16,12 @@ */ package group.rxcloud.capa.springboot.pubsub; -import com.kevinten.vrml.core.beans.SpringContextConfigurator; import group.rxcloud.capa.component.pubsub.CapaPubSub; import group.rxcloud.capa.component.pubsub.NewMessage; import group.rxcloud.capa.component.pubsub.SubscribeRequest; -import group.rxcloud.capa.pubsub.domain.TopicEventRequest; -import group.rxcloud.capa.pubsub.domain.TopicSubscription; +import group.rxcloud.cloudruntimes.domain.core.pubsub.TopicEventRequest; +import group.rxcloud.cloudruntimes.domain.core.pubsub.TopicSubscription; +import group.rxcloud.vrml.core.beans.SpringContextConfigurator; import reactor.core.publisher.Flux; import java.util.List; diff --git a/sdk-springboot/src/main/java/group/rxcloud/capa/springboot/rpc/client/CapaRpcClientFactory.java b/sdk-springboot/src/main/java/group/rxcloud/capa/springboot/rpc/client/CapaRpcClientFactory.java new file mode 100644 index 0000000..e70ba25 --- /dev/null +++ b/sdk-springboot/src/main/java/group/rxcloud/capa/springboot/rpc/client/CapaRpcClientFactory.java @@ -0,0 +1,52 @@ +package group.rxcloud.capa.springboot.rpc.client; + +import group.rxcloud.capa.infrastructure.exceptions.CapaErrorContext; +import group.rxcloud.capa.infrastructure.exceptions.CapaException; +import group.rxcloud.capa.infrastructure.plugin.PluginLoader; +import group.rxcloud.capa.springboot.rpc.client.plugin.CapaRpcFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Optional; +import java.util.function.Consumer; + +/** + * Rpc client factory. + */ +public interface CapaRpcClientFactory { + + Logger log = LoggerFactory.getLogger(CapaRpcClientFactory.class); + + /** + * Gets rpc client proxy instance. + * + * @param the rpc contract type + * @param interfaceClazz the interface clazz + * @param serviceId the service id + * @return the proxy instance + */ + static T getInstance(Class interfaceClazz, String serviceId) { + return getInstance(interfaceClazz, serviceId, null); + } + + /** + * Gets rpc client proxy instance. + * + * @param the rpc contract type + * @param interfaceClazz the interface clazz + * @param serviceId the service id + * @param clientConfigBuilderConsumer the client config builder consumer + * @return the proxy instance + */ + static T getInstance(Class interfaceClazz, String serviceId, Consumer clientConfigBuilderConsumer) { + Optional capaRpcFactory = PluginLoader.loadPluginImpl(CapaRpcFactory.class); + if (!capaRpcFactory.isPresent()) { + if (log.isErrorEnabled()) { + log.error("[Capa.Rpc.Client] [RpcClientFactory.getInstance] can't found rpc client factory."); + } + throw new CapaException(CapaErrorContext.SYSTEM_ERROR, "CapaRpcClient get factory error"); + } + return capaRpcFactory.get() + .getInstance(interfaceClazz, serviceId, clientConfigBuilderConsumer); + } +} diff --git a/sdk-springboot/src/main/java/group/rxcloud/capa/springboot/rpc/client/ServiceClientConfig.java b/sdk-springboot/src/main/java/group/rxcloud/capa/springboot/rpc/client/ServiceClientConfig.java new file mode 100644 index 0000000..157899c --- /dev/null +++ b/sdk-springboot/src/main/java/group/rxcloud/capa/springboot/rpc/client/ServiceClientConfig.java @@ -0,0 +1,27 @@ +package group.rxcloud.capa.springboot.rpc.client; + + +import java.util.Map; + +public class ServiceClientConfig { + + private Map headers; + + private int requestTimeoutInMilliseconds; + + public Map getHeaders() { + return headers; + } + + void setHeaders(Map headers) { + this.headers = headers; + } + + public int getRequestTimeoutInMilliseconds() { + return requestTimeoutInMilliseconds; + } + + void setRequestTimeoutInMilliseconds(int requestTimeoutInMilliseconds) { + this.requestTimeoutInMilliseconds = requestTimeoutInMilliseconds; + } +} diff --git a/sdk-springboot/src/main/java/group/rxcloud/capa/springboot/rpc/client/ServiceClientConfigBuilder.java b/sdk-springboot/src/main/java/group/rxcloud/capa/springboot/rpc/client/ServiceClientConfigBuilder.java new file mode 100644 index 0000000..901f1e6 --- /dev/null +++ b/sdk-springboot/src/main/java/group/rxcloud/capa/springboot/rpc/client/ServiceClientConfigBuilder.java @@ -0,0 +1,30 @@ +package group.rxcloud.capa.springboot.rpc.client; + +import java.util.Map; + +public class ServiceClientConfigBuilder { + + private Map headers; + + private int requestTimeoutInMilliseconds; + + public ServiceClientConfigBuilder() { + } + + public ServiceClientConfigBuilder withHeaders(Map headers) { + this.headers = headers; + return this; + } + + public ServiceClientConfigBuilder withRequestTimeoutInMilliseconds(int requestTimeoutInMilliseconds) { + this.requestTimeoutInMilliseconds = requestTimeoutInMilliseconds; + return this; + } + + public ServiceClientConfig build() { + ServiceClientConfig serviceClientConfig = new ServiceClientConfig(); + serviceClientConfig.setHeaders(this.headers); + serviceClientConfig.setRequestTimeoutInMilliseconds(this.requestTimeoutInMilliseconds); + return serviceClientConfig; + } +} diff --git a/sdk-springboot/src/main/java/group/rxcloud/capa/springboot/rpc/client/plugin/CapaRpcFactory.java b/sdk-springboot/src/main/java/group/rxcloud/capa/springboot/rpc/client/plugin/CapaRpcFactory.java new file mode 100644 index 0000000..9638a6c --- /dev/null +++ b/sdk-springboot/src/main/java/group/rxcloud/capa/springboot/rpc/client/plugin/CapaRpcFactory.java @@ -0,0 +1,23 @@ +package group.rxcloud.capa.springboot.rpc.client.plugin; + + +import group.rxcloud.capa.springboot.rpc.client.ServiceClientConfigBuilder; + +import java.util.function.Consumer; + +/** + * Inner Factory. + */ +public interface CapaRpcFactory { + + /** + * Gets rpc client instance. + * + * @param the rpc contract type + * @param interfaceClazz the interface clazz + * @param serviceId the service id + * @param clientConfigBuilderConsumer the client config builder consumer + * @return the client instance + */ + T getInstance(Class interfaceClazz, String serviceId, Consumer clientConfigBuilderConsumer); +} diff --git a/sdk-springboot/src/main/java/group/rxcloud/capa/springboot/rpc/client/proxy/CapaRpcProxyFactory.java b/sdk-springboot/src/main/java/group/rxcloud/capa/springboot/rpc/client/proxy/CapaRpcProxyFactory.java new file mode 100644 index 0000000..87915f0 --- /dev/null +++ b/sdk-springboot/src/main/java/group/rxcloud/capa/springboot/rpc/client/proxy/CapaRpcProxyFactory.java @@ -0,0 +1,65 @@ +package group.rxcloud.capa.springboot.rpc.client.proxy; + +import group.rxcloud.capa.infrastructure.exceptions.CapaErrorContext; +import group.rxcloud.capa.infrastructure.exceptions.CapaException; +import group.rxcloud.capa.springboot.rpc.client.ServiceClientConfig; +import group.rxcloud.capa.springboot.rpc.client.ServiceClientConfigBuilder; +import group.rxcloud.capa.springboot.rpc.client.plugin.CapaRpcFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Proxy; +import java.util.function.Consumer; + +/** + * Generate Capa proxy objects for The interface Client and initiate RPC calls through the Capa SDK. + */ +public class CapaRpcProxyFactory implements CapaRpcFactory { + + private final Logger log = LoggerFactory.getLogger(CapaRpcProxyFactory.class); + + @Override + public T getInstance(Class interfaceClazz, String serviceId, Consumer clientConfigBuilderConsumer) { + final String interfaceClazzSimpleName = interfaceClazz.getSimpleName(); + + Object interfaceProxyObj; + try { + Class[] interfaceClazzes = {interfaceClazz}; + ClassLoader interfaceClazzClassLoader = interfaceClazz.getClassLoader(); + Class interfaceProxyClazz = Proxy.getProxyClass(interfaceClazzClassLoader, interfaceClazzes); + + Class[] invocationHandlerClazz = {InvocationHandler.class}; + Constructor interfaceProxyConstructor = interfaceProxyClazz.getConstructor(invocationHandlerClazz); + + ServiceClientConfig config = null; + if (clientConfigBuilderConsumer != null) { + ServiceClientConfigBuilder configBuilder = new ServiceClientConfigBuilder(); + clientConfigBuilderConsumer.accept(configBuilder); + config = configBuilder.build(); + } + + InvocationHandler invocationHandler = new ServiceInvocationHandler(capaRpcClient, serviceId, config); + interfaceProxyObj = interfaceProxyConstructor.newInstance(invocationHandler); + } catch (NoSuchMethodException | InvocationTargetException | InstantiationException | IllegalAccessException e) { + if (log.isErrorEnabled()) { + log.error("[Capa.Rpc.Client] [RpcClientFactory.getInstance] interface[{}] instance init catches error.", + interfaceClazzSimpleName, e); + } + throw new CapaException(CapaErrorContext.SYSTEM_ERROR, "CapaRpcClient getInstance() catches error", e); + } catch (Exception e) { + if (log.isErrorEnabled()) { + log.error("[Capa.Rpc.Client] [RpcClientFactory.getInstance] interface[{}] instance init catches error.", + interfaceClazzSimpleName, e); + } + throw new CapaException(CapaErrorContext.SYSTEM_ERROR, "CapaRpcClient getInstance() error", e); + } + + if (log.isInfoEnabled()) { + log.info("[Capa.Rpc.Client] [RpcClientFactory.getInstance] interface[{}] instance has been init.", interfaceClazzSimpleName); + } + return (T) interfaceProxyObj; + } +} diff --git a/sdk-springboot/src/main/java/group/rxcloud/capa/springboot/rpc/client/proxy/ServiceInvocationHandler.java b/sdk-springboot/src/main/java/group/rxcloud/capa/springboot/rpc/client/proxy/ServiceInvocationHandler.java new file mode 100644 index 0000000..3d3aeb7 --- /dev/null +++ b/sdk-springboot/src/main/java/group/rxcloud/capa/springboot/rpc/client/proxy/ServiceInvocationHandler.java @@ -0,0 +1,56 @@ +package group.rxcloud.capa.springboot.rpc.client.proxy; + +import group.rxcloud.capa.infrastructure.exceptions.CapaErrorContext; +import group.rxcloud.capa.infrastructure.exceptions.CapaException; +import group.rxcloud.capa.infrastructure.metainfo.CapaEnvironment; +import group.rxcloud.capa.rpc.CapaRpcClient; +import group.rxcloud.capa.springboot.rpc.client.ServiceClientConfig; +import group.rxcloud.cloudruntimes.domain.core.invocation.HttpExtension; +import group.rxcloud.vrml.core.serialization.Serialization; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.util.concurrent.ListenableFuture; +import reactor.core.publisher.Mono; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.time.Duration; +import java.time.temporal.ChronoUnit; + +public class ServiceInvocationHandler implements InvocationHandler { + + private static final Logger log = LoggerFactory.getLogger(ServiceInvocationHandler.class); + + private final CapaRpcClient capaRpcClient; + private final String serviceId; + private final ServiceClientConfig clientConfig; + + ServiceInvocationHandler(CapaRpcClient capaRpcClient, String serviceId, ServiceClientConfig clientConfig) { + this.capaRpcClient = capaRpcClient; + this.serviceId = adapterServiceId(serviceId); + this.clientConfig = clientConfig; + } + + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + + } + + private String adapterServiceId(String serviceId) { + + return serviceId; + } + + private Mono setCallTimeout(Mono responseMono) { + if (clientConfig != null) { + int requestTimeoutInMilliseconds = clientConfig.getRequestTimeoutInMilliseconds(); + if (requestTimeoutInMilliseconds > 0) { + Duration timeout = Duration.of(requestTimeoutInMilliseconds, ChronoUnit.MILLIS); + responseMono = responseMono.timeout(timeout); + } + } + return responseMono; + } +} diff --git a/sdk-springboot/src/main/java/group/rxcloud/capa/springboot/rpc/server/CapaController.java b/sdk-springboot/src/main/java/group/rxcloud/capa/springboot/rpc/server/CapaController.java new file mode 100644 index 0000000..e2c9b60 --- /dev/null +++ b/sdk-springboot/src/main/java/group/rxcloud/capa/springboot/rpc/server/CapaController.java @@ -0,0 +1,16 @@ +package group.rxcloud.capa.springboot.rpc.server; + +import org.springframework.web.bind.annotation.RestController; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +@Documented +@RestController +public @interface CapaController { +} diff --git a/sdk-springboot/src/main/java/group/rxcloud/capa/springboot/rpc/server/CapaRequestMapping.java b/sdk-springboot/src/main/java/group/rxcloud/capa/springboot/rpc/server/CapaRequestMapping.java new file mode 100644 index 0000000..856dba4 --- /dev/null +++ b/sdk-springboot/src/main/java/group/rxcloud/capa/springboot/rpc/server/CapaRequestMapping.java @@ -0,0 +1,13 @@ +package group.rxcloud.capa.springboot.rpc.server; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface CapaRequestMapping { +} diff --git a/sdk-springboot/src/main/java/group/rxcloud/capa/springboot/rpc/server/CapaServerSettings.java b/sdk-springboot/src/main/java/group/rxcloud/capa/springboot/rpc/server/CapaServerSettings.java new file mode 100644 index 0000000..4290e4d --- /dev/null +++ b/sdk-springboot/src/main/java/group/rxcloud/capa/springboot/rpc/server/CapaServerSettings.java @@ -0,0 +1,29 @@ +package group.rxcloud.capa.springboot.rpc.server; + +/** + * Set custom parameters. If not necessary, use the default Settings. Note that this is set in the static phase. + */ +public interface CapaServerSettings { + + /** + * Internal module running parameters, generally used for debugging + */ + abstract class Internal { + + } + + /** + * Exposes run parameters, typically for custom Settings + */ + abstract class Public { + + /** + * The prefix used when the service is exposed. The default is /API/ + */ + public static String SERVLET_MAPPING_PREFIX = "/api/"; + + public static void setCustomServletMappingPrefix(String servletMappingPrefix) { + SERVLET_MAPPING_PREFIX = servletMappingPrefix; + } + } +} diff --git a/sdk-springboot/src/main/java/group/rxcloud/capa/springboot/rpc/server/CapaServerSpringInitializer.java b/sdk-springboot/src/main/java/group/rxcloud/capa/springboot/rpc/server/CapaServerSpringInitializer.java new file mode 100644 index 0000000..1794d6c --- /dev/null +++ b/sdk-springboot/src/main/java/group/rxcloud/capa/springboot/rpc/server/CapaServerSpringInitializer.java @@ -0,0 +1,35 @@ +package group.rxcloud.capa.springboot.rpc.server; + +import group.rxcloud.vrml.core.beans.SpringContextConfigurator; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.BeansException; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.context.ApplicationListener; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.event.ContextRefreshedEvent; + +@Configuration +public class CapaServerSpringInitializer implements ApplicationContextAware, + ApplicationListener { + + private static final Logger logger = LoggerFactory.getLogger(CapaServerSpringInitializer.class); + + public CapaServerSpringInitializer() { + logger.info("[Capa.Rpc.Server] server init..."); + } + + /** + * Use `vrml` to set all spring beans to static field + */ + @Override + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { + SpringContextConfigurator.setStaticApplicationContext(applicationContext); + } + + @Override + public void onApplicationEvent(ContextRefreshedEvent event) { + SpringContextConfigurator.setStaticApplicationContext(event.getApplicationContext()); + } +} diff --git a/sdk-springboot/src/main/java/group/rxcloud/capa/springboot/rpc/server/plugin/CapaServerWarmupPlugin.java b/sdk-springboot/src/main/java/group/rxcloud/capa/springboot/rpc/server/plugin/CapaServerWarmupPlugin.java new file mode 100644 index 0000000..669e1e9 --- /dev/null +++ b/sdk-springboot/src/main/java/group/rxcloud/capa/springboot/rpc/server/plugin/CapaServerWarmupPlugin.java @@ -0,0 +1,17 @@ +package group.rxcloud.capa.springboot.rpc.server.plugin; + +/** + * The Capa server warmup plugin. + */ +public interface CapaServerWarmupPlugin { + + /** + * True will skip warmup logic. + */ + boolean isInited(); + + /** + * Custom sync warmup logic. + */ + void warmup(); +} diff --git a/sdk-springboot/src/main/java/group/rxcloud/capa/springboot/rpc/server/plugin/CapaServletContext.java b/sdk-springboot/src/main/java/group/rxcloud/capa/springboot/rpc/server/plugin/CapaServletContext.java new file mode 100644 index 0000000..6afc036 --- /dev/null +++ b/sdk-springboot/src/main/java/group/rxcloud/capa/springboot/rpc/server/plugin/CapaServletContext.java @@ -0,0 +1,16 @@ +package group.rxcloud.capa.springboot.rpc.server.plugin; + +import javax.servlet.http.HttpServletRequest; + +/** + * The Capa servlet context plugin. + */ +public interface CapaServletContext { + + /** + * Gets servlet request. + * + * @return the servlet request + */ + HttpServletRequest getServletRequest(); +} diff --git a/sdk-springboot/src/main/java/group/rxcloud/capa/springboot/schedule/Schedule.java b/sdk-springboot/src/main/java/group/rxcloud/capa/springboot/schedule/Schedule.java new file mode 100644 index 0000000..de10290 --- /dev/null +++ b/sdk-springboot/src/main/java/group/rxcloud/capa/springboot/schedule/Schedule.java @@ -0,0 +1,33 @@ +package group.rxcloud.capa.springboot.schedule; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * The Schedule. + * + * @author capa + */ +@Documented +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.TYPE, ElementType.METHOD}) +public @interface Schedule { + + /** + * The name of the job, which is globally unique + */ + String value() default ""; + + /** + * Name of the shared thread pool bean + */ + String executor() default ""; + + /** + * Filter bean Name, in order + */ + String[] filters() default {}; +} diff --git a/sdk-springboot/src/main/java/group/rxcloud/capa/springboot/schedule/ScheduleAutoConfiguration.java b/sdk-springboot/src/main/java/group/rxcloud/capa/springboot/schedule/ScheduleAutoConfiguration.java new file mode 100644 index 0000000..2daf895 --- /dev/null +++ b/sdk-springboot/src/main/java/group/rxcloud/capa/springboot/schedule/ScheduleAutoConfiguration.java @@ -0,0 +1,42 @@ +package group.rxcloud.capa.springboot.schedule; + +import org.springframework.beans.factory.config.AutowireCapableBeanFactory; +import org.springframework.beans.factory.support.BeanDefinitionRegistry; +import org.springframework.beans.factory.support.GenericBeanDefinition; +import org.springframework.boot.autoconfigure.AutoConfigureOrder; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; +import org.springframework.context.annotation.ImportBeanDefinitionRegistrar; +import org.springframework.core.type.AnnotationMetadata; + +/** + * The Schedule autoconfiguration. + */ +@Configuration +@AutoConfigureOrder +@Import(ScheduleAutoConfiguration.Register.class) +public class ScheduleAutoConfiguration { + + /** + * The Register. + */ + public static class Register implements ImportBeanDefinitionRegistrar { + + /** + * The Schedule name. + */ + static final String SCHEDULE_ANNOTATION = "SCHEDULE_ANNOTATION"; + + @Override + public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { + GenericBeanDefinition beanDefinition = new GenericBeanDefinition(); + beanDefinition.setBeanClass(ScheduleRegister.class); + beanDefinition.setRole(2); + beanDefinition.setSynthetic(true); + beanDefinition.setAutowireMode(AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE); + beanDefinition.setAutowireCandidate(false); + beanDefinition.setLazyInit(true); + registry.registerBeanDefinition(SCHEDULE_ANNOTATION, beanDefinition); + } + } +} diff --git a/sdk-springboot/src/main/java/group/rxcloud/capa/springboot/schedule/ScheduleRegister.java b/sdk-springboot/src/main/java/group/rxcloud/capa/springboot/schedule/ScheduleRegister.java new file mode 100644 index 0000000..219e560 --- /dev/null +++ b/sdk-springboot/src/main/java/group/rxcloud/capa/springboot/schedule/ScheduleRegister.java @@ -0,0 +1,65 @@ +package group.rxcloud.capa.springboot.schedule; + +import group.rxcloud.capa.environment.CapaEnvironmentClient; +import group.rxcloud.capa.infrastructure.exceptions.CapaExceptions; +import group.rxcloud.capa.schedule.CapaScheduleClient; +import group.rxcloud.vrml.core.serialization.Serialization; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.BeanPostProcessor; +import org.springframework.core.annotation.AnnotationUtils; +import reactor.core.publisher.Flux; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.HashMap; + +public class ScheduleRegister implements BeanPostProcessor { + + private static final Logger logger = LoggerFactory.getLogger(ScheduleRegister.class); + + @Autowired + private CapaEnvironmentClient capaEnvironmentClient; + @Autowired + private CapaScheduleClient capaScheduleClient; + + @Override + public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { + final Method[] declaredMethods = bean.getClass().getDeclaredMethods(); + for (Method method : declaredMethods) { + Schedule scheduleAnnotation = AnnotationUtils.findAnnotation(method, Schedule.class); + if (scheduleAnnotation != null) { + registerSchedule(bean, method, scheduleAnnotation); + } + } + return bean; + } + + private void registerSchedule(Object bean, Method method, Schedule annotation) { + final String appId = capaEnvironmentClient.appId(); + final String jobName = annotation.value(); + logger.info("[Capa.@Schedule.register] register schedule appId[{}] jobName[{}]", + appId, jobName); + + Flux flux = capaScheduleClient.invokeSchedule(appId, jobName, new HashMap<>(2)); + flux.subscribe(param -> { + logger.info("[Capa.@Schedule.invoke] schedule appId[{}] jobName[{}] invoked with param[{}]", + appId, jobName, Serialization.toJsonSafe(param)); + + Throwable ex = null; + try { + method.invoke(bean, param); + } catch (InvocationTargetException e) { + ex = e.getTargetException(); + } catch (Throwable e) { + ex = e; + } + if (ex != null) { + logger.error("[Capa.@Schedule.invoke] schedule error", ex); + throw CapaExceptions.propagate(ex); + } + }); + } +} diff --git a/sdk-springboot/src/main/resources/META-INF/spring.factories b/sdk-springboot/src/main/resources/META-INF/spring.factories new file mode 100644 index 0000000..ccde74b --- /dev/null +++ b/sdk-springboot/src/main/resources/META-INF/spring.factories @@ -0,0 +1,2 @@ +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ + group.rxcloud.capa.springboot.schedule.ScheduleAutoConfiguration \ No newline at end of file diff --git a/sdk/pom.xml b/sdk/pom.xml index 7bfd1b4..ad9c4c2 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -23,7 +23,7 @@ group.rxcloud capa-parent - 1.11.13.2.RELEASE + 2.12.1.RELEASE capa-sdk @@ -38,6 +38,65 @@ capa-sdk-component + + + group.rxcloud + cloud-runtimes-api + true + + + + io.projectreactor + reactor-core + true + + + + org.slf4j + slf4j-api + true + + + + io.opentelemetry + opentelemetry-api + true + + + io.opentelemetry + opentelemetry-api-metrics + true + + + + io.vavr + vavr + true + + + + com.google.code.gson + gson + true + + + + com.squareup.okhttp3 + okhttp + true + + + + org.jetbrains.kotlin + kotlin-stdlib + true + + + org.jetbrains.kotlin + kotlin-stdlib-common + true + + org.junit.jupiter diff --git a/sdk/src/main/java/group/rxcloud/capa/AbstractCapaClient.java b/sdk/src/main/java/group/rxcloud/capa/AbstractCapaClient.java new file mode 100644 index 0000000..0721a43 --- /dev/null +++ b/sdk/src/main/java/group/rxcloud/capa/AbstractCapaClient.java @@ -0,0 +1,13 @@ +package group.rxcloud.capa; + +import java.util.List; + +public abstract class AbstractCapaClient implements CapaClient { + + protected List registryNames; + + @Override + public List registryNames() { + return registryNames; + } +} diff --git a/sdk/src/main/java/group/rxcloud/capa/CapaClient.java b/sdk/src/main/java/group/rxcloud/capa/CapaClient.java new file mode 100644 index 0000000..f83b1e8 --- /dev/null +++ b/sdk/src/main/java/group/rxcloud/capa/CapaClient.java @@ -0,0 +1,20 @@ +package group.rxcloud.capa; + +import group.rxcloud.cloudruntimes.client.DefaultCloudRuntimesClient; +import reactor.core.publisher.Mono; + +import java.util.List; + +public interface CapaClient extends DefaultCloudRuntimesClient { + + @Override + List registryNames(); + + @Override + default Mono shutdown() { + return Mono.empty(); + } + + @Override + void close(); +} diff --git a/sdk/src/main/java/group/rxcloud/capa/binding/AbstractCapaBindingClient.java b/sdk/src/main/java/group/rxcloud/capa/binding/AbstractCapaBindingClient.java new file mode 100644 index 0000000..f5ec7e8 --- /dev/null +++ b/sdk/src/main/java/group/rxcloud/capa/binding/AbstractCapaBindingClient.java @@ -0,0 +1,72 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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. + */ +package group.rxcloud.capa.binding; + + +import group.rxcloud.capa.AbstractCapaClient; +import group.rxcloud.capa.configuration.CapaConfigurationClient; +import group.rxcloud.capa.configuration.CapaConfigurationClientStore; +import group.rxcloud.cloudruntimes.domain.core.binding.InvokeBindingRequest; +import group.rxcloud.cloudruntimes.domain.core.configuration.ConfigurationRequestItem; +import group.rxcloud.cloudruntimes.domain.core.configuration.SaveConfigurationRequest; +import group.rxcloud.cloudruntimes.utils.TypeRef; +import reactor.core.publisher.Mono; + +import java.util.Map; + +/** + * Abstract class with convenient methods common between client implementations. + */ +public abstract class AbstractCapaBindingClient + extends AbstractCapaClient + implements CapaBindingClient { + + @Override + public Mono invokeBinding(String bindingName, String operation, Object data) { + return null; + } + + @Override + public Mono invokeBinding(String bindingName, String operation, byte[] data, Map metadata) { + return null; + } + + @Override + public Mono invokeBinding(String bindingName, String operation, Object data, TypeRef type) { + return null; + } + + @Override + public Mono invokeBinding(String bindingName, String operation, Object data, Class clazz) { + return null; + } + + @Override + public Mono invokeBinding(String bindingName, String operation, Object data, Map metadata, TypeRef type) { + return null; + } + + @Override + public Mono invokeBinding(String bindingName, String operation, Object data, Map metadata, Class clazz) { + return null; + } + + @Override + public Mono invokeBinding(InvokeBindingRequest request, TypeRef type) { + return null; + } +} diff --git a/sdk/src/main/java/group/rxcloud/capa/binding/CapaBindingClient.java b/sdk/src/main/java/group/rxcloud/capa/binding/CapaBindingClient.java new file mode 100644 index 0000000..1bbee2e --- /dev/null +++ b/sdk/src/main/java/group/rxcloud/capa/binding/CapaBindingClient.java @@ -0,0 +1,35 @@ +package group.rxcloud.capa.binding; + +import group.rxcloud.capa.CapaClient; +import group.rxcloud.cloudruntimes.domain.core.binding.InvokeBindingRequest; +import group.rxcloud.cloudruntimes.utils.TypeRef; +import reactor.core.publisher.Mono; + +import java.util.Map; + +/** + * The Capa binding client. + */ +public interface CapaBindingClient extends CapaClient { + + @Override + Mono invokeBinding(String bindingName, String operation, Object data); + + @Override + Mono invokeBinding(String bindingName, String operation, byte[] data, Map metadata); + + @Override + Mono invokeBinding(String bindingName, String operation, Object data, TypeRef type); + + @Override + Mono invokeBinding(String bindingName, String operation, Object data, Class clazz); + + @Override + Mono invokeBinding(String bindingName, String operation, Object data, Map metadata, TypeRef type); + + @Override + Mono invokeBinding(String bindingName, String operation, Object data, Map metadata, Class clazz); + + @Override + Mono invokeBinding(InvokeBindingRequest request, TypeRef type); +} diff --git a/sdk/src/main/java/group/rxcloud/capa/configuration/AbstractCapaConfigurationClient.java b/sdk/src/main/java/group/rxcloud/capa/configuration/AbstractCapaConfigurationClient.java index e11cbaa..898efe2 100644 --- a/sdk/src/main/java/group/rxcloud/capa/configuration/AbstractCapaConfigurationClient.java +++ b/sdk/src/main/java/group/rxcloud/capa/configuration/AbstractCapaConfigurationClient.java @@ -17,47 +17,55 @@ package group.rxcloud.capa.configuration; +import group.rxcloud.capa.AbstractCapaClient; import group.rxcloud.cloudruntimes.domain.core.configuration.ConfigurationItem; import group.rxcloud.cloudruntimes.domain.core.configuration.ConfigurationRequestItem; import group.rxcloud.cloudruntimes.domain.core.configuration.SaveConfigurationRequest; -import group.rxcloud.cloudruntimes.domain.core.configuration.SubConfigurationResp; import group.rxcloud.cloudruntimes.utils.TypeRef; -import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import java.util.List; +import java.util.Map; +import java.util.Objects; /** * Abstract class with convenient methods common between client implementations. * * @see CapaConfigurationClientStore */ -public abstract class AbstractCapaConfigurationClient implements CapaConfigurationClient { - - protected List registryNames; +public abstract class AbstractCapaConfigurationClient + extends AbstractCapaClient + implements CapaConfigurationClient { @Override - public List registryNames() { - return registryNames; + public Mono>> getConfiguration(String storeName, String appId, List keys, Map metadata, TypeRef type) { + return getConfiguration(storeName, appId, keys, metadata, null, null, type); } @Override - public Mono saveConfiguration(SaveConfigurationRequest saveConfigurationRequest) { - return Mono.error(new UnsupportedOperationException("unsupported save configuration")); + public Mono>> getConfiguration(String storeName, String appId, List keys, Map metadata, String group, TypeRef type) { + return getConfiguration(storeName, appId, keys, metadata, group, null, type); } @Override - public Mono deleteConfiguration(ConfigurationRequestItem configurationRequestItem) { - return Mono.error(new UnsupportedOperationException("unsupported delete configuration")); + public Mono>> getConfiguration(ConfigurationRequestItem configurationRequestItem, TypeRef type) { + Objects.requireNonNull(configurationRequestItem, "[Capa] configurationRequestItem cannot be null."); + return getConfiguration(configurationRequestItem.getStoreName(), + configurationRequestItem.getAppId(), + configurationRequestItem.getKeys(), + configurationRequestItem.getMetadata(), + configurationRequestItem.getGroup(), + configurationRequestItem.getLabel(), + type); } @Override - public Mono>> getConfiguration(ConfigurationRequestItem configurationRequestItem, TypeRef type) { - return Mono.error(new UnsupportedOperationException("unsupported get configuration with ConfigurationRequestItem as parameter")); + public Mono saveConfiguration(SaveConfigurationRequest saveConfigurationRequest) { + return Mono.error(new UnsupportedOperationException("[Capa] Unsupported save configuration")); } @Override - public Flux> subscribeConfiguration(ConfigurationRequestItem configurationRequestItem, TypeRef type) { - return Flux.error(new UnsupportedOperationException("unsupported subscribe configuration with ConfigurationRequestItem as parameter")); + public Mono deleteConfiguration(ConfigurationRequestItem configurationRequestItem) { + return Mono.error(new UnsupportedOperationException("[Capa] Unsupported delete configuration")); } } diff --git a/sdk/src/main/java/group/rxcloud/capa/configuration/CapaConfigurationClient.java b/sdk/src/main/java/group/rxcloud/capa/configuration/CapaConfigurationClient.java index aa213e1..753b20e 100644 --- a/sdk/src/main/java/group/rxcloud/capa/configuration/CapaConfigurationClient.java +++ b/sdk/src/main/java/group/rxcloud/capa/configuration/CapaConfigurationClient.java @@ -16,6 +16,7 @@ */ package group.rxcloud.capa.configuration; +import group.rxcloud.capa.CapaClient; import group.rxcloud.cloudruntimes.client.DefaultCloudRuntimesClient; import group.rxcloud.cloudruntimes.domain.core.configuration.ConfigurationItem; import group.rxcloud.cloudruntimes.domain.core.configuration.ConfigurationRequestItem; @@ -31,7 +32,7 @@ /** * Generic Client Adapter to be used regardless of the specific Configuration Client implementation required. */ -public interface CapaConfigurationClient extends DefaultCloudRuntimesClient { +public interface CapaConfigurationClient extends CapaClient { @Override Mono>> getConfiguration(String storeName, String appId, List keys, Map metadata, TypeRef type); @@ -62,12 +63,4 @@ public interface CapaConfigurationClient extends DefaultCloudRuntimesClient { @Override Mono deleteConfiguration(ConfigurationRequestItem configurationRequestItem); - - @Override - default Mono shutdown() { - return Mono.empty(); - } - - @Override - void close(); } diff --git a/sdk/src/main/java/group/rxcloud/capa/configuration/CapaConfigurationClientStore.java b/sdk/src/main/java/group/rxcloud/capa/configuration/CapaConfigurationClientStore.java index 2a143e4..525c858 100644 --- a/sdk/src/main/java/group/rxcloud/capa/configuration/CapaConfigurationClientStore.java +++ b/sdk/src/main/java/group/rxcloud/capa/configuration/CapaConfigurationClientStore.java @@ -22,6 +22,7 @@ import group.rxcloud.capa.component.configstore.SubscribeResp; import group.rxcloud.capa.infrastructure.exceptions.CapaExceptions; import group.rxcloud.cloudruntimes.domain.core.configuration.ConfigurationItem; +import group.rxcloud.cloudruntimes.domain.core.configuration.ConfigurationRequestItem; import group.rxcloud.cloudruntimes.domain.core.configuration.SubConfigurationResp; import group.rxcloud.cloudruntimes.utils.TypeRef; import reactor.core.publisher.Flux; @@ -64,19 +65,10 @@ public CapaConfigurationClientStore(List stores) { private CapaConfigStore getStore(String storeName) { // check storeName if (storeName == null || storeName.trim().isEmpty()) { - throw new IllegalArgumentException("Store Name cannot be null or empty."); + throw new IllegalArgumentException("[Capa] store Name cannot be null or empty."); } - return Objects.requireNonNull(configStores.get(storeName), "Store Component cannot be null."); - } - - @Override - public Mono>> getConfiguration(String storeName, String appId, List keys, Map metadata, TypeRef type) { - return getConfiguration(storeName, appId, keys, metadata, null, null, type); - } - - @Override - public Mono>> getConfiguration(String storeName, String appId, List keys, Map metadata, String group, TypeRef type) { - return getConfiguration(storeName, appId, keys, metadata, group, null, type); + final CapaConfigStore configStore = configStores.get(storeName); + return Objects.requireNonNull(configStore, "[Capa] store Component cannot be null."); } @Override @@ -136,6 +128,18 @@ public Flux> subscribeConfiguration(String storeName return subscribeConfiguration(storeName, appId, keys, metadata, group, null, type); } + @Override + public Flux> subscribeConfiguration(ConfigurationRequestItem configurationRequestItem, TypeRef type) { + Objects.requireNonNull(configurationRequestItem, "[Capa] configurationRequestItem cannot be null."); + return subscribeConfiguration(configurationRequestItem.getStoreName(), + configurationRequestItem.getAppId(), + configurationRequestItem.getKeys(), + configurationRequestItem.getMetadata(), + configurationRequestItem.getGroup(), + configurationRequestItem.getLabel(), + type); + } + @Override public Flux> subscribeConfiguration(String storeName, String appId, List keys, Map metadata, String group, String label, TypeRef type) { try { diff --git a/sdk/src/main/java/group/rxcloud/capa/database/AbstractCapaDatabaseClient.java b/sdk/src/main/java/group/rxcloud/capa/database/AbstractCapaDatabaseClient.java new file mode 100644 index 0000000..f7007c6 --- /dev/null +++ b/sdk/src/main/java/group/rxcloud/capa/database/AbstractCapaDatabaseClient.java @@ -0,0 +1,45 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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. + */ +package group.rxcloud.capa.database; + + +import group.rxcloud.capa.AbstractCapaClient; +import group.rxcloud.capa.configuration.CapaConfigurationClient; +import group.rxcloud.capa.configuration.CapaConfigurationClientStore; +import group.rxcloud.cloudruntimes.domain.core.configuration.ConfigurationRequestItem; +import group.rxcloud.cloudruntimes.domain.core.configuration.SaveConfigurationRequest; +import reactor.core.publisher.Mono; + +/** + * Abstract class with convenient methods common between client implementations. + * + * @see CapaConfigurationClientStore + */ +public abstract class AbstractCapaDatabaseClient + extends AbstractCapaClient + implements CapaConfigurationClient { + + @Override + public Mono saveConfiguration(SaveConfigurationRequest saveConfigurationRequest) { + return Mono.error(new UnsupportedOperationException("[Capa] Unsupported save configuration")); + } + + @Override + public Mono deleteConfiguration(ConfigurationRequestItem configurationRequestItem) { + return Mono.error(new UnsupportedOperationException("[Capa] Unsupported delete configuration")); + } +} diff --git a/sdk/src/main/java/group/rxcloud/capa/database/CapaDatabaseClient.java b/sdk/src/main/java/group/rxcloud/capa/database/CapaDatabaseClient.java new file mode 100644 index 0000000..f1f5e7b --- /dev/null +++ b/sdk/src/main/java/group/rxcloud/capa/database/CapaDatabaseClient.java @@ -0,0 +1,68 @@ +package group.rxcloud.capa.database; + +import group.rxcloud.capa.CapaClient; +import group.rxcloud.cloudruntimes.client.DefaultCloudRuntimesClient; +import group.rxcloud.cloudruntimes.domain.enhanced.database.CreateTableRequest; +import group.rxcloud.cloudruntimes.domain.enhanced.database.CreateTableResponse; +import group.rxcloud.cloudruntimes.domain.enhanced.database.DeleteTableRequest; +import group.rxcloud.cloudruntimes.domain.enhanced.database.DeleteTableResponse; +import group.rxcloud.cloudruntimes.domain.enhanced.database.GetConnectionRequest; +import group.rxcloud.cloudruntimes.domain.enhanced.database.GetConnectionResponse; +import group.rxcloud.cloudruntimes.domain.enhanced.database.InsertRequest; +import group.rxcloud.cloudruntimes.domain.enhanced.database.InsertResponse; +import group.rxcloud.cloudruntimes.domain.enhanced.database.QueryRequest; +import group.rxcloud.cloudruntimes.domain.enhanced.database.QueryResponse; +import group.rxcloud.cloudruntimes.domain.enhanced.database.UpdateRequest; +import group.rxcloud.cloudruntimes.domain.enhanced.database.UpdateResponse; +import group.rxcloud.cloudruntimes.utils.TypeRef; +import reactor.core.publisher.Mono; + +import java.util.List; + +/** + * The Capa database client. + */ +public interface CapaDatabaseClient extends CapaClient { + + @Override + Mono getConnection(GetConnectionRequest req); + + @Override + Mono createTable(CreateTableRequest req); + + @Override + Mono deleteTable(DeleteTableRequest req); + + @Override + Mono insert(InsertRequest req); + + @Override + Mono insert(String dbName, String tableName, Object data); + + @Override + Mono> query(QueryRequest req, TypeRef type); + + @Override + Mono> query(String dbName, String tableName, Object data, TypeRef type); + + @Override + Mono update(UpdateRequest req); + + @Override + Mono update(String dbName, String tableName, Object data); + + @Override + Mono BeginTransaction(); + + @Override + Mono UpdateTransaction(); + + @Override + Mono QueryTransaction(); + + @Override + Mono CommitTransaction(); + + @Override + Mono RollbackTransaction(); +} diff --git a/sdk/src/main/java/group/rxcloud/capa/environment/AbstractCapaEnvironmentClient.java b/sdk/src/main/java/group/rxcloud/capa/environment/AbstractCapaEnvironmentClient.java new file mode 100644 index 0000000..1e3f481 --- /dev/null +++ b/sdk/src/main/java/group/rxcloud/capa/environment/AbstractCapaEnvironmentClient.java @@ -0,0 +1,45 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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. + */ +package group.rxcloud.capa.environment; + + +import group.rxcloud.capa.AbstractCapaClient; +import group.rxcloud.capa.configuration.CapaConfigurationClient; +import group.rxcloud.capa.configuration.CapaConfigurationClientStore; +import group.rxcloud.cloudruntimes.domain.core.configuration.ConfigurationRequestItem; +import group.rxcloud.cloudruntimes.domain.core.configuration.SaveConfigurationRequest; +import reactor.core.publisher.Mono; + +/** + * Abstract class with convenient methods common between client implementations. + * + * @see CapaConfigurationClientStore + */ +public abstract class AbstractCapaEnvironmentClient + extends AbstractCapaClient + implements CapaConfigurationClient { + + @Override + public Mono saveConfiguration(SaveConfigurationRequest saveConfigurationRequest) { + return Mono.error(new UnsupportedOperationException("[Capa] Unsupported save configuration")); + } + + @Override + public Mono deleteConfiguration(ConfigurationRequestItem configurationRequestItem) { + return Mono.error(new UnsupportedOperationException("[Capa] Unsupported delete configuration")); + } +} diff --git a/sdk/src/main/java/group/rxcloud/capa/environment/CapaEnvironmentClient.java b/sdk/src/main/java/group/rxcloud/capa/environment/CapaEnvironmentClient.java new file mode 100644 index 0000000..c3a4cf6 --- /dev/null +++ b/sdk/src/main/java/group/rxcloud/capa/environment/CapaEnvironmentClient.java @@ -0,0 +1,42 @@ +package group.rxcloud.capa.environment; + +import group.rxcloud.capa.CapaClient; +import reactor.core.publisher.Flux; + +import java.util.Map; + +/** + * The Capa environment client. + */ +public interface CapaEnvironmentClient extends CapaClient { + + @Override + default String appId() { + return CapaClient.super.appId(); + } + + @Override + default String env() { + return CapaClient.super.env(); + } + + @Override + default String ip() { + return CapaClient.super.ip(); + } + + @Override + default String cloud() { + return CapaClient.super.cloud(); + } + + @Override + default String region() { + return CapaClient.super.region(); + } + + @Override + default String getProperty(String name, String defaultValue) { + return CapaClient.super.getProperty(name, defaultValue); + } +} diff --git a/sdk/src/main/java/group/rxcloud/capa/file/AbstractCapaFileClient.java b/sdk/src/main/java/group/rxcloud/capa/file/AbstractCapaFileClient.java new file mode 100644 index 0000000..36cde92 --- /dev/null +++ b/sdk/src/main/java/group/rxcloud/capa/file/AbstractCapaFileClient.java @@ -0,0 +1,45 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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. + */ +package group.rxcloud.capa.file; + + +import group.rxcloud.capa.AbstractCapaClient; +import group.rxcloud.capa.configuration.CapaConfigurationClient; +import group.rxcloud.capa.configuration.CapaConfigurationClientStore; +import group.rxcloud.cloudruntimes.domain.core.configuration.ConfigurationRequestItem; +import group.rxcloud.cloudruntimes.domain.core.configuration.SaveConfigurationRequest; +import reactor.core.publisher.Mono; + +/** + * Abstract class with convenient methods common between client implementations. + * + * @see CapaConfigurationClientStore + */ +public abstract class AbstractCapaFileClient + extends AbstractCapaClient + implements CapaConfigurationClient { + + @Override + public Mono saveConfiguration(SaveConfigurationRequest saveConfigurationRequest) { + return Mono.error(new UnsupportedOperationException("[Capa] Unsupported save configuration")); + } + + @Override + public Mono deleteConfiguration(ConfigurationRequestItem configurationRequestItem) { + return Mono.error(new UnsupportedOperationException("[Capa] Unsupported delete configuration")); + } +} diff --git a/sdk/src/main/java/group/rxcloud/capa/file/CapaFileClient.java b/sdk/src/main/java/group/rxcloud/capa/file/CapaFileClient.java new file mode 100644 index 0000000..1cc21e9 --- /dev/null +++ b/sdk/src/main/java/group/rxcloud/capa/file/CapaFileClient.java @@ -0,0 +1,32 @@ +package group.rxcloud.capa.file; + +import group.rxcloud.capa.CapaClient; +import group.rxcloud.cloudruntimes.client.DefaultCloudRuntimesClient; +import group.rxcloud.cloudruntimes.domain.enhanced.file.DelFileRequest; +import group.rxcloud.cloudruntimes.domain.enhanced.file.GetFileRequest; +import group.rxcloud.cloudruntimes.domain.enhanced.file.GetFileResponse; +import group.rxcloud.cloudruntimes.domain.enhanced.file.ListFileRequest; +import group.rxcloud.cloudruntimes.domain.enhanced.file.ListFileResp; +import group.rxcloud.cloudruntimes.domain.enhanced.file.PutFileRequest; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +import java.util.List; + +/** + * The Capa file client. + */ +public interface CapaFileClient extends CapaClient { + + @Override + Mono getFile(GetFileRequest request); + + @Override + Mono putFile(Flux requests); + + @Override + Mono listFile(ListFileRequest request); + + @Override + Mono delFile(DelFileRequest request); +} diff --git a/sdk/src/main/java/group/rxcloud/capa/lock/AbstractCapaLockClient.java b/sdk/src/main/java/group/rxcloud/capa/lock/AbstractCapaLockClient.java new file mode 100644 index 0000000..94238b3 --- /dev/null +++ b/sdk/src/main/java/group/rxcloud/capa/lock/AbstractCapaLockClient.java @@ -0,0 +1,45 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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. + */ +package group.rxcloud.capa.lock; + + +import group.rxcloud.capa.AbstractCapaClient; +import group.rxcloud.capa.configuration.CapaConfigurationClient; +import group.rxcloud.capa.configuration.CapaConfigurationClientStore; +import group.rxcloud.cloudruntimes.domain.core.configuration.ConfigurationRequestItem; +import group.rxcloud.cloudruntimes.domain.core.configuration.SaveConfigurationRequest; +import reactor.core.publisher.Mono; + +/** + * Abstract class with convenient methods common between client implementations. + * + * @see CapaConfigurationClientStore + */ +public abstract class AbstractCapaLockClient + extends AbstractCapaClient + implements CapaConfigurationClient { + + @Override + public Mono saveConfiguration(SaveConfigurationRequest saveConfigurationRequest) { + return Mono.error(new UnsupportedOperationException("[Capa] Unsupported save configuration")); + } + + @Override + public Mono deleteConfiguration(ConfigurationRequestItem configurationRequestItem) { + return Mono.error(new UnsupportedOperationException("[Capa] Unsupported delete configuration")); + } +} diff --git a/sdk/src/main/java/group/rxcloud/capa/lock/CapaLockClient.java b/sdk/src/main/java/group/rxcloud/capa/lock/CapaLockClient.java new file mode 100644 index 0000000..cf05d87 --- /dev/null +++ b/sdk/src/main/java/group/rxcloud/capa/lock/CapaLockClient.java @@ -0,0 +1,23 @@ +package group.rxcloud.capa.lock; + +import group.rxcloud.capa.CapaClient; +import group.rxcloud.cloudruntimes.client.DefaultCloudRuntimesClient; +import group.rxcloud.cloudruntimes.domain.enhanced.lock.TryLockRequest; +import group.rxcloud.cloudruntimes.domain.enhanced.lock.TryLockResponse; +import group.rxcloud.cloudruntimes.domain.enhanced.lock.UnlockRequest; +import group.rxcloud.cloudruntimes.domain.enhanced.lock.UnlockResponse; +import reactor.core.publisher.Mono; + +import java.util.List; + +/** + * The Capa lock client. + */ +public interface CapaLockClient extends CapaClient { + + @Override + Mono tryLock(TryLockRequest request); + + @Override + Mono unlock(UnlockRequest request); +} diff --git a/sdk/src/main/java/group/rxcloud/capa/nativeredis/AbstractCapaNativeRedisClient.java b/sdk/src/main/java/group/rxcloud/capa/nativeredis/AbstractCapaNativeRedisClient.java new file mode 100644 index 0000000..170b896 --- /dev/null +++ b/sdk/src/main/java/group/rxcloud/capa/nativeredis/AbstractCapaNativeRedisClient.java @@ -0,0 +1,45 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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. + */ +package group.rxcloud.capa.nativeredis; + + +import group.rxcloud.capa.AbstractCapaClient; +import group.rxcloud.capa.configuration.CapaConfigurationClient; +import group.rxcloud.capa.configuration.CapaConfigurationClientStore; +import group.rxcloud.cloudruntimes.domain.core.configuration.ConfigurationRequestItem; +import group.rxcloud.cloudruntimes.domain.core.configuration.SaveConfigurationRequest; +import reactor.core.publisher.Mono; + +/** + * Abstract class with convenient methods common between client implementations. + * + * @see CapaConfigurationClientStore + */ +public abstract class AbstractCapaNativeRedisClient + extends AbstractCapaClient + implements CapaConfigurationClient { + + @Override + public Mono saveConfiguration(SaveConfigurationRequest saveConfigurationRequest) { + return Mono.error(new UnsupportedOperationException("[Capa] Unsupported save configuration")); + } + + @Override + public Mono deleteConfiguration(ConfigurationRequestItem configurationRequestItem) { + return Mono.error(new UnsupportedOperationException("[Capa] Unsupported delete configuration")); + } +} diff --git a/sdk/src/main/java/group/rxcloud/capa/nativeredis/CapaNativeRedisClient.java b/sdk/src/main/java/group/rxcloud/capa/nativeredis/CapaNativeRedisClient.java new file mode 100644 index 0000000..1928bbe --- /dev/null +++ b/sdk/src/main/java/group/rxcloud/capa/nativeredis/CapaNativeRedisClient.java @@ -0,0 +1,344 @@ +package group.rxcloud.capa.nativeredis; + +import group.rxcloud.capa.CapaClient; +import group.rxcloud.cloudruntimes.client.DefaultCloudRuntimesClient; +import group.rxcloud.cloudruntimes.domain.nativeproto.redis.geo.GeoRadiusResponse; +import group.rxcloud.cloudruntimes.domain.nativeproto.redis.geo.GeoUnit; +import reactor.core.publisher.Mono; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * The Capa native redis client. + */ +public interface CapaNativeRedisClient extends CapaClient { + + @Override + Mono invokeRedis(String storeName, String cmd, byte[] args, Map metadata); + + @Override + Boolean move(String key, int dbIndex); + + @Override + long dbSize(); + + @Override + String flushDB(); + + @Override + String flushAll(); + + @Override + String select(int index); + + @Override + String swapDB(int index1, int index2); + + @Override + String ping(); + + @Override + Long geoadd(String key, double longitude, double latitude, String member); + + @Override + Double geodist(String key, String member1, String member2, GeoUnit unit); + + @Override + List georadius(String key, double longitude, double latitude, double radius, GeoUnit unit, String withX, String sortX, int count); + + @Override + List georadiusByMember(String key, String member, double radius, GeoUnit unit, String withX, String sortX, int count); + + @Override + List geohash(String key, String... members); + + @Override + Boolean hset(String key, String field, String value); + + @Override + Boolean hsetnx(String key, String field, String value); + + @Override + String hget(String key, String field); + + @Override + Boolean hexists(String key, String field); + + @Override + Long hdel(String key, String... fields); + + @Override + Long hlen(String key); + + @Override + Long hstrlen(String key, String field); + + @Override + Long hincrBy(String key, String field, long increment); + + @Override + Double hincrByFloat(String key, String field, double increment); + + @Override + Boolean hmset(String key, Map keyValues); + + @Override + List hmget(String key, String... fields); + + @Override + Set hkeys(String key); + + @Override + List hvals(String key); + + @Override + Map hgetAll(String key); + + @Override + Boolean exists(String key); + + @Override + String type(String key); + + @Override + String rename(String oldkey, String newkey); + + @Override + long renamenx(String oldkey, String newkey); + + @Override + Long del(String... keys); + + @Override + String randomKey(); + + @Override + Set keys(String pattern); + + @Override + Boolean expire(String key, long seconds); + + @Override + Boolean expireAt(String key, long unixtime); + + @Override + Long ttl(String key); + + @Override + Boolean persist(String key); + + @Override + Boolean pexpire(String key, long milliseconds); + + @Override + long pexpireAt(String key, long millisecondsTimestamp); + + @Override + long pttl(String key); + + @Override + Long lpush(String key, String... elements); + + @Override + Long lpushx(String key, String... elements); + + @Override + Long rpush(String key, String... elements); + + @Override + Long rpushx(String key, String... elements); + + @Override + String lpop(String key); + + @Override + String rpop(String key); + + @Override + String rpoplpush(String src, String dst); + + @Override + Long lrem(String key, long count, String element); + + @Override + Long llen(String key); + + @Override + String lindex(String key, long index); + + @Override + Long linsert(String key, String beforeORafter, String pivot, String value); + + @Override + Boolean lset(String key, long index, String element); + + @Override + List lrange(String key, long start, long end); + + @Override + Boolean ltrim(String key, long start, long end); + + @Override + List blpop(int timeout, String... keys); + + @Override + List brpop(int timeout, String... keys); + + @Override + String brpoplpush(String src, String dst, int timeout); + + @Override + Long sadd(String key, String... members); + + @Override + Boolean sismember(String key, String member); + + @Override + Set spop(String key, long count); + + @Override + List srandmember(String key, long count); + + @Override + Long srem(String key, String... members); + + @Override + long smove(String srckey, String dstkey, String member); + + @Override + Long scard(String key); + + @Override + Set smembers(String key); + + @Override + Set sinter(String... keys); + + @Override + long sinterstore(String dstkey, String... keys); + + @Override + Set sunion(String... keys); + + @Override + long sunionstore(String dstkey, String... keys); + + @Override + Set sdiff(String... keys); + + @Override + long sdiffstore(String dstkey, String... keys); + + @Override + Long zadd(String key, Map scoresAndMembers); + + @Override + Double zscore(String key, String member); + + @Override + Double zincrby(String key, double increment, String member); + + @Override + Long zcard(String key); + + @Override + Long zcount(String key, double min, double max); + + @Override + Set zrange(String key, long start, long end); + + @Override + Set zrevrange(String key, long start, long end); + + @Override + Set zrangeByScore(String key, double min, double max, int offset, int count); + + @Override + Set zrevrangeByScore(String key, double max, double min, int offset, int count); + + @Override + Long zrank(String key, String member); + + @Override + Long zrevrank(String key, String member); + + @Override + Long zrem(String key, String... member); + + @Override + Long zremrangeByRank(String key, long start, long end); + + @Override + Long zremrangeByScore(String key, double start, double end); + + @Override + Set zrangeByLex(String key, String min, String max, int offset, int count); + + @Override + long zlexcount(String key, String min, String max); + + @Override + Long zremrangeByLex(String key, String min, String max); + + @Override + long zunionstore(String dstkey, String... sets); + + @Override + long zinterstore(String dstkey, String... sets); + + @Override + Boolean set(String key, String value, String nxxx, String expx, long time); + + @Override + Boolean setnx(String key, String value); + + @Override + Boolean setex(String key, long seconds, String value); + + @Override + Boolean psetex(String key, long milliseconds, String value); + + @Override + String get(String key); + + @Override + String getSet(String key, String value); + + @Override + Long strlen(String key); + + @Override + Long append(String key, String value); + + @Override + Long setrange(String key, long offset, String value); + + @Override + String getrange(String key, long startOffset, long endOffset); + + @Override + Long incr(String key); + + @Override + Long incrBy(String key, long amount); + + @Override + Double incrByFloat(String key, double amount); + + @Override + Long decr(String key); + + @Override + Long decrBy(String key, long amount); + + @Override + String mset(String... keysvalues); + + @Override + Boolean msetnx(String... keysvalues); + + @Override + List mget(String... keys); +} diff --git a/sdk/src/main/java/group/rxcloud/capa/natives3/AbstractCapaNativeS3Client.java b/sdk/src/main/java/group/rxcloud/capa/natives3/AbstractCapaNativeS3Client.java new file mode 100644 index 0000000..afb752a --- /dev/null +++ b/sdk/src/main/java/group/rxcloud/capa/natives3/AbstractCapaNativeS3Client.java @@ -0,0 +1,45 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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. + */ +package group.rxcloud.capa.natives3; + + +import group.rxcloud.capa.AbstractCapaClient; +import group.rxcloud.capa.configuration.CapaConfigurationClient; +import group.rxcloud.capa.configuration.CapaConfigurationClientStore; +import group.rxcloud.cloudruntimes.domain.core.configuration.ConfigurationRequestItem; +import group.rxcloud.cloudruntimes.domain.core.configuration.SaveConfigurationRequest; +import reactor.core.publisher.Mono; + +/** + * Abstract class with convenient methods common between client implementations. + * + * @see CapaConfigurationClientStore + */ +public abstract class AbstractCapaNativeS3Client + extends AbstractCapaClient + implements CapaConfigurationClient { + + @Override + public Mono saveConfiguration(SaveConfigurationRequest saveConfigurationRequest) { + return Mono.error(new UnsupportedOperationException("[Capa] Unsupported save configuration")); + } + + @Override + public Mono deleteConfiguration(ConfigurationRequestItem configurationRequestItem) { + return Mono.error(new UnsupportedOperationException("[Capa] Unsupported delete configuration")); + } +} diff --git a/sdk/src/main/java/group/rxcloud/capa/natives3/CapaNativeS3Client.java b/sdk/src/main/java/group/rxcloud/capa/natives3/CapaNativeS3Client.java new file mode 100644 index 0000000..b8aac54 --- /dev/null +++ b/sdk/src/main/java/group/rxcloud/capa/natives3/CapaNativeS3Client.java @@ -0,0 +1,13 @@ +package group.rxcloud.capa.natives3; + +import group.rxcloud.capa.CapaClient; +import group.rxcloud.cloudruntimes.client.DefaultCloudRuntimesClient; +import reactor.core.publisher.Mono; + +import java.util.List; + +/** + * The Capa native s3 client. + */ +public interface CapaNativeS3Client extends CapaClient { +} diff --git a/sdk/src/main/java/group/rxcloud/capa/nativesql/AbstractCapaNativeSqlClient.java b/sdk/src/main/java/group/rxcloud/capa/nativesql/AbstractCapaNativeSqlClient.java new file mode 100644 index 0000000..8c510c8 --- /dev/null +++ b/sdk/src/main/java/group/rxcloud/capa/nativesql/AbstractCapaNativeSqlClient.java @@ -0,0 +1,45 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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. + */ +package group.rxcloud.capa.nativesql; + + +import group.rxcloud.capa.AbstractCapaClient; +import group.rxcloud.capa.configuration.CapaConfigurationClient; +import group.rxcloud.capa.configuration.CapaConfigurationClientStore; +import group.rxcloud.cloudruntimes.domain.core.configuration.ConfigurationRequestItem; +import group.rxcloud.cloudruntimes.domain.core.configuration.SaveConfigurationRequest; +import reactor.core.publisher.Mono; + +/** + * Abstract class with convenient methods common between client implementations. + * + * @see CapaConfigurationClientStore + */ +public abstract class AbstractCapaNativeSqlClient + extends AbstractCapaClient + implements CapaConfigurationClient { + + @Override + public Mono saveConfiguration(SaveConfigurationRequest saveConfigurationRequest) { + return Mono.error(new UnsupportedOperationException("[Capa] Unsupported save configuration")); + } + + @Override + public Mono deleteConfiguration(ConfigurationRequestItem configurationRequestItem) { + return Mono.error(new UnsupportedOperationException("[Capa] Unsupported delete configuration")); + } +} diff --git a/sdk/src/main/java/group/rxcloud/capa/nativesql/CapaNativeSqlClient.java b/sdk/src/main/java/group/rxcloud/capa/nativesql/CapaNativeSqlClient.java new file mode 100644 index 0000000..73affb6 --- /dev/null +++ b/sdk/src/main/java/group/rxcloud/capa/nativesql/CapaNativeSqlClient.java @@ -0,0 +1,17 @@ +package group.rxcloud.capa.nativesql; + +import group.rxcloud.capa.CapaClient; +import group.rxcloud.cloudruntimes.client.DefaultCloudRuntimesClient; +import reactor.core.publisher.Mono; + +import java.util.List; +import java.util.Map; + +/** + * The Capa native sql client. + */ +public interface CapaNativeSqlClient extends CapaClient { + + @Override + Mono invokeSql(String storeName, String sql, Map metadata); +} diff --git a/sdk/src/main/java/group/rxcloud/capa/pubsub/AbstractCapaPubSubClient.java b/sdk/src/main/java/group/rxcloud/capa/pubsub/AbstractCapaPubSubClient.java index 1c051ec..a7606b0 100644 --- a/sdk/src/main/java/group/rxcloud/capa/pubsub/AbstractCapaPubSubClient.java +++ b/sdk/src/main/java/group/rxcloud/capa/pubsub/AbstractCapaPubSubClient.java @@ -16,7 +16,11 @@ */ package group.rxcloud.capa.pubsub; +import group.rxcloud.capa.AbstractCapaClient; import group.rxcloud.cloudruntimes.domain.core.pubsub.PublishEventRequest; +import group.rxcloud.cloudruntimes.domain.core.pubsub.TopicEventRequest; +import group.rxcloud.cloudruntimes.domain.core.pubsub.TopicSubscription; +import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import java.util.List; @@ -27,14 +31,9 @@ * * @see CapaPubSubClientPubSub */ -public abstract class AbstractCapaPubSubClient implements CapaPubSubClient { - - protected List registryNames; - - @Override - public List registryNames() { - return registryNames; - } +public abstract class AbstractCapaPubSubClient + extends AbstractCapaClient + implements CapaPubSubClient { @Override public Mono publishEvent(String pubsubName, String topicName, Object data) { @@ -48,4 +47,13 @@ public Mono publishEvent(String pubsubName, String topicName, Object dat request.setMetadata(metadata); return this.publishEvent(request); } + + @Override + public Flux subscribeEvents(String pubsubName, String topicName, Map metadata) { + TopicSubscription topicSubscription = new TopicSubscription(); + topicSubscription.setPubSubName(pubsubName); + topicSubscription.setTopicName(topicName); + topicSubscription.setMetadata(metadata); + return this.subscribeEvents(topicSubscription); + } } diff --git a/sdk/src/main/java/group/rxcloud/capa/pubsub/CapaPubSubClient.java b/sdk/src/main/java/group/rxcloud/capa/pubsub/CapaPubSubClient.java index 2f24d74..043fd4f 100644 --- a/sdk/src/main/java/group/rxcloud/capa/pubsub/CapaPubSubClient.java +++ b/sdk/src/main/java/group/rxcloud/capa/pubsub/CapaPubSubClient.java @@ -16,13 +16,21 @@ */ package group.rxcloud.capa.pubsub; +import group.rxcloud.capa.CapaClient; import group.rxcloud.cloudruntimes.client.DefaultCloudRuntimesClient; import group.rxcloud.cloudruntimes.domain.core.pubsub.PublishEventRequest; +import group.rxcloud.cloudruntimes.domain.core.pubsub.TopicEventRequest; +import group.rxcloud.cloudruntimes.domain.core.pubsub.TopicSubscription; +import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; +import java.util.List; import java.util.Map; -public interface CapaPubSubClient extends DefaultCloudRuntimesClient { +/** + * The Capa pub sub client. + */ +public interface CapaPubSubClient extends CapaClient { @Override Mono publishEvent(String pubsubName, String topicName, Object data); @@ -34,10 +42,8 @@ public interface CapaPubSubClient extends DefaultCloudRuntimesClient { Mono publishEvent(PublishEventRequest request); @Override - default Mono shutdown() { - return Mono.empty(); - } + Flux subscribeEvents(String pubsubName, String topicName, Map metadata); @Override - void close(); + Flux subscribeEvents(TopicSubscription topicSubscription); } diff --git a/sdk/src/main/java/group/rxcloud/capa/pubsub/CapaPubSubClientPubSub.java b/sdk/src/main/java/group/rxcloud/capa/pubsub/CapaPubSubClientPubSub.java index 2816c5b..dc5a07e 100644 --- a/sdk/src/main/java/group/rxcloud/capa/pubsub/CapaPubSubClientPubSub.java +++ b/sdk/src/main/java/group/rxcloud/capa/pubsub/CapaPubSubClientPubSub.java @@ -17,9 +17,14 @@ package group.rxcloud.capa.pubsub; import group.rxcloud.capa.component.pubsub.CapaPubSub; +import group.rxcloud.capa.component.pubsub.NewMessage; import group.rxcloud.capa.component.pubsub.PublishRequest; +import group.rxcloud.capa.component.pubsub.SubscribeRequest; import group.rxcloud.capa.infrastructure.exceptions.CapaExceptions; import group.rxcloud.cloudruntimes.domain.core.pubsub.PublishEventRequest; +import group.rxcloud.cloudruntimes.domain.core.pubsub.TopicEventRequest; +import group.rxcloud.cloudruntimes.domain.core.pubsub.TopicSubscription; +import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import java.util.ArrayList; @@ -65,13 +70,13 @@ public Mono publishEvent(PublishEventRequest request) { final String topic = request.getTopic(); // check topic if (topic == null || topic.trim().isEmpty()) { - throw new IllegalArgumentException("Topic cannot be null or empty."); + throw new IllegalArgumentException("[Capa] topic cannot be null or empty."); } final Object data = request.getData(); // check data if (data == null) { - throw new IllegalArgumentException("Data cannot be null or empty."); + throw new IllegalArgumentException("[Capa] data cannot be null or empty."); } Map metadata = request.getMetadata(); @@ -103,12 +108,35 @@ public Mono publishEvent(PublishEventRequest request) { } } + @Override + public Flux subscribeEvents(TopicSubscription topicSubscription) { + try { + final String pubSubName = topicSubscription.getPubSubName(); + final CapaPubSub pubSub = this.getPubSub(pubSubName); + + return Flux.deferWithContext(Mono::just) + .flatMap(context -> { + SubscribeRequest subscribeRequest = this.getSubscribeRequest(topicSubscription); + return pubSub.subscribe(subscribeRequest); + }) + .flatMap(newMessage -> { + if (newMessage == null) { + return Flux.empty(); + } + TopicEventRequest topicEventRequest = this.getTopicEventRequest(pubSubName, newMessage); + return Flux.just(topicEventRequest); + }); + } catch (Exception ex) { + return CapaExceptions.wrapFlux(ex); + } + } + private CapaPubSub getPubSub(String pubsubName) { // check pubsubName if (pubsubName == null || pubsubName.trim().isEmpty()) { - throw new IllegalArgumentException("PubSub Name cannot be null or empty."); + throw new IllegalArgumentException("[Capa] PubSub Name cannot be null or empty."); } - return Objects.requireNonNull(pubSubs.get(pubsubName), "PubSub Component cannot be null."); + return Objects.requireNonNull(pubSubs.get(pubsubName), "[Capa] PubSub Component cannot be null."); } private PublishRequest getPublishRequest(String pubsubName, String topic, Object data, String contentType, Map metadata) { @@ -118,6 +146,24 @@ private PublishRequest getPublishRequest(String pubsubName, String topic, Object return publishRequest; } + private SubscribeRequest getSubscribeRequest(TopicSubscription topicSubscription) { + final String topicName = topicSubscription.getTopicName(); + final Map metadata = topicSubscription.getMetadata(); + SubscribeRequest subscribeRequest = new SubscribeRequest(topicName); + subscribeRequest.setMetadata(metadata); + return subscribeRequest; + } + + private TopicEventRequest getTopicEventRequest(String pubSubName, NewMessage newMessage) { + TopicEventRequest topicEventRequest = new TopicEventRequest(); + topicEventRequest.setPubsubName(pubSubName); + topicEventRequest.setTopic(newMessage.getTopic()); + topicEventRequest.setData(newMessage.getData()); + topicEventRequest.setMetadata(newMessage.getMetadata()); + topicEventRequest.setSpecVersion(CapaPubSub.API_VERSION); + return topicEventRequest; + } + @Override public void close() { try { diff --git a/sdk/src/main/java/group/rxcloud/capa/pubsub/domain/TopicEventRequest.java b/sdk/src/main/java/group/rxcloud/capa/pubsub/domain/TopicEventRequest.java deleted file mode 100644 index f5048bd..0000000 --- a/sdk/src/main/java/group/rxcloud/capa/pubsub/domain/TopicEventRequest.java +++ /dev/null @@ -1,217 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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. - */ -package group.rxcloud.capa.pubsub.domain; - -import java.util.Map; - -public class TopicEventRequest { - - // id identifies the event. Producers MUST ensure that source + id - // is unique for each distinct event. If a duplicate event is re-sent - // (e.g. due to a network error) it MAY have the same id. - private String id; - - // source identifies the context in which an event happened. - // Often this will include information such as the type of the - // event source, the organization publishing the event or the process - // that produced the event. The exact syntax and semantics behind - // the data encoded in the URI is defined by the event producer. - private String source; - - // The type of event related to the originating occurrence. - private String type; - - // The version of the CloudEvents specification. - private String specVersion; - - // The content type of data value. - private String contentType; - - // The content of the event. - private Object data; - - // The pubsub topic which publisher sent to. - private String topic; - - // The name of the pubsub the publisher sent to. - private String pubsubName; - - // add a map to pass some extra properties. - private Map metadata; - - /** - * Getter method for property id. - * - * @return property value of id - */ - public String getId() { - return id; - } - - /** - * Setter method for property id. - * - * @param id value to be assigned to property id - */ - public void setId(String id) { - this.id = id; - } - - /** - * Getter method for property source. - * - * @return property value of source - */ - public String getSource() { - return source; - } - - /** - * Setter method for property source. - * - * @param source value to be assigned to property source - */ - public void setSource(String source) { - this.source = source; - } - - /** - * Getter method for property type. - * - * @return property value of type - */ - public String getType() { - return type; - } - - /** - * Setter method for property type. - * - * @param type value to be assigned to property type - */ - public void setType(String type) { - this.type = type; - } - - /** - * Getter method for property specVersion. - * - * @return property value of specVersion - */ - public String getSpecVersion() { - return specVersion; - } - - /** - * Setter method for property specVersion. - * - * @param specVersion value to be assigned to property specVersion - */ - public void setSpecVersion(String specVersion) { - this.specVersion = specVersion; - } - - /** - * Getter method for property contentType. - * - * @return property value of contentType - */ - public String getContentType() { - return contentType; - } - - /** - * Setter method for property contentType. - * - * @param contentType value to be assigned to property contentType - */ - public void setContentType(String contentType) { - this.contentType = contentType; - } - - /** - * Getter method for property data. - * - * @return property value of data - */ - public Object getData() { - return data; - } - - /** - * Setter method for property data. - * - * @param data value to be assigned to property data - */ - public void setData(Object data) { - this.data = data; - } - - /** - * Getter method for property topic. - * - * @return property value of topic - */ - public String getTopic() { - return topic; - } - - /** - * Setter method for property topic. - * - * @param topic value to be assigned to property topic - */ - public void setTopic(String topic) { - this.topic = topic; - } - - /** - * Getter method for property pubsubName. - * - * @return property value of pubsubName - */ - public String getPubsubName() { - return pubsubName; - } - - /** - * Setter method for property pubsubName. - * - * @param pubsubName value to be assigned to property pubsubName - */ - public void setPubsubName(String pubsubName) { - this.pubsubName = pubsubName; - } - - /** - * Getter method for property metadata. - * - * @return property value of metadata - */ - public Map getMetadata() { - return metadata; - } - - /** - * Setter method for property metadata. - * - * @param metadata value to be assigned to property metadata - */ - public void setMetadata(Map metadata) { - this.metadata = metadata; - } -} diff --git a/sdk/src/main/java/group/rxcloud/capa/pubsub/domain/TopicSubscription.java b/sdk/src/main/java/group/rxcloud/capa/pubsub/domain/TopicSubscription.java deleted file mode 100644 index 3793704..0000000 --- a/sdk/src/main/java/group/rxcloud/capa/pubsub/domain/TopicSubscription.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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. - */ -package group.rxcloud.capa.pubsub.domain; - -import java.util.Map; - -public class TopicSubscription { - - /** - * Required. The name of the pubsub containing the topic below to subscribe to. - */ - private String pubSubName; - /** - * Required. The name of topic which will be subscribed - */ - private String topicName; - /** - * The optional properties used for this topic's subscription e.g. session id - */ - private Map metadata; - - public String getPubSubName() { - return pubSubName; - } - - public void setPubSubName(String pubSubName) { - this.pubSubName = pubSubName; - } - - public String getTopicName() { - return topicName; - } - - public void setTopicName(String topicName) { - this.topicName = topicName; - } - - public Map getMetadata() { - return metadata; - } - - public void setMetadata(Map metadata) { - this.metadata = metadata; - } -} diff --git a/sdk/src/main/java/group/rxcloud/capa/ratelimit/AbstractCapaRatelimitClient.java b/sdk/src/main/java/group/rxcloud/capa/ratelimit/AbstractCapaRatelimitClient.java new file mode 100644 index 0000000..6a7b796 --- /dev/null +++ b/sdk/src/main/java/group/rxcloud/capa/ratelimit/AbstractCapaRatelimitClient.java @@ -0,0 +1,45 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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. + */ +package group.rxcloud.capa.ratelimit; + + +import group.rxcloud.capa.AbstractCapaClient; +import group.rxcloud.capa.configuration.CapaConfigurationClient; +import group.rxcloud.capa.configuration.CapaConfigurationClientStore; +import group.rxcloud.cloudruntimes.domain.core.configuration.ConfigurationRequestItem; +import group.rxcloud.cloudruntimes.domain.core.configuration.SaveConfigurationRequest; +import reactor.core.publisher.Mono; + +/** + * Abstract class with convenient methods common between client implementations. + * + * @see CapaConfigurationClientStore + */ +public abstract class AbstractCapaRatelimitClient + extends AbstractCapaClient + implements CapaConfigurationClient { + + @Override + public Mono saveConfiguration(SaveConfigurationRequest saveConfigurationRequest) { + return Mono.error(new UnsupportedOperationException("[Capa] Unsupported save configuration")); + } + + @Override + public Mono deleteConfiguration(ConfigurationRequestItem configurationRequestItem) { + return Mono.error(new UnsupportedOperationException("[Capa] Unsupported delete configuration")); + } +} diff --git a/sdk/src/main/java/group/rxcloud/capa/ratelimit/CapaRatelimitClient.java b/sdk/src/main/java/group/rxcloud/capa/ratelimit/CapaRatelimitClient.java new file mode 100644 index 0000000..4cb4de9 --- /dev/null +++ b/sdk/src/main/java/group/rxcloud/capa/ratelimit/CapaRatelimitClient.java @@ -0,0 +1,14 @@ +package group.rxcloud.capa.ratelimit; + +import group.rxcloud.capa.CapaClient; +import reactor.core.publisher.Flux; + +import java.util.Map; + +/** + * The Capa schedule client. + */ +public interface CapaRatelimitClient extends CapaClient { + + +} diff --git a/sdk/src/main/java/group/rxcloud/capa/rpc/AbstractCapaRpcClient.java b/sdk/src/main/java/group/rxcloud/capa/rpc/AbstractCapaRpcClient.java index ebaf8ef..3bfc5ef 100644 --- a/sdk/src/main/java/group/rxcloud/capa/rpc/AbstractCapaRpcClient.java +++ b/sdk/src/main/java/group/rxcloud/capa/rpc/AbstractCapaRpcClient.java @@ -16,6 +16,7 @@ */ package group.rxcloud.capa.rpc; +import group.rxcloud.capa.AbstractCapaClient; import group.rxcloud.capa.rpc.domain.InvokeMethodRequestBuilder; import group.rxcloud.cloudruntimes.domain.core.invocation.HttpExtension; import group.rxcloud.cloudruntimes.domain.core.invocation.InvokeMethodRequest; @@ -30,14 +31,9 @@ * * @see CapaRpcClientHttp */ -public abstract class AbstractCapaRpcClient implements CapaRpcClient { - - protected List registryNames; - - @Override - public List registryNames() { - return registryNames; - } +public abstract class AbstractCapaRpcClient + extends AbstractCapaClient + implements CapaRpcClient { @Override public Mono invokeMethod(String appId, String methodName, Object request, HttpExtension httpExtension, Map metadata, TypeRef type) { diff --git a/sdk/src/main/java/group/rxcloud/capa/rpc/CapaRpcClient.java b/sdk/src/main/java/group/rxcloud/capa/rpc/CapaRpcClient.java index 6a84829..25729f1 100644 --- a/sdk/src/main/java/group/rxcloud/capa/rpc/CapaRpcClient.java +++ b/sdk/src/main/java/group/rxcloud/capa/rpc/CapaRpcClient.java @@ -16,18 +16,22 @@ */ package group.rxcloud.capa.rpc; +import group.rxcloud.capa.CapaClient; import group.rxcloud.cloudruntimes.client.DefaultCloudRuntimesClient; import group.rxcloud.cloudruntimes.domain.core.invocation.HttpExtension; import group.rxcloud.cloudruntimes.domain.core.invocation.InvokeMethodRequest; +import group.rxcloud.cloudruntimes.domain.core.invocation.RegisterServerRequest; import group.rxcloud.cloudruntimes.utils.TypeRef; import reactor.core.publisher.Mono; +import java.util.List; import java.util.Map; +import java.util.function.Function; /** * Generic Client Adapter to be used regardless of the specific RPC Client implementation required. */ -public interface CapaRpcClient extends DefaultCloudRuntimesClient { +public interface CapaRpcClient extends CapaClient { @Override Mono invokeMethod(String appId, String methodName, Object data, HttpExtension httpExtension, Map metadata, TypeRef type); @@ -63,10 +67,8 @@ public interface CapaRpcClient extends DefaultCloudRuntimesClient { Mono invokeMethod(InvokeMethodRequest invokeMethodRequest, TypeRef type); @Override - default Mono shutdown() { - return Mono.empty(); - } + Mono registerMethod(String methodName, List httpExtensions, Function onInvoke, Map metadata); @Override - void close(); + Mono registerServer(RegisterServerRequest registerServerRequest); } diff --git a/sdk/src/main/java/group/rxcloud/capa/rpc/CapaRpcClientBuilder.java b/sdk/src/main/java/group/rxcloud/capa/rpc/CapaRpcClientBuilder.java index 91ecce5..2d5128f 100644 --- a/sdk/src/main/java/group/rxcloud/capa/rpc/CapaRpcClientBuilder.java +++ b/sdk/src/main/java/group/rxcloud/capa/rpc/CapaRpcClientBuilder.java @@ -19,6 +19,7 @@ import group.rxcloud.capa.component.CapaRpcProperties; import group.rxcloud.capa.component.http.CapaHttpBuilder; +import group.rxcloud.capa.rpc.domain.CapaApiProtocol; import java.util.function.Supplier; @@ -78,12 +79,15 @@ public CapaRpcClient build() { */ private CapaRpcClient buildCapaClient(CapaApiProtocol protocol) { if (protocol == null) { - throw new IllegalStateException("Protocol is required."); + throw new IllegalStateException("[Capa] ApiProtocol is required."); } if (protocol == CapaApiProtocol.HTTP) { return buildCapaClientHttp(); } - throw new IllegalStateException("Unsupported protocol: " + protocol.name()); + if (protocol == CapaApiProtocol.GRPC) { + return buildCapaClientGrpc(); + } + throw new IllegalStateException("[Capa] Unsupported ApiProtocol: " + protocol.name()); } /** @@ -94,4 +98,13 @@ private CapaRpcClient buildCapaClient(CapaApiProtocol protocol) { private CapaRpcClient buildCapaClientHttp() { return new CapaRpcClientHttp(this.httpBuilder.build()); } + + /** + * Creates and instance of CapaClient over GRPC. + * + * @return CapaClient over GRPC. + */ + private CapaRpcClient buildCapaClientGrpc() { + return new CapaRpcClientGrpc(); + } } diff --git a/sdk/src/main/java/group/rxcloud/capa/rpc/CapaRpcClientGrpc.java b/sdk/src/main/java/group/rxcloud/capa/rpc/CapaRpcClientGrpc.java new file mode 100644 index 0000000..5e237c7 --- /dev/null +++ b/sdk/src/main/java/group/rxcloud/capa/rpc/CapaRpcClientGrpc.java @@ -0,0 +1,61 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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. + */ +package group.rxcloud.capa.rpc; + +import group.rxcloud.cloudruntimes.domain.core.invocation.HttpExtension; +import group.rxcloud.cloudruntimes.domain.core.invocation.InvokeMethodRequest; +import group.rxcloud.cloudruntimes.domain.core.invocation.RegisterServerRequest; +import group.rxcloud.cloudruntimes.utils.TypeRef; +import reactor.core.publisher.Mono; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.function.Function; + +/** + * TODO An adapter for the GRPC RPC Client. + */ +public class CapaRpcClientGrpc extends AbstractCapaRpcClient { + + public CapaRpcClientGrpc() { + this.registryNames = new ArrayList<>(1); + this.registryNames.add("grpc"); + } + + @Override + public Mono invokeMethod(InvokeMethodRequest invokeMethodRequest, TypeRef type) { + return null; + } + + @Override + public Mono registerMethod(String methodName, List httpExtensions, Function onInvoke, Map metadata) { + return null; + } + + @Override + public Mono registerServer(RegisterServerRequest registerServerRequest) { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public void close() { + } +} diff --git a/sdk/src/main/java/group/rxcloud/capa/rpc/CapaRpcClientHttp.java b/sdk/src/main/java/group/rxcloud/capa/rpc/CapaRpcClientHttp.java index 6e7ea9c..95df172 100644 --- a/sdk/src/main/java/group/rxcloud/capa/rpc/CapaRpcClientHttp.java +++ b/sdk/src/main/java/group/rxcloud/capa/rpc/CapaRpcClientHttp.java @@ -20,6 +20,7 @@ import group.rxcloud.capa.infrastructure.exceptions.CapaExceptions; import group.rxcloud.cloudruntimes.domain.core.invocation.HttpExtension; import group.rxcloud.cloudruntimes.domain.core.invocation.InvokeMethodRequest; +import group.rxcloud.cloudruntimes.domain.core.invocation.RegisterServerRequest; import group.rxcloud.cloudruntimes.utils.TypeRef; import reactor.core.publisher.Mono; @@ -27,6 +28,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.function.Function; /** * An adapter for the HTTP RPC Client. @@ -57,15 +59,15 @@ public Mono invokeMethod(InvokeMethodRequest invokeMethodRequest, TypeRef final Map metadata = invokeMethodRequest.getMetadata(); // check appId if (appId == null || appId.trim().isEmpty()) { - throw new IllegalArgumentException("App Id cannot be null or empty."); + throw new IllegalArgumentException("[Capa] App Id cannot be null or empty."); } // check method if (method == null || method.trim().isEmpty()) { - throw new IllegalArgumentException("Method name cannot be null or empty."); + throw new IllegalArgumentException("[Capa] Method name cannot be null or empty."); } // check httpExtension if (httpExtension == null) { - throw new IllegalArgumentException("HttpExtension cannot be null. Use HttpExtension.NONE instead."); + throw new IllegalArgumentException("[Capa] HttpExtension cannot be null. Use HttpExtension.NONE instead."); } // If the httpExtension is not null, then the method will not be null based on checks in constructor final String httpMethod = httpExtension.getMethod().toString(); @@ -104,6 +106,16 @@ public Mono invokeMethod(InvokeMethodRequest invokeMethodRequest, TypeRef } } + @Override + public Mono registerMethod(String methodName, List httpExtensions, Function onInvoke, Map metadata) { + return null; + } + + @Override + public Mono registerServer(RegisterServerRequest registerServerRequest) { + return null; + } + /** * {@inheritDoc} */ diff --git a/sdk/src/main/java/group/rxcloud/capa/rpc/Controller.java b/sdk/src/main/java/group/rxcloud/capa/rpc/Controller.java deleted file mode 100644 index 5667ee9..0000000 --- a/sdk/src/main/java/group/rxcloud/capa/rpc/Controller.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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. - */ -package group.rxcloud.capa.rpc; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Rpc Server controller. - */ -@Documented -@Target(ElementType.TYPE) -@Retention(RetentionPolicy.RUNTIME) -public @interface Controller { -} diff --git a/sdk/src/main/java/group/rxcloud/capa/rpc/RequestMapping.java b/sdk/src/main/java/group/rxcloud/capa/rpc/RequestMapping.java deleted file mode 100644 index 05ef223..0000000 --- a/sdk/src/main/java/group/rxcloud/capa/rpc/RequestMapping.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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. - */ -package group.rxcloud.capa.rpc; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Rpc Server controller method. - */ -@Documented -@Target(ElementType.METHOD) -@Retention(RetentionPolicy.RUNTIME) -public @interface RequestMapping { -} diff --git a/sdk/src/main/java/group/rxcloud/capa/rpc/CapaApiProtocol.java b/sdk/src/main/java/group/rxcloud/capa/rpc/domain/CapaApiProtocol.java similarity index 83% rename from sdk/src/main/java/group/rxcloud/capa/rpc/CapaApiProtocol.java rename to sdk/src/main/java/group/rxcloud/capa/rpc/domain/CapaApiProtocol.java index c0a6e9b..f12a77a 100644 --- a/sdk/src/main/java/group/rxcloud/capa/rpc/CapaApiProtocol.java +++ b/sdk/src/main/java/group/rxcloud/capa/rpc/domain/CapaApiProtocol.java @@ -14,7 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package group.rxcloud.capa.rpc; +package group.rxcloud.capa.rpc.domain; /** * Transport protocol for Capa's API. @@ -34,7 +34,13 @@ public enum CapaApiProtocol { * @return the capa api protocol */ public static CapaApiProtocol parseProtocol(String protocol) { - // FIXME: Fix to HTTP + if ("HTTP".equalsIgnoreCase(protocol)) { + return HTTP; + } + if ("GRPC".equalsIgnoreCase(protocol)) { + return GRPC; + } + // default HTTP return HTTP; } } diff --git a/sdk/src/main/java/group/rxcloud/capa/schedule/AbstractCapaScheduleClient.java b/sdk/src/main/java/group/rxcloud/capa/schedule/AbstractCapaScheduleClient.java new file mode 100644 index 0000000..d6dbb01 --- /dev/null +++ b/sdk/src/main/java/group/rxcloud/capa/schedule/AbstractCapaScheduleClient.java @@ -0,0 +1,45 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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. + */ +package group.rxcloud.capa.schedule; + + +import group.rxcloud.capa.AbstractCapaClient; +import group.rxcloud.capa.configuration.CapaConfigurationClient; +import group.rxcloud.capa.configuration.CapaConfigurationClientStore; +import group.rxcloud.cloudruntimes.domain.core.configuration.ConfigurationRequestItem; +import group.rxcloud.cloudruntimes.domain.core.configuration.SaveConfigurationRequest; +import reactor.core.publisher.Mono; + +/** + * Abstract class with convenient methods common between client implementations. + * + * @see CapaConfigurationClientStore + */ +public abstract class AbstractCapaScheduleClient + extends AbstractCapaClient + implements CapaConfigurationClient { + + @Override + public Mono saveConfiguration(SaveConfigurationRequest saveConfigurationRequest) { + return Mono.error(new UnsupportedOperationException("[Capa] Unsupported save configuration")); + } + + @Override + public Mono deleteConfiguration(ConfigurationRequestItem configurationRequestItem) { + return Mono.error(new UnsupportedOperationException("[Capa] Unsupported delete configuration")); + } +} diff --git a/sdk/src/main/java/group/rxcloud/capa/schedule/CapaScheduleClient.java b/sdk/src/main/java/group/rxcloud/capa/schedule/CapaScheduleClient.java new file mode 100644 index 0000000..a4f66b5 --- /dev/null +++ b/sdk/src/main/java/group/rxcloud/capa/schedule/CapaScheduleClient.java @@ -0,0 +1,15 @@ +package group.rxcloud.capa.schedule; + +import group.rxcloud.capa.CapaClient; +import reactor.core.publisher.Flux; + +import java.util.Map; + +/** + * The Capa schedule client. + */ +public interface CapaScheduleClient extends CapaClient { + + @Override + Flux invokeSchedule(String appId, String jobName, Map metadata); +} diff --git a/sdk/src/main/java/group/rxcloud/capa/secret/AbstractCapaSecretClient.java b/sdk/src/main/java/group/rxcloud/capa/secret/AbstractCapaSecretClient.java new file mode 100644 index 0000000..4f3fc92 --- /dev/null +++ b/sdk/src/main/java/group/rxcloud/capa/secret/AbstractCapaSecretClient.java @@ -0,0 +1,45 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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. + */ +package group.rxcloud.capa.secret; + + +import group.rxcloud.capa.AbstractCapaClient; +import group.rxcloud.capa.configuration.CapaConfigurationClient; +import group.rxcloud.capa.configuration.CapaConfigurationClientStore; +import group.rxcloud.cloudruntimes.domain.core.configuration.ConfigurationRequestItem; +import group.rxcloud.cloudruntimes.domain.core.configuration.SaveConfigurationRequest; +import reactor.core.publisher.Mono; + +/** + * Abstract class with convenient methods common between client implementations. + * + * @see CapaConfigurationClientStore + */ +public abstract class AbstractCapaSecretClient + extends AbstractCapaClient + implements CapaConfigurationClient { + + @Override + public Mono saveConfiguration(SaveConfigurationRequest saveConfigurationRequest) { + return Mono.error(new UnsupportedOperationException("[Capa] Unsupported save configuration")); + } + + @Override + public Mono deleteConfiguration(ConfigurationRequestItem configurationRequestItem) { + return Mono.error(new UnsupportedOperationException("[Capa] Unsupported delete configuration")); + } +} diff --git a/sdk/src/main/java/group/rxcloud/capa/secret/CapaSecretClient.java b/sdk/src/main/java/group/rxcloud/capa/secret/CapaSecretClient.java new file mode 100644 index 0000000..1a88f41 --- /dev/null +++ b/sdk/src/main/java/group/rxcloud/capa/secret/CapaSecretClient.java @@ -0,0 +1,32 @@ +package group.rxcloud.capa.secret; + +import group.rxcloud.capa.CapaClient; +import group.rxcloud.cloudruntimes.domain.core.secrets.GetBulkSecretRequest; +import group.rxcloud.cloudruntimes.domain.core.secrets.GetSecretRequest; +import reactor.core.publisher.Mono; + +import java.util.Map; + +/** + * The Capa secret client. + */ +public interface CapaSecretClient extends CapaClient { + + @Override + Mono> getSecret(String storeName, String secretName, Map metadata); + + @Override + Mono> getSecret(String storeName, String secretName); + + @Override + Mono> getSecret(GetSecretRequest request); + + @Override + Mono>> getBulkSecret(String storeName); + + @Override + Mono>> getBulkSecret(String storeName, Map metadata); + + @Override + Mono>> getBulkSecret(GetBulkSecretRequest request); +} diff --git a/sdk/src/main/java/group/rxcloud/capa/sequencer/AbstractCapaSequencerClient.java b/sdk/src/main/java/group/rxcloud/capa/sequencer/AbstractCapaSequencerClient.java new file mode 100644 index 0000000..daac11d --- /dev/null +++ b/sdk/src/main/java/group/rxcloud/capa/sequencer/AbstractCapaSequencerClient.java @@ -0,0 +1,45 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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. + */ +package group.rxcloud.capa.sequencer; + + +import group.rxcloud.capa.AbstractCapaClient; +import group.rxcloud.capa.configuration.CapaConfigurationClient; +import group.rxcloud.capa.configuration.CapaConfigurationClientStore; +import group.rxcloud.cloudruntimes.domain.core.configuration.ConfigurationRequestItem; +import group.rxcloud.cloudruntimes.domain.core.configuration.SaveConfigurationRequest; +import reactor.core.publisher.Mono; + +/** + * Abstract class with convenient methods common between client implementations. + * + * @see CapaConfigurationClientStore + */ +public abstract class AbstractCapaSequencerClient + extends AbstractCapaClient + implements CapaConfigurationClient { + + @Override + public Mono saveConfiguration(SaveConfigurationRequest saveConfigurationRequest) { + return Mono.error(new UnsupportedOperationException("[Capa] Unsupported save configuration")); + } + + @Override + public Mono deleteConfiguration(ConfigurationRequestItem configurationRequestItem) { + return Mono.error(new UnsupportedOperationException("[Capa] Unsupported delete configuration")); + } +} diff --git a/sdk/src/main/java/group/rxcloud/capa/sequencer/CapaSequencerClient.java b/sdk/src/main/java/group/rxcloud/capa/sequencer/CapaSequencerClient.java new file mode 100644 index 0000000..e9f91c7 --- /dev/null +++ b/sdk/src/main/java/group/rxcloud/capa/sequencer/CapaSequencerClient.java @@ -0,0 +1,15 @@ +package group.rxcloud.capa.sequencer; + +import group.rxcloud.capa.CapaClient; +import reactor.core.publisher.Flux; + +import java.util.Map; + +/** + * The Capa schedule client. + */ +public interface CapaSequencerClient extends CapaClient { + + @Override + Flux invokeSchedule(String appId, String jobName, Map metadata); +} diff --git a/sdk/src/main/java/group/rxcloud/capa/state/AbstractCapaStateClient.java b/sdk/src/main/java/group/rxcloud/capa/state/AbstractCapaStateClient.java new file mode 100644 index 0000000..4e05fb8 --- /dev/null +++ b/sdk/src/main/java/group/rxcloud/capa/state/AbstractCapaStateClient.java @@ -0,0 +1,45 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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. + */ +package group.rxcloud.capa.state; + + +import group.rxcloud.capa.AbstractCapaClient; +import group.rxcloud.capa.configuration.CapaConfigurationClient; +import group.rxcloud.capa.configuration.CapaConfigurationClientStore; +import group.rxcloud.cloudruntimes.domain.core.configuration.ConfigurationRequestItem; +import group.rxcloud.cloudruntimes.domain.core.configuration.SaveConfigurationRequest; +import reactor.core.publisher.Mono; + +/** + * Abstract class with convenient methods common between client implementations. + * + * @see CapaConfigurationClientStore + */ +public abstract class AbstractCapaStateClient + extends AbstractCapaClient + implements CapaConfigurationClient { + + @Override + public Mono saveConfiguration(SaveConfigurationRequest saveConfigurationRequest) { + return Mono.error(new UnsupportedOperationException("[Capa] Unsupported save configuration")); + } + + @Override + public Mono deleteConfiguration(ConfigurationRequestItem configurationRequestItem) { + return Mono.error(new UnsupportedOperationException("[Capa] Unsupported delete configuration")); + } +} diff --git a/sdk/src/main/java/group/rxcloud/capa/state/CapaStateClient.java b/sdk/src/main/java/group/rxcloud/capa/state/CapaStateClient.java index d884c39..67ec68e 100644 --- a/sdk/src/main/java/group/rxcloud/capa/state/CapaStateClient.java +++ b/sdk/src/main/java/group/rxcloud/capa/state/CapaStateClient.java @@ -16,7 +16,7 @@ */ package group.rxcloud.capa.state; -import group.rxcloud.cloudruntimes.client.DefaultCloudRuntimesClient; +import group.rxcloud.capa.CapaClient; import group.rxcloud.cloudruntimes.domain.core.state.DeleteStateRequest; import group.rxcloud.cloudruntimes.domain.core.state.ExecuteStateTransactionRequest; import group.rxcloud.cloudruntimes.domain.core.state.GetBulkStateRequest; @@ -30,7 +30,10 @@ import java.util.List; -public interface CapaStateClient extends DefaultCloudRuntimesClient { +/** + * The Capa state client. + */ +public interface CapaStateClient extends CapaClient { @Override Mono> getState(String storeName, State state, TypeRef type); @@ -88,12 +91,4 @@ public interface CapaStateClient extends DefaultCloudRuntimesClient { @Override Mono deleteState(DeleteStateRequest request); - - @Override - default Mono shutdown() { - return Mono.empty(); - } - - @Override - void close(); } diff --git a/sdk/src/main/java/group/rxcloud/capa/telemetry/CapaTelemetryClientGlobal.java b/sdk/src/main/java/group/rxcloud/capa/telemetry/CapTelemetryClientExporter.java similarity index 93% rename from sdk/src/main/java/group/rxcloud/capa/telemetry/CapaTelemetryClientGlobal.java rename to sdk/src/main/java/group/rxcloud/capa/telemetry/CapTelemetryClientExporter.java index 62c3ce6..6dc9efc 100644 --- a/sdk/src/main/java/group/rxcloud/capa/telemetry/CapaTelemetryClientGlobal.java +++ b/sdk/src/main/java/group/rxcloud/capa/telemetry/CapTelemetryClientExporter.java @@ -16,6 +16,7 @@ */ package group.rxcloud.capa.telemetry; +import group.rxcloud.capa.AbstractCapaClient; import io.opentelemetry.api.OpenTelemetry; import io.opentelemetry.api.metrics.Meter; import io.opentelemetry.api.metrics.MeterProvider; @@ -27,13 +28,13 @@ import java.util.ArrayList; import java.util.List; -public class CapaTelemetryClientGlobal implements CapaTelemetryClient, OpenTelemetry { +public class CapTelemetryClientExporter + extends AbstractCapaClient + implements CapaTelemetryClient, OpenTelemetry { // noop as default. private TracerProvider tracerProvider = TracerProvider.noop(); - private MeterProvider meterProvider = MeterProvider.noop(); - private ContextPropagators contextPropagators = ContextPropagators.noop(); protected List registryNames; @@ -43,7 +44,7 @@ public List registryNames() { return registryNames; } - CapaTelemetryClientGlobal() { + CapTelemetryClientExporter() { this.registryNames = new ArrayList<>(1); this.registryNames.add("opentelemetry"); } @@ -129,5 +130,8 @@ public Mono buildMeter(String meterName, String version, String schemaUrl @Override public void close() { + tracerProvider = null; + meterProvider = null; + contextPropagators = null; } } diff --git a/sdk/src/main/java/group/rxcloud/capa/telemetry/CapaTelemetryClient.java b/sdk/src/main/java/group/rxcloud/capa/telemetry/CapaTelemetryClient.java index b7f06ff..5bafdaf 100644 --- a/sdk/src/main/java/group/rxcloud/capa/telemetry/CapaTelemetryClient.java +++ b/sdk/src/main/java/group/rxcloud/capa/telemetry/CapaTelemetryClient.java @@ -16,13 +16,16 @@ */ package group.rxcloud.capa.telemetry; -import group.rxcloud.cloudruntimes.client.DefaultCloudRuntimesClient; +import group.rxcloud.capa.CapaClient; import io.opentelemetry.api.metrics.Meter; import io.opentelemetry.api.trace.Tracer; import io.opentelemetry.context.propagation.ContextPropagators; import reactor.core.publisher.Mono; -public interface CapaTelemetryClient extends DefaultCloudRuntimesClient { +/** + * The Capa telemetry client. + */ +public interface CapaTelemetryClient extends CapaClient { @Override Mono buildTracer(String tracerName); @@ -44,7 +47,4 @@ public interface CapaTelemetryClient extends DefaultCloudRuntimesClient { @Override Mono buildMeter(String meterName, String version, String schemaUrl); - - @Override - void close(); } diff --git a/sdk/src/main/java/group/rxcloud/capa/telemetry/CapaTelemetryClientBuilder.java b/sdk/src/main/java/group/rxcloud/capa/telemetry/CapaTelemetryClientBuilder.java index fb8d324..eb065e4 100644 --- a/sdk/src/main/java/group/rxcloud/capa/telemetry/CapaTelemetryClientBuilder.java +++ b/sdk/src/main/java/group/rxcloud/capa/telemetry/CapaTelemetryClientBuilder.java @@ -16,102 +16,36 @@ */ package group.rxcloud.capa.telemetry; -import group.rxcloud.capa.component.telemetry.SamplerConfig; import group.rxcloud.capa.component.telemetry.context.CapaContextPropagatorBuilder; -import group.rxcloud.capa.component.telemetry.context.CapaContextPropagatorSettings; -import group.rxcloud.capa.component.telemetry.context.ContextConfig; import group.rxcloud.capa.component.telemetry.metrics.CapaMeterProviderBuilder; -import group.rxcloud.capa.component.telemetry.metrics.CapaMeterProviderSettings; -import group.rxcloud.capa.component.telemetry.metrics.MeterConfig; -import group.rxcloud.capa.component.telemetry.metrics.MetricsReaderConfig; import group.rxcloud.capa.component.telemetry.trace.CapaTracerProviderBuilder; -import group.rxcloud.capa.component.telemetry.trace.CapaTracerProviderSettings; -import group.rxcloud.capa.component.telemetry.trace.SpanLimitsConfig; -import group.rxcloud.capa.component.telemetry.trace.TracerConfig; -import io.opentelemetry.context.propagation.TextMapPropagator; -import io.opentelemetry.sdk.trace.IdGenerator; -import io.opentelemetry.sdk.trace.SpanProcessor; - -import java.util.function.Supplier; /** * A builder for the {@link CapaTelemetryClient} */ -public class CapaTelemetryClientBuilder implements CapaContextPropagatorSettings, CapaTracerProviderSettings, CapaMeterProviderSettings { - - private final CapaTracerProviderBuilder tracerProviderBuilder = new CapaTracerProviderBuilder(); - - private final CapaMeterProviderBuilder meterProviderBuilder = new CapaMeterProviderBuilder(); - - private final CapaContextPropagatorBuilder contextPropagatorBuilder = new CapaContextPropagatorBuilder(); - - @Override - public CapaTelemetryClientBuilder setTracerConfig(TracerConfig tracerConfig) { - tracerProviderBuilder.setTracerConfig(tracerConfig); - return this; - } +public class CapaTelemetryClientBuilder { - @Override - public CapaTelemetryClientBuilder setSpanLimits(SpanLimitsConfig spanLimits) { - tracerProviderBuilder.setSpanLimits(spanLimits); - return this; - } - - @Override - public CapaTelemetryClientBuilder setIdGenerator(IdGenerator idGenerator) { - tracerProviderBuilder.setIdGenerator(idGenerator); - return this; - } + /** + * Bind to {@code telemetry} component + */ + private final CapaTracerProviderBuilder tracerProviderBuilder; + private final CapaMeterProviderBuilder meterProviderBuilder; + private final CapaContextPropagatorBuilder contextPropagatorBuilder; - @Override - public CapaTelemetryClientBuilder addProcessor(SpanProcessor processor) { - tracerProviderBuilder.addProcessor(processor); - return this; - } - - @Override - public CapaTelemetryClientBuilder setContextConfig(ContextConfig config) { - contextPropagatorBuilder.setContextConfig(config); - return this; - } - - @Override - public CapaTelemetryClientBuilder addContextPropagators(TextMapPropagator processor) { - contextPropagatorBuilder.addContextPropagators(processor); - return this; - } - - @Override - public CapaTelemetryClientBuilder setMeterConfig(MeterConfig config) { - meterProviderBuilder.setMeterConfig(config); - return this; - } - - @Override - public CapaTelemetryClientBuilder addMetricReaderConfig(MetricsReaderConfig config) { - meterProviderBuilder.addMetricReaderConfig(config); - return this; - } - - @Override - public CapaTelemetryClientBuilder setSamplerConfig(Supplier samplerConfig) { - meterProviderBuilder.setSamplerConfig(samplerConfig); - tracerProviderBuilder.setSamplerConfig(samplerConfig); - return this; + public CapaTelemetryClientBuilder() { + tracerProviderBuilder = new CapaTracerProviderBuilder(); + meterProviderBuilder = new CapaMeterProviderBuilder(); + contextPropagatorBuilder = new CapaContextPropagatorBuilder(); } public CapaTelemetryClient build() { - CapaTelemetryClientGlobal client = new CapaTelemetryClientGlobal(); - + CapTelemetryClientExporter client = new CapTelemetryClientExporter(); // context client.setContextPropagators(contextPropagatorBuilder.buildContextPropagators()); - // tracer client.setTracerProvider(tracerProviderBuilder.buildTracerProvider()); - // meter client.setMeterProvider(meterProviderBuilder.buildMeterProvider()); - return client; } } diff --git a/sdk/src/test/java/group/rxcloud/capa/configuration/CapaConfigurationClientBuilderTest.java b/sdk/src/test/java/group/rxcloud/capa/configuration/CapaConfigurationClientBuilderTest.java index 1e7a8a2..bb18586 100644 --- a/sdk/src/test/java/group/rxcloud/capa/configuration/CapaConfigurationClientBuilderTest.java +++ b/sdk/src/test/java/group/rxcloud/capa/configuration/CapaConfigurationClientBuilderTest.java @@ -34,7 +34,9 @@ public class CapaConfigurationClientBuilderTest { public void testBuild_WithCapaConfigStoreBuilderListAsParametersConstructor() { CapaConfigStoreBuilder storeBuilder = Mockito.mock(CapaConfigStoreBuilder.class); CapaConfigStore configStore = Mockito.mock(CapaConfigStore.class); - Mockito.when(storeBuilder.build()).thenReturn(configStore); + Mockito.when(storeBuilder.build()) + .thenReturn(configStore); + CapaConfigurationClientBuilder builder = new CapaConfigurationClientBuilder(Lists.newArrayList(storeBuilder)); Assertions.assertNotNull(builder.build()); } @@ -43,7 +45,9 @@ public void testBuild_WithCapaConfigStoreBuilderListAsParametersConstructor() { public void testBuild_WithCapaConfigStoreBuilderSupplierAsParametersConstructor() { CapaConfigStoreBuilder storeBuilder = Mockito.mock(CapaConfigStoreBuilder.class); CapaConfigStore configStore = Mockito.mock(CapaConfigStore.class); - Mockito.when(storeBuilder.build()).thenReturn(configStore); + Mockito.when(storeBuilder.build()) + .thenReturn(configStore); + CapaConfigurationClientBuilder builder = new CapaConfigurationClientBuilder(() -> storeBuilder); Assertions.assertNotNull(builder.build()); } diff --git a/sdk/src/test/java/group/rxcloud/capa/configuration/CapaConfigurationClientStoreTest.java b/sdk/src/test/java/group/rxcloud/capa/configuration/CapaConfigurationClientStoreTest.java index 3538fcb..55feee5 100644 --- a/sdk/src/test/java/group/rxcloud/capa/configuration/CapaConfigurationClientStoreTest.java +++ b/sdk/src/test/java/group/rxcloud/capa/configuration/CapaConfigurationClientStoreTest.java @@ -48,25 +48,29 @@ public class CapaConfigurationClientStoreTest { @Test public void testSaveConfiguration_FailWhenThrowUnsupportedOperationException() { CapaConfigurationClientStore clientStore = new CapaConfigurationClientStore(Collections.emptyList()); - Assertions.assertThrows(UnsupportedOperationException.class, () -> clientStore.saveConfiguration(new SaveConfigurationRequest()).block()); + Assertions.assertThrows(UnsupportedOperationException.class, + () -> clientStore.saveConfiguration(new SaveConfigurationRequest()).block()); } @Test public void testDeleteConfiguration_FailWhenThrowUnsupportedOperationException() { CapaConfigurationClientStore clientStore = new CapaConfigurationClientStore(Collections.emptyList()); - Assertions.assertThrows(UnsupportedOperationException.class, () -> clientStore.deleteConfiguration(new ConfigurationRequestItem()).block()); + Assertions.assertThrows(UnsupportedOperationException.class, + () -> clientStore.deleteConfiguration(new ConfigurationRequestItem()).block()); } @Test public void testGetConfiguration_FailWhenThrowUnsupportedOperationException() { CapaConfigurationClientStore clientStore = new CapaConfigurationClientStore(Collections.emptyList()); - Assertions.assertThrows(UnsupportedOperationException.class, () -> clientStore.getConfiguration(new ConfigurationRequestItem(),TypeRef.STRING).block()); + Assertions.assertThrows(UnsupportedOperationException.class, + () -> clientStore.getConfiguration(new ConfigurationRequestItem(), TypeRef.STRING).block()); } @Test public void testSubscribeConfiguration_FailWhenThrowUnsupportedOperationException() { CapaConfigurationClientStore clientStore = new CapaConfigurationClientStore(Collections.emptyList()); - Assertions.assertThrows(UnsupportedOperationException.class, () -> clientStore.subscribeConfiguration(new ConfigurationRequestItem(),TypeRef.STRING).blockFirst()); + Assertions.assertThrows(UnsupportedOperationException.class, + () -> clientStore.subscribeConfiguration(new ConfigurationRequestItem(), TypeRef.STRING).blockFirst()); } @Test @@ -78,19 +82,21 @@ public void testShutDown_Success() { @Test public void testGetConfiguration_FailWhenStoreNameIsNull() { CapaConfigurationClientStore clientStore = new CapaConfigurationClientStore(Collections.emptyList()); - Assertions.assertThrows(CapaException.class, () -> clientStore.getConfiguration("qconfig", "123", Lists.newArrayList("testKey1"), Collections.emptyMap(), TypeRef.STRING).block()); + Assertions.assertThrows(CapaException.class, + () -> clientStore.getConfiguration("apollo", "123", Lists.newArrayList("testKey1"), Collections.emptyMap(), TypeRef.STRING).block()); } @Test public void testGetConfigurationLevel1_FailWhenStoreNameIsNull() { CapaConfigurationClientStore clientStore = new CapaConfigurationClientStore(Collections.emptyList()); - Assertions.assertThrows(CapaException.class, () -> clientStore.getConfiguration("qconfig", "123", Lists.newArrayList("testKey1"), Collections.emptyMap(), null, TypeRef.STRING).block()); + Assertions.assertThrows(CapaException.class, + () -> clientStore.getConfiguration("apollo", "123", Lists.newArrayList("testKey1"), Collections.emptyMap(), null, TypeRef.STRING).block()); } @Test public void testGetConfiguration_SuccessWithConfigurationHasValue() { CapaConfigurationClientStore clientStore = new CapaConfigurationClientStore(constructConfigStoreListWithConfirgurationItemHasValue()); - Mono>> configuration = clientStore.getConfiguration("qconfig", "123", Lists.newArrayList(), Collections.emptyMap(), null, null, TypeRef.STRING); + Mono>> configuration = clientStore.getConfiguration("apollo", "123", Lists.newArrayList(), Collections.emptyMap(), null, null, TypeRef.STRING); List> configurationItems = configuration.block(); Assertions.assertNotNull(configurationItems); Assertions.assertEquals(1, configurationItems.size()); @@ -105,7 +111,7 @@ public void testGetConfiguration_SuccessWithConfigurationHasValue() { @Test public void testGetConfiguration_SuccessWithConfigurationItemIsEmpty() { CapaConfigurationClientStore clientStore = new CapaConfigurationClientStore(constructConfigStoreListWithConfigurationItemIsEmpty()); - Mono>> configuration = clientStore.getConfiguration("qconfig", "123", Lists.newArrayList("testKey1"), Collections.emptyMap(), "testGroup", "testLabel", TypeRef.STRING); + Mono>> configuration = clientStore.getConfiguration("apollo", "123", Lists.newArrayList("testKey1"), Collections.emptyMap(), "testGroup", "testLabel", TypeRef.STRING); List> configurationItems = configuration.block(); Assertions.assertNull(configurationItems); } @@ -113,7 +119,8 @@ public void testGetConfiguration_SuccessWithConfigurationItemIsEmpty() { @Test public void testSubscribeConfiguration_SuccessWithSubscribeRespHasValue() { CapaConfigStore mockConfigStore = Mockito.mock(CapaConfigStore.class); - Mockito.when(mockConfigStore.getStoreName()).thenReturn("qconfig"); + Mockito.when(mockConfigStore.getStoreName()) + .thenReturn("apollo"); SubscribeResp subscribeResp = new SubscribeResp<>(); List> result = new ArrayList<>(); @@ -124,16 +131,17 @@ public void testSubscribeConfiguration_SuccessWithSubscribeRespHasValue() { configurationItem.setLabel("testLabel"); result.add(configurationItem); subscribeResp.setItems(result); - Mockito.when(mockConfigStore.subscribe(any(SubscribeReq.class), any(TypeRef.class))).thenReturn(Flux.just(subscribeResp)); + Mockito.when(mockConfigStore.subscribe(any(SubscribeReq.class), any(TypeRef.class))) + .thenReturn(Flux.just(subscribeResp)); CapaConfigurationClientStore clientStore = new CapaConfigurationClientStore(Lists.newArrayList(mockConfigStore)); - ConfigurationRequestItem configurationRequestItem = new ConfigurationRequestItem(); - configurationRequestItem.setStoreName("qconfig"); - Flux> subConfigurationRespFlux = clientStore.subscribeConfiguration("qconfig", "123", Lists.newArrayList("testKey1"), Collections.emptyMap(), TypeRef.STRING); + configurationRequestItem.setStoreName("apollo"); + Flux> subConfigurationRespFlux = clientStore.subscribeConfiguration("apollo", "123", Lists.newArrayList("testKey1"), Collections.emptyMap(), TypeRef.STRING); SubConfigurationResp stringSubConfigurationResp = subConfigurationRespFlux.blockFirst(); Assertions.assertNotNull(stringSubConfigurationResp); Assertions.assertEquals(1, stringSubConfigurationResp.getItems().size()); + ConfigurationItem firstItem = stringSubConfigurationResp.getItems().get(0); Assertions.assertEquals("testKey1", firstItem.getKey()); Assertions.assertEquals("testContent", firstItem.getContent()); @@ -144,7 +152,10 @@ public void testSubscribeConfiguration_SuccessWithSubscribeRespHasValue() { @Test public void testClose_Success() throws Exception { CapaConfigStore mockConfigStore = Mockito.mock(CapaConfigStore.class); - Mockito.doNothing().when(mockConfigStore).close(); + Mockito.doNothing() + .when(mockConfigStore) + .close(); + CapaConfigurationClientStore clientStore = new CapaConfigurationClientStore(Lists.newArrayList(mockConfigStore)); clientStore.close(); Mockito.verify(mockConfigStore).close(); @@ -152,7 +163,8 @@ public void testClose_Success() throws Exception { private List constructConfigStoreListWithConfirgurationItemHasValue() { CapaConfigStore mockConfigStore = Mockito.mock(CapaConfigStore.class); - Mockito.when(mockConfigStore.getStoreName()).thenReturn("qconfig"); + Mockito.when(mockConfigStore.getStoreName()) + .thenReturn("apollo"); List> result = new ArrayList<>(); group.rxcloud.capa.component.configstore.ConfigurationItem configurationItem = new group.rxcloud.capa.component.configstore.ConfigurationItem(); @@ -162,17 +174,20 @@ private List constructConfigStoreListWithConfirgurationItemHasV configurationItem.setLabel("testLabel"); result.add(configurationItem); Mono>> just = Mono.just(result); - Mockito.when(mockConfigStore.get(any(GetRequest.class), any(TypeRef.class))).thenReturn(just); + Mockito.when(mockConfigStore.get(any(GetRequest.class), any(TypeRef.class))) + .thenReturn(just); return Lists.newArrayList(mockConfigStore); } private List constructConfigStoreListWithConfigurationItemIsEmpty() { CapaConfigStore mockConfigStore = Mockito.mock(CapaConfigStore.class); - Mockito.when(mockConfigStore.getStoreName()).thenReturn("qconfig"); + Mockito.when(mockConfigStore.getStoreName()) + .thenReturn("apollo"); List result = new ArrayList<>(); Mono> just = Mono.just(result); - Mockito.when(mockConfigStore.get(any(GetRequest.class), any(TypeRef.class))).thenReturn(just); + Mockito.when(mockConfigStore.get(any(GetRequest.class), any(TypeRef.class))) + .thenReturn(just); return Lists.newArrayList(mockConfigStore); } } \ No newline at end of file diff --git a/sdk/src/test/java/group/rxcloud/capa/rpc/CapaRpcClientBuilderTest.java b/sdk/src/test/java/group/rxcloud/capa/rpc/CapaRpcClientBuilderTest.java index 178176d..0711e4e 100644 --- a/sdk/src/test/java/group/rxcloud/capa/rpc/CapaRpcClientBuilderTest.java +++ b/sdk/src/test/java/group/rxcloud/capa/rpc/CapaRpcClientBuilderTest.java @@ -52,7 +52,8 @@ public class CapaRpcClientBuilderTest { public void setUp() { okHttpClient = new OkHttpClient.Builder().build(); defaultObjectSerializer = new DefaultObjectSerializer(); - capaRpcClientHttp = new CapaRpcClientHttp(new TestCapaHttp(okHttpClient, defaultObjectSerializer)); + TestCapaHttp client = new TestCapaHttp(okHttpClient, defaultObjectSerializer); + capaRpcClientHttp = new CapaRpcClientHttp(client); } @Test diff --git a/sdk/src/test/java/group/rxcloud/capa/telemetry/CapaTelemetryClientGlobalTest.java b/sdk/src/test/java/group/rxcloud/capa/telemetry/CapTelemetryClientExporterTest.java similarity index 76% rename from sdk/src/test/java/group/rxcloud/capa/telemetry/CapaTelemetryClientGlobalTest.java rename to sdk/src/test/java/group/rxcloud/capa/telemetry/CapTelemetryClientExporterTest.java index 4c2d13e..6604e6c 100644 --- a/sdk/src/test/java/group/rxcloud/capa/telemetry/CapaTelemetryClientGlobalTest.java +++ b/sdk/src/test/java/group/rxcloud/capa/telemetry/CapTelemetryClientExporterTest.java @@ -19,7 +19,6 @@ import io.opentelemetry.api.GlobalOpenTelemetry; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -27,16 +26,16 @@ * @author: chenyijiang * @date: 2021/11/26 14:12 */ -public class CapaTelemetryClientGlobalTest { +public class CapTelemetryClientExporterTest { @Test public void getOrCreate() { CapaTelemetryClient client = new CapaTelemetryClientBuilder().build(); - assertTrue(client instanceof CapaTelemetryClientGlobal); + assertTrue(client instanceof CapTelemetryClientExporter); assertNotNull(client.getContextPropagators()); - assertNotNull(((CapaTelemetryClientGlobal) client).getPropagators()); - assertNotNull(((CapaTelemetryClientGlobal) client).getMeterProvider()); - assertNotNull(((CapaTelemetryClientGlobal) client).getTracerProvider()); + assertNotNull(((CapTelemetryClientExporter) client).getPropagators()); + assertNotNull(((CapTelemetryClientExporter) client).getMeterProvider()); + assertNotNull(((CapTelemetryClientExporter) client).getTracerProvider()); assertNotNull(GlobalOpenTelemetry.get()); } } \ No newline at end of file diff --git a/sdk/src/test/java/group/rxcloud/capa/telemetry/CapaTelemetryClientBuilderTest.java b/sdk/src/test/java/group/rxcloud/capa/telemetry/CapaTelemetryClientBuilderTest.java index b1632f8..5f55403 100644 --- a/sdk/src/test/java/group/rxcloud/capa/telemetry/CapaTelemetryClientBuilderTest.java +++ b/sdk/src/test/java/group/rxcloud/capa/telemetry/CapaTelemetryClientBuilderTest.java @@ -17,11 +17,10 @@ package group.rxcloud.capa.telemetry; import group.rxcloud.capa.component.telemetry.SamplerConfig; -import group.rxcloud.capa.component.telemetry.context.ContextConfig; -import group.rxcloud.capa.component.telemetry.metrics.MeterConfig; +import group.rxcloud.capa.component.telemetry.metrics.MeterConfigLoader; import group.rxcloud.capa.component.telemetry.metrics.MetricsReaderConfig; import group.rxcloud.capa.component.telemetry.trace.SpanLimitsConfig; -import group.rxcloud.capa.component.telemetry.trace.TracerConfig; +import group.rxcloud.capa.component.telemetry.trace.TracerConfigLoader; import io.opentelemetry.api.metrics.LongCounter; import io.opentelemetry.api.trace.Span; import io.opentelemetry.api.trace.Tracer; @@ -62,8 +61,8 @@ public void buildManual() throws InterruptedException { .setSamplerConfig(() -> SamplerConfig.DEFAULT_CONFIG) .setSpanLimits(new SpanLimitsConfig()) .setIdGenerator(IdGenerator.random()) - .setTracerConfig(new TracerConfig()) - .setMeterConfig(new MeterConfig()) + .setTracerConfig(new TracerConfigLoader()) + .setMeterConfig(new MeterConfigLoader()) .addMetricReaderConfig(readerConfig) .setContextConfig(new ContextConfig()) .addContextPropagators(W3CTraceContextPropagator.getInstance()) @@ -71,17 +70,17 @@ public void buildManual() throws InterruptedException { // tracer Tracer tracer = capaTelemetryClient.buildTracer("tracer-test") - .block(); + .block(); LongCounter counter = capaTelemetryClient.buildMeter("meter-test") - .block() - .counterBuilder("counter-test") - .build(); + .block() + .counterBuilder("counter-test") + .build(); Span span = tracer.spanBuilder("span-test") - .setAttribute("key1", 1) - .setAttribute("key2", 2) - .startSpan(); + .setAttribute("key1", 1) + .setAttribute("key2", 2) + .startSpan(); // working for (int i = 0; i < 10; i++) { Thread.sleep(200); diff --git a/sdk/src/test/java/group/rxcloud/capa/telemetry/MetricTestExporter.java b/sdk/src/test/java/group/rxcloud/capa/telemetry/MetricTestExporter.java index 3d184b6..4500d6d 100644 --- a/sdk/src/test/java/group/rxcloud/capa/telemetry/MetricTestExporter.java +++ b/sdk/src/test/java/group/rxcloud/capa/telemetry/MetricTestExporter.java @@ -26,8 +26,7 @@ public class MetricTestExporter extends CapaMetricsExporter { - public MetricTestExporter( - Supplier samplerConfig) { + public MetricTestExporter(Supplier samplerConfig) { super(samplerConfig); } diff --git a/sdk/src/test/java/group/rxcloud/capa/telemetry/TraceProcessor.java b/sdk/src/test/java/group/rxcloud/capa/telemetry/TraceProcessor.java index ab579b0..ddb0108 100644 --- a/sdk/src/test/java/group/rxcloud/capa/telemetry/TraceProcessor.java +++ b/sdk/src/test/java/group/rxcloud/capa/telemetry/TraceProcessor.java @@ -25,7 +25,6 @@ public class TraceProcessor implements SpanProcessor { @Override public void onStart(Context context, ReadWriteSpan span) { - } @Override