From dad2bd9c7b95a76257a0d3fa99e3928c2b262346 Mon Sep 17 00:00:00 2001 From: eutkin Date: Tue, 18 Feb 2020 20:26:23 +0300 Subject: [PATCH 01/61] ISSUE-708 Extract interface from Microservices --- .../java/io/scalecube/services/IMicroservices.java | 14 ++++++++++++++ .../java/io/scalecube/services/Microservices.java | 5 ++++- 2 files changed, 18 insertions(+), 1 deletion(-) create mode 100644 services-api/src/main/java/io/scalecube/services/IMicroservices.java diff --git a/services-api/src/main/java/io/scalecube/services/IMicroservices.java b/services-api/src/main/java/io/scalecube/services/IMicroservices.java new file mode 100644 index 000000000..b6529f8cf --- /dev/null +++ b/services-api/src/main/java/io/scalecube/services/IMicroservices.java @@ -0,0 +1,14 @@ +package io.scalecube.services; + +import io.scalecube.net.Address; +import io.scalecube.services.discovery.api.ServiceDiscovery; + +public interface IMicroservices { + + ServiceCall call(); + + Address serviceAddress(); + + ServiceDiscovery discovery(); + +} diff --git a/services/src/main/java/io/scalecube/services/Microservices.java b/services/src/main/java/io/scalecube/services/Microservices.java index e289bae90..3af7e63bd 100644 --- a/services/src/main/java/io/scalecube/services/Microservices.java +++ b/services/src/main/java/io/scalecube/services/Microservices.java @@ -113,7 +113,7 @@ * * } */ -public class Microservices { +public class Microservices implements IMicroservices { public static final Logger LOGGER = LoggerFactory.getLogger(Microservices.class); @@ -241,6 +241,7 @@ public Metrics metrics() { return this.metrics; } + @Override public Address serviceAddress() { return transportBootstrap.address; } @@ -250,6 +251,7 @@ public Address serviceAddress() { * * @return new {@code ServiceCall} instance. */ + @Override public ServiceCall call() { return new ServiceCall() .transport(transportBootstrap.clientTransport) @@ -266,6 +268,7 @@ public Gateway gateway(String id) { return gatewayBootstrap.gateway(id); } + @Override public ServiceDiscovery discovery() { return discoveryBootstrap.discovery; } From 3d4011c6dabba3f0ea4a368380a62f2d6c8ad8c1 Mon Sep 17 00:00:00 2001 From: eutkin Date: Tue, 18 Feb 2020 21:04:20 +0300 Subject: [PATCH 02/61] ISSUE-708 New entrypoint for DI frameworks --- .../DeprecatedServiceProviderAdapter.java | 22 +++++++++++++++++++ .../scalecube/services/ServiceProvider.java | 4 ++++ .../scalecube/services/ServicesProvider.java | 11 ++++++++++ 3 files changed, 37 insertions(+) create mode 100644 services-api/src/main/java/io/scalecube/services/DeprecatedServiceProviderAdapter.java create mode 100644 services-api/src/main/java/io/scalecube/services/ServicesProvider.java diff --git a/services-api/src/main/java/io/scalecube/services/DeprecatedServiceProviderAdapter.java b/services-api/src/main/java/io/scalecube/services/DeprecatedServiceProviderAdapter.java new file mode 100644 index 000000000..f74e8bf83 --- /dev/null +++ b/services-api/src/main/java/io/scalecube/services/DeprecatedServiceProviderAdapter.java @@ -0,0 +1,22 @@ +package io.scalecube.services; + +import reactor.core.publisher.Mono; + +import java.util.Collection; + +import static java.util.Objects.requireNonNull; + +@Deprecated +public class DeprecatedServiceProviderAdapter implements ServicesProvider { + + private final ServiceProvider delegate; + + public DeprecatedServiceProviderAdapter(ServiceProvider delegate) { + this.delegate = requireNonNull(delegate); + } + + @Override + public Mono> provide(IMicroservices microservices) { + return Mono.defer(() -> Mono.fromSupplier(() -> delegate.provide(microservices.call()))); + } +} diff --git a/services-api/src/main/java/io/scalecube/services/ServiceProvider.java b/services-api/src/main/java/io/scalecube/services/ServiceProvider.java index 3c55e23f4..ee7a1584c 100644 --- a/services-api/src/main/java/io/scalecube/services/ServiceProvider.java +++ b/services-api/src/main/java/io/scalecube/services/ServiceProvider.java @@ -2,7 +2,11 @@ import java.util.Collection; +/** + * @deprecated use {@link ServicesProvider} + */ @FunctionalInterface +@Deprecated public interface ServiceProvider { Collection provide(ServiceCall call); diff --git a/services-api/src/main/java/io/scalecube/services/ServicesProvider.java b/services-api/src/main/java/io/scalecube/services/ServicesProvider.java new file mode 100644 index 000000000..ed591314a --- /dev/null +++ b/services-api/src/main/java/io/scalecube/services/ServicesProvider.java @@ -0,0 +1,11 @@ +package io.scalecube.services; + +import reactor.core.publisher.Mono; + +import java.util.Collection; + +@FunctionalInterface +public interface ServicesProvider { + + Mono> provide(IMicroservices microservices); +} From 0c89c390ed231821dc503bc87d869fb4d13b59cc Mon Sep 17 00:00:00 2001 From: eutkin Date: Tue, 18 Feb 2020 21:44:37 +0300 Subject: [PATCH 03/61] ISSUE-708 fix code style --- eclipse-java-google-style.xml | 730 ++++++++++++++++++ eclipse.importorder | 9 + .../DeprecatedServiceProviderAdapter.java | 5 +- .../io/scalecube/services/IMicroservices.java | 7 +- .../scalecube/services/ServiceProvider.java | 2 + .../scalecube/services/ServicesProvider.java | 5 +- style.importorder | 9 + 7 files changed, 757 insertions(+), 10 deletions(-) create mode 100644 eclipse-java-google-style.xml create mode 100644 eclipse.importorder create mode 100644 style.importorder diff --git a/eclipse-java-google-style.xml b/eclipse-java-google-style.xml new file mode 100644 index 000000000..7719b620b --- /dev/null +++ b/eclipse-java-google-style.xml @@ -0,0 +1,730 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/eclipse.importorder b/eclipse.importorder new file mode 100644 index 000000000..45e32f951 --- /dev/null +++ b/eclipse.importorder @@ -0,0 +1,9 @@ +#Organize Import Order +#Fri Apr 13 21:16:47 IDT 2018 +6=javax +5=java +4=rx +3=org +2=io +1=com +0=io.scalecube \ No newline at end of file diff --git a/services-api/src/main/java/io/scalecube/services/DeprecatedServiceProviderAdapter.java b/services-api/src/main/java/io/scalecube/services/DeprecatedServiceProviderAdapter.java index f74e8bf83..fe0d667dc 100644 --- a/services-api/src/main/java/io/scalecube/services/DeprecatedServiceProviderAdapter.java +++ b/services-api/src/main/java/io/scalecube/services/DeprecatedServiceProviderAdapter.java @@ -1,10 +1,9 @@ package io.scalecube.services; -import reactor.core.publisher.Mono; +import static java.util.Objects.requireNonNull; import java.util.Collection; - -import static java.util.Objects.requireNonNull; +import reactor.core.publisher.Mono; @Deprecated public class DeprecatedServiceProviderAdapter implements ServicesProvider { diff --git a/services-api/src/main/java/io/scalecube/services/IMicroservices.java b/services-api/src/main/java/io/scalecube/services/IMicroservices.java index b6529f8cf..8b0b431c8 100644 --- a/services-api/src/main/java/io/scalecube/services/IMicroservices.java +++ b/services-api/src/main/java/io/scalecube/services/IMicroservices.java @@ -5,10 +5,9 @@ public interface IMicroservices { - ServiceCall call(); + ServiceCall call(); - Address serviceAddress(); - - ServiceDiscovery discovery(); + Address serviceAddress(); + ServiceDiscovery discovery(); } diff --git a/services-api/src/main/java/io/scalecube/services/ServiceProvider.java b/services-api/src/main/java/io/scalecube/services/ServiceProvider.java index ee7a1584c..92faa6f1e 100644 --- a/services-api/src/main/java/io/scalecube/services/ServiceProvider.java +++ b/services-api/src/main/java/io/scalecube/services/ServiceProvider.java @@ -3,6 +3,8 @@ import java.util.Collection; /** + * Provide service instances. + * * @deprecated use {@link ServicesProvider} */ @FunctionalInterface diff --git a/services-api/src/main/java/io/scalecube/services/ServicesProvider.java b/services-api/src/main/java/io/scalecube/services/ServicesProvider.java index ed591314a..bc1bd5228 100644 --- a/services-api/src/main/java/io/scalecube/services/ServicesProvider.java +++ b/services-api/src/main/java/io/scalecube/services/ServicesProvider.java @@ -1,11 +1,10 @@ package io.scalecube.services; -import reactor.core.publisher.Mono; - import java.util.Collection; +import reactor.core.publisher.Mono; @FunctionalInterface public interface ServicesProvider { - Mono> provide(IMicroservices microservices); + Mono> provide(IMicroservices microservices); } diff --git a/style.importorder b/style.importorder new file mode 100644 index 000000000..1de78c902 --- /dev/null +++ b/style.importorder @@ -0,0 +1,9 @@ +1=io.scalecube# +2=\# +3=io.scalecube +4=com +5=io +6=org +7=rx +8=java +9=javax \ No newline at end of file From 07a56504f74dce8dd68ca394430640283b2b63dd Mon Sep 17 00:00:00 2001 From: eutkin Date: Tue, 18 Feb 2020 21:46:53 +0300 Subject: [PATCH 04/61] ISSUE-708 fix code style --- eclipse-java-google-style.xml | 730 ---------------------------------- eclipse.importorder | 9 - style.importorder | 9 - 3 files changed, 748 deletions(-) delete mode 100644 eclipse-java-google-style.xml delete mode 100644 eclipse.importorder delete mode 100644 style.importorder diff --git a/eclipse-java-google-style.xml b/eclipse-java-google-style.xml deleted file mode 100644 index 7719b620b..000000000 --- a/eclipse-java-google-style.xml +++ /dev/null @@ -1,730 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/eclipse.importorder b/eclipse.importorder deleted file mode 100644 index 45e32f951..000000000 --- a/eclipse.importorder +++ /dev/null @@ -1,9 +0,0 @@ -#Organize Import Order -#Fri Apr 13 21:16:47 IDT 2018 -6=javax -5=java -4=rx -3=org -2=io -1=com -0=io.scalecube \ No newline at end of file diff --git a/style.importorder b/style.importorder deleted file mode 100644 index 1de78c902..000000000 --- a/style.importorder +++ /dev/null @@ -1,9 +0,0 @@ -1=io.scalecube# -2=\# -3=io.scalecube -4=com -5=io -6=org -7=rx -8=java -9=javax \ No newline at end of file From 6140c6d922c7376618f5cc916e6b154efbf1f1a9 Mon Sep 17 00:00:00 2001 From: eutkin Date: Wed, 19 Feb 2020 18:06:50 +0300 Subject: [PATCH 05/61] ISSUE-708 replace service instance to service instance supplier --- .../DeprecatedServiceProviderAdapter.java | 17 ++++++--- .../java/io/scalecube/services/Reflect.java | 11 +++--- .../io/scalecube/services/ServiceInfo.java | 30 ++++++++++------ .../io/scalecube/services/ServiceScanner.java | 3 +- .../methods/ServiceMethodInvoker.java | 36 ++++++++++++++----- .../methods/ServiceMethodInvokerTest.java | 25 +++++++++---- .../io/scalecube/services/Microservices.java | 31 +++++++++------- .../methods/ServiceMethodRegistryImpl.java | 5 +-- 8 files changed, 107 insertions(+), 51 deletions(-) diff --git a/services-api/src/main/java/io/scalecube/services/DeprecatedServiceProviderAdapter.java b/services-api/src/main/java/io/scalecube/services/DeprecatedServiceProviderAdapter.java index fe0d667dc..a5be65f56 100644 --- a/services-api/src/main/java/io/scalecube/services/DeprecatedServiceProviderAdapter.java +++ b/services-api/src/main/java/io/scalecube/services/DeprecatedServiceProviderAdapter.java @@ -3,19 +3,28 @@ import static java.util.Objects.requireNonNull; import java.util.Collection; +import java.util.function.Supplier; +import java.util.stream.Collectors; import reactor.core.publisher.Mono; @Deprecated public class DeprecatedServiceProviderAdapter implements ServicesProvider { - private final ServiceProvider delegate; + private final Collection delegates; - public DeprecatedServiceProviderAdapter(ServiceProvider delegate) { - this.delegate = requireNonNull(delegate); + public DeprecatedServiceProviderAdapter(Collection delegates) { + this.delegates = requireNonNull(delegates); } @Override public Mono> provide(IMicroservices microservices) { - return Mono.defer(() -> Mono.fromSupplier(() -> delegate.provide(microservices.call()))); + Supplier>> beanSupplier = + () -> + Mono.just( + delegates.stream() + .map(delegate -> delegate.provide(microservices.call())) + .flatMap(Collection::stream) + .collect(Collectors.toList())); + return Mono.defer(beanSupplier); } } diff --git a/services-api/src/main/java/io/scalecube/services/Reflect.java b/services-api/src/main/java/io/scalecube/services/Reflect.java index 7171ff7c3..f52a7fe16 100644 --- a/services-api/src/main/java/io/scalecube/services/Reflect.java +++ b/services-api/src/main/java/io/scalecube/services/Reflect.java @@ -25,6 +25,8 @@ import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; +import java.util.stream.Stream; + import org.reactivestreams.Publisher; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @@ -249,14 +251,13 @@ public static Map serviceMethods(Class serviceInterface) { /** * Util function to get service interfaces collections from service instance. * - * @param serviceObject with extends service interface with @Service annotation. + * @param serviceType type with extends service interface with @Service annotation. * @return service interface class. */ - public static Collection> serviceInterfaces(Object serviceObject) { - Class[] interfaces = serviceObject.getClass().getInterfaces(); + public static Stream> serviceInterfaces(Class serviceType) { + Class[] interfaces = serviceType.getInterfaces(); return Arrays.stream(interfaces) - .filter(interfaceClass -> interfaceClass.isAnnotationPresent(Service.class)) - .collect(Collectors.toList()); + .filter(interfaceClass -> interfaceClass.isAnnotationPresent(Service.class)); } public static String methodName(Method method) { diff --git a/services-api/src/main/java/io/scalecube/services/ServiceInfo.java b/services-api/src/main/java/io/scalecube/services/ServiceInfo.java index f99630563..4037e19ae 100644 --- a/services-api/src/main/java/io/scalecube/services/ServiceInfo.java +++ b/services-api/src/main/java/io/scalecube/services/ServiceInfo.java @@ -7,18 +7,21 @@ import java.util.HashMap; import java.util.Map; import java.util.StringJoiner; +import java.util.function.Supplier; @SuppressWarnings("rawtypes") public class ServiceInfo { - private final Object serviceInstance; + private final Class serviceType; + private final Supplier serviceInstanceSupplier; private final Map tags; private final ServiceProviderErrorMapper errorMapper; private final ServiceMessageDataDecoder dataDecoder; private final Authenticator authenticator; private ServiceInfo(Builder builder) { - this.serviceInstance = builder.serviceInstance; + this.serviceType = builder.serviceType; + this.serviceInstanceSupplier = builder.serviceInstanceSupplier; this.tags = Collections.unmodifiableMap(new HashMap<>(builder.tags)); this.errorMapper = builder.errorMapper; this.dataDecoder = builder.dataDecoder; @@ -30,11 +33,11 @@ public static Builder from(ServiceInfo serviceInfo) { } public static Builder fromServiceInstance(Object serviceInstance) { - return new Builder(serviceInstance); + return new Builder(serviceInstance.getClass(), () -> serviceInstance); } - public Object serviceInstance() { - return serviceInstance; + public Supplier serviceInstanceSupplier() { + return serviceInstanceSupplier; } public Map tags() { @@ -53,10 +56,14 @@ public Authenticator authenticator() { return authenticator; } + public Class type() { + return serviceType; + } + @Override public String toString() { return new StringJoiner(", ", ServiceInfo.class.getSimpleName() + "[", "]") - .add("serviceInstance=" + serviceInstance) + .add("serviceInstance=" + serviceInstanceSupplier) .add("tags=" + tags) .add("errorMapper=" + errorMapper) .add("dataDecoder=" + dataDecoder) @@ -67,22 +74,25 @@ public String toString() { @SuppressWarnings("rawtypes") public static class Builder { - private Object serviceInstance; + private final Class serviceType; + private final Supplier serviceInstanceSupplier; private Map tags = new HashMap<>(); private ServiceProviderErrorMapper errorMapper; private ServiceMessageDataDecoder dataDecoder; private Authenticator authenticator; private Builder(ServiceInfo serviceInfo) { - this.serviceInstance = serviceInfo.serviceInstance; + this.serviceInstanceSupplier = serviceInfo.serviceInstanceSupplier; + this.serviceType = serviceInfo.serviceType; this.tags.putAll(new HashMap<>(serviceInfo.tags)); this.errorMapper = serviceInfo.errorMapper; this.dataDecoder = serviceInfo.dataDecoder; this.authenticator = serviceInfo.authenticator; } - private Builder(Object serviceInstance) { - this.serviceInstance = serviceInstance; + private Builder(Class serviceType, Supplier serviceInstanceSupplier) { + this.serviceType = serviceType; + this.serviceInstanceSupplier = serviceInstanceSupplier; } public Builder tag(String key, String value) { diff --git a/services-api/src/main/java/io/scalecube/services/ServiceScanner.java b/services-api/src/main/java/io/scalecube/services/ServiceScanner.java index 460deb58f..208e5dda6 100644 --- a/services-api/src/main/java/io/scalecube/services/ServiceScanner.java +++ b/services-api/src/main/java/io/scalecube/services/ServiceScanner.java @@ -22,8 +22,7 @@ private ServiceScanner() { * @return list of {@code ServiceRegistration}-s */ public static List scanServiceInfo(ServiceInfo serviceInfo) { - return Arrays.stream(serviceInfo.serviceInstance().getClass().getInterfaces()) - .filter(serviceInterface -> serviceInterface.isAnnotationPresent(Service.class)) + return Reflect.serviceInterfaces(serviceInfo.type()) .map( serviceInterface -> { Map serviceInfoTags = serviceInfo.tags(); diff --git a/services-api/src/main/java/io/scalecube/services/methods/ServiceMethodInvoker.java b/services-api/src/main/java/io/scalecube/services/methods/ServiceMethodInvoker.java index cea6bd210..7184548f7 100644 --- a/services-api/src/main/java/io/scalecube/services/methods/ServiceMethodInvoker.java +++ b/services-api/src/main/java/io/scalecube/services/methods/ServiceMethodInvoker.java @@ -11,7 +11,10 @@ import java.lang.reflect.Method; import java.util.Optional; import java.util.StringJoiner; +import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; +import java.util.function.Supplier; + import org.reactivestreams.Publisher; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @@ -25,11 +28,12 @@ public final class ServiceMethodInvoker { private static final Object NO_PRINCIPAL = new Object(); private final Method method; - private final Object service; + private final Supplier service; private final MethodInfo methodInfo; private final ServiceProviderErrorMapper errorMapper; private final ServiceMessageDataDecoder dataDecoder; private final Authenticator authenticator; + private final Class serviceType; /** * Constructs a service method invoker out of real service object instance and method info. @@ -41,15 +45,26 @@ public final class ServiceMethodInvoker { * @param dataDecoder data decoder */ @SuppressWarnings({"unchecked", "rawtypes"}) - public ServiceMethodInvoker( + public ServiceMethodInvoker( + Class serviceType, Method method, - Object service, + Supplier service, MethodInfo methodInfo, ServiceProviderErrorMapper errorMapper, ServiceMessageDataDecoder dataDecoder, Authenticator authenticator) { + this.serviceType = serviceType; this.method = method; - this.service = service; + this.service = + new Supplier() { + private final AtomicReference instance = new AtomicReference<>(); + + @Override + public Object get() { + instance.compareAndSet(null, service.get()); + return instance.get(); + } + }; this.methodInfo = methodInfo; this.errorMapper = errorMapper; this.dataDecoder = dataDecoder; @@ -114,10 +129,10 @@ private Publisher invoke(Object request, Object principal) { Throwable throwable = null; try { if (methodInfo.parameterCount() == 0) { - result = (Publisher) method.invoke(service); + result = (Publisher) method.invoke(service.get()); } else { Object[] arguments = prepareArguments(request, principal); - result = (Publisher) method.invoke(service, arguments); + result = (Publisher) method.invoke(service.get(), arguments); } if (result == null) { result = Mono.empty(); @@ -199,8 +214,13 @@ private void applyRequestReleaser(ServiceMessage request, Consumer reque } } + public Class serviceType() { + return serviceType; + } + + @Deprecated public Object service() { - return service; + return service.get(); } public MethodInfo methodInfo() { @@ -211,7 +231,7 @@ public MethodInfo methodInfo() { public String toString() { return new StringJoiner(", ", ServiceMethodInvoker.class.getSimpleName() + "[", "]") .add("method=" + method) - .add("service=" + service) + .add("service=" + serviceType) .add("methodInfo=" + methodInfo) .add("errorMapper=" + errorMapper) .add("dataDecoder=" + dataDecoder) diff --git a/services-api/src/test/java/io/scalecube/services/methods/ServiceMethodInvokerTest.java b/services-api/src/test/java/io/scalecube/services/methods/ServiceMethodInvokerTest.java index c30e41bec..0d2c8d731 100644 --- a/services-api/src/test/java/io/scalecube/services/methods/ServiceMethodInvokerTest.java +++ b/services-api/src/test/java/io/scalecube/services/methods/ServiceMethodInvokerTest.java @@ -48,10 +48,12 @@ void testInvokeOneWhenReturnNull() throws Exception { false, AUTH); + // FIXME: 19.02.2020 serviceMethodInvoker = new ServiceMethodInvoker( + stubService.getClass(), method, - stubService, + () -> stubService, methodInfo, DefaultErrorMapper.INSTANCE, dataDecoder, @@ -81,11 +83,12 @@ void testInvokeManyWhenReturnNull() throws Exception { Void.TYPE, false, AUTH); - + // FIXME: 19.02.2020 serviceMethodInvoker = new ServiceMethodInvoker( + stubService.getClass(), method, - stubService, + () -> stubService, methodInfo, DefaultErrorMapper.INSTANCE, dataDecoder, @@ -116,10 +119,12 @@ void testInvokeBidirectionalWhenReturnNull() throws Exception { false, AUTH); + // FIXME: 19.02.2020 serviceMethodInvoker = new ServiceMethodInvoker( + stubService.getClass(), method, - stubService, + () -> stubService, methodInfo, DefaultErrorMapper.INSTANCE, dataDecoder, @@ -152,10 +157,12 @@ void testInvokeOneWhenThrowException() throws Exception { false, AUTH); + // FIXME: 19.02.2020 serviceMethodInvoker = new ServiceMethodInvoker( + stubService.getClass(), method, - stubService, + () -> stubService, methodInfo, DefaultErrorMapper.INSTANCE, dataDecoder, @@ -189,10 +196,12 @@ void testInvokeManyWhenThrowException() throws Exception { false, AUTH); + // FIXME: 19.02.2020 serviceMethodInvoker = new ServiceMethodInvoker( + stubService.getClass(), method, - stubService, + () -> stubService, methodInfo, DefaultErrorMapper.INSTANCE, dataDecoder, @@ -226,10 +235,12 @@ void testInvokeBidirectionalWhenThrowException() throws Exception { false, AUTH); + // FIXME: 19.02.2020 serviceMethodInvoker = new ServiceMethodInvoker( + stubService.getClass(), method, - stubService, + () -> stubService, methodInfo, DefaultErrorMapper.INSTANCE, dataDecoder, diff --git a/services/src/main/java/io/scalecube/services/Microservices.java b/services/src/main/java/io/scalecube/services/Microservices.java index cd99d6ab1..221841161 100644 --- a/services/src/main/java/io/scalecube/services/Microservices.java +++ b/services/src/main/java/io/scalecube/services/Microservices.java @@ -23,6 +23,7 @@ import io.scalecube.services.transport.api.ServerTransport; import io.scalecube.services.transport.api.ServiceMessageDataDecoder; import io.scalecube.services.transport.api.ServiceTransport; + import java.lang.management.ManagementFactory; import java.util.ArrayList; import java.util.Arrays; @@ -192,23 +193,27 @@ private Mono start() { .tags(tags); // invoke service providers and register services - List serviceInstances = - serviceProviders.stream() - .flatMap(serviceProvider -> serviceProvider.provide(call).stream()) - .peek(this::registerInMethodRegistry) - .peek( + ServicesProvider servicesProvider = + new DeprecatedServiceProviderAdapter(serviceProviders); + Mono> serviceInstanceSuppliers = + servicesProvider + .provide(this) + .flatMapIterable(i -> i) + .doOnNext(this::registerInMethodRegistry) + .doOnNext( serviceInfo -> serviceEndpointBuilder.appendServiceRegistrations( ServiceScanner.scanServiceInfo(serviceInfo))) - .map(ServiceInfo::serviceInstance) - .collect(Collectors.toList()); + .collectList(); - return discoveryBootstrap - .createInstance(serviceEndpointBuilder.build()) + return serviceInstanceSuppliers + .publishOn(scheduler) + // FIXME: 19.02.2020 if use then(Mono), incorrect order of operations + .flatMap( + ignore -> discoveryBootstrap.createInstance(serviceEndpointBuilder.build())) .publishOn(scheduler) .then(startGateway(call)) .publishOn(scheduler) - .then(Mono.fromCallable(() -> Injector.inject(this, serviceInstances))) .then(Mono.fromCallable(() -> JmxMonitorMBean.start(this))) .then(discoveryBootstrap.startListen(this)) .publishOn(scheduler) @@ -313,7 +318,7 @@ private Mono doShutdown() { private Mono processBeforeDestroy() { return Mono.whenDelayError( methodRegistry.listServices().stream() - .map(ServiceInfo::serviceInstance) + .map(ServiceInfo::serviceInstanceSupplier) .map(s -> Mono.fromRunnable(() -> Injector.processBeforeDestroy(this, s))) .collect(Collectors.toList())); } @@ -688,7 +693,7 @@ private static String asString(ServiceMethodInvoker invoker) { .add("methodInfo=" + asString(invoker.methodInfo())) .add( "serviceMethod=" - + invoker.service().getClass().getCanonicalName() + + invoker.serviceType().getCanonicalName() + "." + invoker.methodInfo().methodName() + "(" @@ -706,7 +711,7 @@ private static String asString(MethodInfo methodInfo) { private static String asString(ServiceInfo serviceInfo) { return new StringJoiner(", ", ServiceMethodInvoker.class.getSimpleName() + "[", "]") - .add("serviceInstance=" + serviceInfo.serviceInstance()) + .add("serviceInstance=" + serviceInfo.serviceInstanceSupplier()) .add("tags=" + serviceInfo.tags()) .add("authenticator=" + serviceInfo.authenticator()) .toString(); diff --git a/services/src/main/java/io/scalecube/services/methods/ServiceMethodRegistryImpl.java b/services/src/main/java/io/scalecube/services/methods/ServiceMethodRegistryImpl.java index 01850d025..61fa9595e 100644 --- a/services/src/main/java/io/scalecube/services/methods/ServiceMethodRegistryImpl.java +++ b/services/src/main/java/io/scalecube/services/methods/ServiceMethodRegistryImpl.java @@ -19,7 +19,7 @@ public final class ServiceMethodRegistryImpl implements ServiceMethodRegistry { public void registerService(ServiceInfo serviceInfo) { serviceInfos.add(serviceInfo); - Reflect.serviceInterfaces(serviceInfo.serviceInstance()) + Reflect.serviceInterfaces(serviceInfo.type()) .forEach( serviceInterface -> Reflect.serviceMethods(serviceInterface) @@ -51,8 +51,9 @@ public void registerService(ServiceInfo serviceInfo) { ServiceMethodInvoker invoker = new ServiceMethodInvoker( + serviceInfo.type(), method, - serviceInfo.serviceInstance(), + serviceInfo.serviceInstanceSupplier(), methodInfo, serviceInfo.errorMapper(), serviceInfo.dataDecoder(), From c48041b72f2254501641365ef72e6abccbd2912a Mon Sep 17 00:00:00 2001 From: eutkin Date: Sat, 22 Feb 2020 22:13:43 +0300 Subject: [PATCH 06/61] ISSUE-708 Renaming: Microservices -> ScaleCube, IMicroservices -> Microservices --- .../DeprecatedServiceProviderAdapter.java | 2 +- ...IMicroservices.java => Microservices.java} | 2 +- .../scalecube/services/ServicesProvider.java | 2 +- .../transport/BenchmarkServiceState.java | 12 ++--- .../services/examples/ExamplesRunner.java | 4 +- .../exceptions/ExceptionMapperExample.java | 10 ++--- .../examples/helloworld/Example1.java | 10 ++--- .../examples/helloworld/Example2.java | 10 ++--- .../examples/helloworld/Example3.java | 10 ++--- .../services/examples/orderbook/Example1.java | 10 ++--- .../services/examples/services/Example1.java | 14 +++--- .../services/examples/services/Example2.java | 14 +++--- .../java/io/scalecube/services/Injector.java | 14 +++--- .../{Microservices.java => ScaleCube.java} | 30 ++++++------- .../io/scalecube/services/ErrorFlowTest.java | 8 ++-- .../services/ServiceAuthLocalTest.java | 12 ++--- .../services/ServiceAuthRemoteTest.java | 20 ++++----- .../services/ServiceCallLocalTest.java | 6 +-- .../services/ServiceCallRemoteTest.java | 14 +++--- .../ServiceLifecycleAnnotationsTest.java | 6 +-- .../scalecube/services/ServiceLocalTest.java | 6 +-- .../services/ServiceRegistryTest.java | 44 +++++++++---------- .../scalecube/services/ServiceRemoteTest.java | 32 +++++++------- .../services/StreamingServiceTest.java | 8 ++-- .../services/routings/RoutersTest.java | 18 ++++---- .../services/routings/ServiceTagsExample.java | 14 +++--- .../services/sut/AnnotationServiceImpl.java | 4 +- .../sut/CoarseGrainedServiceImpl.java | 4 +- .../services/sut/GreetingServiceImpl.java | 5 ++- ...ocketNettyColocatedEventLoopGroupTest.java | 24 +++++----- .../rsocket/RSocketServiceTransportTest.java | 14 +++--- 31 files changed, 192 insertions(+), 191 deletions(-) rename services-api/src/main/java/io/scalecube/services/{IMicroservices.java => Microservices.java} (86%) rename services/src/main/java/io/scalecube/services/{Microservices.java => ScaleCube.java} (96%) diff --git a/services-api/src/main/java/io/scalecube/services/DeprecatedServiceProviderAdapter.java b/services-api/src/main/java/io/scalecube/services/DeprecatedServiceProviderAdapter.java index a5be65f56..e971d94b2 100644 --- a/services-api/src/main/java/io/scalecube/services/DeprecatedServiceProviderAdapter.java +++ b/services-api/src/main/java/io/scalecube/services/DeprecatedServiceProviderAdapter.java @@ -17,7 +17,7 @@ public DeprecatedServiceProviderAdapter(Collection delegates) { } @Override - public Mono> provide(IMicroservices microservices) { + public Mono> provide(Microservices microservices) { Supplier>> beanSupplier = () -> Mono.just( diff --git a/services-api/src/main/java/io/scalecube/services/IMicroservices.java b/services-api/src/main/java/io/scalecube/services/Microservices.java similarity index 86% rename from services-api/src/main/java/io/scalecube/services/IMicroservices.java rename to services-api/src/main/java/io/scalecube/services/Microservices.java index 8b0b431c8..3de736a49 100644 --- a/services-api/src/main/java/io/scalecube/services/IMicroservices.java +++ b/services-api/src/main/java/io/scalecube/services/Microservices.java @@ -3,7 +3,7 @@ import io.scalecube.net.Address; import io.scalecube.services.discovery.api.ServiceDiscovery; -public interface IMicroservices { +public interface Microservices { ServiceCall call(); diff --git a/services-api/src/main/java/io/scalecube/services/ServicesProvider.java b/services-api/src/main/java/io/scalecube/services/ServicesProvider.java index bc1bd5228..12fa242cc 100644 --- a/services-api/src/main/java/io/scalecube/services/ServicesProvider.java +++ b/services-api/src/main/java/io/scalecube/services/ServicesProvider.java @@ -6,5 +6,5 @@ @FunctionalInterface public interface ServicesProvider { - Mono> provide(IMicroservices microservices); + Mono> provide(Microservices microservices); } diff --git a/services-benchmarks/src/main/java/io/scalecube/services/benchmarks/transport/BenchmarkServiceState.java b/services-benchmarks/src/main/java/io/scalecube/services/benchmarks/transport/BenchmarkServiceState.java index 29722131a..8996f8cd5 100644 --- a/services-benchmarks/src/main/java/io/scalecube/services/benchmarks/transport/BenchmarkServiceState.java +++ b/services-benchmarks/src/main/java/io/scalecube/services/benchmarks/transport/BenchmarkServiceState.java @@ -3,7 +3,7 @@ import io.scalecube.benchmarks.BenchmarkSettings; import io.scalecube.benchmarks.BenchmarkState; import io.scalecube.net.Address; -import io.scalecube.services.Microservices; +import io.scalecube.services.ScaleCube; import io.scalecube.services.ServiceCall; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.transport.rsocket.RSocketServiceTransport; @@ -20,8 +20,8 @@ public class BenchmarkServiceState extends BenchmarkState private final Object[] services; - private Microservices seed; - private Microservices node; + private ScaleCube seed; + private ScaleCube node; public BenchmarkServiceState(BenchmarkSettings settings, Object... services) { super(settings); @@ -31,7 +31,7 @@ public BenchmarkServiceState(BenchmarkSettings settings, Object... services) { @Override public void beforeAll() { seed = - Microservices.builder() + ScaleCube.builder() .metrics(registry()) .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) @@ -40,7 +40,7 @@ public void beforeAll() { final Address seedAddress = seed.discovery().address(); node = - Microservices.builder() + ScaleCube.builder() .metrics(registry()) .discovery( endpoint -> @@ -66,7 +66,7 @@ public void afterAll() { } } - public Microservices seed() { + public ScaleCube seed() { return seed; } diff --git a/services-examples-parent/services-examples-runner/src/main/java/io/scalecube/services/examples/ExamplesRunner.java b/services-examples-parent/services-examples-runner/src/main/java/io/scalecube/services/examples/ExamplesRunner.java index 631e505fe..a5d7c3da9 100644 --- a/services-examples-parent/services-examples-runner/src/main/java/io/scalecube/services/examples/ExamplesRunner.java +++ b/services-examples-parent/services-examples-runner/src/main/java/io/scalecube/services/examples/ExamplesRunner.java @@ -7,7 +7,7 @@ import io.scalecube.config.source.SystemEnvironmentConfigSource; import io.scalecube.config.source.SystemPropertiesConfigSource; import io.scalecube.net.Address; -import io.scalecube.services.Microservices; +import io.scalecube.services.ScaleCube; import io.scalecube.services.ServiceEndpoint; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.discovery.api.ServiceDiscovery; @@ -51,7 +51,7 @@ public static void main(String[] args) { .orElse(Runtime.getRuntime().availableProcessors()); LOGGER.info("Number of worker threads: " + numOfThreads); - Microservices.builder() + ScaleCube.builder() .discovery(endpoint -> serviceDiscovery(endpoint, config)) .transport( () -> diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/exceptions/ExceptionMapperExample.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/exceptions/ExceptionMapperExample.java index bafd07b87..6487fc40d 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/exceptions/ExceptionMapperExample.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/exceptions/ExceptionMapperExample.java @@ -1,7 +1,7 @@ package io.scalecube.services.examples.exceptions; import io.scalecube.net.Address; -import io.scalecube.services.Microservices; +import io.scalecube.services.ScaleCube; import io.scalecube.services.ServiceInfo; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.transport.rsocket.RSocketServiceTransport; @@ -16,8 +16,8 @@ public class ExceptionMapperExample { * @throws InterruptedException exception. */ public static void main(String[] args) throws InterruptedException { - Microservices ms1 = - Microservices.builder() + ScaleCube ms1 = + ScaleCube.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) .defaultErrorMapper(new ServiceAProviderErrorMapper()) // default mapper for whole node @@ -31,8 +31,8 @@ public static void main(String[] args) throws InterruptedException { final Address address1 = ms1.discovery().address(); - Microservices ms2 = - Microservices.builder() + ScaleCube ms2 = + ScaleCube.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example1.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example1.java index 1ca40f956..403c05922 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example1.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example1.java @@ -1,7 +1,7 @@ package io.scalecube.services.examples.helloworld; import io.scalecube.net.Address; -import io.scalecube.services.Microservices; +import io.scalecube.services.ScaleCube; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.examples.helloworld.service.GreetingServiceImpl; import io.scalecube.services.examples.helloworld.service.api.GreetingsService; @@ -24,8 +24,8 @@ public class Example1 { */ public static void main(String[] args) { // ScaleCube Node node with no members - Microservices seed = - Microservices.builder() + ScaleCube seed = + ScaleCube.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) .startAwait(); @@ -33,8 +33,8 @@ public static void main(String[] args) { final Address seedAddress = seed.discovery().address(); // Construct a ScaleCube node which joins the cluster hosting the Greeting Service - Microservices ms = - Microservices.builder() + ScaleCube ms = + ScaleCube.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example2.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example2.java index fc20274db..b4944fc2f 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example2.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example2.java @@ -1,7 +1,7 @@ package io.scalecube.services.examples.helloworld; import io.scalecube.net.Address; -import io.scalecube.services.Microservices; +import io.scalecube.services.ScaleCube; import io.scalecube.services.ServiceCall; import io.scalecube.services.api.ServiceMessage; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; @@ -32,8 +32,8 @@ public class Example2 { */ public static void main(String[] args) { // ScaleCube Node node with no members - Microservices seed = - Microservices.builder() + ScaleCube seed = + ScaleCube.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) .startAwait(); @@ -41,8 +41,8 @@ public static void main(String[] args) { // Construct a ScaleCube node which joins the cluster hosting the Greeting Service final Address seedAddress = seed.discovery().address(); - Microservices ms = - Microservices.builder() + ScaleCube ms = + ScaleCube.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example3.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example3.java index 8891ffa1e..cacffaf7a 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example3.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example3.java @@ -1,7 +1,7 @@ package io.scalecube.services.examples.helloworld; import io.scalecube.net.Address; -import io.scalecube.services.Microservices; +import io.scalecube.services.ScaleCube; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.examples.helloworld.service.BidiGreetingImpl; import io.scalecube.services.examples.helloworld.service.api.BidiGreetingService; @@ -25,8 +25,8 @@ public class Example3 { */ public static void main(String[] args) { // ScaleCube Node node with no members - Microservices seed = - Microservices.builder() + ScaleCube seed = + ScaleCube.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) .startAwait(); @@ -34,8 +34,8 @@ public static void main(String[] args) { final Address seedAddress = seed.discovery().address(); // Construct a ScaleCube node which joins the cluster hosting the Greeting Service - Microservices ms = - Microservices.builder() + ScaleCube ms = + ScaleCube.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/orderbook/Example1.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/orderbook/Example1.java index b2bd1b737..a57a3d39f 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/orderbook/Example1.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/orderbook/Example1.java @@ -1,7 +1,7 @@ package io.scalecube.services.examples.orderbook; import io.scalecube.net.Address; -import io.scalecube.services.Microservices; +import io.scalecube.services.ScaleCube; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.examples.orderbook.service.DefaultMarketDataService; import io.scalecube.services.examples.orderbook.service.OrderBookSnapshoot; @@ -32,16 +32,16 @@ public class Example1 { */ public static void main(String[] args) throws InterruptedException { - Microservices gateway = - Microservices.builder() + ScaleCube gateway = + ScaleCube.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) .startAwait(); final Address gatewayAddress = gateway.discovery().address(); - Microservices ms = - Microservices.builder() + ScaleCube ms = + ScaleCube.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example1.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example1.java index b6b039151..c0d3f2480 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example1.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example1.java @@ -1,7 +1,7 @@ package io.scalecube.services.examples.services; import io.scalecube.net.Address; -import io.scalecube.services.Microservices; +import io.scalecube.services.ScaleCube; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.transport.rsocket.RSocketServiceTransport; import reactor.core.publisher.Mono; @@ -15,16 +15,16 @@ public class Example1 { * @param args - program arguments */ public static void main(String[] args) { - Microservices gateway = - Microservices.builder() + ScaleCube gateway = + ScaleCube.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) .startAwait(); final Address gatewayAddress = gateway.discovery().address(); - Microservices service2Node = - Microservices.builder() + ScaleCube service2Node = + ScaleCube.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) @@ -33,8 +33,8 @@ public static void main(String[] args) { .services(new Service2Impl()) .startAwait(); - Microservices service1Node = - Microservices.builder() + ScaleCube service1Node = + ScaleCube.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example2.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example2.java index a5c528d20..a9769c862 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example2.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example2.java @@ -1,7 +1,7 @@ package io.scalecube.services.examples.services; import io.scalecube.net.Address; -import io.scalecube.services.Microservices; +import io.scalecube.services.ScaleCube; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.transport.rsocket.RSocketServiceTransport; import reactor.core.publisher.Mono; @@ -15,16 +15,16 @@ public class Example2 { * @param args - program arguments */ public static void main(String[] args) { - Microservices gateway = - Microservices.builder() + ScaleCube gateway = + ScaleCube.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) .startAwait(); final Address gatewayAddress = gateway.discovery().address(); - Microservices service2Node = - Microservices.builder() + ScaleCube service2Node = + ScaleCube.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) @@ -33,8 +33,8 @@ public static void main(String[] args) { .services(new Service2Impl()) .startAwait(); - Microservices service1Node = - Microservices.builder() + ScaleCube service1Node = + ScaleCube.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) diff --git a/services/src/main/java/io/scalecube/services/Injector.java b/services/src/main/java/io/scalecube/services/Injector.java index c7433dbfe..892167bd7 100644 --- a/services/src/main/java/io/scalecube/services/Injector.java +++ b/services/src/main/java/io/scalecube/services/Injector.java @@ -26,7 +26,7 @@ private Injector() { * @param services services set * @return microservices instance */ - public static Microservices inject(Microservices microservices, Collection services) { + public static ScaleCube inject(ScaleCube microservices, Collection services) { services.forEach( service -> Arrays.stream(service.getClass().getDeclaredFields()) @@ -35,8 +35,8 @@ public static Microservices inject(Microservices microservices, Collection void processMethodWithAnnotation( - Microservices microservices, Object targetInstance, Class annotation) { + ScaleCube microservices, Object targetInstance, Class annotation) { Method[] declaredMethods = targetInstance.getClass().getDeclaredMethods(); Arrays.stream(declaredMethods) .filter(method -> method.isAnnotationPresent(annotation)) @@ -80,7 +80,7 @@ private static void processMethodWithAnnotation( Arrays.stream(targetMethod.getParameters()) .map( mapper -> { - if (mapper.getType().equals(Microservices.class)) { + if (mapper.getType().equals(ScaleCube.class)) { return microservices; } else if (Reflect.isService(mapper.getType())) { return microservices.call().api(mapper.getType()); diff --git a/services/src/main/java/io/scalecube/services/Microservices.java b/services/src/main/java/io/scalecube/services/ScaleCube.java similarity index 96% rename from services/src/main/java/io/scalecube/services/Microservices.java rename to services/src/main/java/io/scalecube/services/ScaleCube.java index 221841161..cff383c68 100644 --- a/services/src/main/java/io/scalecube/services/Microservices.java +++ b/services/src/main/java/io/scalecube/services/ScaleCube.java @@ -114,9 +114,9 @@ * * } */ -public final class Microservices implements IMicroservices { +public final class ScaleCube implements Microservices { - public static final Logger LOGGER = LoggerFactory.getLogger(Microservices.class); + public static final Logger LOGGER = LoggerFactory.getLogger(ScaleCube.class); private final String id = generateId(); private final Metrics metrics; @@ -133,7 +133,7 @@ public final class Microservices implements IMicroservices { private final MonoProcessor shutdown = MonoProcessor.create(); private final MonoProcessor onShutdown = MonoProcessor.create(); - private Microservices(Builder builder) { + private ScaleCube(Builder builder) { this.metrics = builder.metrics; this.tags = new HashMap<>(builder.tags); this.serviceProviders = new ArrayList<>(builder.serviceProviders); @@ -171,7 +171,7 @@ public String toString() { return "Microservices@" + id; } - private Mono start() { + private Mono start() { LOGGER.info("[{}][start] Starting", id); // Create bootstrap scheduler @@ -222,7 +222,7 @@ private Mono start() { .onErrorResume( ex -> { // return original error then shutdown - return Mono.whenDelayError(Mono.error(ex), shutdown()).cast(Microservices.class); + return Mono.whenDelayError(Mono.error(ex), shutdown()).cast(ScaleCube.class); }) .doOnSuccess(m -> listenJvmShutdown()) .doOnSuccess(m -> LOGGER.info("[{}][start] Started", id)) @@ -339,11 +339,11 @@ public static final class Builder { Optional.ofNullable(ServiceMessageDataDecoder.INSTANCE) .orElse((message, dataType) -> message); - public Mono start() { - return Mono.defer(() -> new Microservices(this).start()); + public Mono start() { + return Mono.defer(() -> new ScaleCube(this).start()); } - public Microservices startAwait() { + public ScaleCube startAwait() { return start().block(); } @@ -450,7 +450,7 @@ private Mono createInstance(ServiceEndpoint serviceEndpoint) { : Mono.defer(() -> Mono.just(discovery = factory.apply(serviceEndpoint))); } - private Mono startListen(Microservices microservices) { + private Mono startListen(ScaleCube microservices) { return Mono.defer( () -> { if (discovery == null) { @@ -483,7 +483,7 @@ private Mono startListen(Microservices microservices) { }); } - private void onDiscoveryEvent(Microservices microservices, ServiceDiscoveryEvent event) { + private void onDiscoveryEvent(ScaleCube microservices, ServiceDiscoveryEvent event) { if (event.isEndpointAdded()) { microservices.serviceRegistry.registerService(event.serviceEndpoint()); } @@ -513,7 +513,7 @@ private GatewayBootstrap addFactory(Function factory) { return this; } - private Mono start(Microservices microservices, GatewayOptions options) { + private Mono start(ScaleCube microservices, GatewayOptions options) { return Flux.fromIterable(factories) .flatMap( factory -> { @@ -582,7 +582,7 @@ public ServiceTransportBootstrap(Supplier supplier) { this.supplier = supplier; } - private Mono start(Microservices microservices) { + private Mono start(ScaleCube microservices) { if (supplier == NULL_SUPPLIER || (serviceTransport = supplier.get()) == null) { LOGGER.info("[{}] ServiceTransport not set", microservices.id()); return Mono.just(NULL_INSTANCE); @@ -647,9 +647,9 @@ public interface MonitorMBean { private static class JmxMonitorMBean implements MonitorMBean { - private final Microservices microservices; + private final ScaleCube microservices; - private static JmxMonitorMBean start(Microservices instance) throws Exception { + private static JmxMonitorMBean start(ScaleCube instance) throws Exception { MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer(); JmxMonitorMBean jmxMBean = new JmxMonitorMBean(instance); ObjectName objectName = new ObjectName("io.scalecube.services:name=" + instance.toString()); @@ -658,7 +658,7 @@ private static JmxMonitorMBean start(Microservices instance) throws Exception { return jmxMBean; } - private JmxMonitorMBean(Microservices microservices) { + private JmxMonitorMBean(ScaleCube microservices) { this.microservices = microservices; } diff --git a/services/src/test/java/io/scalecube/services/ErrorFlowTest.java b/services/src/test/java/io/scalecube/services/ErrorFlowTest.java index bd6f56ef0..20ac3bfef 100644 --- a/services/src/test/java/io/scalecube/services/ErrorFlowTest.java +++ b/services/src/test/java/io/scalecube/services/ErrorFlowTest.java @@ -23,13 +23,13 @@ public class ErrorFlowTest extends BaseTest { private static AtomicInteger port = new AtomicInteger(4000); - private static Microservices provider; - private static Microservices consumer; + private static ScaleCube provider; + private static ScaleCube consumer; @BeforeAll public static void initNodes() { provider = - Microservices.builder() + ScaleCube.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) @@ -41,7 +41,7 @@ public static void initNodes() { final Address seedAddress = provider.discovery().address(); consumer = - Microservices.builder() + ScaleCube.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) diff --git a/services/src/test/java/io/scalecube/services/ServiceAuthLocalTest.java b/services/src/test/java/io/scalecube/services/ServiceAuthLocalTest.java index 40605d399..e07b4928f 100644 --- a/services/src/test/java/io/scalecube/services/ServiceAuthLocalTest.java +++ b/services/src/test/java/io/scalecube/services/ServiceAuthLocalTest.java @@ -45,7 +45,7 @@ final class ServiceAuthLocalTest extends BaseTest { return Mono.error(new UnauthorizedException("Authentication failed")); }; - private Microservices service; + private ScaleCube service; @BeforeAll static void beforeAll() { @@ -63,7 +63,7 @@ void afterEach() { @DisplayName("Successful authentication") void successfulAuthentication() { service = - Microservices.builder() + ScaleCube.builder() .authenticator(authenticator) .services(new SecuredServiceImpl()) .startAwait(); @@ -87,7 +87,7 @@ void successfulAuthentication() { @Test @DisplayName("Authentication failed if authenticator not provided") void failedAuthenticationWhenAuthenticatorNotProvided() { - service = Microservices.builder().services(new SecuredServiceImpl()).startAwait(); + service = ScaleCube.builder().services(new SecuredServiceImpl()).startAwait(); SecuredService securedService = service.call().credentials(CREDENTIALS).api(SecuredService.class); @@ -115,7 +115,7 @@ void failedAuthenticationWhenAuthenticatorNotProvided() { @DisplayName("Authentication failed with invalid or empty credentials") void failedAuthenticationWithInvalidOrEmptyCredentials() { service = - Microservices.builder() + ScaleCube.builder() .authenticator(authenticator) .services(new SecuredServiceImpl()) .startAwait(); @@ -145,7 +145,7 @@ void failedAuthenticationWithInvalidOrEmptyCredentials() { @DisplayName("Successful authentication of partially secured service") void successfulAuthenticationOnPartiallySecuredService() { service = - Microservices.builder() + ScaleCube.builder() .authenticator(authenticator) .services(new PartiallySecuredServiceImpl()) .startAwait(); @@ -161,7 +161,7 @@ void successfulAuthenticationOnPartiallySecuredService() { @Test @DisplayName("Successful call public method of partially secured service without authentication") void successfulCallOfPublicMethodWithoutAuthentication() { - service = Microservices.builder().services(new PartiallySecuredServiceImpl()).startAwait(); + service = ScaleCube.builder().services(new PartiallySecuredServiceImpl()).startAwait(); PartiallySecuredService proxy = service.call().api(PartiallySecuredService.class); diff --git a/services/src/test/java/io/scalecube/services/ServiceAuthRemoteTest.java b/services/src/test/java/io/scalecube/services/ServiceAuthRemoteTest.java index 78fb41d7f..fb8145152 100644 --- a/services/src/test/java/io/scalecube/services/ServiceAuthRemoteTest.java +++ b/services/src/test/java/io/scalecube/services/ServiceAuthRemoteTest.java @@ -48,21 +48,21 @@ final class ServiceAuthRemoteTest { return Mono.error(new UnauthorizedException("Authentication failed")); }; - private static Microservices caller; - private static Microservices service; + private static ScaleCube caller; + private static ScaleCube service; @BeforeAll static void beforeAll() { StepVerifier.setDefaultTimeout(TIMEOUT); caller = - Microservices.builder() + ScaleCube.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) .startAwait(); service = - Microservices.builder() + ScaleCube.builder() .discovery(ServiceAuthRemoteTest::serviceDiscovery) .transport(RSocketServiceTransport::new) .authenticator(authenticator) @@ -103,8 +103,8 @@ void successfulAuthentication() { @Test @DisplayName("Authentication failed if authenticator not provided") void failedAuthenticationWhenAuthenticatorNotProvided() { - Microservices service = - Microservices.builder() + ScaleCube service = + ScaleCube.builder() .discovery(ServiceAuthRemoteTest::serviceDiscovery) .transport(RSocketServiceTransport::new) .services(new SecuredServiceImpl()) @@ -161,8 +161,8 @@ void failedAuthenticationWithInvalidOrEmptyCredentials() { @Test @DisplayName("Successful authentication of partially secured service") void successfulAuthenticationOnPartiallySecuredService() { - Microservices service = - Microservices.builder() + ScaleCube service = + ScaleCube.builder() .discovery(ServiceAuthRemoteTest::serviceDiscovery) .transport(RSocketServiceTransport::new) .authenticator(authenticator) @@ -182,8 +182,8 @@ void successfulAuthenticationOnPartiallySecuredService() { @Test @DisplayName("Successful call public method of partially secured service without authentication") void successfulCallOfPublicMethodWithoutAuthentication() { - Microservices service = - Microservices.builder() + ScaleCube service = + ScaleCube.builder() .discovery(ServiceAuthRemoteTest::serviceDiscovery) .transport(RSocketServiceTransport::new) .services(new PartiallySecuredServiceImpl()) diff --git a/services/src/test/java/io/scalecube/services/ServiceCallLocalTest.java b/services/src/test/java/io/scalecube/services/ServiceCallLocalTest.java index e39bfda6a..0ecc79c57 100644 --- a/services/src/test/java/io/scalecube/services/ServiceCallLocalTest.java +++ b/services/src/test/java/io/scalecube/services/ServiceCallLocalTest.java @@ -37,7 +37,7 @@ public class ServiceCallLocalTest extends BaseTest { public static final int TIMEOUT = 3; private Duration timeout = Duration.ofSeconds(TIMEOUT); - private static Microservices provider; + private static ScaleCube provider; @BeforeAll public static void setup() { @@ -63,8 +63,8 @@ public void test_local_async_no_params() { GREETING_NO_PARAMS_REQUEST.qualifier(), message.qualifier(), "Didn't get desired response"); } - private static Microservices serviceProvider() { - return Microservices.builder() + private static ScaleCube serviceProvider() { + return ScaleCube.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) .services(new GreetingServiceImpl()) diff --git a/services/src/test/java/io/scalecube/services/ServiceCallRemoteTest.java b/services/src/test/java/io/scalecube/services/ServiceCallRemoteTest.java index 4143c90db..a1cae8148 100644 --- a/services/src/test/java/io/scalecube/services/ServiceCallRemoteTest.java +++ b/services/src/test/java/io/scalecube/services/ServiceCallRemoteTest.java @@ -40,8 +40,8 @@ public class ServiceCallRemoteTest extends BaseTest { public static final int TIMEOUT = 3; private Duration timeout = Duration.ofSeconds(TIMEOUT); - private static Microservices gateway; - private static Microservices provider; + private static ScaleCube gateway; + private static ScaleCube provider; @BeforeAll public static void setup() { @@ -64,8 +64,8 @@ public static void tearDown() { } } - private static Microservices serviceProvider(Object service) { - return Microservices.builder() + private static ScaleCube serviceProvider(Object service) { + return ScaleCube.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) @@ -226,7 +226,7 @@ public void test_service_address_lookup_occur_only_after_subscription() { // Add service to cluster AFTER creating a call object. // (prove address lookup occur only after subscription) - Microservices quotesService = serviceProvider(new SimpleQuoteService()); + ScaleCube quotesService = serviceProvider(new SimpleQuoteService()); StepVerifier.create(quotes.take(1)).expectNextCount(1).expectComplete().verify(timeout); @@ -255,8 +255,8 @@ public void test_many_stream_block_first() { } } - private static Microservices gateway() { - return Microservices.builder() + private static ScaleCube gateway() { + return ScaleCube.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) .startAwait(); diff --git a/services/src/test/java/io/scalecube/services/ServiceLifecycleAnnotationsTest.java b/services/src/test/java/io/scalecube/services/ServiceLifecycleAnnotationsTest.java index 0255e28d9..4155bf109 100644 --- a/services/src/test/java/io/scalecube/services/ServiceLifecycleAnnotationsTest.java +++ b/services/src/test/java/io/scalecube/services/ServiceLifecycleAnnotationsTest.java @@ -18,8 +18,8 @@ void testAfterConstructThenBeforeDestroy() throws Exception { final CountDownLatch afterConstruct = new CountDownLatch(1); final CountDownLatch beforeDestroy = new CountDownLatch(1); - Microservices microservices = - Microservices.builder() + ScaleCube microservices = + ScaleCube.builder() .services( ServiceInfo.fromServiceInstance( new TestService() { @@ -55,7 +55,7 @@ void testAfterConstructFailsThenBeforeDestroy() throws Exception { Assertions.assertThrows( Exception.class, () -> - Microservices.builder() + ScaleCube.builder() .services( ServiceInfo.fromServiceInstance( new TestService() { diff --git a/services/src/test/java/io/scalecube/services/ServiceLocalTest.java b/services/src/test/java/io/scalecube/services/ServiceLocalTest.java index 16c62d3f2..7a212acc2 100644 --- a/services/src/test/java/io/scalecube/services/ServiceLocalTest.java +++ b/services/src/test/java/io/scalecube/services/ServiceLocalTest.java @@ -23,11 +23,11 @@ public class ServiceLocalTest extends BaseTest { private static final Duration timeout = Duration.ofSeconds(3); - private Microservices microservices; + private ScaleCube microservices; @BeforeEach public void setUp() { - microservices = Microservices.builder().services(new GreetingServiceImpl()).startAwait(); + microservices = ScaleCube.builder().services(new GreetingServiceImpl()).startAwait(); } @AfterEach @@ -304,7 +304,7 @@ public void test_local_bidi_greeting_expect_GreetingResponse() { .verify(Duration.ofSeconds(3)); } - private GreetingService createProxy(Microservices gateway) { + private GreetingService createProxy(ScaleCube gateway) { return gateway.call().api(GreetingService.class); // create proxy for GreetingService API } } diff --git a/services/src/test/java/io/scalecube/services/ServiceRegistryTest.java b/services/src/test/java/io/scalecube/services/ServiceRegistryTest.java index a064b556f..9c4106c2d 100644 --- a/services/src/test/java/io/scalecube/services/ServiceRegistryTest.java +++ b/services/src/test/java/io/scalecube/services/ServiceRegistryTest.java @@ -47,8 +47,8 @@ public void test_added_removed_registration_events(MetadataCodec metadataCodec) List events = new ArrayList<>(); - Microservices seed = - Microservices.builder() + ScaleCube seed = + ScaleCube.builder() .discovery(defServiceDiscovery(metadataCodec)) .transport(RSocketServiceTransport::new) .startAwait(); @@ -57,15 +57,15 @@ public void test_added_removed_registration_events(MetadataCodec metadataCodec) Address seedAddress = seed.discovery().address(); - Microservices ms1 = - Microservices.builder() + ScaleCube ms1 = + ScaleCube.builder() .discovery(defServiceDiscovery(seedAddress, metadataCodec)) .transport(RSocketServiceTransport::new) .services(new GreetingServiceImpl()) .startAwait(); - Microservices ms2 = - Microservices.builder() + ScaleCube ms2 = + ScaleCube.builder() .discovery(defServiceDiscovery(seedAddress, metadataCodec)) .transport(RSocketServiceTransport::new) .services(new GreetingServiceImpl()) @@ -89,10 +89,10 @@ public void test_added_removed_registration_events(MetadataCodec metadataCodec) public void test_listen_to_discovery_events(MetadataCodec metadataCodec) { ReplayProcessor processor = ReplayProcessor.create(); - List cluster = new CopyOnWriteArrayList<>(); + List cluster = new CopyOnWriteArrayList<>(); - Microservices seed = - Microservices.builder() + ScaleCube seed = + ScaleCube.builder() .discovery(defServiceDiscovery(metadataCodec)) .transport(RSocketServiceTransport::new) .services(new AnnotationServiceImpl()) @@ -106,8 +106,8 @@ public void test_listen_to_discovery_events(MetadataCodec metadataCodec) { StepVerifier.create(processor) .then( () -> { - Microservices ms1 = - Microservices.builder() + ScaleCube ms1 = + ScaleCube.builder() .discovery(defServiceDiscovery(seedAddress, metadataCodec)) .transport(RSocketServiceTransport::new) .services(new GreetingServiceImpl()) @@ -117,8 +117,8 @@ public void test_listen_to_discovery_events(MetadataCodec metadataCodec) { .assertNext(event -> assertEquals(ENDPOINT_ADDED, event.type())) .then( () -> { - Microservices ms2 = - Microservices.builder() + ScaleCube ms2 = + ScaleCube.builder() .discovery(defServiceDiscovery(seedAddress, metadataCodec)) .transport(RSocketServiceTransport::new) .services(new GreetingServiceImpl()) @@ -147,7 +147,7 @@ public void test_listen_to_discovery_events(MetadataCodec metadataCodec) { .thenCancel() .verify(TIMEOUT); - Mono.when(cluster.stream().map(Microservices::shutdown).toArray(Mono[]::new)) + Mono.when(cluster.stream().map(ScaleCube::shutdown).toArray(Mono[]::new)) .then(Mono.delay(TIMEOUT)) .block(); } @@ -157,10 +157,10 @@ public void test_listen_to_discovery_events(MetadataCodec metadataCodec) { public void test_delayed_listen_to_discovery_events(MetadataCodec metadataCodec) { ReplayProcessor processor = ReplayProcessor.create(); - List cluster = new CopyOnWriteArrayList<>(); + List cluster = new CopyOnWriteArrayList<>(); - Microservices seed = - Microservices.builder() + ScaleCube seed = + ScaleCube.builder() .discovery(defServiceDiscovery(metadataCodec)) .transport(RSocketServiceTransport::new) .services(new GreetingServiceImpl()) @@ -174,8 +174,8 @@ public void test_delayed_listen_to_discovery_events(MetadataCodec metadataCodec) StepVerifier.create(processor) .then( () -> { - Microservices ms1 = - Microservices.builder() + ScaleCube ms1 = + ScaleCube.builder() .discovery(defServiceDiscovery(seedAddress, metadataCodec)) .transport(RSocketServiceTransport::new) .services(new GreetingServiceImpl(), new AnnotationServiceImpl()) @@ -185,8 +185,8 @@ public void test_delayed_listen_to_discovery_events(MetadataCodec metadataCodec) .assertNext(event -> assertEquals(ENDPOINT_ADDED, event.type())) .then( () -> { - Microservices ms2 = - Microservices.builder() + ScaleCube ms2 = + ScaleCube.builder() .discovery(defServiceDiscovery(seedAddress, metadataCodec)) .transport(RSocketServiceTransport::new) .services(new GreetingServiceImpl()) @@ -203,7 +203,7 @@ public void test_delayed_listen_to_discovery_events(MetadataCodec metadataCodec) .thenCancel() .verify(TIMEOUT); - Mono.when(cluster.stream().map(Microservices::shutdown).toArray(Mono[]::new)) + Mono.when(cluster.stream().map(ScaleCube::shutdown).toArray(Mono[]::new)) .then(Mono.delay(TIMEOUT)) .block(); } diff --git a/services/src/test/java/io/scalecube/services/ServiceRemoteTest.java b/services/src/test/java/io/scalecube/services/ServiceRemoteTest.java index 03ddfb7ca..a90c4c4f7 100644 --- a/services/src/test/java/io/scalecube/services/ServiceRemoteTest.java +++ b/services/src/test/java/io/scalecube/services/ServiceRemoteTest.java @@ -36,8 +36,8 @@ public class ServiceRemoteTest extends BaseTest { private static final Duration TIMEOUT = Duration.ofSeconds(10); public static final Duration TIMEOUT2 = Duration.ofSeconds(6); - private static Microservices gateway; - private static Microservices provider; + private static ScaleCube gateway; + private static ScaleCube provider; @BeforeAll public static void setup() { @@ -61,15 +61,15 @@ public static void tearDown() { } } - private static Microservices gateway() { - return Microservices.builder() + private static ScaleCube gateway() { + return ScaleCube.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) .startAwait(); } - private static Microservices serviceProvider() { - return Microservices.builder() + private static ScaleCube serviceProvider() { + return ScaleCube.builder() .discovery(ServiceRemoteTest::serviceDiscovery) .transport(RSocketServiceTransport::new) .services(new GreetingServiceImpl()) @@ -264,8 +264,8 @@ public void test_remote_serviceA_calls_serviceB_using_setter() { // Create microservices instance cluster. // noinspection unused - Microservices provider = - Microservices.builder() + ScaleCube provider = + ScaleCube.builder() .discovery(ServiceRemoteTest::serviceDiscovery) .transport(RSocketServiceTransport::new) .services(new CoarseGrainedServiceImpl()) // add service a and b @@ -287,8 +287,8 @@ public void test_remote_serviceA_calls_serviceB() { // Create microservices instance cluster. // noinspection unused - Microservices provider = - Microservices.builder() + ScaleCube provider = + ScaleCube.builder() .discovery(ServiceRemoteTest::serviceDiscovery) .transport(RSocketServiceTransport::new) .services(another) @@ -307,8 +307,8 @@ public void test_remote_serviceA_calls_serviceB_with_timeout() { CoarseGrainedServiceImpl another = new CoarseGrainedServiceImpl(); // Create microservices instance cluster. - Microservices ms = - Microservices.builder() + ScaleCube ms = + ScaleCube.builder() .discovery(ServiceRemoteTest::serviceDiscovery) .transport(RSocketServiceTransport::new) .services(another) // add service a and b @@ -332,8 +332,8 @@ public void test_remote_serviceA_calls_serviceB_with_dispatcher() { CoarseGrainedServiceImpl another = new CoarseGrainedServiceImpl(); // Create microservices instance cluster. - Microservices provider = - Microservices.builder() + ScaleCube provider = + ScaleCube.builder() .discovery(ServiceRemoteTest::serviceDiscovery) .transport(RSocketServiceTransport::new) .services(another) // add service a and b @@ -416,8 +416,8 @@ public void test_services_contribute_to_cluster_metadata() { Map tags = new HashMap<>(); tags.put("HOSTNAME", "host1"); - Microservices ms = - Microservices.builder() + ScaleCube ms = + ScaleCube.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) .tags(tags) diff --git a/services/src/test/java/io/scalecube/services/StreamingServiceTest.java b/services/src/test/java/io/scalecube/services/StreamingServiceTest.java index db4c56a8b..941080a7e 100644 --- a/services/src/test/java/io/scalecube/services/StreamingServiceTest.java +++ b/services/src/test/java/io/scalecube/services/StreamingServiceTest.java @@ -21,20 +21,20 @@ public class StreamingServiceTest extends BaseTest { - private static Microservices gateway; - private static Microservices node; + private static ScaleCube gateway; + private static ScaleCube node; @BeforeAll public static void setup() { gateway = - Microservices.builder() + ScaleCube.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) .defaultDataDecoder(ServiceMessageCodec::decodeData) .startAwait(); node = - Microservices.builder() + ScaleCube.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) diff --git a/services/src/test/java/io/scalecube/services/routings/RoutersTest.java b/services/src/test/java/io/scalecube/services/routings/RoutersTest.java index 8e588e62c..5e714a54b 100644 --- a/services/src/test/java/io/scalecube/services/routings/RoutersTest.java +++ b/services/src/test/java/io/scalecube/services/routings/RoutersTest.java @@ -11,7 +11,7 @@ import io.scalecube.net.Address; import io.scalecube.services.BaseTest; -import io.scalecube.services.Microservices; +import io.scalecube.services.ScaleCube; import io.scalecube.services.Reflect; import io.scalecube.services.ServiceCall; import io.scalecube.services.ServiceInfo; @@ -47,16 +47,16 @@ public class RoutersTest extends BaseTest { public static final int TIMEOUT = 10; private Duration timeout = Duration.ofSeconds(TIMEOUT); - private static Microservices gateway; + private static ScaleCube gateway; private static Address gatewayAddress; - private static Microservices provider1; - private static Microservices provider2; - private static Microservices provider3; + private static ScaleCube provider1; + private static ScaleCube provider2; + private static ScaleCube provider3; @BeforeAll public static void setup() { gateway = - Microservices.builder() // + ScaleCube.builder() // .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) .startAwait(); @@ -65,7 +65,7 @@ public static void setup() { // Create microservices instance cluster. provider1 = - Microservices.builder() + ScaleCube.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) @@ -83,7 +83,7 @@ public static void setup() { // Create microservices instance cluster. provider2 = - Microservices.builder() + ScaleCube.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) @@ -101,7 +101,7 @@ public static void setup() { TagService tagService = input -> input.map(String::toUpperCase); provider3 = - Microservices.builder() + ScaleCube.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) diff --git a/services/src/test/java/io/scalecube/services/routings/ServiceTagsExample.java b/services/src/test/java/io/scalecube/services/routings/ServiceTagsExample.java index 1151880c8..eb92945ad 100644 --- a/services/src/test/java/io/scalecube/services/routings/ServiceTagsExample.java +++ b/services/src/test/java/io/scalecube/services/routings/ServiceTagsExample.java @@ -1,7 +1,7 @@ package io.scalecube.services.routings; import io.scalecube.net.Address; -import io.scalecube.services.Microservices; +import io.scalecube.services.ScaleCube; import io.scalecube.services.ServiceInfo; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.routings.sut.CanaryService; @@ -20,16 +20,16 @@ public class ServiceTagsExample { * @param args arguments */ public static void main(String[] args) { - Microservices gateway = - Microservices.builder() + ScaleCube gateway = + ScaleCube.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) .startAwait(); Address seedAddress = gateway.discovery().address(); - Microservices services1 = - Microservices.builder() + ScaleCube services1 = + ScaleCube.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) @@ -41,8 +41,8 @@ public static void main(String[] args) { .build()) .startAwait(); - Microservices services2 = - Microservices.builder() + ScaleCube services2 = + ScaleCube.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) diff --git a/services/src/test/java/io/scalecube/services/sut/AnnotationServiceImpl.java b/services/src/test/java/io/scalecube/services/sut/AnnotationServiceImpl.java index 3beee526f..5186d4539 100644 --- a/services/src/test/java/io/scalecube/services/sut/AnnotationServiceImpl.java +++ b/services/src/test/java/io/scalecube/services/sut/AnnotationServiceImpl.java @@ -1,6 +1,6 @@ package io.scalecube.services.sut; -import io.scalecube.services.Microservices; +import io.scalecube.services.ScaleCube; import io.scalecube.services.annotations.AfterConstruct; import io.scalecube.services.discovery.api.ServiceDiscoveryEvent; import reactor.core.publisher.Flux; @@ -11,7 +11,7 @@ public class AnnotationServiceImpl implements AnnotationService { private ReplayProcessor serviceDiscoveryEvents; @AfterConstruct - void init(Microservices microservices) { + void init(ScaleCube microservices) { this.serviceDiscoveryEvents = ReplayProcessor.create(); microservices.discovery().listenDiscovery().subscribe(serviceDiscoveryEvents); } diff --git a/services/src/test/java/io/scalecube/services/sut/CoarseGrainedServiceImpl.java b/services/src/test/java/io/scalecube/services/sut/CoarseGrainedServiceImpl.java index be297b306..d697695e6 100644 --- a/services/src/test/java/io/scalecube/services/sut/CoarseGrainedServiceImpl.java +++ b/services/src/test/java/io/scalecube/services/sut/CoarseGrainedServiceImpl.java @@ -1,6 +1,6 @@ package io.scalecube.services.sut; -import io.scalecube.services.Microservices; +import io.scalecube.services.ScaleCube; import io.scalecube.services.annotations.Inject; import io.scalecube.services.api.ServiceMessage; import java.time.Duration; @@ -12,7 +12,7 @@ public class CoarseGrainedServiceImpl implements CoarseGrainedService { @Inject private GreetingService greetingService; - @Inject private Microservices microservices; + @Inject private ScaleCube microservices; @Override public Mono callGreeting(String name) { diff --git a/services/src/test/java/io/scalecube/services/sut/GreetingServiceImpl.java b/services/src/test/java/io/scalecube/services/sut/GreetingServiceImpl.java index 01c87f7fc..76fe63e8c 100644 --- a/services/src/test/java/io/scalecube/services/sut/GreetingServiceImpl.java +++ b/services/src/test/java/io/scalecube/services/sut/GreetingServiceImpl.java @@ -1,6 +1,6 @@ package io.scalecube.services.sut; -import io.scalecube.services.Microservices; +import io.scalecube.services.ScaleCube; import io.scalecube.services.annotations.Inject; import io.scalecube.services.api.ServiceMessage; import io.scalecube.services.exceptions.UnauthorizedException; @@ -12,7 +12,8 @@ public final class GreetingServiceImpl implements GreetingService { - @Inject Microservices ms; + @Inject + ScaleCube ms; private int instanceId; diff --git a/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketNettyColocatedEventLoopGroupTest.java b/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketNettyColocatedEventLoopGroupTest.java index d333a1b93..ba64df20c 100644 --- a/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketNettyColocatedEventLoopGroupTest.java +++ b/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketNettyColocatedEventLoopGroupTest.java @@ -3,7 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import io.scalecube.services.BaseTest; -import io.scalecube.services.Microservices; +import io.scalecube.services.ScaleCube; import io.scalecube.services.ServiceCall; import io.scalecube.services.annotations.Inject; import io.scalecube.services.annotations.Service; @@ -19,20 +19,20 @@ public class RSocketNettyColocatedEventLoopGroupTest extends BaseTest { - private Microservices ping; - private Microservices pong; - private Microservices gateway; + private ScaleCube ping; + private ScaleCube pong; + private ScaleCube gateway; @BeforeEach public void setUp() { this.gateway = - Microservices.builder() + ScaleCube.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) .startAwait(); - Microservices facade = - Microservices.builder() + ScaleCube facade = + ScaleCube.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) @@ -42,7 +42,7 @@ public void setUp() { .startAwait(); this.ping = - Microservices.builder() + ScaleCube.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) @@ -52,7 +52,7 @@ public void setUp() { .startAwait(); this.pong = - Microservices.builder() + ScaleCube.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) @@ -80,9 +80,9 @@ public void testColocatedEventLoopGroup() { public void tearDown() { try { Mono.whenDelayError( - Optional.ofNullable(gateway).map(Microservices::shutdown).orElse(Mono.empty()), - Optional.ofNullable(ping).map(Microservices::shutdown).orElse(Mono.empty()), - Optional.ofNullable(pong).map(Microservices::shutdown).orElse(Mono.empty())) + Optional.ofNullable(gateway).map(ScaleCube::shutdown).orElse(Mono.empty()), + Optional.ofNullable(ping).map(ScaleCube::shutdown).orElse(Mono.empty()), + Optional.ofNullable(pong).map(ScaleCube::shutdown).orElse(Mono.empty())) .block(); } catch (Throwable ignore) { // no-op diff --git a/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketServiceTransportTest.java b/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketServiceTransportTest.java index ac042a89d..415e62151 100644 --- a/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketServiceTransportTest.java +++ b/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketServiceTransportTest.java @@ -4,7 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import io.scalecube.services.BaseTest; -import io.scalecube.services.Microservices; +import io.scalecube.services.ScaleCube; import io.scalecube.services.ServiceCall; import io.scalecube.services.api.ServiceMessage; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; @@ -32,19 +32,19 @@ public class RSocketServiceTransportTest extends BaseTest { private static final ServiceMessage ONLY_ONE_AND_THEN_NEVER = ServiceMessage.builder().qualifier(QuoteService.NAME, "onlyOneAndThenNever").build(); - private Microservices gateway; - private Microservices serviceNode; + private ScaleCube gateway; + private ScaleCube serviceNode; @BeforeEach public void setUp() { gateway = - Microservices.builder() + ScaleCube.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) .startAwait(); serviceNode = - Microservices.builder() + ScaleCube.builder() .discovery( serviceEndpoint -> new ScalecubeServiceDiscovery(serviceEndpoint) @@ -58,8 +58,8 @@ public void setUp() { public void cleanUp() { try { Mono.whenDelayError( - Optional.ofNullable(gateway).map(Microservices::shutdown).orElse(Mono.empty()), - Optional.ofNullable(serviceNode).map(Microservices::shutdown).orElse(Mono.empty())) + Optional.ofNullable(gateway).map(ScaleCube::shutdown).orElse(Mono.empty()), + Optional.ofNullable(serviceNode).map(ScaleCube::shutdown).orElse(Mono.empty())) .block(); } catch (Throwable ignore) { // no-op From 7d969cb0a2620c197e156fab777537439e47ea25 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=95=D0=B2=D0=B3=D0=B5=D0=BD=D0=B8=D0=B9=20=D0=A3=D1=82?= =?UTF-8?q?=D0=BA=D0=B8=D0=BD?= Date: Fri, 28 Feb 2020 14:07:42 +0300 Subject: [PATCH 07/61] ISSUE 708, WIP. Add spring extension experiment for example --- .../scalecube-examples-spring/pom.xml | 53 ++++++++++++ .../spring/SpringServicesProvider.java | 75 +++++++++++++++++ .../spring/SpringServicesProviderTest.java | 82 +++++++++++++++++++ .../java/io/scalecube/services/ScaleCube.java | 32 ++++---- 4 files changed, 224 insertions(+), 18 deletions(-) create mode 100644 services-examples-parent/scalecube-examples-spring/pom.xml create mode 100644 services-examples-parent/scalecube-examples-spring/src/main/java/io/scalecube/spring/SpringServicesProvider.java create mode 100644 services-examples-parent/scalecube-examples-spring/src/test/java/io/scalecube/spring/SpringServicesProviderTest.java diff --git a/services-examples-parent/scalecube-examples-spring/pom.xml b/services-examples-parent/scalecube-examples-spring/pom.xml new file mode 100644 index 000000000..9635b6378 --- /dev/null +++ b/services-examples-parent/scalecube-examples-spring/pom.xml @@ -0,0 +1,53 @@ + + + + scalecube-services-parent + io.scalecube + 2.8.10-SNAPSHOT + ../pom.xml + + 4.0.0 + + scalecube-examples-spring + + + + io.scalecube + scalecube-services + ${project.version} + + + io.scalecube + scalecube-services-discovery + ${project.version} + + + io.scalecube + scalecube-services-transport-rsocket + ${project.version} + + + io.scalecube + scalecube-services-transport-jackson + ${project.version} + + + org.springframework + spring-core + LATEST + + + org.springframework + spring-beans + LATEST + + + org.springframework + spring-context + LATEST + + + + \ No newline at end of file diff --git a/services-examples-parent/scalecube-examples-spring/src/main/java/io/scalecube/spring/SpringServicesProvider.java b/services-examples-parent/scalecube-examples-spring/src/main/java/io/scalecube/spring/SpringServicesProvider.java new file mode 100644 index 000000000..8885ddb13 --- /dev/null +++ b/services-examples-parent/scalecube-examples-spring/src/main/java/io/scalecube/spring/SpringServicesProvider.java @@ -0,0 +1,75 @@ +package io.scalecube.spring; + +import io.scalecube.services.Microservices; +import io.scalecube.services.ServiceCall; +import io.scalecube.services.ServiceInfo; +import io.scalecube.services.ServicesProvider; +import io.scalecube.services.annotations.Service; +import io.scalecube.services.annotations.ServiceMethod; +import io.scalecube.services.discovery.api.ServiceDiscovery; +import org.springframework.beans.factory.support.GenericBeanDefinition; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.support.GenericApplicationContext; +import reactor.core.publisher.Mono; + +import java.time.Duration; +import java.util.Collection; +import java.util.List; +import java.util.stream.Collectors; + +public class SpringServicesProvider implements ServicesProvider { + + @Override + public Mono> provide(Microservices microservices) { + GenericApplicationContext context = new GenericApplicationContext(); + context.registerBean(ServiceCall.class, microservices::call); + GenericBeanDefinition bd = new GenericBeanDefinition(); + bd.setBeanClass(Beans.class); + context.registerBeanDefinition("simple", bd); + context.refresh(); + context.start(); + + List beans = + context.getBeansWithAnnotation(Service.class).values().stream() + .map(bean -> ServiceInfo.fromServiceInstance(bean).build()) + .collect(Collectors.toList()); + return Mono.just(beans); + } + + @Configuration + static class Beans { + @Bean + public LocalService simpleBean(ServiceCall serviceCall) { + return new SimpleBean(serviceCall); + } + } + + @Service + public interface SimpleService { + + @ServiceMethod + Mono get(); + } + + @Service + public interface LocalService { + + @ServiceMethod + Monoget(); + } + + public static class SimpleBean implements LocalService { + + private final SimpleService serviceCall; + + public SimpleBean(ServiceCall serviceCall) { + this.serviceCall = serviceCall.api(SimpleService.class); + System.out.println( this.serviceCall.get().block(Duration.ofSeconds(1))); + } + + public Mono get() { + return serviceCall.get().map(n -> n * -1); + } + } +} diff --git a/services-examples-parent/scalecube-examples-spring/src/test/java/io/scalecube/spring/SpringServicesProviderTest.java b/services-examples-parent/scalecube-examples-spring/src/test/java/io/scalecube/spring/SpringServicesProviderTest.java new file mode 100644 index 000000000..41c7061a7 --- /dev/null +++ b/services-examples-parent/scalecube-examples-spring/src/test/java/io/scalecube/spring/SpringServicesProviderTest.java @@ -0,0 +1,82 @@ +package io.scalecube.spring; + +import io.scalecube.services.ScaleCube; +import io.scalecube.services.ServiceEndpoint; +import io.scalecube.services.discovery.ScalecubeServiceDiscovery; +import io.scalecube.services.discovery.api.ServiceDiscovery; +import io.scalecube.services.transport.rsocket.RSocketServiceTransport; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Hooks; +import reactor.core.publisher.Mono; + +import java.time.Duration; + +import static org.junit.jupiter.api.Assertions.*; + +class SpringServicesProviderTest { + + private static ScaleCube gateway; + private static ScaleCube provider; + + @BeforeAll + public static void setup() { + Hooks.onOperatorDebug(); + gateway = gateway(); + provider = serviceProvider(); + } + + @AfterAll + public static void tearDown() { + try { + gateway.shutdown().block(); + } catch (Exception ignore) { + // no-op + } + + try { + provider.shutdown().block(); + } catch (Exception ignore) { + // no-op + } + } + + private static ScaleCube gateway() { + return ScaleCube.builder() + .discovery(ScalecubeServiceDiscovery::new) + .transport(RSocketServiceTransport::new) + .services(new SpringServicesProvider()) + .startAwait(); + } + + private static ScaleCube serviceProvider() { + return ScaleCube.builder() + .discovery(SpringServicesProviderTest::serviceDiscovery) + .transport(RSocketServiceTransport::new) + .services(new SpringServicesProvider.SimpleService() { + @Override + public Mono get() { + return Mono.just(1L); + } + }) + .startAwait(); + } + + @Test + public void test_remote_greeting_request_completes_before_timeout() { + + SpringServicesProvider.LocalService service = gateway.call().api(SpringServicesProvider.LocalService.class); + + // call the service. + Mono result = + service.get(); + Long block = result.block(Duration.ofSeconds(10)); + assertEquals(1L, block.longValue()); + } + + private static ServiceDiscovery serviceDiscovery(ServiceEndpoint endpoint) { + return new ScalecubeServiceDiscovery(endpoint) + .membership(cfg -> cfg.seedMembers(gateway.discovery().address())); + } +} \ No newline at end of file diff --git a/services/src/main/java/io/scalecube/services/ScaleCube.java b/services/src/main/java/io/scalecube/services/ScaleCube.java index cff383c68..ee36e4723 100644 --- a/services/src/main/java/io/scalecube/services/ScaleCube.java +++ b/services/src/main/java/io/scalecube/services/ScaleCube.java @@ -25,14 +25,7 @@ import io.scalecube.services.transport.api.ServiceTransport; import java.lang.management.ManagementFactory; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.StringJoiner; -import java.util.UUID; +import java.util.*; import java.util.concurrent.CopyOnWriteArrayList; import java.util.function.Function; import java.util.function.Supplier; @@ -121,7 +114,7 @@ public final class ScaleCube implements Microservices { private final String id = generateId(); private final Metrics metrics; private final Map tags; - private final List serviceProviders; + private final ServicesProvider serviceProvider; private final ServiceRegistry serviceRegistry; private final ServiceMethodRegistry methodRegistry; private final Authenticator authenticator; @@ -136,7 +129,11 @@ public final class ScaleCube implements Microservices { private ScaleCube(Builder builder) { this.metrics = builder.metrics; this.tags = new HashMap<>(builder.tags); - this.serviceProviders = new ArrayList<>(builder.serviceProviders); + this.serviceProvider = builder.serviceProviders.stream().reduce(microservices -> Mono.just(Collections.emptyList()), + (sp1, sp2) -> microservices -> sp1.provide(microservices) + .mergeWith(sp2.provide(microservices)) + .collectList() + .map(c -> c.stream().flatMap(Collection::stream).collect(Collectors.toList()))); this.serviceRegistry = builder.serviceRegistry; this.methodRegistry = builder.methodRegistry; this.authenticator = builder.authenticator; @@ -193,10 +190,9 @@ private Mono start() { .tags(tags); // invoke service providers and register services - ServicesProvider servicesProvider = - new DeprecatedServiceProviderAdapter(serviceProviders); + Mono> serviceInstanceSuppliers = - servicesProvider + serviceProvider .provide(this) .flatMapIterable(i -> i) .doOnNext(this::registerInMethodRegistry) @@ -327,7 +323,7 @@ public static final class Builder { private Metrics metrics; private Map tags = new HashMap<>(); - private List serviceProviders = new ArrayList<>(); + private List serviceProviders = new ArrayList<>(); private ServiceRegistry serviceRegistry = new ServiceRegistryImpl(); private ServiceMethodRegistry methodRegistry = new ServiceMethodRegistryImpl(); private Authenticator authenticator = null; @@ -348,7 +344,7 @@ public ScaleCube startAwait() { } public Builder services(ServiceInfo... services) { - serviceProviders.add(call -> Arrays.stream(services).collect(Collectors.toList())); + serviceProviders.add(call -> Mono.just(Arrays.stream(services).collect(Collectors.toList()))); return this; } @@ -361,17 +357,17 @@ public Builder services(ServiceInfo... services) { public Builder services(Object... services) { serviceProviders.add( call -> - Arrays.stream(services) + Mono.just(Arrays.stream(services) .map( s -> s instanceof ServiceInfo ? (ServiceInfo) s : ServiceInfo.fromServiceInstance(s).build()) - .collect(Collectors.toList())); + .collect(Collectors.toList()))); return this; } - public Builder services(ServiceProvider serviceProvider) { + public Builder services(ServicesProvider serviceProvider) { serviceProviders.add(serviceProvider); return this; } From 4cbd2ac7a89f0a992b45eedea32220dd7991cd47 Mon Sep 17 00:00:00 2001 From: eutkin Date: Sun, 1 Mar 2020 14:02:51 +0300 Subject: [PATCH 08/61] ISSUE-708 First worked prototype --- services-examples-parent/pom.xml | 1 + .../spring/SpringServicesProvider.java | 19 ++++++++----------- .../spring/SpringServicesProviderTest.java | 2 +- 3 files changed, 10 insertions(+), 12 deletions(-) diff --git a/services-examples-parent/pom.xml b/services-examples-parent/pom.xml index 51c4ea328..22cb00a51 100644 --- a/services-examples-parent/pom.xml +++ b/services-examples-parent/pom.xml @@ -14,6 +14,7 @@ services-examples services-examples-runner + scalecube-examples-spring diff --git a/services-examples-parent/scalecube-examples-spring/src/main/java/io/scalecube/spring/SpringServicesProvider.java b/services-examples-parent/scalecube-examples-spring/src/main/java/io/scalecube/spring/SpringServicesProvider.java index 8885ddb13..71381a4d2 100644 --- a/services-examples-parent/scalecube-examples-spring/src/main/java/io/scalecube/spring/SpringServicesProvider.java +++ b/services-examples-parent/scalecube-examples-spring/src/main/java/io/scalecube/spring/SpringServicesProvider.java @@ -6,8 +6,7 @@ import io.scalecube.services.ServicesProvider; import io.scalecube.services.annotations.Service; import io.scalecube.services.annotations.ServiceMethod; -import io.scalecube.services.discovery.api.ServiceDiscovery; -import org.springframework.beans.factory.support.GenericBeanDefinition; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.support.GenericApplicationContext; @@ -22,11 +21,9 @@ public class SpringServicesProvider implements ServicesProvider { @Override public Mono> provide(Microservices microservices) { - GenericApplicationContext context = new GenericApplicationContext(); + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.registerBean(ServiceCall.class, microservices::call); - GenericBeanDefinition bd = new GenericBeanDefinition(); - bd.setBeanClass(Beans.class); - context.registerBeanDefinition("simple", bd); + context.register(Beans.class); context.refresh(); context.start(); @@ -40,8 +37,8 @@ public Mono> provide(Microservices microservices) { @Configuration static class Beans { @Bean - public LocalService simpleBean(ServiceCall serviceCall) { - return new SimpleBean(serviceCall); + public LocalService localServiceBean(ServiceCall serviceCall) { + return new LocalServiceBean(serviceCall); } } @@ -59,13 +56,13 @@ public interface LocalService { Monoget(); } - public static class SimpleBean implements LocalService { + public static class LocalServiceBean implements LocalService { private final SimpleService serviceCall; - public SimpleBean(ServiceCall serviceCall) { + public LocalServiceBean(ServiceCall serviceCall) { this.serviceCall = serviceCall.api(SimpleService.class); - System.out.println( this.serviceCall.get().block(Duration.ofSeconds(1))); + this.serviceCall.get().subscribe(System.out::println); } public Mono get() { diff --git a/services-examples-parent/scalecube-examples-spring/src/test/java/io/scalecube/spring/SpringServicesProviderTest.java b/services-examples-parent/scalecube-examples-spring/src/test/java/io/scalecube/spring/SpringServicesProviderTest.java index 41c7061a7..eb19b7354 100644 --- a/services-examples-parent/scalecube-examples-spring/src/test/java/io/scalecube/spring/SpringServicesProviderTest.java +++ b/services-examples-parent/scalecube-examples-spring/src/test/java/io/scalecube/spring/SpringServicesProviderTest.java @@ -72,7 +72,7 @@ public void test_remote_greeting_request_completes_before_timeout() { Mono result = service.get(); Long block = result.block(Duration.ofSeconds(10)); - assertEquals(1L, block.longValue()); + assertEquals(-1L, block.longValue()); } private static ServiceDiscovery serviceDiscovery(ServiceEndpoint endpoint) { From 60215ec7fe913753a856d10ab1d300e6ba3da8e7 Mon Sep 17 00:00:00 2001 From: eutkin Date: Sun, 1 Mar 2020 14:21:33 +0300 Subject: [PATCH 09/61] ISSUE-708 Rollback lazy initialization in ServiceInfo and ServiceMethodInvoker --- .../io/scalecube/services/ServiceInfo.java | 27 ++++++++----------- .../methods/ServiceMethodInvoker.java | 27 +++++++------------ .../methods/ServiceMethodInvokerTest.java | 19 +++++++------ .../java/io/scalecube/services/ScaleCube.java | 4 +-- .../methods/ServiceMethodRegistryImpl.java | 2 +- 5 files changed, 34 insertions(+), 45 deletions(-) diff --git a/services-api/src/main/java/io/scalecube/services/ServiceInfo.java b/services-api/src/main/java/io/scalecube/services/ServiceInfo.java index 4037e19ae..ff57e8a23 100644 --- a/services-api/src/main/java/io/scalecube/services/ServiceInfo.java +++ b/services-api/src/main/java/io/scalecube/services/ServiceInfo.java @@ -12,16 +12,14 @@ @SuppressWarnings("rawtypes") public class ServiceInfo { - private final Class serviceType; - private final Supplier serviceInstanceSupplier; + private final Object serviceInstance; private final Map tags; private final ServiceProviderErrorMapper errorMapper; private final ServiceMessageDataDecoder dataDecoder; private final Authenticator authenticator; private ServiceInfo(Builder builder) { - this.serviceType = builder.serviceType; - this.serviceInstanceSupplier = builder.serviceInstanceSupplier; + this.serviceInstance = builder.serviceInstance; this.tags = Collections.unmodifiableMap(new HashMap<>(builder.tags)); this.errorMapper = builder.errorMapper; this.dataDecoder = builder.dataDecoder; @@ -33,11 +31,11 @@ public static Builder from(ServiceInfo serviceInfo) { } public static Builder fromServiceInstance(Object serviceInstance) { - return new Builder(serviceInstance.getClass(), () -> serviceInstance); + return new Builder(serviceInstance); } - public Supplier serviceInstanceSupplier() { - return serviceInstanceSupplier; + public Object serviceInstance() { + return serviceInstance; } public Map tags() { @@ -57,13 +55,13 @@ public Authenticator authenticator() { } public Class type() { - return serviceType; + return this.serviceInstance().getClass(); } @Override public String toString() { return new StringJoiner(", ", ServiceInfo.class.getSimpleName() + "[", "]") - .add("serviceInstance=" + serviceInstanceSupplier) + .add("serviceInstance=" + serviceInstance) .add("tags=" + tags) .add("errorMapper=" + errorMapper) .add("dataDecoder=" + dataDecoder) @@ -74,25 +72,22 @@ public String toString() { @SuppressWarnings("rawtypes") public static class Builder { - private final Class serviceType; - private final Supplier serviceInstanceSupplier; + private final Object serviceInstance; private Map tags = new HashMap<>(); private ServiceProviderErrorMapper errorMapper; private ServiceMessageDataDecoder dataDecoder; private Authenticator authenticator; private Builder(ServiceInfo serviceInfo) { - this.serviceInstanceSupplier = serviceInfo.serviceInstanceSupplier; - this.serviceType = serviceInfo.serviceType; + this.serviceInstance = serviceInfo.serviceInstance; this.tags.putAll(new HashMap<>(serviceInfo.tags)); this.errorMapper = serviceInfo.errorMapper; this.dataDecoder = serviceInfo.dataDecoder; this.authenticator = serviceInfo.authenticator; } - private Builder(Class serviceType, Supplier serviceInstanceSupplier) { - this.serviceType = serviceType; - this.serviceInstanceSupplier = serviceInstanceSupplier; + private Builder(Object serviceInstance) { + this.serviceInstance = serviceInstance; } public Builder tag(String key, String value) { diff --git a/services-api/src/main/java/io/scalecube/services/methods/ServiceMethodInvoker.java b/services-api/src/main/java/io/scalecube/services/methods/ServiceMethodInvoker.java index 7184548f7..98108bf25 100644 --- a/services-api/src/main/java/io/scalecube/services/methods/ServiceMethodInvoker.java +++ b/services-api/src/main/java/io/scalecube/services/methods/ServiceMethodInvoker.java @@ -7,15 +7,15 @@ import io.scalecube.services.exceptions.ServiceProviderErrorMapper; import io.scalecube.services.exceptions.UnauthorizedException; import io.scalecube.services.transport.api.ServiceMessageDataDecoder; + +import org.reactivestreams.Publisher; + import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Optional; import java.util.StringJoiner; -import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; -import java.util.function.Supplier; -import org.reactivestreams.Publisher; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @@ -28,7 +28,7 @@ public final class ServiceMethodInvoker { private static final Object NO_PRINCIPAL = new Object(); private final Method method; - private final Supplier service; + private final Object service; private final MethodInfo methodInfo; private final ServiceProviderErrorMapper errorMapper; private final ServiceMessageDataDecoder dataDecoder; @@ -48,23 +48,14 @@ public final class ServiceMethodInvoker { public ServiceMethodInvoker( Class serviceType, Method method, - Supplier service, + Object service, MethodInfo methodInfo, ServiceProviderErrorMapper errorMapper, ServiceMessageDataDecoder dataDecoder, Authenticator authenticator) { this.serviceType = serviceType; this.method = method; - this.service = - new Supplier() { - private final AtomicReference instance = new AtomicReference<>(); - - @Override - public Object get() { - instance.compareAndSet(null, service.get()); - return instance.get(); - } - }; + this.service = service; this.methodInfo = methodInfo; this.errorMapper = errorMapper; this.dataDecoder = dataDecoder; @@ -129,10 +120,10 @@ private Publisher invoke(Object request, Object principal) { Throwable throwable = null; try { if (methodInfo.parameterCount() == 0) { - result = (Publisher) method.invoke(service.get()); + result = (Publisher) method.invoke(service); } else { Object[] arguments = prepareArguments(request, principal); - result = (Publisher) method.invoke(service.get(), arguments); + result = (Publisher) method.invoke(service, arguments); } if (result == null) { result = Mono.empty(); @@ -220,7 +211,7 @@ public Class serviceType() { @Deprecated public Object service() { - return service.get(); + return service; } public MethodInfo methodInfo() { diff --git a/services-api/src/test/java/io/scalecube/services/methods/ServiceMethodInvokerTest.java b/services-api/src/test/java/io/scalecube/services/methods/ServiceMethodInvokerTest.java index 0d2c8d731..8e8050650 100644 --- a/services-api/src/test/java/io/scalecube/services/methods/ServiceMethodInvokerTest.java +++ b/services-api/src/test/java/io/scalecube/services/methods/ServiceMethodInvokerTest.java @@ -5,10 +5,13 @@ import io.scalecube.services.auth.Authenticator; import io.scalecube.services.exceptions.DefaultErrorMapper; import io.scalecube.services.transport.api.ServiceMessageDataDecoder; -import java.lang.reflect.Method; -import java.util.function.Consumer; + import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; + +import java.lang.reflect.Method; +import java.util.function.Consumer; + import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; @@ -53,7 +56,7 @@ void testInvokeOneWhenReturnNull() throws Exception { new ServiceMethodInvoker( stubService.getClass(), method, - () -> stubService, + stubService, methodInfo, DefaultErrorMapper.INSTANCE, dataDecoder, @@ -88,7 +91,7 @@ void testInvokeManyWhenReturnNull() throws Exception { new ServiceMethodInvoker( stubService.getClass(), method, - () -> stubService, + stubService, methodInfo, DefaultErrorMapper.INSTANCE, dataDecoder, @@ -124,7 +127,7 @@ void testInvokeBidirectionalWhenReturnNull() throws Exception { new ServiceMethodInvoker( stubService.getClass(), method, - () -> stubService, + stubService, methodInfo, DefaultErrorMapper.INSTANCE, dataDecoder, @@ -162,7 +165,7 @@ void testInvokeOneWhenThrowException() throws Exception { new ServiceMethodInvoker( stubService.getClass(), method, - () -> stubService, + stubService, methodInfo, DefaultErrorMapper.INSTANCE, dataDecoder, @@ -201,7 +204,7 @@ void testInvokeManyWhenThrowException() throws Exception { new ServiceMethodInvoker( stubService.getClass(), method, - () -> stubService, + stubService, methodInfo, DefaultErrorMapper.INSTANCE, dataDecoder, @@ -240,7 +243,7 @@ void testInvokeBidirectionalWhenThrowException() throws Exception { new ServiceMethodInvoker( stubService.getClass(), method, - () -> stubService, + stubService, methodInfo, DefaultErrorMapper.INSTANCE, dataDecoder, diff --git a/services/src/main/java/io/scalecube/services/ScaleCube.java b/services/src/main/java/io/scalecube/services/ScaleCube.java index ee36e4723..28241388f 100644 --- a/services/src/main/java/io/scalecube/services/ScaleCube.java +++ b/services/src/main/java/io/scalecube/services/ScaleCube.java @@ -314,7 +314,7 @@ private Mono doShutdown() { private Mono processBeforeDestroy() { return Mono.whenDelayError( methodRegistry.listServices().stream() - .map(ServiceInfo::serviceInstanceSupplier) + .map(ServiceInfo::serviceInstance) .map(s -> Mono.fromRunnable(() -> Injector.processBeforeDestroy(this, s))) .collect(Collectors.toList())); } @@ -707,7 +707,7 @@ private static String asString(MethodInfo methodInfo) { private static String asString(ServiceInfo serviceInfo) { return new StringJoiner(", ", ServiceMethodInvoker.class.getSimpleName() + "[", "]") - .add("serviceInstance=" + serviceInfo.serviceInstanceSupplier()) + .add("serviceInstance=" + serviceInfo.serviceInstance()) .add("tags=" + serviceInfo.tags()) .add("authenticator=" + serviceInfo.authenticator()) .toString(); diff --git a/services/src/main/java/io/scalecube/services/methods/ServiceMethodRegistryImpl.java b/services/src/main/java/io/scalecube/services/methods/ServiceMethodRegistryImpl.java index 61fa9595e..1f6b45f20 100644 --- a/services/src/main/java/io/scalecube/services/methods/ServiceMethodRegistryImpl.java +++ b/services/src/main/java/io/scalecube/services/methods/ServiceMethodRegistryImpl.java @@ -53,7 +53,7 @@ public void registerService(ServiceInfo serviceInfo) { new ServiceMethodInvoker( serviceInfo.type(), method, - serviceInfo.serviceInstanceSupplier(), + serviceInfo.serviceInstance(), methodInfo, serviceInfo.errorMapper(), serviceInfo.dataDecoder(), From c4ae5680a59b5f58e06055d1424171ebebac616c Mon Sep 17 00:00:00 2001 From: eutkin Date: Sun, 1 Mar 2020 15:28:09 +0300 Subject: [PATCH 10/61] ISSUE-708 Refactoring --- .../DeprecatedServiceProviderAdapter.java | 30 -------- .../scalecube/services/ServicesProvider.java | 2 +- .../methods/ServiceMethodInvoker.java | 4 +- .../methods/ServiceMethodInvokerTest.java | 6 +- .../spring/SpringServicesProvider.java | 48 +++---------- .../spring/SpringServicesProviderTest.java | 70 ++++++++++++++----- .../java/io/scalecube/services/ScaleCube.java | 58 +++++++++++---- 7 files changed, 111 insertions(+), 107 deletions(-) delete mode 100644 services-api/src/main/java/io/scalecube/services/DeprecatedServiceProviderAdapter.java diff --git a/services-api/src/main/java/io/scalecube/services/DeprecatedServiceProviderAdapter.java b/services-api/src/main/java/io/scalecube/services/DeprecatedServiceProviderAdapter.java deleted file mode 100644 index e971d94b2..000000000 --- a/services-api/src/main/java/io/scalecube/services/DeprecatedServiceProviderAdapter.java +++ /dev/null @@ -1,30 +0,0 @@ -package io.scalecube.services; - -import static java.util.Objects.requireNonNull; - -import java.util.Collection; -import java.util.function.Supplier; -import java.util.stream.Collectors; -import reactor.core.publisher.Mono; - -@Deprecated -public class DeprecatedServiceProviderAdapter implements ServicesProvider { - - private final Collection delegates; - - public DeprecatedServiceProviderAdapter(Collection delegates) { - this.delegates = requireNonNull(delegates); - } - - @Override - public Mono> provide(Microservices microservices) { - Supplier>> beanSupplier = - () -> - Mono.just( - delegates.stream() - .map(delegate -> delegate.provide(microservices.call())) - .flatMap(Collection::stream) - .collect(Collectors.toList())); - return Mono.defer(beanSupplier); - } -} diff --git a/services-api/src/main/java/io/scalecube/services/ServicesProvider.java b/services-api/src/main/java/io/scalecube/services/ServicesProvider.java index 12fa242cc..a7c64efff 100644 --- a/services-api/src/main/java/io/scalecube/services/ServicesProvider.java +++ b/services-api/src/main/java/io/scalecube/services/ServicesProvider.java @@ -6,5 +6,5 @@ @FunctionalInterface public interface ServicesProvider { - Mono> provide(Microservices microservices); + Mono> provide(Microservices microservices); } diff --git a/services-api/src/main/java/io/scalecube/services/methods/ServiceMethodInvoker.java b/services-api/src/main/java/io/scalecube/services/methods/ServiceMethodInvoker.java index 98108bf25..712a76062 100644 --- a/services-api/src/main/java/io/scalecube/services/methods/ServiceMethodInvoker.java +++ b/services-api/src/main/java/io/scalecube/services/methods/ServiceMethodInvoker.java @@ -8,14 +8,14 @@ import io.scalecube.services.exceptions.UnauthorizedException; import io.scalecube.services.transport.api.ServiceMessageDataDecoder; -import org.reactivestreams.Publisher; - import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Optional; import java.util.StringJoiner; import java.util.function.Consumer; +import org.reactivestreams.Publisher; + import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; diff --git a/services-api/src/test/java/io/scalecube/services/methods/ServiceMethodInvokerTest.java b/services-api/src/test/java/io/scalecube/services/methods/ServiceMethodInvokerTest.java index 8e8050650..082674397 100644 --- a/services-api/src/test/java/io/scalecube/services/methods/ServiceMethodInvokerTest.java +++ b/services-api/src/test/java/io/scalecube/services/methods/ServiceMethodInvokerTest.java @@ -9,13 +9,13 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import java.lang.reflect.Method; -import java.util.function.Consumer; - import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; +import java.lang.reflect.Method; +import java.util.function.Consumer; + class ServiceMethodInvokerTest { private static final String qualifierPrefix = "io.scalecube.services.methods.StubService/"; diff --git a/services-examples-parent/scalecube-examples-spring/src/main/java/io/scalecube/spring/SpringServicesProvider.java b/services-examples-parent/scalecube-examples-spring/src/main/java/io/scalecube/spring/SpringServicesProvider.java index 71381a4d2..b74ea2736 100644 --- a/services-examples-parent/scalecube-examples-spring/src/main/java/io/scalecube/spring/SpringServicesProvider.java +++ b/services-examples-parent/scalecube-examples-spring/src/main/java/io/scalecube/spring/SpringServicesProvider.java @@ -5,25 +5,27 @@ import io.scalecube.services.ServiceInfo; import io.scalecube.services.ServicesProvider; import io.scalecube.services.annotations.Service; -import io.scalecube.services.annotations.ServiceMethod; +import java.util.stream.Stream; import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.support.GenericApplicationContext; import reactor.core.publisher.Mono; -import java.time.Duration; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; public class SpringServicesProvider implements ServicesProvider { + private final Class[] configurations; + + public SpringServicesProvider(Class... configurations) { + this.configurations = configurations; + } + @Override public Mono> provide(Microservices microservices) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.registerBean(ServiceCall.class, microservices::call); - context.register(Beans.class); + Stream.of(configurations).forEach(context::register); context.refresh(); context.start(); @@ -34,39 +36,5 @@ public Mono> provide(Microservices microservices) { return Mono.just(beans); } - @Configuration - static class Beans { - @Bean - public LocalService localServiceBean(ServiceCall serviceCall) { - return new LocalServiceBean(serviceCall); - } - } - - @Service - public interface SimpleService { - - @ServiceMethod - Mono get(); - } - - @Service - public interface LocalService { - - @ServiceMethod - Monoget(); - } - - public static class LocalServiceBean implements LocalService { - private final SimpleService serviceCall; - - public LocalServiceBean(ServiceCall serviceCall) { - this.serviceCall = serviceCall.api(SimpleService.class); - this.serviceCall.get().subscribe(System.out::println); - } - - public Mono get() { - return serviceCall.get().map(n -> n * -1); - } - } } diff --git a/services-examples-parent/scalecube-examples-spring/src/test/java/io/scalecube/spring/SpringServicesProviderTest.java b/services-examples-parent/scalecube-examples-spring/src/test/java/io/scalecube/spring/SpringServicesProviderTest.java index eb19b7354..4ee4eb9ce 100644 --- a/services-examples-parent/scalecube-examples-spring/src/test/java/io/scalecube/spring/SpringServicesProviderTest.java +++ b/services-examples-parent/scalecube-examples-spring/src/test/java/io/scalecube/spring/SpringServicesProviderTest.java @@ -1,13 +1,18 @@ package io.scalecube.spring; import io.scalecube.services.ScaleCube; +import io.scalecube.services.ServiceCall; import io.scalecube.services.ServiceEndpoint; +import io.scalecube.services.annotations.Service; +import io.scalecube.services.annotations.ServiceMethod; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.discovery.api.ServiceDiscovery; import io.scalecube.services.transport.rsocket.RSocketServiceTransport; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; import reactor.core.publisher.Hooks; import reactor.core.publisher.Mono; @@ -17,56 +22,51 @@ class SpringServicesProviderTest { - private static ScaleCube gateway; - private static ScaleCube provider; + private static ScaleCube microserviceWithSpring; + private static ScaleCube microserviceWithoutSpring; @BeforeAll public static void setup() { Hooks.onOperatorDebug(); - gateway = gateway(); - provider = serviceProvider(); + microserviceWithSpring = microserviceWithSpring(); + microserviceWithoutSpring = microserviceWithoutSpring(); } @AfterAll public static void tearDown() { try { - gateway.shutdown().block(); + microserviceWithSpring.shutdown().block(); } catch (Exception ignore) { // no-op } try { - provider.shutdown().block(); + microserviceWithoutSpring.shutdown().block(); } catch (Exception ignore) { // no-op } } - private static ScaleCube gateway() { + private static ScaleCube microserviceWithSpring() { return ScaleCube.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) - .services(new SpringServicesProvider()) + .services(new SpringServicesProvider(Beans.class)) .startAwait(); } - private static ScaleCube serviceProvider() { + private static ScaleCube microserviceWithoutSpring() { return ScaleCube.builder() .discovery(SpringServicesProviderTest::serviceDiscovery) .transport(RSocketServiceTransport::new) - .services(new SpringServicesProvider.SimpleService() { - @Override - public Mono get() { - return Mono.just(1L); - } - }) + .services((SimpleService) () -> Mono.just(1L)) .startAwait(); } @Test public void test_remote_greeting_request_completes_before_timeout() { - SpringServicesProvider.LocalService service = gateway.call().api(SpringServicesProvider.LocalService.class); + LocalService service = microserviceWithSpring.call().api(LocalService.class); // call the service. Mono result = @@ -77,6 +77,42 @@ public void test_remote_greeting_request_completes_before_timeout() { private static ServiceDiscovery serviceDiscovery(ServiceEndpoint endpoint) { return new ScalecubeServiceDiscovery(endpoint) - .membership(cfg -> cfg.seedMembers(gateway.discovery().address())); + .membership(cfg -> cfg.seedMembers(microserviceWithSpring.discovery().address())); } + @Configuration + static class Beans { + @Bean + public LocalService localServiceBean(ServiceCall serviceCall) { + return new LocalServiceBean(serviceCall); + } + } + + @Service + public interface SimpleService { + + @ServiceMethod + Mono get(); + } + + @Service + public interface LocalService { + + @ServiceMethod + Monoget(); + } + + public static class LocalServiceBean implements LocalService { + + private final SimpleService serviceCall; + + public LocalServiceBean(ServiceCall serviceCall) { + this.serviceCall = serviceCall.api(SimpleService.class); + this.serviceCall.get().subscribe(System.out::println); + } + + public Mono get() { + return serviceCall.get().map(n -> n * -1); + } + } + } \ No newline at end of file diff --git a/services/src/main/java/io/scalecube/services/ScaleCube.java b/services/src/main/java/io/scalecube/services/ScaleCube.java index 28241388f..78973fe01 100644 --- a/services/src/main/java/io/scalecube/services/ScaleCube.java +++ b/services/src/main/java/io/scalecube/services/ScaleCube.java @@ -1,5 +1,7 @@ package io.scalecube.services; +import static java.util.Arrays.asList; + import com.codahale.metrics.MetricRegistry; import io.scalecube.net.Address; import io.scalecube.services.auth.Authenticator; @@ -25,7 +27,15 @@ import io.scalecube.services.transport.api.ServiceTransport; import java.lang.management.ManagementFactory; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.StringJoiner; +import java.util.UUID; import java.util.concurrent.CopyOnWriteArrayList; import java.util.function.Function; import java.util.function.Supplier; @@ -129,11 +139,16 @@ public final class ScaleCube implements Microservices { private ScaleCube(Builder builder) { this.metrics = builder.metrics; this.tags = new HashMap<>(builder.tags); - this.serviceProvider = builder.serviceProviders.stream().reduce(microservices -> Mono.just(Collections.emptyList()), - (sp1, sp2) -> microservices -> sp1.provide(microservices) - .mergeWith(sp2.provide(microservices)) - .collectList() - .map(c -> c.stream().flatMap(Collection::stream).collect(Collectors.toList()))); + this.serviceProvider = + builder.serviceProviders.stream() + .reduce( + microservices -> Mono.just(Collections.emptyList()), + (sp1, sp2) -> + microservices -> { + Flux services1 = sp1.provide(this).flatMapIterable(i -> i); + Flux services2 = sp2.provide(this).flatMapIterable(i -> i); + return services1.mergeWith(services2).collectList(); + }); this.serviceRegistry = builder.serviceRegistry; this.methodRegistry = builder.methodRegistry; this.authenticator = builder.authenticator; @@ -344,7 +359,7 @@ public ScaleCube startAwait() { } public Builder services(ServiceInfo... services) { - serviceProviders.add(call -> Mono.just(Arrays.stream(services).collect(Collectors.toList()))); + serviceProviders.add(call -> Mono.just(asList(services))); return this; } @@ -357,13 +372,28 @@ public Builder services(ServiceInfo... services) { public Builder services(Object... services) { serviceProviders.add( call -> - Mono.just(Arrays.stream(services) - .map( - s -> - s instanceof ServiceInfo - ? (ServiceInfo) s - : ServiceInfo.fromServiceInstance(s).build()) - .collect(Collectors.toList()))); + Mono.just( + Arrays.stream(services) + .map( + s -> + s instanceof ServiceInfo + ? (ServiceInfo) s + : ServiceInfo.fromServiceInstance(s).build()) + .collect(Collectors.toList()))); + return this; + } + + /** + * Set up service provider + * + * @param serviceProvider - old service provider + * @return this + * @deprecated use {@link this#services(ServicesProvider)} + */ + @Deprecated + public Builder services(ServiceProvider serviceProvider) { + serviceProviders.add( + microservices -> Mono.just(serviceProvider.provide(microservices.call()))); return this; } From 5c759deb47efaa3c84fb6add46e727c788d1d682 Mon Sep 17 00:00:00 2001 From: eutkin Date: Mon, 2 Mar 2020 20:10:59 +0300 Subject: [PATCH 11/61] ISSUE-708 Refactoring --- .../scalecube/services/ServicesProvider.java | 46 ++++++++++++++- .../spring/SpringServicesProvider.java | 48 ++++++++++++--- .../java/io/scalecube/services/ScaleCube.java | 44 ++++++-------- .../services/{ => inject}/Injector.java | 33 ++++++----- .../inject/ScaleCubeServicesProvider.java | 59 +++++++++++++++++++ .../inject/ServiceProviderAdapter.java | 42 +++++++++++++ 6 files changed, 220 insertions(+), 52 deletions(-) rename services/src/main/java/io/scalecube/services/{ => inject}/Injector.java (74%) create mode 100644 services/src/main/java/io/scalecube/services/inject/ScaleCubeServicesProvider.java create mode 100644 services/src/main/java/io/scalecube/services/inject/ServiceProviderAdapter.java diff --git a/services-api/src/main/java/io/scalecube/services/ServicesProvider.java b/services-api/src/main/java/io/scalecube/services/ServicesProvider.java index a7c64efff..81453ea5c 100644 --- a/services-api/src/main/java/io/scalecube/services/ServicesProvider.java +++ b/services-api/src/main/java/io/scalecube/services/ServicesProvider.java @@ -1,10 +1,54 @@ package io.scalecube.services; import java.util.Collection; +import java.util.Collections; +import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; -@FunctionalInterface public interface ServicesProvider { + ServicesProvider EMPTY = + new ServicesProvider() { + @Override + public Mono> provide(Microservices microservices) { + return Mono.just(Collections.emptyList()); + } + + @Override + public Mono shutDown(Microservices microservices) { + return Mono.just(microservices); + } + }; + + /** + * Union of two services providers. + * + * @param provider1 first provider + * @param provider2 second provider + * @return provider + */ + static ServicesProvider union(ServicesProvider provider1, ServicesProvider provider2) { + return new ServicesProvider() { + @Override + public Mono> provide(Microservices microservices) { + Flux services1 = flatService(microservices, provider1); + Flux services2 = flatService(microservices, provider2); + return services1.mergeWith(services2).collectList(); + } + + @Override + public Mono shutDown(Microservices microservices) { + return provider1.shutDown(microservices).then(provider2.shutDown(microservices)); + } + + private Flux flatService( + Microservices microservices, ServicesProvider provider) { + return provider.provide(microservices).flatMapIterable(i -> i); + } + }; + } + Mono> provide(Microservices microservices); + + Mono shutDown(Microservices microservices); } diff --git a/services-examples-parent/scalecube-examples-spring/src/main/java/io/scalecube/spring/SpringServicesProvider.java b/services-examples-parent/scalecube-examples-spring/src/main/java/io/scalecube/spring/SpringServicesProvider.java index b74ea2736..191b3ddd3 100644 --- a/services-examples-parent/scalecube-examples-spring/src/main/java/io/scalecube/spring/SpringServicesProvider.java +++ b/services-examples-parent/scalecube-examples-spring/src/main/java/io/scalecube/spring/SpringServicesProvider.java @@ -5,7 +5,11 @@ import io.scalecube.services.ServiceInfo; import io.scalecube.services.ServicesProvider; import io.scalecube.services.annotations.Service; +import java.util.Objects; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.BiFunction; import java.util.stream.Stream; +import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import reactor.core.publisher.Mono; @@ -15,20 +19,34 @@ public class SpringServicesProvider implements ServicesProvider { - private final Class[] configurations; + private final BiFunction< + Microservices, AnnotationConfigApplicationContext, AnnotationConfigApplicationContext> + ctxFactory; + + private final AtomicReference ctx = new AtomicReference<>(); public SpringServicesProvider(Class... configurations) { - this.configurations = configurations; + this.ctxFactory = + (microservices, ctx) -> { + AnnotationConfigApplicationContext springContext; + if (Objects.isNull(ctx)) { + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); + context.registerBean(ServiceCall.class, microservices::call); + Stream.of(configurations).forEach(context::register); + springContext = context; + } else { + springContext = ctx; + } + springContext.refresh(); + springContext.start(); + return springContext; + }; } @Override public Mono> provide(Microservices microservices) { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); - context.registerBean(ServiceCall.class, microservices::call); - Stream.of(configurations).forEach(context::register); - context.refresh(); - context.start(); - + AnnotationConfigApplicationContext context = + this.ctx.updateAndGet(c -> ctxFactory.apply(microservices, c)); List beans = context.getBeansWithAnnotation(Service.class).values().stream() .map(bean -> ServiceInfo.fromServiceInstance(bean).build()) @@ -36,5 +54,17 @@ public Mono> provide(Microservices microservices) { return Mono.just(beans); } - + @Override + public Mono shutDown(Microservices microservices) { + return Mono.fromCallable( + () -> { + this.ctx.updateAndGet( + ctx -> { + ctx.stop(); + ctx.close(); + return ctx; + }); + return microservices; + }); + } } diff --git a/services/src/main/java/io/scalecube/services/ScaleCube.java b/services/src/main/java/io/scalecube/services/ScaleCube.java index 78973fe01..eb86dbec2 100644 --- a/services/src/main/java/io/scalecube/services/ScaleCube.java +++ b/services/src/main/java/io/scalecube/services/ScaleCube.java @@ -1,7 +1,5 @@ package io.scalecube.services; -import static java.util.Arrays.asList; - import com.codahale.metrics.MetricRegistry; import io.scalecube.net.Address; import io.scalecube.services.auth.Authenticator; @@ -11,6 +9,8 @@ import io.scalecube.services.exceptions.ServiceProviderErrorMapper; import io.scalecube.services.gateway.Gateway; import io.scalecube.services.gateway.GatewayOptions; +import io.scalecube.services.inject.ScaleCubeServicesProvider; +import io.scalecube.services.inject.ServiceProviderAdapter; import io.scalecube.services.methods.MethodInfo; import io.scalecube.services.methods.ServiceMethodInvoker; import io.scalecube.services.methods.ServiceMethodRegistry; @@ -28,8 +28,6 @@ import java.lang.management.ManagementFactory; import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -140,15 +138,7 @@ private ScaleCube(Builder builder) { this.metrics = builder.metrics; this.tags = new HashMap<>(builder.tags); this.serviceProvider = - builder.serviceProviders.stream() - .reduce( - microservices -> Mono.just(Collections.emptyList()), - (sp1, sp2) -> - microservices -> { - Flux services1 = sp1.provide(this).flatMapIterable(i -> i); - Flux services2 = sp2.provide(this).flatMapIterable(i -> i); - return services1.mergeWith(services2).collectList(); - }); + builder.serviceProviders.stream().reduce(ServicesProvider.EMPTY, ServicesProvider::union); this.serviceRegistry = builder.serviceRegistry; this.methodRegistry = builder.methodRegistry; this.authenticator = builder.authenticator; @@ -330,7 +320,7 @@ private Mono processBeforeDestroy() { return Mono.whenDelayError( methodRegistry.listServices().stream() .map(ServiceInfo::serviceInstance) - .map(s -> Mono.fromRunnable(() -> Injector.processBeforeDestroy(this, s))) + .map(s -> serviceProvider.shutDown(this)) .collect(Collectors.toList())); } @@ -358,8 +348,16 @@ public ScaleCube startAwait() { return start().block(); } + /** + * Adds service instance to microservice. + * + * @param services service info instance. + * @return builder + * @deprecated use {@link this#services(ServicesProvider)} + */ + @Deprecated public Builder services(ServiceInfo... services) { - serviceProviders.add(call -> Mono.just(asList(services))); + serviceProviders.add(ScaleCubeServicesProvider.from(services)); return this; } @@ -368,18 +366,11 @@ public Builder services(ServiceInfo... services) { * * @param services service instance. * @return builder + * @deprecated use {@link this#services(ServicesProvider)} */ + @Deprecated public Builder services(Object... services) { - serviceProviders.add( - call -> - Mono.just( - Arrays.stream(services) - .map( - s -> - s instanceof ServiceInfo - ? (ServiceInfo) s - : ServiceInfo.fromServiceInstance(s).build()) - .collect(Collectors.toList()))); + serviceProviders.add(ScaleCubeServicesProvider.from(services)); return this; } @@ -392,8 +383,7 @@ public Builder services(Object... services) { */ @Deprecated public Builder services(ServiceProvider serviceProvider) { - serviceProviders.add( - microservices -> Mono.just(serviceProvider.provide(microservices.call()))); + serviceProviders.add(new ServiceProviderAdapter(serviceProvider)); return this; } diff --git a/services/src/main/java/io/scalecube/services/Injector.java b/services/src/main/java/io/scalecube/services/inject/Injector.java similarity index 74% rename from services/src/main/java/io/scalecube/services/Injector.java rename to services/src/main/java/io/scalecube/services/inject/Injector.java index 892167bd7..ab3155a7c 100644 --- a/services/src/main/java/io/scalecube/services/Injector.java +++ b/services/src/main/java/io/scalecube/services/inject/Injector.java @@ -1,5 +1,9 @@ -package io.scalecube.services; +package io.scalecube.services.inject; +import io.scalecube.services.Microservices; +import io.scalecube.services.Reflect; +import io.scalecube.services.ScaleCube; +import io.scalecube.services.ServiceCall; import io.scalecube.services.annotations.AfterConstruct; import io.scalecube.services.annotations.BeforeDestroy; import io.scalecube.services.annotations.Inject; @@ -19,23 +23,22 @@ private Injector() { } /** - * Inject instances to the microservices instance. either Microservices or ServiceProxy. Scan all + * Inject instance to the microservices instance. either Microservices or ServiceProxy. Scan all * local service instances and inject a service proxy. * * @param microservices microservices instance - * @param services services set - * @return microservices instance + * @param service service + * @return service instance */ - public static ScaleCube inject(ScaleCube microservices, Collection services) { - services.forEach( - service -> - Arrays.stream(service.getClass().getDeclaredFields()) - .forEach(field -> injectField(microservices, field, service))); - services.forEach(service -> processAfterConstruct(microservices, service)); - return microservices; + public static Object inject(Microservices microservices, Object service) { + Arrays.stream(service.getClass().getDeclaredFields()) + .forEach(field -> injectField(microservices, field, service)); + processAfterConstruct(microservices, service); + return service; } - private static void injectField(ScaleCube microservices, Field field, Object service) { + + private static void injectField(Microservices microservices, Field field, Object service) { if (field.isAnnotationPresent(Inject.class) && field.getType().equals(ScaleCube.class)) { setField(field, service, microservices); } else if (field.isAnnotationPresent(Inject.class) && Reflect.isService(field.getType())) { @@ -59,16 +62,16 @@ private static void setField(Field field, Object object, Object value) { } } - private static void processAfterConstruct(ScaleCube microservices, Object targetInstance) { + private static void processAfterConstruct(Microservices microservices, Object targetInstance) { processMethodWithAnnotation(microservices, targetInstance, AfterConstruct.class); } - public static void processBeforeDestroy(ScaleCube microservices, Object targetInstance) { + public static void processBeforeDestroy(Microservices microservices, Object targetInstance) { processMethodWithAnnotation(microservices, targetInstance, BeforeDestroy.class); } private static void processMethodWithAnnotation( - ScaleCube microservices, Object targetInstance, Class annotation) { + Microservices microservices, Object targetInstance, Class annotation) { Method[] declaredMethods = targetInstance.getClass().getDeclaredMethods(); Arrays.stream(declaredMethods) .filter(method -> method.isAnnotationPresent(annotation)) diff --git a/services/src/main/java/io/scalecube/services/inject/ScaleCubeServicesProvider.java b/services/src/main/java/io/scalecube/services/inject/ScaleCubeServicesProvider.java new file mode 100644 index 000000000..8f531225a --- /dev/null +++ b/services/src/main/java/io/scalecube/services/inject/ScaleCubeServicesProvider.java @@ -0,0 +1,59 @@ +package io.scalecube.services.inject; + +import static java.util.Arrays.asList; + +import io.scalecube.services.Microservices; +import io.scalecube.services.ServiceInfo; +import io.scalecube.services.ServicesProvider; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import reactor.core.publisher.Mono; + +public class ScaleCubeServicesProvider implements ServicesProvider { + + private final Collection services; + + public static ScaleCubeServicesProvider from(Object... services) { + return from(services == null ? Collections.emptyList() : asList(services)); + } + + public static ScaleCubeServicesProvider from(Collection services) { + return new ScaleCubeServicesProvider(services); + } + + private ScaleCubeServicesProvider(Collection services) { + this.services = services == null ? Collections.emptyList() : services; + } + + @Override + public Mono> provide(Microservices microservices) { + List services = + this.services.stream() + .map( + service -> { + Object serviceInstance; + ServiceInfo serviceInfo; + if (service instanceof ServiceInfo) { + serviceInfo = (ServiceInfo) service; + serviceInstance = serviceInfo.serviceInstance(); + } else { + serviceInstance = service; + serviceInfo = ServiceInfo.fromServiceInstance(serviceInstance).build(); + } + Injector.inject(microservices, serviceInstance); + return serviceInfo; + }) + .collect(Collectors.toList()); + return Mono.just(services); + } + + @Override + public Mono shutDown(Microservices microservices) { + Stream.of(this.services) + .forEach(service -> Injector.processBeforeDestroy(microservices, service)); + return Mono.just(microservices); + } +} diff --git a/services/src/main/java/io/scalecube/services/inject/ServiceProviderAdapter.java b/services/src/main/java/io/scalecube/services/inject/ServiceProviderAdapter.java new file mode 100644 index 000000000..d0576f9c2 --- /dev/null +++ b/services/src/main/java/io/scalecube/services/inject/ServiceProviderAdapter.java @@ -0,0 +1,42 @@ +package io.scalecube.services.inject; + +import io.scalecube.services.Microservices; +import io.scalecube.services.ServiceInfo; +import io.scalecube.services.ServiceProvider; +import io.scalecube.services.ServicesProvider; +import java.util.Collection; +import java.util.Objects; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.BiFunction; +import java.util.function.BinaryOperator; +import java.util.function.UnaryOperator; +import reactor.core.publisher.Mono; + +public class ServiceProviderAdapter implements ServicesProvider { + + // lazy + private final AtomicReference delegate; + + private final BiFunction factory; + + public ServiceProviderAdapter(ServiceProvider serviceProvider) { + this.factory = + (microservices, provider) -> + Objects.isNull(provider) + ? ScaleCubeServicesProvider.from(serviceProvider.provide(microservices.call())) + : provider; + this.delegate = new AtomicReference<>(); + } + + @Override + public Mono> provide(Microservices microservices) { + return delegate + .updateAndGet(provider -> factory.apply(microservices, provider)) + .provide(microservices); + } + + @Override + public Mono shutDown(Microservices microservices) { + return this.delegate.get().shutDown(microservices); + } +} From afee8d0444263741a5a2a220e83eae4e4f575e44 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=95=D0=B2=D0=B3=D0=B5=D0=BD=D0=B8=D0=B9=20=D0=A3=D1=82?= =?UTF-8?q?=D0=BA=D0=B8=D0=BD?= Date: Tue, 10 Mar 2020 17:51:05 +0300 Subject: [PATCH 12/61] ISSUE 708, WIP. Refactoring --- .../scalecube/services/ServiceProvider.java | 2 +- .../services/ServicesLifeCycleManager.java | 70 +++++++++++ .../scalecube/services/ServicesProvider.java | 54 -------- .../scalecube-examples-spring/pom.xml | 3 +- ...va => SpringServicesLifeCycleManager.java} | 49 +++++--- .../SpringServicesLifeCycleManagerTest.java | 118 ++++++++++++++++++ .../spring/SpringServicesProviderTest.java | 118 ------------------ .../services-examples-runner/pom.xml | 1 + .../java/io/scalecube/services/ScaleCube.java | 47 +++---- .../scalecube/services/inject/Injector.java | 5 +- ...=> ScaleCubeServicesLifeCycleManager.java} | 27 ++-- .../ServiceLifeCycleManagerAdapter.java | 53 ++++++++ .../inject/ServiceProviderAdapter.java | 42 ------- 13 files changed, 318 insertions(+), 271 deletions(-) create mode 100644 services-api/src/main/java/io/scalecube/services/ServicesLifeCycleManager.java delete mode 100644 services-api/src/main/java/io/scalecube/services/ServicesProvider.java rename services-examples-parent/scalecube-examples-spring/src/main/java/io/scalecube/spring/{SpringServicesProvider.java => SpringServicesLifeCycleManager.java} (58%) create mode 100644 services-examples-parent/scalecube-examples-spring/src/test/java/io/scalecube/spring/SpringServicesLifeCycleManagerTest.java delete mode 100644 services-examples-parent/scalecube-examples-spring/src/test/java/io/scalecube/spring/SpringServicesProviderTest.java rename services/src/main/java/io/scalecube/services/inject/{ScaleCubeServicesProvider.java => ScaleCubeServicesLifeCycleManager.java} (63%) create mode 100644 services/src/main/java/io/scalecube/services/inject/ServiceLifeCycleManagerAdapter.java delete mode 100644 services/src/main/java/io/scalecube/services/inject/ServiceProviderAdapter.java diff --git a/services-api/src/main/java/io/scalecube/services/ServiceProvider.java b/services-api/src/main/java/io/scalecube/services/ServiceProvider.java index 92faa6f1e..adbdd81b2 100644 --- a/services-api/src/main/java/io/scalecube/services/ServiceProvider.java +++ b/services-api/src/main/java/io/scalecube/services/ServiceProvider.java @@ -5,7 +5,7 @@ /** * Provide service instances. * - * @deprecated use {@link ServicesProvider} + * @deprecated use {@link ServicesLifeCycleManager} */ @FunctionalInterface @Deprecated diff --git a/services-api/src/main/java/io/scalecube/services/ServicesLifeCycleManager.java b/services-api/src/main/java/io/scalecube/services/ServicesLifeCycleManager.java new file mode 100644 index 000000000..181148b5f --- /dev/null +++ b/services-api/src/main/java/io/scalecube/services/ServicesLifeCycleManager.java @@ -0,0 +1,70 @@ +package io.scalecube.services; + +import java.util.Collection; +import java.util.Collections; + +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +public interface ServicesLifeCycleManager { + + ServicesLifeCycleManager EMPTY = + new ServicesLifeCycleManager() { + @Override + public Mono> constructServices(Microservices microservices) { + return Mono.just(Collections.emptyList()); + } + + @Override + public Mono postConstruct(Microservices microservices) { + return Mono.empty(); + } + + @Override + public Mono shutDown(Microservices microservices) { + return Mono.just(microservices); + } + }; + + /** + * Union of two services providers. + * + * @param provider1 first provider + * @param provider2 second provider + * @return provider + */ + static ServicesLifeCycleManager union( + ServicesLifeCycleManager provider1, ServicesLifeCycleManager provider2) { + return new ServicesLifeCycleManager() { + @Override + public Mono> constructServices(Microservices microservices) { + Flux services1 = flatService(microservices, provider1); + Flux services2 = flatService(microservices, provider2); + return services1.mergeWith(services2).collectList(); + } + + @Override + public Mono postConstruct(Microservices microservices) { + Mono void1 = provider1.postConstruct(microservices); + Mono void2 = provider2.postConstruct(microservices); + return void1.then(void2); + } + + @Override + public Mono shutDown(Microservices microservices) { + return provider1.shutDown(microservices).then(provider2.shutDown(microservices)); + } + + private Flux flatService( + Microservices microservices, ServicesLifeCycleManager provider) { + return provider.constructServices(microservices).flatMapIterable(i -> i); + } + }; + } + + Mono> constructServices(Microservices microservices); + + Mono postConstruct(Microservices microservices); + + Mono shutDown(Microservices microservices); +} diff --git a/services-api/src/main/java/io/scalecube/services/ServicesProvider.java b/services-api/src/main/java/io/scalecube/services/ServicesProvider.java deleted file mode 100644 index 81453ea5c..000000000 --- a/services-api/src/main/java/io/scalecube/services/ServicesProvider.java +++ /dev/null @@ -1,54 +0,0 @@ -package io.scalecube.services; - -import java.util.Collection; -import java.util.Collections; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; - -public interface ServicesProvider { - - ServicesProvider EMPTY = - new ServicesProvider() { - @Override - public Mono> provide(Microservices microservices) { - return Mono.just(Collections.emptyList()); - } - - @Override - public Mono shutDown(Microservices microservices) { - return Mono.just(microservices); - } - }; - - /** - * Union of two services providers. - * - * @param provider1 first provider - * @param provider2 second provider - * @return provider - */ - static ServicesProvider union(ServicesProvider provider1, ServicesProvider provider2) { - return new ServicesProvider() { - @Override - public Mono> provide(Microservices microservices) { - Flux services1 = flatService(microservices, provider1); - Flux services2 = flatService(microservices, provider2); - return services1.mergeWith(services2).collectList(); - } - - @Override - public Mono shutDown(Microservices microservices) { - return provider1.shutDown(microservices).then(provider2.shutDown(microservices)); - } - - private Flux flatService( - Microservices microservices, ServicesProvider provider) { - return provider.provide(microservices).flatMapIterable(i -> i); - } - }; - } - - Mono> provide(Microservices microservices); - - Mono shutDown(Microservices microservices); -} diff --git a/services-examples-parent/scalecube-examples-spring/pom.xml b/services-examples-parent/scalecube-examples-spring/pom.xml index 9635b6378..3deb5772b 100644 --- a/services-examples-parent/scalecube-examples-spring/pom.xml +++ b/services-examples-parent/scalecube-examples-spring/pom.xml @@ -3,10 +3,9 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - scalecube-services-parent + scalecube-services-examples-parent io.scalecube 2.8.10-SNAPSHOT - ../pom.xml 4.0.0 diff --git a/services-examples-parent/scalecube-examples-spring/src/main/java/io/scalecube/spring/SpringServicesProvider.java b/services-examples-parent/scalecube-examples-spring/src/main/java/io/scalecube/spring/SpringServicesLifeCycleManager.java similarity index 58% rename from services-examples-parent/scalecube-examples-spring/src/main/java/io/scalecube/spring/SpringServicesProvider.java rename to services-examples-parent/scalecube-examples-spring/src/main/java/io/scalecube/spring/SpringServicesLifeCycleManager.java index 191b3ddd3..b90c8e993 100644 --- a/services-examples-parent/scalecube-examples-spring/src/main/java/io/scalecube/spring/SpringServicesProvider.java +++ b/services-examples-parent/scalecube-examples-spring/src/main/java/io/scalecube/spring/SpringServicesLifeCycleManager.java @@ -3,21 +3,21 @@ import io.scalecube.services.Microservices; import io.scalecube.services.ServiceCall; import io.scalecube.services.ServiceInfo; -import io.scalecube.services.ServicesProvider; +import io.scalecube.services.ServicesLifeCycleManager; import io.scalecube.services.annotations.Service; -import java.util.Objects; -import java.util.concurrent.atomic.AtomicReference; -import java.util.function.BiFunction; -import java.util.stream.Stream; -import org.springframework.context.ApplicationContext; +import io.scalecube.services.discovery.api.ServiceDiscovery; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import reactor.core.publisher.Mono; import java.util.Collection; import java.util.List; +import java.util.Objects; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.BiFunction; import java.util.stream.Collectors; +import java.util.stream.Stream; -public class SpringServicesProvider implements ServicesProvider { +public class SpringServicesLifeCycleManager implements ServicesLifeCycleManager { private final BiFunction< Microservices, AnnotationConfigApplicationContext, AnnotationConfigApplicationContext> @@ -25,26 +25,21 @@ public class SpringServicesProvider implements ServicesProvider { private final AtomicReference ctx = new AtomicReference<>(); - public SpringServicesProvider(Class... configurations) { + public SpringServicesLifeCycleManager(Class... configurations) { this.ctxFactory = (microservices, ctx) -> { - AnnotationConfigApplicationContext springContext; - if (Objects.isNull(ctx)) { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); - context.registerBean(ServiceCall.class, microservices::call); - Stream.of(configurations).forEach(context::register); - springContext = context; - } else { - springContext = ctx; + if (Objects.nonNull(ctx)) { + return ctx; } - springContext.refresh(); - springContext.start(); - return springContext; + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); + context.registerBean(ServiceCall.class, microservices::call); + Stream.of(configurations).forEach(context::register); + return context; }; } @Override - public Mono> provide(Microservices microservices) { + public Mono> constructServices(Microservices microservices) { AnnotationConfigApplicationContext context = this.ctx.updateAndGet(c -> ctxFactory.apply(microservices, c)); List beans = @@ -54,6 +49,20 @@ public Mono> provide(Microservices microservices) { return Mono.just(beans); } + @Override + public Mono postConstruct(Microservices microservices) { + Mono ctxMono = + Mono.just( + this.ctx.updateAndGet( + ctx -> { + ctx.registerBean(ServiceDiscovery.class, microservices::discovery); + ctx.refresh(); + ctx.start(); + return ctx; + })); + return Mono.defer(() -> ctxMono).then(); + } + @Override public Mono shutDown(Microservices microservices) { return Mono.fromCallable( diff --git a/services-examples-parent/scalecube-examples-spring/src/test/java/io/scalecube/spring/SpringServicesLifeCycleManagerTest.java b/services-examples-parent/scalecube-examples-spring/src/test/java/io/scalecube/spring/SpringServicesLifeCycleManagerTest.java new file mode 100644 index 000000000..b44e5e972 --- /dev/null +++ b/services-examples-parent/scalecube-examples-spring/src/test/java/io/scalecube/spring/SpringServicesLifeCycleManagerTest.java @@ -0,0 +1,118 @@ +package io.scalecube.spring; + +import io.scalecube.services.ScaleCube; +import io.scalecube.services.ServiceCall; +import io.scalecube.services.ServiceEndpoint; +import io.scalecube.services.annotations.Service; +import io.scalecube.services.annotations.ServiceMethod; +import io.scalecube.services.discovery.ScalecubeServiceDiscovery; +import io.scalecube.services.discovery.api.ServiceDiscovery; +import io.scalecube.services.transport.rsocket.RSocketServiceTransport; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import reactor.core.publisher.Hooks; +import reactor.core.publisher.Mono; + +import java.time.Duration; + +import static org.junit.jupiter.api.Assertions.*; + +class SpringServicesLifeCycleManagerTest { + + private static ScaleCube microserviceWithSpring; + private static ScaleCube microserviceWithoutSpring; + + @BeforeAll + public static void setup() { + Hooks.onOperatorDebug(); + microserviceWithSpring = microserviceWithSpring(); + microserviceWithoutSpring = microserviceWithoutSpring(); + } + + @AfterAll + public static void tearDown() { + try { + microserviceWithSpring.shutdown().block(); + } catch (Exception ignore) { + // no-op + } + + try { + microserviceWithoutSpring.shutdown().block(); + } catch (Exception ignore) { + // no-op + } + } + + private static ScaleCube microserviceWithSpring() { + return ScaleCube.builder() + .discovery(ScalecubeServiceDiscovery::new) + .transport(RSocketServiceTransport::new) + .services(new SpringServicesLifeCycleManager(Beans.class)) + .startAwait(); + } + + private static ScaleCube microserviceWithoutSpring() { + return ScaleCube.builder() + .discovery(SpringServicesLifeCycleManagerTest::serviceDiscovery) + .transport(RSocketServiceTransport::new) + .services((SimpleService) () -> Mono.just(1L)) + .startAwait(); + } + + @Test + public void test_remote_greeting_request_completes_before_timeout() { + + LocalService service = microserviceWithSpring.call().api(LocalService.class); + + // call the service. + Mono result = service.get(); + Long block = result.block(Duration.ofSeconds(10)); + assertEquals(-1L, block.longValue()); + } + + private static ServiceDiscovery serviceDiscovery(ServiceEndpoint endpoint) { + return new ScalecubeServiceDiscovery(endpoint) + .membership(cfg -> cfg.seedMembers(microserviceWithSpring.discovery().address())); + } + + @Configuration + static class Beans { + @Bean + public LocalService localServiceBean(ServiceCall serviceCall, ServiceDiscovery serviceDiscovery) { + return new LocalServiceBean(serviceCall, serviceDiscovery); + } + } + + @Service + public interface SimpleService { + + @ServiceMethod + Mono get(); + } + + @Service + public interface LocalService { + + @ServiceMethod + Mono get(); + } + + public static class LocalServiceBean implements LocalService { + + private final SimpleService serviceCall; + + public LocalServiceBean(ServiceCall serviceCall, ServiceDiscovery serviceDiscovery) { + this.serviceCall = serviceCall.api(SimpleService.class); + this.serviceCall.get().subscribe(System.out::println); + serviceDiscovery.listenDiscovery().subscribe(System.out::println); + } + + public Mono get() { + return serviceCall.get().map(n -> n * -1); + } + } +} diff --git a/services-examples-parent/scalecube-examples-spring/src/test/java/io/scalecube/spring/SpringServicesProviderTest.java b/services-examples-parent/scalecube-examples-spring/src/test/java/io/scalecube/spring/SpringServicesProviderTest.java deleted file mode 100644 index 4ee4eb9ce..000000000 --- a/services-examples-parent/scalecube-examples-spring/src/test/java/io/scalecube/spring/SpringServicesProviderTest.java +++ /dev/null @@ -1,118 +0,0 @@ -package io.scalecube.spring; - -import io.scalecube.services.ScaleCube; -import io.scalecube.services.ServiceCall; -import io.scalecube.services.ServiceEndpoint; -import io.scalecube.services.annotations.Service; -import io.scalecube.services.annotations.ServiceMethod; -import io.scalecube.services.discovery.ScalecubeServiceDiscovery; -import io.scalecube.services.discovery.api.ServiceDiscovery; -import io.scalecube.services.transport.rsocket.RSocketServiceTransport; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import reactor.core.publisher.Hooks; -import reactor.core.publisher.Mono; - -import java.time.Duration; - -import static org.junit.jupiter.api.Assertions.*; - -class SpringServicesProviderTest { - - private static ScaleCube microserviceWithSpring; - private static ScaleCube microserviceWithoutSpring; - - @BeforeAll - public static void setup() { - Hooks.onOperatorDebug(); - microserviceWithSpring = microserviceWithSpring(); - microserviceWithoutSpring = microserviceWithoutSpring(); - } - - @AfterAll - public static void tearDown() { - try { - microserviceWithSpring.shutdown().block(); - } catch (Exception ignore) { - // no-op - } - - try { - microserviceWithoutSpring.shutdown().block(); - } catch (Exception ignore) { - // no-op - } - } - - private static ScaleCube microserviceWithSpring() { - return ScaleCube.builder() - .discovery(ScalecubeServiceDiscovery::new) - .transport(RSocketServiceTransport::new) - .services(new SpringServicesProvider(Beans.class)) - .startAwait(); - } - - private static ScaleCube microserviceWithoutSpring() { - return ScaleCube.builder() - .discovery(SpringServicesProviderTest::serviceDiscovery) - .transport(RSocketServiceTransport::new) - .services((SimpleService) () -> Mono.just(1L)) - .startAwait(); - } - - @Test - public void test_remote_greeting_request_completes_before_timeout() { - - LocalService service = microserviceWithSpring.call().api(LocalService.class); - - // call the service. - Mono result = - service.get(); - Long block = result.block(Duration.ofSeconds(10)); - assertEquals(-1L, block.longValue()); - } - - private static ServiceDiscovery serviceDiscovery(ServiceEndpoint endpoint) { - return new ScalecubeServiceDiscovery(endpoint) - .membership(cfg -> cfg.seedMembers(microserviceWithSpring.discovery().address())); - } - @Configuration - static class Beans { - @Bean - public LocalService localServiceBean(ServiceCall serviceCall) { - return new LocalServiceBean(serviceCall); - } - } - - @Service - public interface SimpleService { - - @ServiceMethod - Mono get(); - } - - @Service - public interface LocalService { - - @ServiceMethod - Monoget(); - } - - public static class LocalServiceBean implements LocalService { - - private final SimpleService serviceCall; - - public LocalServiceBean(ServiceCall serviceCall) { - this.serviceCall = serviceCall.api(SimpleService.class); - this.serviceCall.get().subscribe(System.out::println); - } - - public Mono get() { - return serviceCall.get().map(n -> n * -1); - } - } - -} \ No newline at end of file diff --git a/services-examples-parent/services-examples-runner/pom.xml b/services-examples-parent/services-examples-runner/pom.xml index aa36bdca6..1949f7bb2 100644 --- a/services-examples-parent/services-examples-runner/pom.xml +++ b/services-examples-parent/services-examples-runner/pom.xml @@ -10,6 +10,7 @@ scalecube-services-examples-runner + ${env.TRAVIS_COMMIT} io.scalecube.services.examples.ExamplesRunner diff --git a/services/src/main/java/io/scalecube/services/ScaleCube.java b/services/src/main/java/io/scalecube/services/ScaleCube.java index eb86dbec2..d01d034ae 100644 --- a/services/src/main/java/io/scalecube/services/ScaleCube.java +++ b/services/src/main/java/io/scalecube/services/ScaleCube.java @@ -9,8 +9,8 @@ import io.scalecube.services.exceptions.ServiceProviderErrorMapper; import io.scalecube.services.gateway.Gateway; import io.scalecube.services.gateway.GatewayOptions; -import io.scalecube.services.inject.ScaleCubeServicesProvider; -import io.scalecube.services.inject.ServiceProviderAdapter; +import io.scalecube.services.inject.ScaleCubeServicesLifeCycleManager; +import io.scalecube.services.inject.ServiceLifeCycleManagerAdapter; import io.scalecube.services.methods.MethodInfo; import io.scalecube.services.methods.ServiceMethodInvoker; import io.scalecube.services.methods.ServiceMethodRegistry; @@ -38,17 +38,21 @@ import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; + import javax.management.MBeanServer; import javax.management.ObjectName; import javax.management.StandardMBean; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; + import reactor.core.Disposable; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.core.publisher.MonoProcessor; import reactor.core.scheduler.Scheduler; import reactor.core.scheduler.Schedulers; + import sun.misc.Signal; import sun.misc.SignalHandler; @@ -122,7 +126,7 @@ public final class ScaleCube implements Microservices { private final String id = generateId(); private final Metrics metrics; private final Map tags; - private final ServicesProvider serviceProvider; + private final ServicesLifeCycleManager serviceProvider; private final ServiceRegistry serviceRegistry; private final ServiceMethodRegistry methodRegistry; private final Authenticator authenticator; @@ -138,7 +142,8 @@ private ScaleCube(Builder builder) { this.metrics = builder.metrics; this.tags = new HashMap<>(builder.tags); this.serviceProvider = - builder.serviceProviders.stream().reduce(ServicesProvider.EMPTY, ServicesProvider::union); + builder.serviceProviders.stream() + .reduce(ServicesLifeCycleManager.EMPTY, ServicesLifeCycleManager::union); this.serviceRegistry = builder.serviceRegistry; this.methodRegistry = builder.methodRegistry; this.authenticator = builder.authenticator; @@ -196,9 +201,9 @@ private Mono start() { // invoke service providers and register services - Mono> serviceInstanceSuppliers = + Mono> serviceInstances = serviceProvider - .provide(this) + .constructServices(this) .flatMapIterable(i -> i) .doOnNext(this::registerInMethodRegistry) .doOnNext( @@ -207,16 +212,16 @@ private Mono start() { ServiceScanner.scanServiceInfo(serviceInfo))) .collectList(); - return serviceInstanceSuppliers - .publishOn(scheduler) - // FIXME: 19.02.2020 if use then(Mono), incorrect order of operations - .flatMap( - ignore -> discoveryBootstrap.createInstance(serviceEndpointBuilder.build())) + Mono discoveryBootstrap = + this.discoveryBootstrap.createInstance(serviceEndpointBuilder.build()); + + return serviceInstances + .flatMap(services -> discoveryBootstrap.flatMap(ignore -> serviceProvider.postConstruct(this))) .publishOn(scheduler) .then(startGateway(call)) .publishOn(scheduler) .then(Mono.fromCallable(() -> JmxMonitorMBean.start(this))) - .then(discoveryBootstrap.startListen(this)) + .then(this.discoveryBootstrap.startListen(this)) .publishOn(scheduler) .thenReturn(this); }) @@ -328,7 +333,7 @@ public static final class Builder { private Metrics metrics; private Map tags = new HashMap<>(); - private List serviceProviders = new ArrayList<>(); + private List serviceProviders = new ArrayList<>(); private ServiceRegistry serviceRegistry = new ServiceRegistryImpl(); private ServiceMethodRegistry methodRegistry = new ServiceMethodRegistryImpl(); private Authenticator authenticator = null; @@ -353,11 +358,11 @@ public ScaleCube startAwait() { * * @param services service info instance. * @return builder - * @deprecated use {@link this#services(ServicesProvider)} + * @deprecated use {@link this#services(ServicesLifeCycleManager)} */ @Deprecated public Builder services(ServiceInfo... services) { - serviceProviders.add(ScaleCubeServicesProvider.from(services)); + serviceProviders.add(ScaleCubeServicesLifeCycleManager.from(services)); return this; } @@ -366,28 +371,28 @@ public Builder services(ServiceInfo... services) { * * @param services service instance. * @return builder - * @deprecated use {@link this#services(ServicesProvider)} + * @deprecated use {@link this#services(ServicesLifeCycleManager)} */ @Deprecated public Builder services(Object... services) { - serviceProviders.add(ScaleCubeServicesProvider.from(services)); + serviceProviders.add(ScaleCubeServicesLifeCycleManager.from(services)); return this; } /** - * Set up service provider + * Set up service provider. * * @param serviceProvider - old service provider * @return this - * @deprecated use {@link this#services(ServicesProvider)} + * @deprecated use {@link this#services(ServicesLifeCycleManager)} */ @Deprecated public Builder services(ServiceProvider serviceProvider) { - serviceProviders.add(new ServiceProviderAdapter(serviceProvider)); + serviceProviders.add(new ServiceLifeCycleManagerAdapter(serviceProvider)); return this; } - public Builder services(ServicesProvider serviceProvider) { + public Builder services(ServicesLifeCycleManager serviceProvider) { serviceProviders.add(serviceProvider); return this; } diff --git a/services/src/main/java/io/scalecube/services/inject/Injector.java b/services/src/main/java/io/scalecube/services/inject/Injector.java index ab3155a7c..70356caec 100644 --- a/services/src/main/java/io/scalecube/services/inject/Injector.java +++ b/services/src/main/java/io/scalecube/services/inject/Injector.java @@ -16,7 +16,7 @@ import reactor.core.Exceptions; /** Service Injector scan and injects beans to a given Microservices instance. */ -final class Injector { +public final class Injector { private Injector() { // Do not instantiate @@ -33,7 +33,6 @@ private Injector() { public static Object inject(Microservices microservices, Object service) { Arrays.stream(service.getClass().getDeclaredFields()) .forEach(field -> injectField(microservices, field, service)); - processAfterConstruct(microservices, service); return service; } @@ -62,7 +61,7 @@ private static void setField(Field field, Object object, Object value) { } } - private static void processAfterConstruct(Microservices microservices, Object targetInstance) { + public static void processAfterConstruct(Microservices microservices, Object targetInstance) { processMethodWithAnnotation(microservices, targetInstance, AfterConstruct.class); } diff --git a/services/src/main/java/io/scalecube/services/inject/ScaleCubeServicesProvider.java b/services/src/main/java/io/scalecube/services/inject/ScaleCubeServicesLifeCycleManager.java similarity index 63% rename from services/src/main/java/io/scalecube/services/inject/ScaleCubeServicesProvider.java rename to services/src/main/java/io/scalecube/services/inject/ScaleCubeServicesLifeCycleManager.java index 8f531225a..c9ec6f204 100644 --- a/services/src/main/java/io/scalecube/services/inject/ScaleCubeServicesProvider.java +++ b/services/src/main/java/io/scalecube/services/inject/ScaleCubeServicesLifeCycleManager.java @@ -1,35 +1,36 @@ package io.scalecube.services.inject; -import static java.util.Arrays.asList; - import io.scalecube.services.Microservices; import io.scalecube.services.ServiceInfo; -import io.scalecube.services.ServicesProvider; +import io.scalecube.services.ServicesLifeCycleManager; + +import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; + import reactor.core.publisher.Mono; -public class ScaleCubeServicesProvider implements ServicesProvider { +public class ScaleCubeServicesLifeCycleManager implements ServicesLifeCycleManager { private final Collection services; - public static ScaleCubeServicesProvider from(Object... services) { - return from(services == null ? Collections.emptyList() : asList(services)); + public static ScaleCubeServicesLifeCycleManager from(Object... services) { + return from(services == null ? Collections.emptyList() : Arrays.asList(services)); } - public static ScaleCubeServicesProvider from(Collection services) { - return new ScaleCubeServicesProvider(services); + public static ScaleCubeServicesLifeCycleManager from(Collection services) { + return new ScaleCubeServicesLifeCycleManager(services); } - private ScaleCubeServicesProvider(Collection services) { + private ScaleCubeServicesLifeCycleManager(Collection services) { this.services = services == null ? Collections.emptyList() : services; } @Override - public Mono> provide(Microservices microservices) { + public Mono> constructServices(Microservices microservices) { List services = this.services.stream() .map( @@ -50,6 +51,12 @@ public Mono> provide(Microservices microservic return Mono.just(services); } + @Override + public Mono postConstruct(Microservices microservices) { + this.services.forEach(service -> Injector.processAfterConstruct(microservices, service)); + return Mono.empty(); + } + @Override public Mono shutDown(Microservices microservices) { Stream.of(this.services) diff --git a/services/src/main/java/io/scalecube/services/inject/ServiceLifeCycleManagerAdapter.java b/services/src/main/java/io/scalecube/services/inject/ServiceLifeCycleManagerAdapter.java new file mode 100644 index 000000000..7ff4fc95e --- /dev/null +++ b/services/src/main/java/io/scalecube/services/inject/ServiceLifeCycleManagerAdapter.java @@ -0,0 +1,53 @@ +package io.scalecube.services.inject; + +import io.scalecube.services.Microservices; +import io.scalecube.services.ServiceInfo; +import io.scalecube.services.ServiceProvider; +import io.scalecube.services.ServicesLifeCycleManager; +import java.util.Collection; +import java.util.Objects; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.BiFunction; + +import reactor.core.publisher.Mono; + +public class ServiceLifeCycleManagerAdapter implements ServicesLifeCycleManager { + + // lazy + private final AtomicReference delegate; + + private final BiFunction + factory; + + /** + * Create {@link ServicesLifeCycleManager} from old {@link ServiceProvider}. + * + * @param serviceProvider old service provider. + */ + public ServiceLifeCycleManagerAdapter(ServiceProvider serviceProvider) { + this.factory = + (microservices, provider) -> + Objects.isNull(provider) + ? ScaleCubeServicesLifeCycleManager.from( + serviceProvider.provide(microservices.call())) + : provider; + this.delegate = new AtomicReference<>(EMPTY); + } + + @Override + public Mono> constructServices(Microservices microservices) { + return delegate + .updateAndGet(provider -> factory.apply(microservices, provider)) + .constructServices(microservices); + } + + @Override + public Mono postConstruct(Microservices microservices) { + return delegate.get().postConstruct(microservices); + } + + @Override + public Mono shutDown(Microservices microservices) { + return this.delegate.get().shutDown(microservices); + } +} diff --git a/services/src/main/java/io/scalecube/services/inject/ServiceProviderAdapter.java b/services/src/main/java/io/scalecube/services/inject/ServiceProviderAdapter.java deleted file mode 100644 index d0576f9c2..000000000 --- a/services/src/main/java/io/scalecube/services/inject/ServiceProviderAdapter.java +++ /dev/null @@ -1,42 +0,0 @@ -package io.scalecube.services.inject; - -import io.scalecube.services.Microservices; -import io.scalecube.services.ServiceInfo; -import io.scalecube.services.ServiceProvider; -import io.scalecube.services.ServicesProvider; -import java.util.Collection; -import java.util.Objects; -import java.util.concurrent.atomic.AtomicReference; -import java.util.function.BiFunction; -import java.util.function.BinaryOperator; -import java.util.function.UnaryOperator; -import reactor.core.publisher.Mono; - -public class ServiceProviderAdapter implements ServicesProvider { - - // lazy - private final AtomicReference delegate; - - private final BiFunction factory; - - public ServiceProviderAdapter(ServiceProvider serviceProvider) { - this.factory = - (microservices, provider) -> - Objects.isNull(provider) - ? ScaleCubeServicesProvider.from(serviceProvider.provide(microservices.call())) - : provider; - this.delegate = new AtomicReference<>(); - } - - @Override - public Mono> provide(Microservices microservices) { - return delegate - .updateAndGet(provider -> factory.apply(microservices, provider)) - .provide(microservices); - } - - @Override - public Mono shutDown(Microservices microservices) { - return this.delegate.get().shutDown(microservices); - } -} From 5fc6cac2a9e84ac834d022dc5e3b17e2f03f8a18 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=95=D0=B2=D0=B3=D0=B5=D0=BD=D0=B8=D0=B9=20=D0=A3=D1=82?= =?UTF-8?q?=D0=BA=D0=B8=D0=BD?= Date: Wed, 11 Mar 2020 13:00:34 +0300 Subject: [PATCH 13/61] ISSUE 708, WIP. Fix tests --- .../services/ServicesLifeCycleManager.java | 6 ++- .../java/io/scalecube/services/ScaleCube.java | 50 +++++++++---------- .../ScaleCubeServicesLifeCycleManager.java | 20 ++++++-- 3 files changed, 42 insertions(+), 34 deletions(-) diff --git a/services-api/src/main/java/io/scalecube/services/ServicesLifeCycleManager.java b/services-api/src/main/java/io/scalecube/services/ServicesLifeCycleManager.java index 181148b5f..bee8bac5b 100644 --- a/services-api/src/main/java/io/scalecube/services/ServicesLifeCycleManager.java +++ b/services-api/src/main/java/io/scalecube/services/ServicesLifeCycleManager.java @@ -11,7 +11,8 @@ public interface ServicesLifeCycleManager { ServicesLifeCycleManager EMPTY = new ServicesLifeCycleManager() { @Override - public Mono> constructServices(Microservices microservices) { + public Mono> constructServices( + Microservices microservices) { return Mono.just(Collections.emptyList()); } @@ -37,7 +38,8 @@ static ServicesLifeCycleManager union( ServicesLifeCycleManager provider1, ServicesLifeCycleManager provider2) { return new ServicesLifeCycleManager() { @Override - public Mono> constructServices(Microservices microservices) { + public Mono> constructServices( + Microservices microservices) { Flux services1 = flatService(microservices, provider1); Flux services2 = flatService(microservices, provider2); return services1.mergeWith(services2).collectList(); diff --git a/services/src/main/java/io/scalecube/services/ScaleCube.java b/services/src/main/java/io/scalecube/services/ScaleCube.java index d01d034ae..b74d9a024 100644 --- a/services/src/main/java/io/scalecube/services/ScaleCube.java +++ b/services/src/main/java/io/scalecube/services/ScaleCube.java @@ -192,31 +192,31 @@ private Mono start() { final ServiceCall call = call(); final Address serviceAddress = input.address; - final ServiceEndpoint.Builder serviceEndpointBuilder = - ServiceEndpoint.builder() - .id(id) - .address(serviceAddress) - .contentTypes(DataCodec.getAllContentTypes()) - .tags(tags); - // invoke service providers and register services - Mono> serviceInstances = - serviceProvider + Mono serviceInstances = + this.serviceProvider .constructServices(this) - .flatMapIterable(i -> i) - .doOnNext(this::registerInMethodRegistry) - .doOnNext( - serviceInfo -> - serviceEndpointBuilder.appendServiceRegistrations( - ServiceScanner.scanServiceInfo(serviceInfo))) - .collectList(); - - Mono discoveryBootstrap = - this.discoveryBootstrap.createInstance(serviceEndpointBuilder.build()); + .doOnNext(services -> services.forEach(this::registerInMethodRegistry)) + .map( + services -> { + final ServiceEndpoint.Builder serviceEndpointBuilder = + ServiceEndpoint.builder() + .id(id) + .address(serviceAddress) + .contentTypes(DataCodec.getAllContentTypes()) + .tags(tags); + services.forEach( + service -> + serviceEndpointBuilder.appendServiceRegistrations( + ServiceScanner.scanServiceInfo(service))); + return serviceEndpointBuilder.build(); + }); return serviceInstances - .flatMap(services -> discoveryBootstrap.flatMap(ignore -> serviceProvider.postConstruct(this))) + .flatMap(this.discoveryBootstrap::createInstance) + .publishOn(scheduler) + .then(this.serviceProvider.postConstruct(this)) .publishOn(scheduler) .then(startGateway(call)) .publishOn(scheduler) @@ -321,12 +321,8 @@ private Mono doShutdown() { }); } - private Mono processBeforeDestroy() { - return Mono.whenDelayError( - methodRegistry.listServices().stream() - .map(ServiceInfo::serviceInstance) - .map(s -> serviceProvider.shutDown(this)) - .collect(Collectors.toList())); + private Mono processBeforeDestroy() { + return serviceProvider.shutDown(this); } public static final class Builder { @@ -362,7 +358,7 @@ public ScaleCube startAwait() { */ @Deprecated public Builder services(ServiceInfo... services) { - serviceProviders.add(ScaleCubeServicesLifeCycleManager.from(services)); + serviceProviders.add(ScaleCubeServicesLifeCycleManager.from((Object[]) services)); return this; } diff --git a/services/src/main/java/io/scalecube/services/inject/ScaleCubeServicesLifeCycleManager.java b/services/src/main/java/io/scalecube/services/inject/ScaleCubeServicesLifeCycleManager.java index c9ec6f204..cc4377b26 100644 --- a/services/src/main/java/io/scalecube/services/inject/ScaleCubeServicesLifeCycleManager.java +++ b/services/src/main/java/io/scalecube/services/inject/ScaleCubeServicesLifeCycleManager.java @@ -26,7 +26,16 @@ public static ScaleCubeServicesLifeCycleManager from(Collection services) { } private ScaleCubeServicesLifeCycleManager(Collection services) { - this.services = services == null ? Collections.emptyList() : services; + this.services = + services == null + ? Collections.emptyList() + : services.stream() + .map( + service -> + service instanceof ServiceInfo + ? ((ServiceInfo) service).serviceInstance() + : service) + .collect(Collectors.toList()); } @Override @@ -53,14 +62,15 @@ public Mono> constructServices(Microservices m @Override public Mono postConstruct(Microservices microservices) { - this.services.forEach(service -> Injector.processAfterConstruct(microservices, service)); - return Mono.empty(); + return Mono.fromRunnable( + () -> + this.services.forEach( + service -> Injector.processAfterConstruct(microservices, service))); } @Override public Mono shutDown(Microservices microservices) { - Stream.of(this.services) - .forEach(service -> Injector.processBeforeDestroy(microservices, service)); + this.services.forEach(service -> Injector.processBeforeDestroy(microservices, service)); return Mono.just(microservices); } } From 695b7e8c7fcb138724783c300925d1d19135cfdf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=95=D0=B2=D0=B3=D0=B5=D0=BD=D0=B8=D0=B9=20=D0=A3=D1=82?= =?UTF-8?q?=D0=BA=D0=B8=D0=BD?= Date: Wed, 11 Mar 2020 16:05:44 +0300 Subject: [PATCH 14/61] ISSUE 708, WIP. Refactoring --- .../io/scalecube/services/ServiceInfo.java | 56 ++++++++++++ .../services/ServicesLifeCycleManager.java | 73 ++++----------- .../scalecube/services/ServicesProvider.java | 21 +++++ .../scalecube-examples-spring/pom.xml | 88 +++++++++---------- .../SpringServicesLifeCycleManager.java | 79 ----------------- .../spring/SpringServicesProvider.java | 75 ++++++++++++++++ ...t.java => SpringServicesProviderTest.java} | 6 +- .../java/io/scalecube/services/ScaleCube.java | 81 ++++++++++++----- .../scalecube/services/inject/Injector.java | 23 +++-- .../ScaleCubeServicesLifeCycleManager.java | 85 ++++++++++-------- .../ServiceLifeCycleManagerAdapter.java | 53 ----------- 11 files changed, 335 insertions(+), 305 deletions(-) create mode 100644 services-api/src/main/java/io/scalecube/services/ServicesProvider.java delete mode 100644 services-examples-parent/scalecube-examples-spring/src/main/java/io/scalecube/spring/SpringServicesLifeCycleManager.java create mode 100644 services-examples-parent/scalecube-examples-spring/src/main/java/io/scalecube/spring/SpringServicesProvider.java rename services-examples-parent/scalecube-examples-spring/src/test/java/io/scalecube/spring/{SpringServicesLifeCycleManagerTest.java => SpringServicesProviderTest.java} (94%) delete mode 100644 services/src/main/java/io/scalecube/services/inject/ServiceLifeCycleManagerAdapter.java diff --git a/services-api/src/main/java/io/scalecube/services/ServiceInfo.java b/services-api/src/main/java/io/scalecube/services/ServiceInfo.java index ff57e8a23..f73a9d8ed 100644 --- a/services-api/src/main/java/io/scalecube/services/ServiceInfo.java +++ b/services-api/src/main/java/io/scalecube/services/ServiceInfo.java @@ -90,26 +90,82 @@ private Builder(Object serviceInstance) { this.serviceInstance = serviceInstance; } + /** + * Add tag for service info. + * + * @param key tag name. + * @param value tag value. + * @return current builder's state. + */ public Builder tag(String key, String value) { tags.put(key, value); return this; } + /** + * Set up {@link ServiceProviderErrorMapper}. + * + * @param errorMapper error mapper. + * @return current builder's state. + */ public Builder errorMapper(ServiceProviderErrorMapper errorMapper) { this.errorMapper = errorMapper; return this; } + /** + * Set up {@link ServiceMessageDataDecoder}. + * + * @param dataDecoder data decoder. + * @return current builder's state. + */ public Builder dataDecoder(ServiceMessageDataDecoder dataDecoder) { this.dataDecoder = dataDecoder; return this; } + /** + * Set up {@link ServiceProviderErrorMapper} if it hasn't been set up before. + * + * @param errorMapper error mapper. + * @return current builder's state. + */ + public Builder errorMapperIfAbsent(ServiceProviderErrorMapper errorMapper) { + if (this.errorMapper == null) { + this.errorMapper = errorMapper; + } + return this; + } + + /** + * Set up {@link ServiceMessageDataDecoder} if it hasn't been set up before. + * + * @param dataDecoder data decoder. + * @return current builder's state. + */ + public Builder dataDecoderIfAbsent(ServiceMessageDataDecoder dataDecoder) { + if (this.dataDecoder == null) { + this.dataDecoder = dataDecoder; + } + return this; + } + + /** + * Set up {@link Authenticator}. + * + * @param authenticator authenticator. + * @return current builder's state. + */ public Builder authenticator(Authenticator authenticator) { this.authenticator = authenticator; return this; } + /** + * Build service info. + * + * @return service info. + */ public ServiceInfo build() { return new ServiceInfo(this); } diff --git a/services-api/src/main/java/io/scalecube/services/ServicesLifeCycleManager.java b/services-api/src/main/java/io/scalecube/services/ServicesLifeCycleManager.java index bee8bac5b..bb1532c00 100644 --- a/services-api/src/main/java/io/scalecube/services/ServicesLifeCycleManager.java +++ b/services-api/src/main/java/io/scalecube/services/ServicesLifeCycleManager.java @@ -1,72 +1,33 @@ package io.scalecube.services; import java.util.Collection; -import java.util.Collections; -import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; -public interface ServicesLifeCycleManager { - - ServicesLifeCycleManager EMPTY = - new ServicesLifeCycleManager() { - @Override - public Mono> constructServices( - Microservices microservices) { - return Mono.just(Collections.emptyList()); - } - - @Override - public Mono postConstruct(Microservices microservices) { - return Mono.empty(); - } - - @Override - public Mono shutDown(Microservices microservices) { - return Mono.just(microservices); - } - }; +/** Manages the life cycle of all services registered with Scale Cube Services. */ +interface ServicesLifeCycleManager { /** - * Union of two services providers. + * Create services. * - * @param provider1 first provider - * @param provider2 second provider - * @return provider + * @param microservices scale cube instance. + * @return collection of created services in Mono. */ - static ServicesLifeCycleManager union( - ServicesLifeCycleManager provider1, ServicesLifeCycleManager provider2) { - return new ServicesLifeCycleManager() { - @Override - public Mono> constructServices( - Microservices microservices) { - Flux services1 = flatService(microservices, provider1); - Flux services2 = flatService(microservices, provider2); - return services1.mergeWith(services2).collectList(); - } - - @Override - public Mono postConstruct(Microservices microservices) { - Mono void1 = provider1.postConstruct(microservices); - Mono void2 = provider2.postConstruct(microservices); - return void1.then(void2); - } - - @Override - public Mono shutDown(Microservices microservices) { - return provider1.shutDown(microservices).then(provider2.shutDown(microservices)); - } - - private Flux flatService( - Microservices microservices, ServicesLifeCycleManager provider) { - return provider.constructServices(microservices).flatMapIterable(i -> i); - } - }; - } - Mono> constructServices(Microservices microservices); + /** + * Initializes instances of services. + * + * @param microservices scale cube instance. + * @return Completed Mono if initialization was successful for all services. + */ Mono postConstruct(Microservices microservices); + /** + * Finalization of service instances. + * + * @param microservices scale cube instance. + * @return completed Mono if finalization was successful for all services. + */ Mono shutDown(Microservices microservices); } diff --git a/services-api/src/main/java/io/scalecube/services/ServicesProvider.java b/services-api/src/main/java/io/scalecube/services/ServicesProvider.java new file mode 100644 index 000000000..d31b7a1d6 --- /dev/null +++ b/services-api/src/main/java/io/scalecube/services/ServicesProvider.java @@ -0,0 +1,21 @@ +package io.scalecube.services; + +import java.util.Collection; + +import reactor.core.publisher.Mono; + +/** + * Type alias for {@link ServicesLifeCycleManager}, for better display of semantics. + */ +public interface ServicesProvider extends ServicesLifeCycleManager { + + /** + * Method alias for {@link ServicesLifeCycleManager#constructServices(Microservices)}. + * + * @param microservices scale cube instance. + * @return collection services. + */ + default Mono> provide(Microservices microservices) { + return this.constructServices(microservices); + } +} diff --git a/services-examples-parent/scalecube-examples-spring/pom.xml b/services-examples-parent/scalecube-examples-spring/pom.xml index 3deb5772b..4d990076a 100644 --- a/services-examples-parent/scalecube-examples-spring/pom.xml +++ b/services-examples-parent/scalecube-examples-spring/pom.xml @@ -2,51 +2,51 @@ - - scalecube-services-examples-parent - io.scalecube - 2.8.10-SNAPSHOT - - 4.0.0 + + scalecube-services-examples-parent + io.scalecube + 2.8.10-SNAPSHOT + + 4.0.0 - scalecube-examples-spring + scalecube-examples-spring - - - io.scalecube - scalecube-services - ${project.version} - - - io.scalecube - scalecube-services-discovery - ${project.version} - - - io.scalecube - scalecube-services-transport-rsocket - ${project.version} - - - io.scalecube - scalecube-services-transport-jackson - ${project.version} - - - org.springframework - spring-core - LATEST - - - org.springframework - spring-beans - LATEST - - - org.springframework - spring-context - LATEST - - + + + io.scalecube + scalecube-services + ${project.version} + + + io.scalecube + scalecube-services-discovery + ${project.version} + + + io.scalecube + scalecube-services-transport-rsocket + ${project.version} + + + io.scalecube + scalecube-services-transport-jackson + ${project.version} + + + org.springframework + spring-core + LATEST + + + org.springframework + spring-beans + LATEST + + + org.springframework + spring-context + LATEST + + \ No newline at end of file diff --git a/services-examples-parent/scalecube-examples-spring/src/main/java/io/scalecube/spring/SpringServicesLifeCycleManager.java b/services-examples-parent/scalecube-examples-spring/src/main/java/io/scalecube/spring/SpringServicesLifeCycleManager.java deleted file mode 100644 index b90c8e993..000000000 --- a/services-examples-parent/scalecube-examples-spring/src/main/java/io/scalecube/spring/SpringServicesLifeCycleManager.java +++ /dev/null @@ -1,79 +0,0 @@ -package io.scalecube.spring; - -import io.scalecube.services.Microservices; -import io.scalecube.services.ServiceCall; -import io.scalecube.services.ServiceInfo; -import io.scalecube.services.ServicesLifeCycleManager; -import io.scalecube.services.annotations.Service; -import io.scalecube.services.discovery.api.ServiceDiscovery; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import reactor.core.publisher.Mono; - -import java.util.Collection; -import java.util.List; -import java.util.Objects; -import java.util.concurrent.atomic.AtomicReference; -import java.util.function.BiFunction; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -public class SpringServicesLifeCycleManager implements ServicesLifeCycleManager { - - private final BiFunction< - Microservices, AnnotationConfigApplicationContext, AnnotationConfigApplicationContext> - ctxFactory; - - private final AtomicReference ctx = new AtomicReference<>(); - - public SpringServicesLifeCycleManager(Class... configurations) { - this.ctxFactory = - (microservices, ctx) -> { - if (Objects.nonNull(ctx)) { - return ctx; - } - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); - context.registerBean(ServiceCall.class, microservices::call); - Stream.of(configurations).forEach(context::register); - return context; - }; - } - - @Override - public Mono> constructServices(Microservices microservices) { - AnnotationConfigApplicationContext context = - this.ctx.updateAndGet(c -> ctxFactory.apply(microservices, c)); - List beans = - context.getBeansWithAnnotation(Service.class).values().stream() - .map(bean -> ServiceInfo.fromServiceInstance(bean).build()) - .collect(Collectors.toList()); - return Mono.just(beans); - } - - @Override - public Mono postConstruct(Microservices microservices) { - Mono ctxMono = - Mono.just( - this.ctx.updateAndGet( - ctx -> { - ctx.registerBean(ServiceDiscovery.class, microservices::discovery); - ctx.refresh(); - ctx.start(); - return ctx; - })); - return Mono.defer(() -> ctxMono).then(); - } - - @Override - public Mono shutDown(Microservices microservices) { - return Mono.fromCallable( - () -> { - this.ctx.updateAndGet( - ctx -> { - ctx.stop(); - ctx.close(); - return ctx; - }); - return microservices; - }); - } -} diff --git a/services-examples-parent/scalecube-examples-spring/src/main/java/io/scalecube/spring/SpringServicesProvider.java b/services-examples-parent/scalecube-examples-spring/src/main/java/io/scalecube/spring/SpringServicesProvider.java new file mode 100644 index 000000000..71e696d33 --- /dev/null +++ b/services-examples-parent/scalecube-examples-spring/src/main/java/io/scalecube/spring/SpringServicesProvider.java @@ -0,0 +1,75 @@ +package io.scalecube.spring; + +import io.scalecube.services.Microservices; +import io.scalecube.services.ServiceCall; +import io.scalecube.services.ServiceInfo; +import io.scalecube.services.ServicesProvider; +import io.scalecube.services.annotations.Service; +import io.scalecube.services.discovery.api.ServiceDiscovery; + +import java.util.Collection; +import java.util.List; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +import reactor.core.publisher.Mono; + +public class SpringServicesProvider implements ServicesProvider { + + private final Function ctxFactory; + + // lazy init + private AnnotationConfigApplicationContext ctx; + + /** + * Create the instance from Spring Context. + * + * @param configurations spring configurations. + */ + public SpringServicesProvider(Class... configurations) { + this.ctxFactory = + microservices -> { + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); + ServiceCall serviceCall = microservices.call(); + context.registerBean(ServiceCall.class, () -> serviceCall); + Stream.of(configurations).forEach(context::register); + return context; + }; + } + + @Override + public Mono> constructServices(Microservices microservices) { + this.ctx = this.ctxFactory.apply(microservices); + List beans = + this.ctx.getBeansWithAnnotation(Service.class).values().stream() + .map(bean -> ServiceInfo.fromServiceInstance(bean).build()) + .collect(Collectors.toList()); + return Mono.just(beans); + } + + @Override + public Mono postConstruct(Microservices microservices) { + Mono ctxMono = + Mono.fromCallable( + () -> { + this.ctx.registerBean(ServiceDiscovery.class, microservices::discovery); + this.ctx.refresh(); + this.ctx.start(); + return this.ctx; + }); + return Mono.defer(() -> ctxMono).then(); + } + + @Override + public Mono shutDown(Microservices microservices) { + return Mono.fromCallable( + () -> { + this.ctx.stop(); + this.ctx.close(); + return microservices; + }); + } +} diff --git a/services-examples-parent/scalecube-examples-spring/src/test/java/io/scalecube/spring/SpringServicesLifeCycleManagerTest.java b/services-examples-parent/scalecube-examples-spring/src/test/java/io/scalecube/spring/SpringServicesProviderTest.java similarity index 94% rename from services-examples-parent/scalecube-examples-spring/src/test/java/io/scalecube/spring/SpringServicesLifeCycleManagerTest.java rename to services-examples-parent/scalecube-examples-spring/src/test/java/io/scalecube/spring/SpringServicesProviderTest.java index b44e5e972..de823788e 100644 --- a/services-examples-parent/scalecube-examples-spring/src/test/java/io/scalecube/spring/SpringServicesLifeCycleManagerTest.java +++ b/services-examples-parent/scalecube-examples-spring/src/test/java/io/scalecube/spring/SpringServicesProviderTest.java @@ -20,7 +20,7 @@ import static org.junit.jupiter.api.Assertions.*; -class SpringServicesLifeCycleManagerTest { +class SpringServicesProviderTest { private static ScaleCube microserviceWithSpring; private static ScaleCube microserviceWithoutSpring; @@ -51,13 +51,13 @@ private static ScaleCube microserviceWithSpring() { return ScaleCube.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) - .services(new SpringServicesLifeCycleManager(Beans.class)) + .serviceProvider(new SpringServicesProvider(Beans.class)) .startAwait(); } private static ScaleCube microserviceWithoutSpring() { return ScaleCube.builder() - .discovery(SpringServicesLifeCycleManagerTest::serviceDiscovery) + .discovery(SpringServicesProviderTest::serviceDiscovery) .transport(RSocketServiceTransport::new) .services((SimpleService) () -> Mono.just(1L)) .startAwait(); diff --git a/services/src/main/java/io/scalecube/services/ScaleCube.java b/services/src/main/java/io/scalecube/services/ScaleCube.java index b74d9a024..928b83bee 100644 --- a/services/src/main/java/io/scalecube/services/ScaleCube.java +++ b/services/src/main/java/io/scalecube/services/ScaleCube.java @@ -10,7 +10,6 @@ import io.scalecube.services.gateway.Gateway; import io.scalecube.services.gateway.GatewayOptions; import io.scalecube.services.inject.ScaleCubeServicesLifeCycleManager; -import io.scalecube.services.inject.ServiceLifeCycleManagerAdapter; import io.scalecube.services.methods.MethodInfo; import io.scalecube.services.methods.ServiceMethodInvoker; import io.scalecube.services.methods.ServiceMethodRegistry; @@ -28,6 +27,7 @@ import java.lang.management.ManagementFactory; import java.util.ArrayList; +import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -38,6 +38,7 @@ import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; +import java.util.stream.Stream; import javax.management.MBeanServer; import javax.management.ObjectName; @@ -126,7 +127,7 @@ public final class ScaleCube implements Microservices { private final String id = generateId(); private final Metrics metrics; private final Map tags; - private final ServicesLifeCycleManager serviceProvider; + private final ServicesProvider servicesProvider; private final ServiceRegistry serviceRegistry; private final ServiceMethodRegistry methodRegistry; private final Authenticator authenticator; @@ -141,9 +142,9 @@ public final class ScaleCube implements Microservices { private ScaleCube(Builder builder) { this.metrics = builder.metrics; this.tags = new HashMap<>(builder.tags); - this.serviceProvider = - builder.serviceProviders.stream() - .reduce(ServicesLifeCycleManager.EMPTY, ServicesLifeCycleManager::union); + + this.servicesProvider = builder.servicesProvider; + this.serviceRegistry = builder.serviceRegistry; this.methodRegistry = builder.methodRegistry; this.authenticator = builder.authenticator; @@ -195,8 +196,8 @@ private Mono start() { // invoke service providers and register services Mono serviceInstances = - this.serviceProvider - .constructServices(this) + this.servicesProvider + .provide(this) .doOnNext(services -> services.forEach(this::registerInMethodRegistry)) .map( services -> { @@ -216,7 +217,7 @@ private Mono start() { return serviceInstances .flatMap(this.discoveryBootstrap::createInstance) .publishOn(scheduler) - .then(this.serviceProvider.postConstruct(this)) + .then(this.servicesProvider.postConstruct(this)) .publishOn(scheduler) .then(startGateway(call)) .publishOn(scheduler) @@ -322,14 +323,16 @@ private Mono doShutdown() { } private Mono processBeforeDestroy() { - return serviceProvider.shutDown(this); + return servicesProvider.shutDown(this); } public static final class Builder { private Metrics metrics; private Map tags = new HashMap<>(); - private List serviceProviders = new ArrayList<>(); + private List services = new ArrayList<>(); + private List serviceProviders = new ArrayList<>(); + private ServicesProvider servicesProvider; private ServiceRegistry serviceRegistry = new ServiceRegistryImpl(); private ServiceMethodRegistry methodRegistry = new ServiceMethodRegistryImpl(); private Authenticator authenticator = null; @@ -341,7 +344,27 @@ public static final class Builder { Optional.ofNullable(ServiceMessageDataDecoder.INSTANCE) .orElse((message, dataType) -> message); + private void build() { + ServiceProvider serviceProvider = + this.services.stream() + .map( + service -> + ServiceInfo.from(service) + .dataDecoderIfAbsent(this.dataDecoder) + .errorMapperIfAbsent(this.errorMapper) + .build()) + .collect( + Collectors.collectingAndThen( + Collectors.toList(), services -> (ServiceProvider) call -> services)); + this.serviceProviders.add(serviceProvider); + this.servicesProvider = + this.servicesProvider == null + ? ScaleCubeServicesLifeCycleManager.create(this.serviceProviders) + : this.servicesProvider; + } + public Mono start() { + build(); return Mono.defer(() -> new ScaleCube(this).start()); } @@ -352,44 +375,58 @@ public ScaleCube startAwait() { /** * Adds service instance to microservice. * + *

WARNING This service will be ignored if custom {@link ServicesProvider} + * is installed. This method has been left for backward compatibility only and will be removed + * in future releases. + * * @param services service info instance. * @return builder - * @deprecated use {@link this#services(ServicesLifeCycleManager)} + * @deprecated use {@link this#serviceProvider(ServicesProvider)} */ @Deprecated public Builder services(ServiceInfo... services) { - serviceProviders.add(ScaleCubeServicesLifeCycleManager.from((Object[]) services)); + this.services.addAll(Arrays.asList(services)); return this; } /** * Adds service instance to microservice. * + *

WARNING This service will be ignored if custom {@link ServicesProvider} + * is installed. This method has been left for backward compatibility only and will be removed + * in future releases. + * * @param services service instance. * @return builder - * @deprecated use {@link this#services(ServicesLifeCycleManager)} + * @deprecated use {@link this#serviceProvider(ServicesProvider)} */ @Deprecated public Builder services(Object... services) { - serviceProviders.add(ScaleCubeServicesLifeCycleManager.from(services)); + Stream.of(services) + .map(service -> ServiceInfo.fromServiceInstance(service).build()) + .forEach(this.services::add); return this; } /** * Set up service provider. * + *

WARNING This service will be ignored if custom {@link ServicesProvider} + * is installed. This method has been left for backward compatibility only and will be removed + * in future releases. + * * @param serviceProvider - old service provider * @return this - * @deprecated use {@link this#services(ServicesLifeCycleManager)} + * @deprecated use {@link this#serviceProvider(ServicesProvider)} */ @Deprecated public Builder services(ServiceProvider serviceProvider) { - serviceProviders.add(new ServiceLifeCycleManagerAdapter(serviceProvider)); + this.serviceProviders.add(serviceProvider); return this; } - public Builder services(ServicesLifeCycleManager serviceProvider) { - serviceProviders.add(serviceProvider); + public Builder serviceProvider(ServicesProvider serviceProvider) { + this.servicesProvider = serviceProvider; return this; } @@ -470,17 +507,17 @@ private Mono createInstance(ServiceEndpoint serviceEndpoint) { private Mono startListen(ScaleCube microservices) { return Mono.defer( () -> { - if (discovery == null) { + if (this.discovery == null) { LOGGER.info("[{}] ServiceDiscovery not set", microservices.id()); return Mono.empty(); } - disposable = - discovery + this.disposable = + this.discovery .listenDiscovery() .subscribe(event -> onDiscoveryEvent(microservices, event)); - return discovery + return this.discovery .start() .doOnSuccess(discovery -> this.discovery = discovery) .doOnSubscribe( diff --git a/services/src/main/java/io/scalecube/services/inject/Injector.java b/services/src/main/java/io/scalecube/services/inject/Injector.java index 70356caec..0508427c0 100644 --- a/services/src/main/java/io/scalecube/services/inject/Injector.java +++ b/services/src/main/java/io/scalecube/services/inject/Injector.java @@ -4,15 +4,17 @@ import io.scalecube.services.Reflect; import io.scalecube.services.ScaleCube; import io.scalecube.services.ServiceCall; +import io.scalecube.services.ServiceInfo; import io.scalecube.services.annotations.AfterConstruct; import io.scalecube.services.annotations.BeforeDestroy; import io.scalecube.services.annotations.Inject; import io.scalecube.services.routing.Router; + import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Arrays; -import java.util.Collection; + import reactor.core.Exceptions; /** Service Injector scan and injects beans to a given Microservices instance. */ @@ -30,13 +32,13 @@ private Injector() { * @param service service * @return service instance */ - public static Object inject(Microservices microservices, Object service) { - Arrays.stream(service.getClass().getDeclaredFields()) - .forEach(field -> injectField(microservices, field, service)); + public static ServiceInfo inject(Microservices microservices, ServiceInfo service) { + Object serviceInstance = service.serviceInstance(); + Arrays.stream(serviceInstance.getClass().getDeclaredFields()) + .forEach(field -> injectField(microservices, field, serviceInstance)); return service; } - private static void injectField(Microservices microservices, Field field, Object service) { if (field.isAnnotationPresent(Inject.class) && field.getType().equals(ScaleCube.class)) { setField(field, service, microservices); @@ -61,12 +63,15 @@ private static void setField(Field field, Object object, Object value) { } } - public static void processAfterConstruct(Microservices microservices, Object targetInstance) { - processMethodWithAnnotation(microservices, targetInstance, AfterConstruct.class); + public static void processAfterConstruct( + Microservices microservices, ServiceInfo targetInstance) { + processMethodWithAnnotation( + microservices, targetInstance.serviceInstance(), AfterConstruct.class); } - public static void processBeforeDestroy(Microservices microservices, Object targetInstance) { - processMethodWithAnnotation(microservices, targetInstance, BeforeDestroy.class); + public static void processBeforeDestroy(Microservices microservices, ServiceInfo targetInstance) { + processMethodWithAnnotation( + microservices, targetInstance.serviceInstance(), BeforeDestroy.class); } private static void processMethodWithAnnotation( diff --git a/services/src/main/java/io/scalecube/services/inject/ScaleCubeServicesLifeCycleManager.java b/services/src/main/java/io/scalecube/services/inject/ScaleCubeServicesLifeCycleManager.java index cc4377b26..8261b3897 100644 --- a/services/src/main/java/io/scalecube/services/inject/ScaleCubeServicesLifeCycleManager.java +++ b/services/src/main/java/io/scalecube/services/inject/ScaleCubeServicesLifeCycleManager.java @@ -2,64 +2,65 @@ import io.scalecube.services.Microservices; import io.scalecube.services.ServiceInfo; -import io.scalecube.services.ServicesLifeCycleManager; +import io.scalecube.services.ServiceProvider; +import io.scalecube.services.ServicesProvider; -import java.util.Arrays; import java.util.Collection; -import java.util.Collections; -import java.util.List; +import java.util.function.Function; import java.util.stream.Collectors; -import java.util.stream.Stream; import reactor.core.publisher.Mono; -public class ScaleCubeServicesLifeCycleManager implements ServicesLifeCycleManager { +/** + * Default {@link ServicesProvider}. + */ +public class ScaleCubeServicesLifeCycleManager implements ServicesProvider { - private final Collection services; + private final Function> serviceFactory; - public static ScaleCubeServicesLifeCycleManager from(Object... services) { - return from(services == null ? Collections.emptyList() : Arrays.asList(services)); - } + // lazy init + private Collection services; - public static ScaleCubeServicesLifeCycleManager from(Collection services) { - return new ScaleCubeServicesLifeCycleManager(services); + /** + * Create instance from {@link ServiceProvider}. + * + * @param serviceProviders old service providers. + * @return default services provider. + */ + public static ServicesProvider create(Collection serviceProviders) { + return new ScaleCubeServicesLifeCycleManager(serviceProviders); } - private ScaleCubeServicesLifeCycleManager(Collection services) { - this.services = - services == null - ? Collections.emptyList() - : services.stream() - .map( - service -> - service instanceof ServiceInfo - ? ((ServiceInfo) service).serviceInstance() - : service) + private ScaleCubeServicesLifeCycleManager(Collection serviceProviders) { + this.serviceFactory = + microservices -> + serviceProviders.stream() + .map(serviceProvider -> serviceProvider.provide(microservices.call())) + .flatMap(Collection::stream) .collect(Collectors.toList()); } + /** + * {@inheritDoc} + * + *

Use {@link io.scalecube.services.annotations.Inject} for inject {@link Microservices}, + * {@link io.scalecube.services.ServiceCall}. + */ @Override public Mono> constructServices(Microservices microservices) { - List services = - this.services.stream() - .map( - service -> { - Object serviceInstance; - ServiceInfo serviceInfo; - if (service instanceof ServiceInfo) { - serviceInfo = (ServiceInfo) service; - serviceInstance = serviceInfo.serviceInstance(); - } else { - serviceInstance = service; - serviceInfo = ServiceInfo.fromServiceInstance(serviceInstance).build(); - } - Injector.inject(microservices, serviceInstance); - return serviceInfo; - }) + this.services = + this.serviceFactory.apply(microservices).stream() + .map(service -> Injector.inject(microservices, service)) .collect(Collectors.toList()); - return Mono.just(services); + return Mono.just(this.services); } + /** + * {@inheritDoc} + * + *

Use {@link io.scalecube.services.annotations.AfterConstruct} for initialization service's + * instance. + */ @Override public Mono postConstruct(Microservices microservices) { return Mono.fromRunnable( @@ -68,6 +69,12 @@ public Mono postConstruct(Microservices microservices) { service -> Injector.processAfterConstruct(microservices, service))); } + /** + * {@inheritDoc} + * + *

Use {@link io.scalecube.services.annotations.BeforeDestroy} for finilization service's + * instance. + */ @Override public Mono shutDown(Microservices microservices) { this.services.forEach(service -> Injector.processBeforeDestroy(microservices, service)); diff --git a/services/src/main/java/io/scalecube/services/inject/ServiceLifeCycleManagerAdapter.java b/services/src/main/java/io/scalecube/services/inject/ServiceLifeCycleManagerAdapter.java deleted file mode 100644 index 7ff4fc95e..000000000 --- a/services/src/main/java/io/scalecube/services/inject/ServiceLifeCycleManagerAdapter.java +++ /dev/null @@ -1,53 +0,0 @@ -package io.scalecube.services.inject; - -import io.scalecube.services.Microservices; -import io.scalecube.services.ServiceInfo; -import io.scalecube.services.ServiceProvider; -import io.scalecube.services.ServicesLifeCycleManager; -import java.util.Collection; -import java.util.Objects; -import java.util.concurrent.atomic.AtomicReference; -import java.util.function.BiFunction; - -import reactor.core.publisher.Mono; - -public class ServiceLifeCycleManagerAdapter implements ServicesLifeCycleManager { - - // lazy - private final AtomicReference delegate; - - private final BiFunction - factory; - - /** - * Create {@link ServicesLifeCycleManager} from old {@link ServiceProvider}. - * - * @param serviceProvider old service provider. - */ - public ServiceLifeCycleManagerAdapter(ServiceProvider serviceProvider) { - this.factory = - (microservices, provider) -> - Objects.isNull(provider) - ? ScaleCubeServicesLifeCycleManager.from( - serviceProvider.provide(microservices.call())) - : provider; - this.delegate = new AtomicReference<>(EMPTY); - } - - @Override - public Mono> constructServices(Microservices microservices) { - return delegate - .updateAndGet(provider -> factory.apply(microservices, provider)) - .constructServices(microservices); - } - - @Override - public Mono postConstruct(Microservices microservices) { - return delegate.get().postConstruct(microservices); - } - - @Override - public Mono shutDown(Microservices microservices) { - return this.delegate.get().shutDown(microservices); - } -} From c73d5e4229f6e9abc166a6fd9d9990a5d1346802 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=95=D0=B2=D0=B3=D0=B5=D0=BD=D0=B8=D0=B9=20=D0=A3=D1=82?= =?UTF-8?q?=D0=BA=D0=B8=D0=BD?= Date: Wed, 11 Mar 2020 16:22:19 +0300 Subject: [PATCH 15/61] ISSUE 708, Set spring version --- .../scalecube-examples-spring/pom.xml | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/services-examples-parent/scalecube-examples-spring/pom.xml b/services-examples-parent/scalecube-examples-spring/pom.xml index 4d990076a..f3296f257 100644 --- a/services-examples-parent/scalecube-examples-spring/pom.xml +++ b/services-examples-parent/scalecube-examples-spring/pom.xml @@ -35,18 +35,21 @@ org.springframework spring-core - LATEST + ${spring.version} org.springframework spring-beans - LATEST + ${spring.version} org.springframework spring-context - LATEST + ${spring.version} + + 5.2.4.RELEASE + \ No newline at end of file From 5cde334589419f45691b5a86a7b245a6144c6b36 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=95=D0=B2=D0=B3=D0=B5=D0=BD=D0=B8=D0=B9=20=D0=A3=D1=82?= =?UTF-8?q?=D0=BA=D0=B8=D0=BD?= Date: Thu, 12 Mar 2020 12:10:09 +0300 Subject: [PATCH 16/61] ISSUE 708, replace ServiceInfo to ServiceDefinition for ServiceEndpoint generation --- .../io/scalecube/services/Microservices.java | 2 + .../scalecube/services/ServiceDefinition.java | 23 +++++++ .../scalecube/services/ServiceProvider.java | 2 +- .../io/scalecube/services/ServiceScanner.java | 10 +-- .../services/ServicesLifeCycleManager.java | 33 ---------- .../scalecube/services/ServicesProvider.java | 32 ++++++--- .../spring/SpringServicesProvider.java | 60 ++++++++++++----- .../spring/SpringServicesProviderTest.java | 3 +- .../java/io/scalecube/services/ScaleCube.java | 65 +++++++++++-------- .../scalecube/services/inject/Injector.java | 20 ++++-- ...er.java => ScaleCubeServicesProvider.java} | 38 +++++++---- 11 files changed, 176 insertions(+), 112 deletions(-) create mode 100644 services-api/src/main/java/io/scalecube/services/ServiceDefinition.java delete mode 100644 services-api/src/main/java/io/scalecube/services/ServicesLifeCycleManager.java rename services/src/main/java/io/scalecube/services/inject/{ScaleCubeServicesLifeCycleManager.java => ScaleCubeServicesProvider.java} (57%) diff --git a/services-api/src/main/java/io/scalecube/services/Microservices.java b/services-api/src/main/java/io/scalecube/services/Microservices.java index 3de736a49..f700f672f 100644 --- a/services-api/src/main/java/io/scalecube/services/Microservices.java +++ b/services-api/src/main/java/io/scalecube/services/Microservices.java @@ -5,6 +5,8 @@ public interface Microservices { + String id(); + ServiceCall call(); Address serviceAddress(); diff --git a/services-api/src/main/java/io/scalecube/services/ServiceDefinition.java b/services-api/src/main/java/io/scalecube/services/ServiceDefinition.java new file mode 100644 index 000000000..0e33ac152 --- /dev/null +++ b/services-api/src/main/java/io/scalecube/services/ServiceDefinition.java @@ -0,0 +1,23 @@ +package io.scalecube.services; + +import java.util.Map; + +/** Definition of service - type and tags. */ +public class ServiceDefinition { + + private final Class serviceType; + private final Map tags; + + public ServiceDefinition(Class serviceType, Map tags) { + this.serviceType = serviceType; + this.tags = tags; + } + + public Class type() { + return serviceType; + } + + public Map tags() { + return tags; + } +} diff --git a/services-api/src/main/java/io/scalecube/services/ServiceProvider.java b/services-api/src/main/java/io/scalecube/services/ServiceProvider.java index adbdd81b2..92faa6f1e 100644 --- a/services-api/src/main/java/io/scalecube/services/ServiceProvider.java +++ b/services-api/src/main/java/io/scalecube/services/ServiceProvider.java @@ -5,7 +5,7 @@ /** * Provide service instances. * - * @deprecated use {@link ServicesLifeCycleManager} + * @deprecated use {@link ServicesProvider} */ @FunctionalInterface @Deprecated diff --git a/services-api/src/main/java/io/scalecube/services/ServiceScanner.java b/services-api/src/main/java/io/scalecube/services/ServiceScanner.java index 208e5dda6..92280cac0 100644 --- a/services-api/src/main/java/io/scalecube/services/ServiceScanner.java +++ b/services-api/src/main/java/io/scalecube/services/ServiceScanner.java @@ -1,6 +1,5 @@ package io.scalecube.services; -import io.scalecube.services.annotations.Service; import io.scalecube.services.annotations.ServiceMethod; import java.util.Arrays; import java.util.Collections; @@ -18,14 +17,15 @@ private ServiceScanner() { /** * Scans {@code ServiceInfo} and builds list of {@code ServiceRegistration}-s. * - * @param serviceInfo service info instance + * @param serviceDefinition service info instance * @return list of {@code ServiceRegistration}-s */ - public static List scanServiceInfo(ServiceInfo serviceInfo) { - return Reflect.serviceInterfaces(serviceInfo.type()) + public static List scanServiceDefinition( + ServiceDefinition serviceDefinition) { + return Reflect.serviceInterfaces(serviceDefinition.type()) .map( serviceInterface -> { - Map serviceInfoTags = serviceInfo.tags(); + Map serviceInfoTags = serviceDefinition.tags(); Map apiTags = Reflect.serviceTags(serviceInterface); Map buffer = new HashMap<>(apiTags); // service tags override tags from @Service diff --git a/services-api/src/main/java/io/scalecube/services/ServicesLifeCycleManager.java b/services-api/src/main/java/io/scalecube/services/ServicesLifeCycleManager.java deleted file mode 100644 index bb1532c00..000000000 --- a/services-api/src/main/java/io/scalecube/services/ServicesLifeCycleManager.java +++ /dev/null @@ -1,33 +0,0 @@ -package io.scalecube.services; - -import java.util.Collection; - -import reactor.core.publisher.Mono; - -/** Manages the life cycle of all services registered with Scale Cube Services. */ -interface ServicesLifeCycleManager { - - /** - * Create services. - * - * @param microservices scale cube instance. - * @return collection of created services in Mono. - */ - Mono> constructServices(Microservices microservices); - - /** - * Initializes instances of services. - * - * @param microservices scale cube instance. - * @return Completed Mono if initialization was successful for all services. - */ - Mono postConstruct(Microservices microservices); - - /** - * Finalization of service instances. - * - * @param microservices scale cube instance. - * @return completed Mono if finalization was successful for all services. - */ - Mono shutDown(Microservices microservices); -} diff --git a/services-api/src/main/java/io/scalecube/services/ServicesProvider.java b/services-api/src/main/java/io/scalecube/services/ServicesProvider.java index d31b7a1d6..cb654bdda 100644 --- a/services-api/src/main/java/io/scalecube/services/ServicesProvider.java +++ b/services-api/src/main/java/io/scalecube/services/ServicesProvider.java @@ -4,18 +4,32 @@ import reactor.core.publisher.Mono; -/** - * Type alias for {@link ServicesLifeCycleManager}, for better display of semantics. - */ -public interface ServicesProvider extends ServicesLifeCycleManager { +/** Manages the life cycle of all services registered with Scale Cube Services. */ +public interface ServicesProvider { /** - * Method alias for {@link ServicesLifeCycleManager#constructServices(Microservices)}. + * Provide service definitions. * * @param microservices scale cube instance. - * @return collection services. + * @return collection of service definitions - service type&tags. + * @see ServiceDefinition */ - default Mono> provide(Microservices microservices) { - return this.constructServices(microservices); - } + Mono> provideServiceDefinitions( + Microservices microservices); + + /** + * Initialize instances of services. + * + * @param microservices scale cube instance. + * @return Completed Mono if initialization was successful for all services. + */ + Mono> provideService(Microservices microservices); + + /** + * Finalization of service instances. + * + * @param microservices scale cube instance. + * @return completed Mono if finalization was successful for all services. + */ + Mono shutDown(Microservices microservices); } diff --git a/services-examples-parent/scalecube-examples-spring/src/main/java/io/scalecube/spring/SpringServicesProvider.java b/services-examples-parent/scalecube-examples-spring/src/main/java/io/scalecube/spring/SpringServicesProvider.java index 71e696d33..5132df05b 100644 --- a/services-examples-parent/scalecube-examples-spring/src/main/java/io/scalecube/spring/SpringServicesProvider.java +++ b/services-examples-parent/scalecube-examples-spring/src/main/java/io/scalecube/spring/SpringServicesProvider.java @@ -2,19 +2,25 @@ import io.scalecube.services.Microservices; import io.scalecube.services.ServiceCall; +import io.scalecube.services.ServiceDefinition; import io.scalecube.services.ServiceInfo; import io.scalecube.services.ServicesProvider; import io.scalecube.services.annotations.Service; import io.scalecube.services.discovery.api.ServiceDiscovery; import java.util.Collection; +import java.util.Collections; import java.util.List; +import java.util.Objects; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.support.GenericBeanDefinition; import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.util.ClassUtils; import reactor.core.publisher.Mono; public class SpringServicesProvider implements ServicesProvider { @@ -32,35 +38,55 @@ public class SpringServicesProvider implements ServicesProvider { public SpringServicesProvider(Class... configurations) { this.ctxFactory = microservices -> { + GenericBeanDefinition discoveryBd = new GenericBeanDefinition(); + discoveryBd.setBeanClass(ServiceDiscovery.class); + discoveryBd.setLazyInit(true); + discoveryBd.setSynthetic(true); + discoveryBd.setInstanceSupplier(microservices::discovery); + discoveryBd.setSource(this); + + GenericBeanDefinition serviceCallBd = new GenericBeanDefinition(); + serviceCallBd.setBeanClass(ServiceCall.class); + serviceCallBd.setLazyInit(true); + serviceCallBd.setSynthetic(true); + serviceCallBd.setInstanceSupplier(microservices::call); + serviceCallBd.setSource(this); + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); - ServiceCall serviceCall = microservices.call(); - context.registerBean(ServiceCall.class, () -> serviceCall); + context.registerBeanDefinition("discovery-" + microservices.id(), discoveryBd); + context.registerBeanDefinition("serviceCall-" + microservices.id(), serviceCallBd); + Stream.of(configurations).forEach(context::register); return context; }; } @Override - public Mono> constructServices(Microservices microservices) { + public Mono> provideServiceDefinitions( + Microservices microservices) { this.ctx = this.ctxFactory.apply(microservices); - List beans = - this.ctx.getBeansWithAnnotation(Service.class).values().stream() - .map(bean -> ServiceInfo.fromServiceInstance(bean).build()) + String[] serviceBeanNames = this.ctx.getBeanDefinitionNames(); + List serviceDefinitions = + Stream.of(serviceBeanNames) + .map(serviceBeanName -> this.ctx.getBeanDefinition(serviceBeanName)) + .map(BeanDefinition::getBeanClassName) + .filter(Objects::nonNull) + .map(className -> ClassUtils.resolveClassName(className, ctx.getClassLoader())) + .filter(type -> type.getAnnotation(Service.class) != null) + .map(type -> new ServiceDefinition(type, Collections.emptyMap())) .collect(Collectors.toList()); - return Mono.just(beans); + return Mono.just(serviceDefinitions); } @Override - public Mono postConstruct(Microservices microservices) { - Mono ctxMono = - Mono.fromCallable( - () -> { - this.ctx.registerBean(ServiceDiscovery.class, microservices::discovery); - this.ctx.refresh(); - this.ctx.start(); - return this.ctx; - }); - return Mono.defer(() -> ctxMono).then(); + public Mono> provideService(Microservices microservices) { + this.ctx.refresh(); + this.ctx.start(); + List services = + this.ctx.getBeansWithAnnotation(Service.class).values().stream() + .map(bean -> ServiceInfo.fromServiceInstance(bean).build()) + .collect(Collectors.toList()); + return Mono.defer(() -> Mono.just(services)); } @Override diff --git a/services-examples-parent/scalecube-examples-spring/src/test/java/io/scalecube/spring/SpringServicesProviderTest.java b/services-examples-parent/scalecube-examples-spring/src/test/java/io/scalecube/spring/SpringServicesProviderTest.java index de823788e..bce4d76a4 100644 --- a/services-examples-parent/scalecube-examples-spring/src/test/java/io/scalecube/spring/SpringServicesProviderTest.java +++ b/services-examples-parent/scalecube-examples-spring/src/test/java/io/scalecube/spring/SpringServicesProviderTest.java @@ -16,6 +16,7 @@ import reactor.core.publisher.Hooks; import reactor.core.publisher.Mono; +import javax.annotation.PostConstruct; import java.time.Duration; import static org.junit.jupiter.api.Assertions.*; @@ -108,7 +109,7 @@ public static class LocalServiceBean implements LocalService { public LocalServiceBean(ServiceCall serviceCall, ServiceDiscovery serviceDiscovery) { this.serviceCall = serviceCall.api(SimpleService.class); this.serviceCall.get().subscribe(System.out::println); - serviceDiscovery.listenDiscovery().subscribe(System.out::println); + serviceDiscovery.listenDiscovery().subscribe(); } public Mono get() { diff --git a/services/src/main/java/io/scalecube/services/ScaleCube.java b/services/src/main/java/io/scalecube/services/ScaleCube.java index 928b83bee..2536debab 100644 --- a/services/src/main/java/io/scalecube/services/ScaleCube.java +++ b/services/src/main/java/io/scalecube/services/ScaleCube.java @@ -9,7 +9,7 @@ import io.scalecube.services.exceptions.ServiceProviderErrorMapper; import io.scalecube.services.gateway.Gateway; import io.scalecube.services.gateway.GatewayOptions; -import io.scalecube.services.inject.ScaleCubeServicesLifeCycleManager; +import io.scalecube.services.inject.ScaleCubeServicesProvider; import io.scalecube.services.methods.MethodInfo; import io.scalecube.services.methods.ServiceMethodInvoker; import io.scalecube.services.methods.ServiceMethodRegistry; @@ -28,6 +28,7 @@ import java.lang.management.ManagementFactory; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -166,6 +167,7 @@ public static Builder builder() { return new Builder(); } + @Override public String id() { return this.id; } @@ -195,29 +197,13 @@ private Mono start() { // invoke service providers and register services - Mono serviceInstances = - this.servicesProvider - .provide(this) - .doOnNext(services -> services.forEach(this::registerInMethodRegistry)) - .map( - services -> { - final ServiceEndpoint.Builder serviceEndpointBuilder = - ServiceEndpoint.builder() - .id(id) - .address(serviceAddress) - .contentTypes(DataCodec.getAllContentTypes()) - .tags(tags); - services.forEach( - service -> - serviceEndpointBuilder.appendServiceRegistrations( - ServiceScanner.scanServiceInfo(service))); - return serviceEndpointBuilder.build(); - }); + Mono serviceInstances = initializeServiceEndpoint(serviceAddress); return serviceInstances .flatMap(this.discoveryBootstrap::createInstance) .publishOn(scheduler) - .then(this.servicesProvider.postConstruct(this)) + .then(this.servicesProvider.provideService(this)) + .doOnNext(this::registerInMethodRegistry) .publishOn(scheduler) .then(startGateway(call)) .publishOn(scheduler) @@ -236,13 +222,36 @@ private Mono start() { .doOnTerminate(scheduler::dispose); } - private void registerInMethodRegistry(ServiceInfo serviceInfo) { - methodRegistry.registerService( - ServiceInfo.from(serviceInfo) - .errorMapper(Optional.ofNullable(serviceInfo.errorMapper()).orElse(errorMapper)) - .dataDecoder(Optional.ofNullable(serviceInfo.dataDecoder()).orElse(dataDecoder)) - .authenticator(Optional.ofNullable(serviceInfo.authenticator()).orElse(authenticator)) - .build()); + private Mono initializeServiceEndpoint(Address serviceAddress) { + return this.servicesProvider + .provideServiceDefinitions(this) + .map( + serviceDefinitions -> { + final ServiceEndpoint.Builder serviceEndpointBuilder = + ServiceEndpoint.builder() + .id(this.id) + .address(serviceAddress) + .contentTypes(DataCodec.getAllContentTypes()) + .tags(this.tags); + serviceDefinitions.forEach( + serviceDefinition -> + serviceEndpointBuilder.appendServiceRegistrations( + ServiceScanner.scanServiceDefinition(serviceDefinition))); + return serviceEndpointBuilder.build(); + }); + } + + private void registerInMethodRegistry(Collection services) { + services.forEach( + serviceInfo -> { + methodRegistry.registerService( + ServiceInfo.from(serviceInfo) + .errorMapperIfAbsent(this.errorMapper) + .dataDecoderIfAbsent(this.dataDecoder) + .authenticator( + Optional.ofNullable(serviceInfo.authenticator()).orElse(this.authenticator)) + .build()); + }); } private Mono startGateway(ServiceCall call) { @@ -359,7 +368,7 @@ private void build() { this.serviceProviders.add(serviceProvider); this.servicesProvider = this.servicesProvider == null - ? ScaleCubeServicesLifeCycleManager.create(this.serviceProviders) + ? ScaleCubeServicesProvider.create(this.serviceProviders) : this.servicesProvider; } diff --git a/services/src/main/java/io/scalecube/services/inject/Injector.java b/services/src/main/java/io/scalecube/services/inject/Injector.java index 0508427c0..a883822de 100644 --- a/services/src/main/java/io/scalecube/services/inject/Injector.java +++ b/services/src/main/java/io/scalecube/services/inject/Injector.java @@ -63,15 +63,21 @@ private static void setField(Field field, Object object, Object value) { } } - public static void processAfterConstruct( - Microservices microservices, ServiceInfo targetInstance) { - processMethodWithAnnotation( - microservices, targetInstance.serviceInstance(), AfterConstruct.class); + /** + * Run methods with {@link AfterConstruct} annotations. + * + * @param microservices scale cube instance. + * @param serviceInfo service info. + * @return service info with modified service's instance. + */ + public static ServiceInfo processAfterConstruct( + Microservices microservices, ServiceInfo serviceInfo) { + processMethodWithAnnotation(microservices, serviceInfo.serviceInstance(), AfterConstruct.class); + return serviceInfo; } - public static void processBeforeDestroy(Microservices microservices, ServiceInfo targetInstance) { - processMethodWithAnnotation( - microservices, targetInstance.serviceInstance(), BeforeDestroy.class); + public static void processBeforeDestroy(Microservices microservices, ServiceInfo serviceInfo) { + processMethodWithAnnotation(microservices, serviceInfo.serviceInstance(), BeforeDestroy.class); } private static void processMethodWithAnnotation( diff --git a/services/src/main/java/io/scalecube/services/inject/ScaleCubeServicesLifeCycleManager.java b/services/src/main/java/io/scalecube/services/inject/ScaleCubeServicesProvider.java similarity index 57% rename from services/src/main/java/io/scalecube/services/inject/ScaleCubeServicesLifeCycleManager.java rename to services/src/main/java/io/scalecube/services/inject/ScaleCubeServicesProvider.java index 8261b3897..6b321a0b4 100644 --- a/services/src/main/java/io/scalecube/services/inject/ScaleCubeServicesLifeCycleManager.java +++ b/services/src/main/java/io/scalecube/services/inject/ScaleCubeServicesProvider.java @@ -1,11 +1,13 @@ package io.scalecube.services.inject; import io.scalecube.services.Microservices; +import io.scalecube.services.ServiceDefinition; import io.scalecube.services.ServiceInfo; import io.scalecube.services.ServiceProvider; import io.scalecube.services.ServicesProvider; import java.util.Collection; +import java.util.List; import java.util.function.Function; import java.util.stream.Collectors; @@ -14,7 +16,7 @@ /** * Default {@link ServicesProvider}. */ -public class ScaleCubeServicesLifeCycleManager implements ServicesProvider { +public class ScaleCubeServicesProvider implements ServicesProvider { private final Function> serviceFactory; @@ -22,16 +24,16 @@ public class ScaleCubeServicesLifeCycleManager implements ServicesProvider { private Collection services; /** - * Create instance from {@link ServiceProvider}. + * Create the instance from {@link ServiceProvider}. * * @param serviceProviders old service providers. * @return default services provider. */ public static ServicesProvider create(Collection serviceProviders) { - return new ScaleCubeServicesLifeCycleManager(serviceProviders); + return new ScaleCubeServicesProvider(serviceProviders); } - private ScaleCubeServicesLifeCycleManager(Collection serviceProviders) { + private ScaleCubeServicesProvider(Collection serviceProviders) { this.serviceFactory = microservices -> serviceProviders.stream() @@ -41,18 +43,31 @@ private ScaleCubeServicesLifeCycleManager(Collection servicePro } /** - * {@inheritDoc} + * Since the service instance factory ({@link ServiceProvider}) we have to leave behind does not + * provide us with information about the types of services produced, there is nothing left for us + * to do but start creating all the services and then retrieve the type of service, previously + * saving it as a {@link ScaleCubeServicesProvider} state. + * + *

{@inheritDoc} * *

Use {@link io.scalecube.services.annotations.Inject} for inject {@link Microservices}, * {@link io.scalecube.services.ServiceCall}. + * + * @see ServiceInfo + * @see ServiceDefinition */ @Override - public Mono> constructServices(Microservices microservices) { + public Mono> provideServiceDefinitions( + Microservices microservices) { this.services = this.serviceFactory.apply(microservices).stream() .map(service -> Injector.inject(microservices, service)) .collect(Collectors.toList()); - return Mono.just(this.services); + List definitions = + this.services.stream() + .map(serviceInfo -> new ServiceDefinition(serviceInfo.type(), serviceInfo.tags())) + .collect(Collectors.toList()); + return Mono.just(definitions); } /** @@ -62,11 +77,12 @@ public Mono> constructServices(Microservices m * instance. */ @Override - public Mono postConstruct(Microservices microservices) { - return Mono.fromRunnable( + public Mono> provideService(Microservices microservices) { + return Mono.fromCallable( () -> - this.services.forEach( - service -> Injector.processAfterConstruct(microservices, service))); + this.services.stream() + .map(service -> Injector.processAfterConstruct(microservices, service)) + .collect(Collectors.toList())); } /** From 5deffbc791ba43e6fe000a82c3cd00cf7f6b7424 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=95=D0=B2=D0=B3=D0=B5=D0=BD=D0=B8=D0=B9=20=D0=A3=D1=82?= =?UTF-8?q?=D0=BA=D0=B8=D0=BD?= Date: Thu, 12 Mar 2020 12:57:46 +0300 Subject: [PATCH 17/61] ISSUE 708, replace Fix async operation order --- .../io/scalecube/services/ServiceInfo.java | 1 - .../spring/SpringServicesProvider.java | 82 ++++++++++--------- .../spring/SpringServicesProviderTest.java | 13 ++- .../java/io/scalecube/services/ScaleCube.java | 6 +- .../inject/ScaleCubeServicesProvider.java | 14 ++-- 5 files changed, 57 insertions(+), 59 deletions(-) diff --git a/services-api/src/main/java/io/scalecube/services/ServiceInfo.java b/services-api/src/main/java/io/scalecube/services/ServiceInfo.java index f73a9d8ed..65ae2115c 100644 --- a/services-api/src/main/java/io/scalecube/services/ServiceInfo.java +++ b/services-api/src/main/java/io/scalecube/services/ServiceInfo.java @@ -7,7 +7,6 @@ import java.util.HashMap; import java.util.Map; import java.util.StringJoiner; -import java.util.function.Supplier; @SuppressWarnings("rawtypes") public class ServiceInfo { diff --git a/services-examples-parent/scalecube-examples-spring/src/main/java/io/scalecube/spring/SpringServicesProvider.java b/services-examples-parent/scalecube-examples-spring/src/main/java/io/scalecube/spring/SpringServicesProvider.java index 5132df05b..2021d70d2 100644 --- a/services-examples-parent/scalecube-examples-spring/src/main/java/io/scalecube/spring/SpringServicesProvider.java +++ b/services-examples-parent/scalecube-examples-spring/src/main/java/io/scalecube/spring/SpringServicesProvider.java @@ -12,7 +12,7 @@ import java.util.Collections; import java.util.List; import java.util.Objects; -import java.util.function.Function; +import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -25,7 +25,7 @@ public class SpringServicesProvider implements ServicesProvider { - private final Function ctxFactory; + private final Class[] configurations; // lazy init private AnnotationConfigApplicationContext ctx; @@ -36,35 +36,22 @@ public class SpringServicesProvider implements ServicesProvider { * @param configurations spring configurations. */ public SpringServicesProvider(Class... configurations) { - this.ctxFactory = - microservices -> { - GenericBeanDefinition discoveryBd = new GenericBeanDefinition(); - discoveryBd.setBeanClass(ServiceDiscovery.class); - discoveryBd.setLazyInit(true); - discoveryBd.setSynthetic(true); - discoveryBd.setInstanceSupplier(microservices::discovery); - discoveryBd.setSource(this); - - GenericBeanDefinition serviceCallBd = new GenericBeanDefinition(); - serviceCallBd.setBeanClass(ServiceCall.class); - serviceCallBd.setLazyInit(true); - serviceCallBd.setSynthetic(true); - serviceCallBd.setInstanceSupplier(microservices::call); - serviceCallBd.setSource(this); - - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); - context.registerBeanDefinition("discovery-" + microservices.id(), discoveryBd); - context.registerBeanDefinition("serviceCall-" + microservices.id(), serviceCallBd); - - Stream.of(configurations).forEach(context::register); - return context; - }; + this.configurations = configurations; } @Override public Mono> provideServiceDefinitions( Microservices microservices) { - this.ctx = this.ctxFactory.apply(microservices); + + this.ctx = new AnnotationConfigApplicationContext(); + String id = microservices.id(); + this.ctx.registerBeanDefinition( + "discovery-" + id, createBeanDef(ServiceDiscovery.class, microservices::discovery)); + this.ctx.registerBeanDefinition( + "serviceCall-" + id, createBeanDef(ServiceCall.class, microservices::call)); + + Stream.of(this.configurations).forEach(this.ctx::register); + String[] serviceBeanNames = this.ctx.getBeanDefinitionNames(); List serviceDefinitions = Stream.of(serviceBeanNames) @@ -75,27 +62,42 @@ public Mono> provideServiceDefinitions( .filter(type -> type.getAnnotation(Service.class) != null) .map(type -> new ServiceDefinition(type, Collections.emptyMap())) .collect(Collectors.toList()); - return Mono.just(serviceDefinitions); + return Mono.defer(() -> Mono.just(serviceDefinitions)); + } + + private GenericBeanDefinition createBeanDef(Class type, Supplier instanceSupplier) { + GenericBeanDefinition discoveryBd = new GenericBeanDefinition(); + discoveryBd.setBeanClass(type); + discoveryBd.setLazyInit(true); + discoveryBd.setSynthetic(true); + discoveryBd.setInstanceSupplier(instanceSupplier); + discoveryBd.setSource(this); + return discoveryBd; } @Override public Mono> provideService(Microservices microservices) { - this.ctx.refresh(); - this.ctx.start(); - List services = - this.ctx.getBeansWithAnnotation(Service.class).values().stream() - .map(bean -> ServiceInfo.fromServiceInstance(bean).build()) - .collect(Collectors.toList()); - return Mono.defer(() -> Mono.just(services)); + return Mono.defer( + () -> { + this.ctx.refresh(); + this.ctx.start(); + List services = + this.ctx.getBeansWithAnnotation(Service.class).values().stream() + .map(bean -> ServiceInfo.fromServiceInstance(bean).build()) + .collect(Collectors.toList()); + return Mono.just(services); + }); } @Override public Mono shutDown(Microservices microservices) { - return Mono.fromCallable( - () -> { - this.ctx.stop(); - this.ctx.close(); - return microservices; - }); + return Mono.defer( + () -> + Mono.fromCallable( + () -> { + this.ctx.stop(); + this.ctx.close(); + return microservices; + })); } } diff --git a/services-examples-parent/scalecube-examples-spring/src/test/java/io/scalecube/spring/SpringServicesProviderTest.java b/services-examples-parent/scalecube-examples-spring/src/test/java/io/scalecube/spring/SpringServicesProviderTest.java index bce4d76a4..069c63374 100644 --- a/services-examples-parent/scalecube-examples-spring/src/test/java/io/scalecube/spring/SpringServicesProviderTest.java +++ b/services-examples-parent/scalecube-examples-spring/src/test/java/io/scalecube/spring/SpringServicesProviderTest.java @@ -16,10 +16,9 @@ import reactor.core.publisher.Hooks; import reactor.core.publisher.Mono; -import javax.annotation.PostConstruct; import java.time.Duration; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; class SpringServicesProviderTest { @@ -27,7 +26,7 @@ class SpringServicesProviderTest { private static ScaleCube microserviceWithoutSpring; @BeforeAll - public static void setup() { + public static void setUp() { Hooks.onOperatorDebug(); microserviceWithSpring = microserviceWithSpring(); microserviceWithoutSpring = microserviceWithoutSpring(); @@ -65,7 +64,7 @@ private static ScaleCube microserviceWithoutSpring() { } @Test - public void test_remote_greeting_request_completes_before_timeout() { + public void testWithSpringServicesProvider() { LocalService service = microserviceWithSpring.call().api(LocalService.class); @@ -83,8 +82,8 @@ private static ServiceDiscovery serviceDiscovery(ServiceEndpoint endpoint) { @Configuration static class Beans { @Bean - public LocalService localServiceBean(ServiceCall serviceCall, ServiceDiscovery serviceDiscovery) { - return new LocalServiceBean(serviceCall, serviceDiscovery); + public LocalService localServiceBean(ServiceCall serviceCall) { + return new LocalServiceBean(serviceCall, null); } } @@ -109,7 +108,7 @@ public static class LocalServiceBean implements LocalService { public LocalServiceBean(ServiceCall serviceCall, ServiceDiscovery serviceDiscovery) { this.serviceCall = serviceCall.api(SimpleService.class); this.serviceCall.get().subscribe(System.out::println); - serviceDiscovery.listenDiscovery().subscribe(); +// serviceDiscovery.listenDiscovery().subscribe(); } public Mono get() { diff --git a/services/src/main/java/io/scalecube/services/ScaleCube.java b/services/src/main/java/io/scalecube/services/ScaleCube.java index 2536debab..8120e9d79 100644 --- a/services/src/main/java/io/scalecube/services/ScaleCube.java +++ b/services/src/main/java/io/scalecube/services/ScaleCube.java @@ -195,11 +195,9 @@ private Mono start() { final ServiceCall call = call(); final Address serviceAddress = input.address; - // invoke service providers and register services + Mono serviceEndpointMono = initializeServiceEndpoint(serviceAddress); - Mono serviceInstances = initializeServiceEndpoint(serviceAddress); - - return serviceInstances + return serviceEndpointMono .flatMap(this.discoveryBootstrap::createInstance) .publishOn(scheduler) .then(this.servicesProvider.provideService(this)) diff --git a/services/src/main/java/io/scalecube/services/inject/ScaleCubeServicesProvider.java b/services/src/main/java/io/scalecube/services/inject/ScaleCubeServicesProvider.java index 6b321a0b4..6bf997a2f 100644 --- a/services/src/main/java/io/scalecube/services/inject/ScaleCubeServicesProvider.java +++ b/services/src/main/java/io/scalecube/services/inject/ScaleCubeServicesProvider.java @@ -13,9 +13,7 @@ import reactor.core.publisher.Mono; -/** - * Default {@link ServicesProvider}. - */ +/** Default {@link ServicesProvider}. */ public class ScaleCubeServicesProvider implements ServicesProvider { private final Function> serviceFactory; @@ -78,11 +76,13 @@ public Mono> provideServiceDefinitions( */ @Override public Mono> provideService(Microservices microservices) { - return Mono.fromCallable( + return Mono.defer( () -> - this.services.stream() - .map(service -> Injector.processAfterConstruct(microservices, service)) - .collect(Collectors.toList())); + Mono.fromCallable( + () -> + this.services.stream() + .map(service -> Injector.processAfterConstruct(microservices, service)) + .collect(Collectors.toList()))); } /** From 0f14e42f428419c2c773cac424780dcb83f07262 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=95=D0=B2=D0=B3=D0=B5=D0=BD=D0=B8=D0=B9=20=D0=A3=D1=82?= =?UTF-8?q?=D0=BA=D0=B8=D0=BD?= Date: Thu, 12 Mar 2020 13:03:51 +0300 Subject: [PATCH 18/61] ISSUE 708, fix check style --- .../scalecube/services/inject/ScaleCubeServicesProvider.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/services/src/main/java/io/scalecube/services/inject/ScaleCubeServicesProvider.java b/services/src/main/java/io/scalecube/services/inject/ScaleCubeServicesProvider.java index 6bf997a2f..fd144badc 100644 --- a/services/src/main/java/io/scalecube/services/inject/ScaleCubeServicesProvider.java +++ b/services/src/main/java/io/scalecube/services/inject/ScaleCubeServicesProvider.java @@ -13,7 +13,9 @@ import reactor.core.publisher.Mono; -/** Default {@link ServicesProvider}. */ +/** + * Default {@link ServicesProvider}. + */ public class ScaleCubeServicesProvider implements ServicesProvider { private final Function> serviceFactory; From 4ad59b060c91964b77307db20251d955eb807669 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=95=D0=B2=D0=B3=D0=B5=D0=BD=D0=B8=D0=B9=20=D0=A3=D1=82?= =?UTF-8?q?=D0=BA=D0=B8=D0=BD?= Date: Thu, 12 Mar 2020 13:48:14 +0300 Subject: [PATCH 19/61] ISSUE 708, return back of ServiceDiscovery --- .../io/scalecube/spring/SpringServicesProviderTest.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/services-examples-parent/scalecube-examples-spring/src/test/java/io/scalecube/spring/SpringServicesProviderTest.java b/services-examples-parent/scalecube-examples-spring/src/test/java/io/scalecube/spring/SpringServicesProviderTest.java index 069c63374..912a5f0f9 100644 --- a/services-examples-parent/scalecube-examples-spring/src/test/java/io/scalecube/spring/SpringServicesProviderTest.java +++ b/services-examples-parent/scalecube-examples-spring/src/test/java/io/scalecube/spring/SpringServicesProviderTest.java @@ -82,8 +82,8 @@ private static ServiceDiscovery serviceDiscovery(ServiceEndpoint endpoint) { @Configuration static class Beans { @Bean - public LocalService localServiceBean(ServiceCall serviceCall) { - return new LocalServiceBean(serviceCall, null); + public LocalService localServiceBean(ServiceCall serviceCall, ServiceDiscovery serviceDiscovery) { + return new LocalServiceBean(serviceCall, serviceDiscovery); } } @@ -108,7 +108,7 @@ public static class LocalServiceBean implements LocalService { public LocalServiceBean(ServiceCall serviceCall, ServiceDiscovery serviceDiscovery) { this.serviceCall = serviceCall.api(SimpleService.class); this.serviceCall.get().subscribe(System.out::println); -// serviceDiscovery.listenDiscovery().subscribe(); + serviceDiscovery.listenDiscovery().subscribe(); } public Mono get() { From 9c001be0f4362d822f89717bdfa63a3b0decccc1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=95=D0=B2=D0=B3=D0=B5=D0=BD=D0=B8=D0=B9=20=D0=A3=D1=82?= =?UTF-8?q?=D0=BA=D0=B8=D0=BD?= Date: Thu, 12 Mar 2020 14:50:16 +0300 Subject: [PATCH 20/61] ISSUE 708, replace flatMap(x -> x.flapMap()) to flatMap().flatMap() --- .../java/io/scalecube/services/ScaleCube.java | 48 +++++++++---------- 1 file changed, 23 insertions(+), 25 deletions(-) diff --git a/services/src/main/java/io/scalecube/services/ScaleCube.java b/services/src/main/java/io/scalecube/services/ScaleCube.java index 8120e9d79..708b074de 100644 --- a/services/src/main/java/io/scalecube/services/ScaleCube.java +++ b/services/src/main/java/io/scalecube/services/ScaleCube.java @@ -50,6 +50,7 @@ import reactor.core.Disposable; import reactor.core.publisher.Flux; +import reactor.core.publisher.Hooks; import reactor.core.publisher.Mono; import reactor.core.publisher.MonoProcessor; import reactor.core.scheduler.Scheduler; @@ -186,30 +187,23 @@ private Mono start() { // Create bootstrap scheduler Scheduler scheduler = Schedulers.newSingle(toString(), true); - + Hooks.onOperatorDebug(); return transportBootstrap .start(this) + // because ServiceTransportBootstrap#address may return nullable value in local case + .map(transport -> (Supplier

) transport::address) + .flatMap(this::initializeServiceEndpoint) + .flatMap(this.discoveryBootstrap::createInstance) .publishOn(scheduler) - .flatMap( - input -> { - final ServiceCall call = call(); - final Address serviceAddress = input.address; - - Mono serviceEndpointMono = initializeServiceEndpoint(serviceAddress); - - return serviceEndpointMono - .flatMap(this.discoveryBootstrap::createInstance) - .publishOn(scheduler) - .then(this.servicesProvider.provideService(this)) - .doOnNext(this::registerInMethodRegistry) - .publishOn(scheduler) - .then(startGateway(call)) - .publishOn(scheduler) - .then(Mono.fromCallable(() -> JmxMonitorMBean.start(this))) - .then(this.discoveryBootstrap.startListen(this)) - .publishOn(scheduler) - .thenReturn(this); - }) + .then(this.servicesProvider.provideService(this)) + .doOnNext(this::registerInMethodRegistry) + .publishOn(scheduler) + .then(startGateway()) + .publishOn(scheduler) + .then(Mono.fromCallable(() -> JmxMonitorMBean.start(this))) + .then(this.discoveryBootstrap.startListen(this)) + .publishOn(scheduler) + .thenReturn(this) .onErrorResume( ex -> { // return original error then shutdown @@ -220,7 +214,7 @@ private Mono start() { .doOnTerminate(scheduler::dispose); } - private Mono initializeServiceEndpoint(Address serviceAddress) { + private Mono initializeServiceEndpoint(Supplier
serviceAddress) { return this.servicesProvider .provideServiceDefinitions(this) .map( @@ -228,7 +222,7 @@ private Mono initializeServiceEndpoint(Address serviceAddress) final ServiceEndpoint.Builder serviceEndpointBuilder = ServiceEndpoint.builder() .id(this.id) - .address(serviceAddress) + .address(serviceAddress.get()) .contentTypes(DataCodec.getAllContentTypes()) .tags(this.tags); serviceDefinitions.forEach( @@ -252,8 +246,8 @@ private void registerInMethodRegistry(Collection services) { }); } - private Mono startGateway(ServiceCall call) { - return gatewayBootstrap.start(this, new GatewayOptions().call(call).metrics(metrics)); + private Mono startGateway() { + return gatewayBootstrap.start(this, new GatewayOptions().call(this.call()).metrics(metrics)); } public Metrics metrics() { @@ -680,6 +674,10 @@ private Mono start(ScaleCube microservices) { ex.toString())); } + public Address address() { + return address; + } + private Mono shutdown() { return Mono.defer( () -> From e8147b029e227895511627b4045c3ef2ff3e1f08 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=95=D0=B2=D0=B3=D0=B5=D0=BD=D0=B8=D0=B9=20=D0=A3=D1=82?= =?UTF-8?q?=D0=BA=D0=B8=D0=BD?= Date: Thu, 12 Mar 2020 16:45:35 +0300 Subject: [PATCH 21/61] ISSUE 708, delete reactor debug hooks --- services/src/main/java/io/scalecube/services/ScaleCube.java | 1 - 1 file changed, 1 deletion(-) diff --git a/services/src/main/java/io/scalecube/services/ScaleCube.java b/services/src/main/java/io/scalecube/services/ScaleCube.java index 708b074de..493b423e8 100644 --- a/services/src/main/java/io/scalecube/services/ScaleCube.java +++ b/services/src/main/java/io/scalecube/services/ScaleCube.java @@ -187,7 +187,6 @@ private Mono start() { // Create bootstrap scheduler Scheduler scheduler = Schedulers.newSingle(toString(), true); - Hooks.onOperatorDebug(); return transportBootstrap .start(this) // because ServiceTransportBootstrap#address may return nullable value in local case From 65d02a0daeba46ead527747c9c0eca153584f228 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=95=D0=B2=D0=B3=D0=B5=D0=BD=D0=B8=D0=B9=20=D0=A3=D1=82?= =?UTF-8?q?=D0=BA=D0=B8=D0=BD?= Date: Fri, 13 Mar 2020 15:45:10 +0300 Subject: [PATCH 22/61] ISSUE 708, revert redundant changes --- .../java/io/scalecube/services/Reflect.java | 9 +++++---- .../io/scalecube/services/ServiceInfo.java | 4 ---- .../methods/ServiceMethodInvoker.java | 15 ++------------ .../methods/ServiceMethodInvokerTest.java | 20 +++---------------- .../java/io/scalecube/services/ScaleCube.java | 2 +- .../inject/ScaleCubeServicesProvider.java | 2 +- .../methods/ServiceMethodRegistryImpl.java | 3 +-- 7 files changed, 13 insertions(+), 42 deletions(-) diff --git a/services-api/src/main/java/io/scalecube/services/Reflect.java b/services-api/src/main/java/io/scalecube/services/Reflect.java index f52a7fe16..6d765a893 100644 --- a/services-api/src/main/java/io/scalecube/services/Reflect.java +++ b/services-api/src/main/java/io/scalecube/services/Reflect.java @@ -251,13 +251,14 @@ public static Map serviceMethods(Class serviceInterface) { /** * Util function to get service interfaces collections from service instance. * - * @param serviceType type with extends service interface with @Service annotation. + * @param serviceObject with extends service interface with @Service annotation. * @return service interface class. */ - public static Stream> serviceInterfaces(Class serviceType) { - Class[] interfaces = serviceType.getInterfaces(); + public static Collection> serviceInterfaces(Object serviceObject) { + Class[] interfaces = serviceObject.getClass().getInterfaces(); return Arrays.stream(interfaces) - .filter(interfaceClass -> interfaceClass.isAnnotationPresent(Service.class)); + .filter(interfaceClass -> interfaceClass.isAnnotationPresent(Service.class)) + .collect(Collectors.toList()); } public static String methodName(Method method) { diff --git a/services-api/src/main/java/io/scalecube/services/ServiceInfo.java b/services-api/src/main/java/io/scalecube/services/ServiceInfo.java index 65ae2115c..1cff854ce 100644 --- a/services-api/src/main/java/io/scalecube/services/ServiceInfo.java +++ b/services-api/src/main/java/io/scalecube/services/ServiceInfo.java @@ -53,10 +53,6 @@ public Authenticator authenticator() { return authenticator; } - public Class type() { - return this.serviceInstance().getClass(); - } - @Override public String toString() { return new StringJoiner(", ", ServiceInfo.class.getSimpleName() + "[", "]") diff --git a/services-api/src/main/java/io/scalecube/services/methods/ServiceMethodInvoker.java b/services-api/src/main/java/io/scalecube/services/methods/ServiceMethodInvoker.java index 712a76062..cea6bd210 100644 --- a/services-api/src/main/java/io/scalecube/services/methods/ServiceMethodInvoker.java +++ b/services-api/src/main/java/io/scalecube/services/methods/ServiceMethodInvoker.java @@ -7,15 +7,12 @@ import io.scalecube.services.exceptions.ServiceProviderErrorMapper; import io.scalecube.services.exceptions.UnauthorizedException; import io.scalecube.services.transport.api.ServiceMessageDataDecoder; - import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Optional; import java.util.StringJoiner; import java.util.function.Consumer; - import org.reactivestreams.Publisher; - import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @@ -33,7 +30,6 @@ public final class ServiceMethodInvoker { private final ServiceProviderErrorMapper errorMapper; private final ServiceMessageDataDecoder dataDecoder; private final Authenticator authenticator; - private final Class serviceType; /** * Constructs a service method invoker out of real service object instance and method info. @@ -45,15 +41,13 @@ public final class ServiceMethodInvoker { * @param dataDecoder data decoder */ @SuppressWarnings({"unchecked", "rawtypes"}) - public ServiceMethodInvoker( - Class serviceType, + public ServiceMethodInvoker( Method method, Object service, MethodInfo methodInfo, ServiceProviderErrorMapper errorMapper, ServiceMessageDataDecoder dataDecoder, Authenticator authenticator) { - this.serviceType = serviceType; this.method = method; this.service = service; this.methodInfo = methodInfo; @@ -205,11 +199,6 @@ private void applyRequestReleaser(ServiceMessage request, Consumer reque } } - public Class serviceType() { - return serviceType; - } - - @Deprecated public Object service() { return service; } @@ -222,7 +211,7 @@ public MethodInfo methodInfo() { public String toString() { return new StringJoiner(", ", ServiceMethodInvoker.class.getSimpleName() + "[", "]") .add("method=" + method) - .add("service=" + serviceType) + .add("service=" + service) .add("methodInfo=" + methodInfo) .add("errorMapper=" + errorMapper) .add("dataDecoder=" + dataDecoder) diff --git a/services-api/src/test/java/io/scalecube/services/methods/ServiceMethodInvokerTest.java b/services-api/src/test/java/io/scalecube/services/methods/ServiceMethodInvokerTest.java index 082674397..c30e41bec 100644 --- a/services-api/src/test/java/io/scalecube/services/methods/ServiceMethodInvokerTest.java +++ b/services-api/src/test/java/io/scalecube/services/methods/ServiceMethodInvokerTest.java @@ -5,17 +5,14 @@ import io.scalecube.services.auth.Authenticator; import io.scalecube.services.exceptions.DefaultErrorMapper; import io.scalecube.services.transport.api.ServiceMessageDataDecoder; - +import java.lang.reflect.Method; +import java.util.function.Consumer; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; - import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; -import java.lang.reflect.Method; -import java.util.function.Consumer; - class ServiceMethodInvokerTest { private static final String qualifierPrefix = "io.scalecube.services.methods.StubService/"; @@ -51,10 +48,8 @@ void testInvokeOneWhenReturnNull() throws Exception { false, AUTH); - // FIXME: 19.02.2020 serviceMethodInvoker = new ServiceMethodInvoker( - stubService.getClass(), method, stubService, methodInfo, @@ -86,10 +81,9 @@ void testInvokeManyWhenReturnNull() throws Exception { Void.TYPE, false, AUTH); - // FIXME: 19.02.2020 + serviceMethodInvoker = new ServiceMethodInvoker( - stubService.getClass(), method, stubService, methodInfo, @@ -122,10 +116,8 @@ void testInvokeBidirectionalWhenReturnNull() throws Exception { false, AUTH); - // FIXME: 19.02.2020 serviceMethodInvoker = new ServiceMethodInvoker( - stubService.getClass(), method, stubService, methodInfo, @@ -160,10 +152,8 @@ void testInvokeOneWhenThrowException() throws Exception { false, AUTH); - // FIXME: 19.02.2020 serviceMethodInvoker = new ServiceMethodInvoker( - stubService.getClass(), method, stubService, methodInfo, @@ -199,10 +189,8 @@ void testInvokeManyWhenThrowException() throws Exception { false, AUTH); - // FIXME: 19.02.2020 serviceMethodInvoker = new ServiceMethodInvoker( - stubService.getClass(), method, stubService, methodInfo, @@ -238,10 +226,8 @@ void testInvokeBidirectionalWhenThrowException() throws Exception { false, AUTH); - // FIXME: 19.02.2020 serviceMethodInvoker = new ServiceMethodInvoker( - stubService.getClass(), method, stubService, methodInfo, diff --git a/services/src/main/java/io/scalecube/services/ScaleCube.java b/services/src/main/java/io/scalecube/services/ScaleCube.java index 493b423e8..2c70bd25a 100644 --- a/services/src/main/java/io/scalecube/services/ScaleCube.java +++ b/services/src/main/java/io/scalecube/services/ScaleCube.java @@ -751,7 +751,7 @@ private static String asString(ServiceMethodInvoker invoker) { .add("methodInfo=" + asString(invoker.methodInfo())) .add( "serviceMethod=" - + invoker.serviceType().getCanonicalName() + + invoker.service() + "." + invoker.methodInfo().methodName() + "(" diff --git a/services/src/main/java/io/scalecube/services/inject/ScaleCubeServicesProvider.java b/services/src/main/java/io/scalecube/services/inject/ScaleCubeServicesProvider.java index fd144badc..62a472842 100644 --- a/services/src/main/java/io/scalecube/services/inject/ScaleCubeServicesProvider.java +++ b/services/src/main/java/io/scalecube/services/inject/ScaleCubeServicesProvider.java @@ -65,7 +65,7 @@ public Mono> provideServiceDefinitions( .collect(Collectors.toList()); List definitions = this.services.stream() - .map(serviceInfo -> new ServiceDefinition(serviceInfo.type(), serviceInfo.tags())) + .map(serviceInfo -> new ServiceDefinition(serviceInfo.serviceInstance().getClass(), serviceInfo.tags())) .collect(Collectors.toList()); return Mono.just(definitions); } diff --git a/services/src/main/java/io/scalecube/services/methods/ServiceMethodRegistryImpl.java b/services/src/main/java/io/scalecube/services/methods/ServiceMethodRegistryImpl.java index 1f6b45f20..01850d025 100644 --- a/services/src/main/java/io/scalecube/services/methods/ServiceMethodRegistryImpl.java +++ b/services/src/main/java/io/scalecube/services/methods/ServiceMethodRegistryImpl.java @@ -19,7 +19,7 @@ public final class ServiceMethodRegistryImpl implements ServiceMethodRegistry { public void registerService(ServiceInfo serviceInfo) { serviceInfos.add(serviceInfo); - Reflect.serviceInterfaces(serviceInfo.type()) + Reflect.serviceInterfaces(serviceInfo.serviceInstance()) .forEach( serviceInterface -> Reflect.serviceMethods(serviceInterface) @@ -51,7 +51,6 @@ public void registerService(ServiceInfo serviceInfo) { ServiceMethodInvoker invoker = new ServiceMethodInvoker( - serviceInfo.type(), method, serviceInfo.serviceInstance(), methodInfo, From 3faf17a12de5216dbb5fc5b2b55f93427b7f20ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=95=D0=B2=D0=B3=D0=B5=D0=BD=D0=B8=D0=B9=20=D0=A3=D1=82?= =?UTF-8?q?=D0=BA=D0=B8=D0=BD?= Date: Fri, 13 Mar 2020 15:49:21 +0300 Subject: [PATCH 23/61] ISSUE 708, fix api --- .../java/io/scalecube/services/Reflect.java | 20 +++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/services-api/src/main/java/io/scalecube/services/Reflect.java b/services-api/src/main/java/io/scalecube/services/Reflect.java index 6d765a893..ea6df6528 100644 --- a/services-api/src/main/java/io/scalecube/services/Reflect.java +++ b/services-api/src/main/java/io/scalecube/services/Reflect.java @@ -20,7 +20,6 @@ import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.Arrays; -import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.function.Function; @@ -251,14 +250,23 @@ public static Map serviceMethods(Class serviceInterface) { /** * Util function to get service interfaces collections from service instance. * - * @param serviceObject with extends service interface with @Service annotation. + * @param serviceObject object with extends service interface with @Service annotation. * @return service interface class. */ - public static Collection> serviceInterfaces(Object serviceObject) { - Class[] interfaces = serviceObject.getClass().getInterfaces(); + public static Stream> serviceInterfaces(Object serviceObject) { + return serviceInterfaces(serviceObject.getClass()); + } + + /** + * Util function to get service interfaces collections from service instance. + * + * @param serviceType with extends service interface with @Service annotation. + * @return service interface class. + */ + public static Stream> serviceInterfaces(Class serviceType) { + Class[] interfaces = serviceType.getInterfaces(); return Arrays.stream(interfaces) - .filter(interfaceClass -> interfaceClass.isAnnotationPresent(Service.class)) - .collect(Collectors.toList()); + .filter(interfaceClass -> interfaceClass.isAnnotationPresent(Service.class)); } public static String methodName(Method method) { From 69145272fcf86912d1d55850029a0b7b4b83d1d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=95=D0=B2=D0=B3=D0=B5=D0=BD=D0=B8=D0=B9=20=D0=A3=D1=82?= =?UTF-8?q?=D0=BA=D0=B8=D0=BD?= Date: Fri, 13 Mar 2020 16:17:09 +0300 Subject: [PATCH 24/61] ISSUE 708, refactoring --- .../transport/BenchmarkServiceState.java | 12 ++--- .../spring/SpringServicesProviderTest.java | 14 ++--- .../services/examples/ExamplesRunner.java | 4 +- .../exceptions/ExceptionMapperExample.java | 10 ++-- .../examples/helloworld/Example1.java | 10 ++-- .../examples/helloworld/Example2.java | 10 ++-- .../examples/helloworld/Example3.java | 10 ++-- .../services/examples/orderbook/Example1.java | 10 ++-- .../services/examples/services/Example1.java | 14 ++--- .../services/examples/services/Example2.java | 14 ++--- .../{ScaleCube.java => Scalecube.java} | 44 +++++++-------- .../scalecube/services/inject/Injector.java | 6 +-- .../inject/ScaleCubeServicesProvider.java | 53 +++++++++++-------- .../io/scalecube/services/ErrorFlowTest.java | 8 +-- .../services/ServiceAuthLocalTest.java | 12 ++--- .../services/ServiceAuthRemoteTest.java | 20 +++---- .../services/ServiceCallLocalTest.java | 6 +-- .../services/ServiceCallRemoteTest.java | 14 ++--- .../ServiceLifecycleAnnotationsTest.java | 6 +-- .../scalecube/services/ServiceLocalTest.java | 6 +-- .../services/ServiceRegistryTest.java | 44 +++++++-------- .../scalecube/services/ServiceRemoteTest.java | 32 +++++------ .../services/StreamingServiceTest.java | 8 +-- .../services/routings/RoutersTest.java | 18 +++---- .../services/routings/ServiceTagsExample.java | 14 ++--- .../services/sut/AnnotationServiceImpl.java | 4 +- .../sut/CoarseGrainedServiceImpl.java | 4 +- .../services/sut/GreetingServiceImpl.java | 4 +- ...ocketNettyColocatedEventLoopGroupTest.java | 24 ++++----- .../rsocket/RSocketServiceTransportTest.java | 14 ++--- 30 files changed, 225 insertions(+), 224 deletions(-) rename services/src/main/java/io/scalecube/services/{ScaleCube.java => Scalecube.java} (96%) diff --git a/services-benchmarks/src/main/java/io/scalecube/services/benchmarks/transport/BenchmarkServiceState.java b/services-benchmarks/src/main/java/io/scalecube/services/benchmarks/transport/BenchmarkServiceState.java index 8996f8cd5..699cf83f5 100644 --- a/services-benchmarks/src/main/java/io/scalecube/services/benchmarks/transport/BenchmarkServiceState.java +++ b/services-benchmarks/src/main/java/io/scalecube/services/benchmarks/transport/BenchmarkServiceState.java @@ -3,7 +3,7 @@ import io.scalecube.benchmarks.BenchmarkSettings; import io.scalecube.benchmarks.BenchmarkState; import io.scalecube.net.Address; -import io.scalecube.services.ScaleCube; +import io.scalecube.services.Scalecube; import io.scalecube.services.ServiceCall; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.transport.rsocket.RSocketServiceTransport; @@ -20,8 +20,8 @@ public class BenchmarkServiceState extends BenchmarkState private final Object[] services; - private ScaleCube seed; - private ScaleCube node; + private Scalecube seed; + private Scalecube node; public BenchmarkServiceState(BenchmarkSettings settings, Object... services) { super(settings); @@ -31,7 +31,7 @@ public BenchmarkServiceState(BenchmarkSettings settings, Object... services) { @Override public void beforeAll() { seed = - ScaleCube.builder() + Scalecube.builder() .metrics(registry()) .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) @@ -40,7 +40,7 @@ public void beforeAll() { final Address seedAddress = seed.discovery().address(); node = - ScaleCube.builder() + Scalecube.builder() .metrics(registry()) .discovery( endpoint -> @@ -66,7 +66,7 @@ public void afterAll() { } } - public ScaleCube seed() { + public Scalecube seed() { return seed; } diff --git a/services-examples-parent/scalecube-examples-spring/src/test/java/io/scalecube/spring/SpringServicesProviderTest.java b/services-examples-parent/scalecube-examples-spring/src/test/java/io/scalecube/spring/SpringServicesProviderTest.java index 912a5f0f9..b306958d6 100644 --- a/services-examples-parent/scalecube-examples-spring/src/test/java/io/scalecube/spring/SpringServicesProviderTest.java +++ b/services-examples-parent/scalecube-examples-spring/src/test/java/io/scalecube/spring/SpringServicesProviderTest.java @@ -1,6 +1,6 @@ package io.scalecube.spring; -import io.scalecube.services.ScaleCube; +import io.scalecube.services.Scalecube; import io.scalecube.services.ServiceCall; import io.scalecube.services.ServiceEndpoint; import io.scalecube.services.annotations.Service; @@ -22,8 +22,8 @@ class SpringServicesProviderTest { - private static ScaleCube microserviceWithSpring; - private static ScaleCube microserviceWithoutSpring; + private static Scalecube microserviceWithSpring; + private static Scalecube microserviceWithoutSpring; @BeforeAll public static void setUp() { @@ -47,16 +47,16 @@ public static void tearDown() { } } - private static ScaleCube microserviceWithSpring() { - return ScaleCube.builder() + private static Scalecube microserviceWithSpring() { + return Scalecube.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) .serviceProvider(new SpringServicesProvider(Beans.class)) .startAwait(); } - private static ScaleCube microserviceWithoutSpring() { - return ScaleCube.builder() + private static Scalecube microserviceWithoutSpring() { + return Scalecube.builder() .discovery(SpringServicesProviderTest::serviceDiscovery) .transport(RSocketServiceTransport::new) .services((SimpleService) () -> Mono.just(1L)) diff --git a/services-examples-parent/services-examples-runner/src/main/java/io/scalecube/services/examples/ExamplesRunner.java b/services-examples-parent/services-examples-runner/src/main/java/io/scalecube/services/examples/ExamplesRunner.java index a5d7c3da9..82848fbb6 100644 --- a/services-examples-parent/services-examples-runner/src/main/java/io/scalecube/services/examples/ExamplesRunner.java +++ b/services-examples-parent/services-examples-runner/src/main/java/io/scalecube/services/examples/ExamplesRunner.java @@ -7,7 +7,7 @@ import io.scalecube.config.source.SystemEnvironmentConfigSource; import io.scalecube.config.source.SystemPropertiesConfigSource; import io.scalecube.net.Address; -import io.scalecube.services.ScaleCube; +import io.scalecube.services.Scalecube; import io.scalecube.services.ServiceEndpoint; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.discovery.api.ServiceDiscovery; @@ -51,7 +51,7 @@ public static void main(String[] args) { .orElse(Runtime.getRuntime().availableProcessors()); LOGGER.info("Number of worker threads: " + numOfThreads); - ScaleCube.builder() + Scalecube.builder() .discovery(endpoint -> serviceDiscovery(endpoint, config)) .transport( () -> diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/exceptions/ExceptionMapperExample.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/exceptions/ExceptionMapperExample.java index 6487fc40d..e1394629f 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/exceptions/ExceptionMapperExample.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/exceptions/ExceptionMapperExample.java @@ -1,7 +1,7 @@ package io.scalecube.services.examples.exceptions; import io.scalecube.net.Address; -import io.scalecube.services.ScaleCube; +import io.scalecube.services.Scalecube; import io.scalecube.services.ServiceInfo; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.transport.rsocket.RSocketServiceTransport; @@ -16,8 +16,8 @@ public class ExceptionMapperExample { * @throws InterruptedException exception. */ public static void main(String[] args) throws InterruptedException { - ScaleCube ms1 = - ScaleCube.builder() + Scalecube ms1 = + Scalecube.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) .defaultErrorMapper(new ServiceAProviderErrorMapper()) // default mapper for whole node @@ -31,8 +31,8 @@ public static void main(String[] args) throws InterruptedException { final Address address1 = ms1.discovery().address(); - ScaleCube ms2 = - ScaleCube.builder() + Scalecube ms2 = + Scalecube.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example1.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example1.java index 403c05922..c511a9755 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example1.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example1.java @@ -1,7 +1,7 @@ package io.scalecube.services.examples.helloworld; import io.scalecube.net.Address; -import io.scalecube.services.ScaleCube; +import io.scalecube.services.Scalecube; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.examples.helloworld.service.GreetingServiceImpl; import io.scalecube.services.examples.helloworld.service.api.GreetingsService; @@ -24,8 +24,8 @@ public class Example1 { */ public static void main(String[] args) { // ScaleCube Node node with no members - ScaleCube seed = - ScaleCube.builder() + Scalecube seed = + Scalecube.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) .startAwait(); @@ -33,8 +33,8 @@ public static void main(String[] args) { final Address seedAddress = seed.discovery().address(); // Construct a ScaleCube node which joins the cluster hosting the Greeting Service - ScaleCube ms = - ScaleCube.builder() + Scalecube ms = + Scalecube.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example2.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example2.java index b4944fc2f..4ec20d086 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example2.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example2.java @@ -1,7 +1,7 @@ package io.scalecube.services.examples.helloworld; import io.scalecube.net.Address; -import io.scalecube.services.ScaleCube; +import io.scalecube.services.Scalecube; import io.scalecube.services.ServiceCall; import io.scalecube.services.api.ServiceMessage; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; @@ -32,8 +32,8 @@ public class Example2 { */ public static void main(String[] args) { // ScaleCube Node node with no members - ScaleCube seed = - ScaleCube.builder() + Scalecube seed = + Scalecube.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) .startAwait(); @@ -41,8 +41,8 @@ public static void main(String[] args) { // Construct a ScaleCube node which joins the cluster hosting the Greeting Service final Address seedAddress = seed.discovery().address(); - ScaleCube ms = - ScaleCube.builder() + Scalecube ms = + Scalecube.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example3.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example3.java index cacffaf7a..8e6c1dad7 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example3.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example3.java @@ -1,7 +1,7 @@ package io.scalecube.services.examples.helloworld; import io.scalecube.net.Address; -import io.scalecube.services.ScaleCube; +import io.scalecube.services.Scalecube; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.examples.helloworld.service.BidiGreetingImpl; import io.scalecube.services.examples.helloworld.service.api.BidiGreetingService; @@ -25,8 +25,8 @@ public class Example3 { */ public static void main(String[] args) { // ScaleCube Node node with no members - ScaleCube seed = - ScaleCube.builder() + Scalecube seed = + Scalecube.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) .startAwait(); @@ -34,8 +34,8 @@ public static void main(String[] args) { final Address seedAddress = seed.discovery().address(); // Construct a ScaleCube node which joins the cluster hosting the Greeting Service - ScaleCube ms = - ScaleCube.builder() + Scalecube ms = + Scalecube.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/orderbook/Example1.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/orderbook/Example1.java index a57a3d39f..4b7a86b5a 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/orderbook/Example1.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/orderbook/Example1.java @@ -1,7 +1,7 @@ package io.scalecube.services.examples.orderbook; import io.scalecube.net.Address; -import io.scalecube.services.ScaleCube; +import io.scalecube.services.Scalecube; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.examples.orderbook.service.DefaultMarketDataService; import io.scalecube.services.examples.orderbook.service.OrderBookSnapshoot; @@ -32,16 +32,16 @@ public class Example1 { */ public static void main(String[] args) throws InterruptedException { - ScaleCube gateway = - ScaleCube.builder() + Scalecube gateway = + Scalecube.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) .startAwait(); final Address gatewayAddress = gateway.discovery().address(); - ScaleCube ms = - ScaleCube.builder() + Scalecube ms = + Scalecube.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example1.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example1.java index c0d3f2480..7a294bb04 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example1.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example1.java @@ -1,7 +1,7 @@ package io.scalecube.services.examples.services; import io.scalecube.net.Address; -import io.scalecube.services.ScaleCube; +import io.scalecube.services.Scalecube; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.transport.rsocket.RSocketServiceTransport; import reactor.core.publisher.Mono; @@ -15,16 +15,16 @@ public class Example1 { * @param args - program arguments */ public static void main(String[] args) { - ScaleCube gateway = - ScaleCube.builder() + Scalecube gateway = + Scalecube.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) .startAwait(); final Address gatewayAddress = gateway.discovery().address(); - ScaleCube service2Node = - ScaleCube.builder() + Scalecube service2Node = + Scalecube.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) @@ -33,8 +33,8 @@ public static void main(String[] args) { .services(new Service2Impl()) .startAwait(); - ScaleCube service1Node = - ScaleCube.builder() + Scalecube service1Node = + Scalecube.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example2.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example2.java index a9769c862..b27521c34 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example2.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example2.java @@ -1,7 +1,7 @@ package io.scalecube.services.examples.services; import io.scalecube.net.Address; -import io.scalecube.services.ScaleCube; +import io.scalecube.services.Scalecube; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.transport.rsocket.RSocketServiceTransport; import reactor.core.publisher.Mono; @@ -15,16 +15,16 @@ public class Example2 { * @param args - program arguments */ public static void main(String[] args) { - ScaleCube gateway = - ScaleCube.builder() + Scalecube gateway = + Scalecube.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) .startAwait(); final Address gatewayAddress = gateway.discovery().address(); - ScaleCube service2Node = - ScaleCube.builder() + Scalecube service2Node = + Scalecube.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) @@ -33,8 +33,8 @@ public static void main(String[] args) { .services(new Service2Impl()) .startAwait(); - ScaleCube service1Node = - ScaleCube.builder() + Scalecube service1Node = + Scalecube.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) diff --git a/services/src/main/java/io/scalecube/services/ScaleCube.java b/services/src/main/java/io/scalecube/services/Scalecube.java similarity index 96% rename from services/src/main/java/io/scalecube/services/ScaleCube.java rename to services/src/main/java/io/scalecube/services/Scalecube.java index 2c70bd25a..5c08fa72d 100644 --- a/services/src/main/java/io/scalecube/services/ScaleCube.java +++ b/services/src/main/java/io/scalecube/services/Scalecube.java @@ -26,15 +26,7 @@ import io.scalecube.services.transport.api.ServiceTransport; import java.lang.management.ManagementFactory; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.StringJoiner; -import java.util.UUID; +import java.util.*; import java.util.concurrent.CopyOnWriteArrayList; import java.util.function.Function; import java.util.function.Supplier; @@ -50,7 +42,6 @@ import reactor.core.Disposable; import reactor.core.publisher.Flux; -import reactor.core.publisher.Hooks; import reactor.core.publisher.Mono; import reactor.core.publisher.MonoProcessor; import reactor.core.scheduler.Scheduler; @@ -122,9 +113,9 @@ * * } */ -public final class ScaleCube implements Microservices { +public final class Scalecube implements Microservices { - public static final Logger LOGGER = LoggerFactory.getLogger(ScaleCube.class); + public static final Logger LOGGER = LoggerFactory.getLogger(Scalecube.class); private final String id = generateId(); private final Metrics metrics; @@ -141,7 +132,7 @@ public final class ScaleCube implements Microservices { private final MonoProcessor shutdown = MonoProcessor.create(); private final MonoProcessor onShutdown = MonoProcessor.create(); - private ScaleCube(Builder builder) { + private Scalecube(Builder builder) { this.metrics = builder.metrics; this.tags = new HashMap<>(builder.tags); @@ -182,7 +173,7 @@ public String toString() { return "Microservices@" + id; } - private Mono start() { + private Mono start() { LOGGER.info("[{}][start] Starting", id); // Create bootstrap scheduler @@ -206,7 +197,7 @@ private Mono start() { .onErrorResume( ex -> { // return original error then shutdown - return Mono.whenDelayError(Mono.error(ex), shutdown()).cast(ScaleCube.class); + return Mono.whenDelayError(Mono.error(ex), shutdown()).cast(Scalecube.class); }) .doOnSuccess(m -> listenJvmShutdown()) .doOnSuccess(m -> LOGGER.info("[{}][start] Started", id)) @@ -357,18 +348,19 @@ private void build() { Collectors.collectingAndThen( Collectors.toList(), services -> (ServiceProvider) call -> services)); this.serviceProviders.add(serviceProvider); + List serviceProviders = Collections.unmodifiableList(this.serviceProviders); this.servicesProvider = this.servicesProvider == null - ? ScaleCubeServicesProvider.create(this.serviceProviders) + ? ScaleCubeServicesProvider.create(serviceProviders) : this.servicesProvider; } - public Mono start() { + public Mono start() { build(); - return Mono.defer(() -> new ScaleCube(this).start()); + return Mono.defer(() -> new Scalecube(this).start()); } - public ScaleCube startAwait() { + public Scalecube startAwait() { return start().block(); } @@ -504,7 +496,7 @@ private Mono createInstance(ServiceEndpoint serviceEndpoint) { : Mono.defer(() -> Mono.just(discovery = factory.apply(serviceEndpoint))); } - private Mono startListen(ScaleCube microservices) { + private Mono startListen(Scalecube microservices) { return Mono.defer( () -> { if (this.discovery == null) { @@ -537,7 +529,7 @@ private Mono startListen(ScaleCube microservices) { }); } - private void onDiscoveryEvent(ScaleCube microservices, ServiceDiscoveryEvent event) { + private void onDiscoveryEvent(Scalecube microservices, ServiceDiscoveryEvent event) { if (event.isEndpointAdded()) { microservices.serviceRegistry.registerService(event.serviceEndpoint()); } @@ -567,7 +559,7 @@ private GatewayBootstrap addFactory(Function factory) { return this; } - private Mono start(ScaleCube microservices, GatewayOptions options) { + private Mono start(Scalecube microservices, GatewayOptions options) { return Flux.fromIterable(factories) .flatMap( factory -> { @@ -636,7 +628,7 @@ public ServiceTransportBootstrap(Supplier supplier) { this.supplier = supplier; } - private Mono start(ScaleCube microservices) { + private Mono start(Scalecube microservices) { if (supplier == NULL_SUPPLIER || (serviceTransport = supplier.get()) == null) { LOGGER.info("[{}] ServiceTransport not set", microservices.id()); return Mono.just(NULL_INSTANCE); @@ -705,9 +697,9 @@ public interface MonitorMBean { private static class JmxMonitorMBean implements MonitorMBean { - private final ScaleCube microservices; + private final Scalecube microservices; - private static JmxMonitorMBean start(ScaleCube instance) throws Exception { + private static JmxMonitorMBean start(Scalecube instance) throws Exception { MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer(); JmxMonitorMBean jmxMBean = new JmxMonitorMBean(instance); ObjectName objectName = new ObjectName("io.scalecube.services:name=" + instance.toString()); @@ -716,7 +708,7 @@ private static JmxMonitorMBean start(ScaleCube instance) throws Exception { return jmxMBean; } - private JmxMonitorMBean(ScaleCube microservices) { + private JmxMonitorMBean(Scalecube microservices) { this.microservices = microservices; } diff --git a/services/src/main/java/io/scalecube/services/inject/Injector.java b/services/src/main/java/io/scalecube/services/inject/Injector.java index a883822de..94c00c588 100644 --- a/services/src/main/java/io/scalecube/services/inject/Injector.java +++ b/services/src/main/java/io/scalecube/services/inject/Injector.java @@ -2,7 +2,7 @@ import io.scalecube.services.Microservices; import io.scalecube.services.Reflect; -import io.scalecube.services.ScaleCube; +import io.scalecube.services.Scalecube; import io.scalecube.services.ServiceCall; import io.scalecube.services.ServiceInfo; import io.scalecube.services.annotations.AfterConstruct; @@ -40,7 +40,7 @@ public static ServiceInfo inject(Microservices microservices, ServiceInfo servic } private static void injectField(Microservices microservices, Field field, Object service) { - if (field.isAnnotationPresent(Inject.class) && field.getType().equals(ScaleCube.class)) { + if (field.isAnnotationPresent(Inject.class) && field.getType().equals(Scalecube.class)) { setField(field, service, microservices); } else if (field.isAnnotationPresent(Inject.class) && Reflect.isService(field.getType())) { Inject injection = field.getAnnotation(Inject.class); @@ -93,7 +93,7 @@ private static void processMethodWithAnnotation( Arrays.stream(targetMethod.getParameters()) .map( mapper -> { - if (mapper.getType().equals(ScaleCube.class)) { + if (mapper.getType().equals(Scalecube.class)) { return microservices; } else if (Reflect.isService(mapper.getType())) { return microservices.call().api(mapper.getType()); diff --git a/services/src/main/java/io/scalecube/services/inject/ScaleCubeServicesProvider.java b/services/src/main/java/io/scalecube/services/inject/ScaleCubeServicesProvider.java index 62a472842..5b4c5b693 100644 --- a/services/src/main/java/io/scalecube/services/inject/ScaleCubeServicesProvider.java +++ b/services/src/main/java/io/scalecube/services/inject/ScaleCubeServicesProvider.java @@ -7,21 +7,19 @@ import io.scalecube.services.ServicesProvider; import java.util.Collection; -import java.util.List; +import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; import java.util.stream.Collectors; import reactor.core.publisher.Mono; -/** - * Default {@link ServicesProvider}. - */ +/** Default {@link ServicesProvider}. Thread-safe. */ public class ScaleCubeServicesProvider implements ServicesProvider { private final Function> serviceFactory; // lazy init - private Collection services; + private AtomicReference> services = new AtomicReference<>(); /** * Create the instance from {@link ServiceProvider}. @@ -39,6 +37,7 @@ private ScaleCubeServicesProvider(Collection serviceProviders) serviceProviders.stream() .map(serviceProvider -> serviceProvider.provide(microservices.call())) .flatMap(Collection::stream) + .map(service -> Injector.inject(microservices, service)) .collect(Collectors.toList()); } @@ -59,15 +58,14 @@ private ScaleCubeServicesProvider(Collection serviceProviders) @Override public Mono> provideServiceDefinitions( Microservices microservices) { - this.services = - this.serviceFactory.apply(microservices).stream() - .map(service -> Injector.inject(microservices, service)) - .collect(Collectors.toList()); - List definitions = - this.services.stream() - .map(serviceInfo -> new ServiceDefinition(serviceInfo.serviceInstance().getClass(), serviceInfo.tags())) - .collect(Collectors.toList()); - return Mono.just(definitions); + return Mono.fromCallable( + () -> + this.services(microservices).stream() + .map( + serviceInfo -> + new ServiceDefinition( + serviceInfo.serviceInstance().getClass(), serviceInfo.tags())) + .collect(Collectors.toList())); } /** @@ -78,13 +76,11 @@ public Mono> provideServiceDefinitions( */ @Override public Mono> provideService(Microservices microservices) { - return Mono.defer( + return Mono.fromCallable( () -> - Mono.fromCallable( - () -> - this.services.stream() - .map(service -> Injector.processAfterConstruct(microservices, service)) - .collect(Collectors.toList()))); + this.services(microservices).stream() + .map(service -> Injector.processAfterConstruct(microservices, service)) + .collect(Collectors.toList())); } /** @@ -95,7 +91,20 @@ public Mono> provideService(Microservices micr */ @Override public Mono shutDown(Microservices microservices) { - this.services.forEach(service -> Injector.processBeforeDestroy(microservices, service)); - return Mono.just(microservices); + return Mono.fromRunnable( + () -> { + if (this.services.get() != null) { + this.services + .get() + .forEach(service -> Injector.processBeforeDestroy(microservices, service)); + } + }) + .thenReturn(microservices); + } + + private Collection services(Microservices microservices) { + return this.services.updateAndGet( + currentValue -> + currentValue == null ? this.serviceFactory.apply(microservices) : currentValue); } } diff --git a/services/src/test/java/io/scalecube/services/ErrorFlowTest.java b/services/src/test/java/io/scalecube/services/ErrorFlowTest.java index 20ac3bfef..55d357719 100644 --- a/services/src/test/java/io/scalecube/services/ErrorFlowTest.java +++ b/services/src/test/java/io/scalecube/services/ErrorFlowTest.java @@ -23,13 +23,13 @@ public class ErrorFlowTest extends BaseTest { private static AtomicInteger port = new AtomicInteger(4000); - private static ScaleCube provider; - private static ScaleCube consumer; + private static Scalecube provider; + private static Scalecube consumer; @BeforeAll public static void initNodes() { provider = - ScaleCube.builder() + Scalecube.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) @@ -41,7 +41,7 @@ public static void initNodes() { final Address seedAddress = provider.discovery().address(); consumer = - ScaleCube.builder() + Scalecube.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) diff --git a/services/src/test/java/io/scalecube/services/ServiceAuthLocalTest.java b/services/src/test/java/io/scalecube/services/ServiceAuthLocalTest.java index e07b4928f..01749d530 100644 --- a/services/src/test/java/io/scalecube/services/ServiceAuthLocalTest.java +++ b/services/src/test/java/io/scalecube/services/ServiceAuthLocalTest.java @@ -45,7 +45,7 @@ final class ServiceAuthLocalTest extends BaseTest { return Mono.error(new UnauthorizedException("Authentication failed")); }; - private ScaleCube service; + private Scalecube service; @BeforeAll static void beforeAll() { @@ -63,7 +63,7 @@ void afterEach() { @DisplayName("Successful authentication") void successfulAuthentication() { service = - ScaleCube.builder() + Scalecube.builder() .authenticator(authenticator) .services(new SecuredServiceImpl()) .startAwait(); @@ -87,7 +87,7 @@ void successfulAuthentication() { @Test @DisplayName("Authentication failed if authenticator not provided") void failedAuthenticationWhenAuthenticatorNotProvided() { - service = ScaleCube.builder().services(new SecuredServiceImpl()).startAwait(); + service = Scalecube.builder().services(new SecuredServiceImpl()).startAwait(); SecuredService securedService = service.call().credentials(CREDENTIALS).api(SecuredService.class); @@ -115,7 +115,7 @@ void failedAuthenticationWhenAuthenticatorNotProvided() { @DisplayName("Authentication failed with invalid or empty credentials") void failedAuthenticationWithInvalidOrEmptyCredentials() { service = - ScaleCube.builder() + Scalecube.builder() .authenticator(authenticator) .services(new SecuredServiceImpl()) .startAwait(); @@ -145,7 +145,7 @@ void failedAuthenticationWithInvalidOrEmptyCredentials() { @DisplayName("Successful authentication of partially secured service") void successfulAuthenticationOnPartiallySecuredService() { service = - ScaleCube.builder() + Scalecube.builder() .authenticator(authenticator) .services(new PartiallySecuredServiceImpl()) .startAwait(); @@ -161,7 +161,7 @@ void successfulAuthenticationOnPartiallySecuredService() { @Test @DisplayName("Successful call public method of partially secured service without authentication") void successfulCallOfPublicMethodWithoutAuthentication() { - service = ScaleCube.builder().services(new PartiallySecuredServiceImpl()).startAwait(); + service = Scalecube.builder().services(new PartiallySecuredServiceImpl()).startAwait(); PartiallySecuredService proxy = service.call().api(PartiallySecuredService.class); diff --git a/services/src/test/java/io/scalecube/services/ServiceAuthRemoteTest.java b/services/src/test/java/io/scalecube/services/ServiceAuthRemoteTest.java index fb8145152..9384744df 100644 --- a/services/src/test/java/io/scalecube/services/ServiceAuthRemoteTest.java +++ b/services/src/test/java/io/scalecube/services/ServiceAuthRemoteTest.java @@ -48,21 +48,21 @@ final class ServiceAuthRemoteTest { return Mono.error(new UnauthorizedException("Authentication failed")); }; - private static ScaleCube caller; - private static ScaleCube service; + private static Scalecube caller; + private static Scalecube service; @BeforeAll static void beforeAll() { StepVerifier.setDefaultTimeout(TIMEOUT); caller = - ScaleCube.builder() + Scalecube.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) .startAwait(); service = - ScaleCube.builder() + Scalecube.builder() .discovery(ServiceAuthRemoteTest::serviceDiscovery) .transport(RSocketServiceTransport::new) .authenticator(authenticator) @@ -103,8 +103,8 @@ void successfulAuthentication() { @Test @DisplayName("Authentication failed if authenticator not provided") void failedAuthenticationWhenAuthenticatorNotProvided() { - ScaleCube service = - ScaleCube.builder() + Scalecube service = + Scalecube.builder() .discovery(ServiceAuthRemoteTest::serviceDiscovery) .transport(RSocketServiceTransport::new) .services(new SecuredServiceImpl()) @@ -161,8 +161,8 @@ void failedAuthenticationWithInvalidOrEmptyCredentials() { @Test @DisplayName("Successful authentication of partially secured service") void successfulAuthenticationOnPartiallySecuredService() { - ScaleCube service = - ScaleCube.builder() + Scalecube service = + Scalecube.builder() .discovery(ServiceAuthRemoteTest::serviceDiscovery) .transport(RSocketServiceTransport::new) .authenticator(authenticator) @@ -182,8 +182,8 @@ void successfulAuthenticationOnPartiallySecuredService() { @Test @DisplayName("Successful call public method of partially secured service without authentication") void successfulCallOfPublicMethodWithoutAuthentication() { - ScaleCube service = - ScaleCube.builder() + Scalecube service = + Scalecube.builder() .discovery(ServiceAuthRemoteTest::serviceDiscovery) .transport(RSocketServiceTransport::new) .services(new PartiallySecuredServiceImpl()) diff --git a/services/src/test/java/io/scalecube/services/ServiceCallLocalTest.java b/services/src/test/java/io/scalecube/services/ServiceCallLocalTest.java index 0ecc79c57..ff1737594 100644 --- a/services/src/test/java/io/scalecube/services/ServiceCallLocalTest.java +++ b/services/src/test/java/io/scalecube/services/ServiceCallLocalTest.java @@ -37,7 +37,7 @@ public class ServiceCallLocalTest extends BaseTest { public static final int TIMEOUT = 3; private Duration timeout = Duration.ofSeconds(TIMEOUT); - private static ScaleCube provider; + private static Scalecube provider; @BeforeAll public static void setup() { @@ -63,8 +63,8 @@ public void test_local_async_no_params() { GREETING_NO_PARAMS_REQUEST.qualifier(), message.qualifier(), "Didn't get desired response"); } - private static ScaleCube serviceProvider() { - return ScaleCube.builder() + private static Scalecube serviceProvider() { + return Scalecube.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) .services(new GreetingServiceImpl()) diff --git a/services/src/test/java/io/scalecube/services/ServiceCallRemoteTest.java b/services/src/test/java/io/scalecube/services/ServiceCallRemoteTest.java index a1cae8148..578123217 100644 --- a/services/src/test/java/io/scalecube/services/ServiceCallRemoteTest.java +++ b/services/src/test/java/io/scalecube/services/ServiceCallRemoteTest.java @@ -40,8 +40,8 @@ public class ServiceCallRemoteTest extends BaseTest { public static final int TIMEOUT = 3; private Duration timeout = Duration.ofSeconds(TIMEOUT); - private static ScaleCube gateway; - private static ScaleCube provider; + private static Scalecube gateway; + private static Scalecube provider; @BeforeAll public static void setup() { @@ -64,8 +64,8 @@ public static void tearDown() { } } - private static ScaleCube serviceProvider(Object service) { - return ScaleCube.builder() + private static Scalecube serviceProvider(Object service) { + return Scalecube.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) @@ -226,7 +226,7 @@ public void test_service_address_lookup_occur_only_after_subscription() { // Add service to cluster AFTER creating a call object. // (prove address lookup occur only after subscription) - ScaleCube quotesService = serviceProvider(new SimpleQuoteService()); + Scalecube quotesService = serviceProvider(new SimpleQuoteService()); StepVerifier.create(quotes.take(1)).expectNextCount(1).expectComplete().verify(timeout); @@ -255,8 +255,8 @@ public void test_many_stream_block_first() { } } - private static ScaleCube gateway() { - return ScaleCube.builder() + private static Scalecube gateway() { + return Scalecube.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) .startAwait(); diff --git a/services/src/test/java/io/scalecube/services/ServiceLifecycleAnnotationsTest.java b/services/src/test/java/io/scalecube/services/ServiceLifecycleAnnotationsTest.java index 4155bf109..df68065db 100644 --- a/services/src/test/java/io/scalecube/services/ServiceLifecycleAnnotationsTest.java +++ b/services/src/test/java/io/scalecube/services/ServiceLifecycleAnnotationsTest.java @@ -18,8 +18,8 @@ void testAfterConstructThenBeforeDestroy() throws Exception { final CountDownLatch afterConstruct = new CountDownLatch(1); final CountDownLatch beforeDestroy = new CountDownLatch(1); - ScaleCube microservices = - ScaleCube.builder() + Scalecube microservices = + Scalecube.builder() .services( ServiceInfo.fromServiceInstance( new TestService() { @@ -55,7 +55,7 @@ void testAfterConstructFailsThenBeforeDestroy() throws Exception { Assertions.assertThrows( Exception.class, () -> - ScaleCube.builder() + Scalecube.builder() .services( ServiceInfo.fromServiceInstance( new TestService() { diff --git a/services/src/test/java/io/scalecube/services/ServiceLocalTest.java b/services/src/test/java/io/scalecube/services/ServiceLocalTest.java index 7a212acc2..bcfdc692c 100644 --- a/services/src/test/java/io/scalecube/services/ServiceLocalTest.java +++ b/services/src/test/java/io/scalecube/services/ServiceLocalTest.java @@ -23,11 +23,11 @@ public class ServiceLocalTest extends BaseTest { private static final Duration timeout = Duration.ofSeconds(3); - private ScaleCube microservices; + private Scalecube microservices; @BeforeEach public void setUp() { - microservices = ScaleCube.builder().services(new GreetingServiceImpl()).startAwait(); + microservices = Scalecube.builder().services(new GreetingServiceImpl()).startAwait(); } @AfterEach @@ -304,7 +304,7 @@ public void test_local_bidi_greeting_expect_GreetingResponse() { .verify(Duration.ofSeconds(3)); } - private GreetingService createProxy(ScaleCube gateway) { + private GreetingService createProxy(Scalecube gateway) { return gateway.call().api(GreetingService.class); // create proxy for GreetingService API } } diff --git a/services/src/test/java/io/scalecube/services/ServiceRegistryTest.java b/services/src/test/java/io/scalecube/services/ServiceRegistryTest.java index 9c4106c2d..ef8e264b2 100644 --- a/services/src/test/java/io/scalecube/services/ServiceRegistryTest.java +++ b/services/src/test/java/io/scalecube/services/ServiceRegistryTest.java @@ -47,8 +47,8 @@ public void test_added_removed_registration_events(MetadataCodec metadataCodec) List events = new ArrayList<>(); - ScaleCube seed = - ScaleCube.builder() + Scalecube seed = + Scalecube.builder() .discovery(defServiceDiscovery(metadataCodec)) .transport(RSocketServiceTransport::new) .startAwait(); @@ -57,15 +57,15 @@ public void test_added_removed_registration_events(MetadataCodec metadataCodec) Address seedAddress = seed.discovery().address(); - ScaleCube ms1 = - ScaleCube.builder() + Scalecube ms1 = + Scalecube.builder() .discovery(defServiceDiscovery(seedAddress, metadataCodec)) .transport(RSocketServiceTransport::new) .services(new GreetingServiceImpl()) .startAwait(); - ScaleCube ms2 = - ScaleCube.builder() + Scalecube ms2 = + Scalecube.builder() .discovery(defServiceDiscovery(seedAddress, metadataCodec)) .transport(RSocketServiceTransport::new) .services(new GreetingServiceImpl()) @@ -89,10 +89,10 @@ public void test_added_removed_registration_events(MetadataCodec metadataCodec) public void test_listen_to_discovery_events(MetadataCodec metadataCodec) { ReplayProcessor processor = ReplayProcessor.create(); - List cluster = new CopyOnWriteArrayList<>(); + List cluster = new CopyOnWriteArrayList<>(); - ScaleCube seed = - ScaleCube.builder() + Scalecube seed = + Scalecube.builder() .discovery(defServiceDiscovery(metadataCodec)) .transport(RSocketServiceTransport::new) .services(new AnnotationServiceImpl()) @@ -106,8 +106,8 @@ public void test_listen_to_discovery_events(MetadataCodec metadataCodec) { StepVerifier.create(processor) .then( () -> { - ScaleCube ms1 = - ScaleCube.builder() + Scalecube ms1 = + Scalecube.builder() .discovery(defServiceDiscovery(seedAddress, metadataCodec)) .transport(RSocketServiceTransport::new) .services(new GreetingServiceImpl()) @@ -117,8 +117,8 @@ public void test_listen_to_discovery_events(MetadataCodec metadataCodec) { .assertNext(event -> assertEquals(ENDPOINT_ADDED, event.type())) .then( () -> { - ScaleCube ms2 = - ScaleCube.builder() + Scalecube ms2 = + Scalecube.builder() .discovery(defServiceDiscovery(seedAddress, metadataCodec)) .transport(RSocketServiceTransport::new) .services(new GreetingServiceImpl()) @@ -147,7 +147,7 @@ public void test_listen_to_discovery_events(MetadataCodec metadataCodec) { .thenCancel() .verify(TIMEOUT); - Mono.when(cluster.stream().map(ScaleCube::shutdown).toArray(Mono[]::new)) + Mono.when(cluster.stream().map(Scalecube::shutdown).toArray(Mono[]::new)) .then(Mono.delay(TIMEOUT)) .block(); } @@ -157,10 +157,10 @@ public void test_listen_to_discovery_events(MetadataCodec metadataCodec) { public void test_delayed_listen_to_discovery_events(MetadataCodec metadataCodec) { ReplayProcessor processor = ReplayProcessor.create(); - List cluster = new CopyOnWriteArrayList<>(); + List cluster = new CopyOnWriteArrayList<>(); - ScaleCube seed = - ScaleCube.builder() + Scalecube seed = + Scalecube.builder() .discovery(defServiceDiscovery(metadataCodec)) .transport(RSocketServiceTransport::new) .services(new GreetingServiceImpl()) @@ -174,8 +174,8 @@ public void test_delayed_listen_to_discovery_events(MetadataCodec metadataCodec) StepVerifier.create(processor) .then( () -> { - ScaleCube ms1 = - ScaleCube.builder() + Scalecube ms1 = + Scalecube.builder() .discovery(defServiceDiscovery(seedAddress, metadataCodec)) .transport(RSocketServiceTransport::new) .services(new GreetingServiceImpl(), new AnnotationServiceImpl()) @@ -185,8 +185,8 @@ public void test_delayed_listen_to_discovery_events(MetadataCodec metadataCodec) .assertNext(event -> assertEquals(ENDPOINT_ADDED, event.type())) .then( () -> { - ScaleCube ms2 = - ScaleCube.builder() + Scalecube ms2 = + Scalecube.builder() .discovery(defServiceDiscovery(seedAddress, metadataCodec)) .transport(RSocketServiceTransport::new) .services(new GreetingServiceImpl()) @@ -203,7 +203,7 @@ public void test_delayed_listen_to_discovery_events(MetadataCodec metadataCodec) .thenCancel() .verify(TIMEOUT); - Mono.when(cluster.stream().map(ScaleCube::shutdown).toArray(Mono[]::new)) + Mono.when(cluster.stream().map(Scalecube::shutdown).toArray(Mono[]::new)) .then(Mono.delay(TIMEOUT)) .block(); } diff --git a/services/src/test/java/io/scalecube/services/ServiceRemoteTest.java b/services/src/test/java/io/scalecube/services/ServiceRemoteTest.java index a90c4c4f7..aafe3dbf2 100644 --- a/services/src/test/java/io/scalecube/services/ServiceRemoteTest.java +++ b/services/src/test/java/io/scalecube/services/ServiceRemoteTest.java @@ -36,8 +36,8 @@ public class ServiceRemoteTest extends BaseTest { private static final Duration TIMEOUT = Duration.ofSeconds(10); public static final Duration TIMEOUT2 = Duration.ofSeconds(6); - private static ScaleCube gateway; - private static ScaleCube provider; + private static Scalecube gateway; + private static Scalecube provider; @BeforeAll public static void setup() { @@ -61,15 +61,15 @@ public static void tearDown() { } } - private static ScaleCube gateway() { - return ScaleCube.builder() + private static Scalecube gateway() { + return Scalecube.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) .startAwait(); } - private static ScaleCube serviceProvider() { - return ScaleCube.builder() + private static Scalecube serviceProvider() { + return Scalecube.builder() .discovery(ServiceRemoteTest::serviceDiscovery) .transport(RSocketServiceTransport::new) .services(new GreetingServiceImpl()) @@ -264,8 +264,8 @@ public void test_remote_serviceA_calls_serviceB_using_setter() { // Create microservices instance cluster. // noinspection unused - ScaleCube provider = - ScaleCube.builder() + Scalecube provider = + Scalecube.builder() .discovery(ServiceRemoteTest::serviceDiscovery) .transport(RSocketServiceTransport::new) .services(new CoarseGrainedServiceImpl()) // add service a and b @@ -287,8 +287,8 @@ public void test_remote_serviceA_calls_serviceB() { // Create microservices instance cluster. // noinspection unused - ScaleCube provider = - ScaleCube.builder() + Scalecube provider = + Scalecube.builder() .discovery(ServiceRemoteTest::serviceDiscovery) .transport(RSocketServiceTransport::new) .services(another) @@ -307,8 +307,8 @@ public void test_remote_serviceA_calls_serviceB_with_timeout() { CoarseGrainedServiceImpl another = new CoarseGrainedServiceImpl(); // Create microservices instance cluster. - ScaleCube ms = - ScaleCube.builder() + Scalecube ms = + Scalecube.builder() .discovery(ServiceRemoteTest::serviceDiscovery) .transport(RSocketServiceTransport::new) .services(another) // add service a and b @@ -332,8 +332,8 @@ public void test_remote_serviceA_calls_serviceB_with_dispatcher() { CoarseGrainedServiceImpl another = new CoarseGrainedServiceImpl(); // Create microservices instance cluster. - ScaleCube provider = - ScaleCube.builder() + Scalecube provider = + Scalecube.builder() .discovery(ServiceRemoteTest::serviceDiscovery) .transport(RSocketServiceTransport::new) .services(another) // add service a and b @@ -416,8 +416,8 @@ public void test_services_contribute_to_cluster_metadata() { Map tags = new HashMap<>(); tags.put("HOSTNAME", "host1"); - ScaleCube ms = - ScaleCube.builder() + Scalecube ms = + Scalecube.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) .tags(tags) diff --git a/services/src/test/java/io/scalecube/services/StreamingServiceTest.java b/services/src/test/java/io/scalecube/services/StreamingServiceTest.java index 941080a7e..56e0b3c72 100644 --- a/services/src/test/java/io/scalecube/services/StreamingServiceTest.java +++ b/services/src/test/java/io/scalecube/services/StreamingServiceTest.java @@ -21,20 +21,20 @@ public class StreamingServiceTest extends BaseTest { - private static ScaleCube gateway; - private static ScaleCube node; + private static Scalecube gateway; + private static Scalecube node; @BeforeAll public static void setup() { gateway = - ScaleCube.builder() + Scalecube.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) .defaultDataDecoder(ServiceMessageCodec::decodeData) .startAwait(); node = - ScaleCube.builder() + Scalecube.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) diff --git a/services/src/test/java/io/scalecube/services/routings/RoutersTest.java b/services/src/test/java/io/scalecube/services/routings/RoutersTest.java index 5e714a54b..7b092c314 100644 --- a/services/src/test/java/io/scalecube/services/routings/RoutersTest.java +++ b/services/src/test/java/io/scalecube/services/routings/RoutersTest.java @@ -11,7 +11,7 @@ import io.scalecube.net.Address; import io.scalecube.services.BaseTest; -import io.scalecube.services.ScaleCube; +import io.scalecube.services.Scalecube; import io.scalecube.services.Reflect; import io.scalecube.services.ServiceCall; import io.scalecube.services.ServiceInfo; @@ -47,16 +47,16 @@ public class RoutersTest extends BaseTest { public static final int TIMEOUT = 10; private Duration timeout = Duration.ofSeconds(TIMEOUT); - private static ScaleCube gateway; + private static Scalecube gateway; private static Address gatewayAddress; - private static ScaleCube provider1; - private static ScaleCube provider2; - private static ScaleCube provider3; + private static Scalecube provider1; + private static Scalecube provider2; + private static Scalecube provider3; @BeforeAll public static void setup() { gateway = - ScaleCube.builder() // + Scalecube.builder() // .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) .startAwait(); @@ -65,7 +65,7 @@ public static void setup() { // Create microservices instance cluster. provider1 = - ScaleCube.builder() + Scalecube.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) @@ -83,7 +83,7 @@ public static void setup() { // Create microservices instance cluster. provider2 = - ScaleCube.builder() + Scalecube.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) @@ -101,7 +101,7 @@ public static void setup() { TagService tagService = input -> input.map(String::toUpperCase); provider3 = - ScaleCube.builder() + Scalecube.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) diff --git a/services/src/test/java/io/scalecube/services/routings/ServiceTagsExample.java b/services/src/test/java/io/scalecube/services/routings/ServiceTagsExample.java index eb92945ad..3aed21031 100644 --- a/services/src/test/java/io/scalecube/services/routings/ServiceTagsExample.java +++ b/services/src/test/java/io/scalecube/services/routings/ServiceTagsExample.java @@ -1,7 +1,7 @@ package io.scalecube.services.routings; import io.scalecube.net.Address; -import io.scalecube.services.ScaleCube; +import io.scalecube.services.Scalecube; import io.scalecube.services.ServiceInfo; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.routings.sut.CanaryService; @@ -20,16 +20,16 @@ public class ServiceTagsExample { * @param args arguments */ public static void main(String[] args) { - ScaleCube gateway = - ScaleCube.builder() + Scalecube gateway = + Scalecube.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) .startAwait(); Address seedAddress = gateway.discovery().address(); - ScaleCube services1 = - ScaleCube.builder() + Scalecube services1 = + Scalecube.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) @@ -41,8 +41,8 @@ public static void main(String[] args) { .build()) .startAwait(); - ScaleCube services2 = - ScaleCube.builder() + Scalecube services2 = + Scalecube.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) diff --git a/services/src/test/java/io/scalecube/services/sut/AnnotationServiceImpl.java b/services/src/test/java/io/scalecube/services/sut/AnnotationServiceImpl.java index 5186d4539..6aa6ec115 100644 --- a/services/src/test/java/io/scalecube/services/sut/AnnotationServiceImpl.java +++ b/services/src/test/java/io/scalecube/services/sut/AnnotationServiceImpl.java @@ -1,6 +1,6 @@ package io.scalecube.services.sut; -import io.scalecube.services.ScaleCube; +import io.scalecube.services.Scalecube; import io.scalecube.services.annotations.AfterConstruct; import io.scalecube.services.discovery.api.ServiceDiscoveryEvent; import reactor.core.publisher.Flux; @@ -11,7 +11,7 @@ public class AnnotationServiceImpl implements AnnotationService { private ReplayProcessor serviceDiscoveryEvents; @AfterConstruct - void init(ScaleCube microservices) { + void init(Scalecube microservices) { this.serviceDiscoveryEvents = ReplayProcessor.create(); microservices.discovery().listenDiscovery().subscribe(serviceDiscoveryEvents); } diff --git a/services/src/test/java/io/scalecube/services/sut/CoarseGrainedServiceImpl.java b/services/src/test/java/io/scalecube/services/sut/CoarseGrainedServiceImpl.java index d697695e6..1d4af8091 100644 --- a/services/src/test/java/io/scalecube/services/sut/CoarseGrainedServiceImpl.java +++ b/services/src/test/java/io/scalecube/services/sut/CoarseGrainedServiceImpl.java @@ -1,6 +1,6 @@ package io.scalecube.services.sut; -import io.scalecube.services.ScaleCube; +import io.scalecube.services.Scalecube; import io.scalecube.services.annotations.Inject; import io.scalecube.services.api.ServiceMessage; import java.time.Duration; @@ -12,7 +12,7 @@ public class CoarseGrainedServiceImpl implements CoarseGrainedService { @Inject private GreetingService greetingService; - @Inject private ScaleCube microservices; + @Inject private Scalecube microservices; @Override public Mono callGreeting(String name) { diff --git a/services/src/test/java/io/scalecube/services/sut/GreetingServiceImpl.java b/services/src/test/java/io/scalecube/services/sut/GreetingServiceImpl.java index 76fe63e8c..5cd7c6412 100644 --- a/services/src/test/java/io/scalecube/services/sut/GreetingServiceImpl.java +++ b/services/src/test/java/io/scalecube/services/sut/GreetingServiceImpl.java @@ -1,6 +1,6 @@ package io.scalecube.services.sut; -import io.scalecube.services.ScaleCube; +import io.scalecube.services.Scalecube; import io.scalecube.services.annotations.Inject; import io.scalecube.services.api.ServiceMessage; import io.scalecube.services.exceptions.UnauthorizedException; @@ -13,7 +13,7 @@ public final class GreetingServiceImpl implements GreetingService { @Inject - ScaleCube ms; + Scalecube ms; private int instanceId; diff --git a/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketNettyColocatedEventLoopGroupTest.java b/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketNettyColocatedEventLoopGroupTest.java index ba64df20c..cb54e0f62 100644 --- a/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketNettyColocatedEventLoopGroupTest.java +++ b/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketNettyColocatedEventLoopGroupTest.java @@ -3,7 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import io.scalecube.services.BaseTest; -import io.scalecube.services.ScaleCube; +import io.scalecube.services.Scalecube; import io.scalecube.services.ServiceCall; import io.scalecube.services.annotations.Inject; import io.scalecube.services.annotations.Service; @@ -19,20 +19,20 @@ public class RSocketNettyColocatedEventLoopGroupTest extends BaseTest { - private ScaleCube ping; - private ScaleCube pong; - private ScaleCube gateway; + private Scalecube ping; + private Scalecube pong; + private Scalecube gateway; @BeforeEach public void setUp() { this.gateway = - ScaleCube.builder() + Scalecube.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) .startAwait(); - ScaleCube facade = - ScaleCube.builder() + Scalecube facade = + Scalecube.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) @@ -42,7 +42,7 @@ public void setUp() { .startAwait(); this.ping = - ScaleCube.builder() + Scalecube.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) @@ -52,7 +52,7 @@ public void setUp() { .startAwait(); this.pong = - ScaleCube.builder() + Scalecube.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) @@ -80,9 +80,9 @@ public void testColocatedEventLoopGroup() { public void tearDown() { try { Mono.whenDelayError( - Optional.ofNullable(gateway).map(ScaleCube::shutdown).orElse(Mono.empty()), - Optional.ofNullable(ping).map(ScaleCube::shutdown).orElse(Mono.empty()), - Optional.ofNullable(pong).map(ScaleCube::shutdown).orElse(Mono.empty())) + Optional.ofNullable(gateway).map(Scalecube::shutdown).orElse(Mono.empty()), + Optional.ofNullable(ping).map(Scalecube::shutdown).orElse(Mono.empty()), + Optional.ofNullable(pong).map(Scalecube::shutdown).orElse(Mono.empty())) .block(); } catch (Throwable ignore) { // no-op diff --git a/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketServiceTransportTest.java b/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketServiceTransportTest.java index 415e62151..4a4941b11 100644 --- a/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketServiceTransportTest.java +++ b/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketServiceTransportTest.java @@ -4,7 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import io.scalecube.services.BaseTest; -import io.scalecube.services.ScaleCube; +import io.scalecube.services.Scalecube; import io.scalecube.services.ServiceCall; import io.scalecube.services.api.ServiceMessage; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; @@ -32,19 +32,19 @@ public class RSocketServiceTransportTest extends BaseTest { private static final ServiceMessage ONLY_ONE_AND_THEN_NEVER = ServiceMessage.builder().qualifier(QuoteService.NAME, "onlyOneAndThenNever").build(); - private ScaleCube gateway; - private ScaleCube serviceNode; + private Scalecube gateway; + private Scalecube serviceNode; @BeforeEach public void setUp() { gateway = - ScaleCube.builder() + Scalecube.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) .startAwait(); serviceNode = - ScaleCube.builder() + Scalecube.builder() .discovery( serviceEndpoint -> new ScalecubeServiceDiscovery(serviceEndpoint) @@ -58,8 +58,8 @@ public void setUp() { public void cleanUp() { try { Mono.whenDelayError( - Optional.ofNullable(gateway).map(ScaleCube::shutdown).orElse(Mono.empty()), - Optional.ofNullable(serviceNode).map(ScaleCube::shutdown).orElse(Mono.empty())) + Optional.ofNullable(gateway).map(Scalecube::shutdown).orElse(Mono.empty()), + Optional.ofNullable(serviceNode).map(Scalecube::shutdown).orElse(Mono.empty())) .block(); } catch (Throwable ignore) { // no-op From 7eae1a79981d444d81f2e920d8971643e1d0245b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=95=D0=B2=D0=B3=D0=B5=D0=BD=D0=B8=D0=B9=20=D0=A3=D1=82?= =?UTF-8?q?=D0=BA=D0=B8=D0=BD?= Date: Fri, 13 Mar 2020 16:24:36 +0300 Subject: [PATCH 25/61] ISSUE 708, fix check style --- .../main/java/io/scalecube/services/Scalecube.java | 11 ++++++++++- .../services/inject/ScaleCubeServicesProvider.java | 4 +++- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/services/src/main/java/io/scalecube/services/Scalecube.java b/services/src/main/java/io/scalecube/services/Scalecube.java index 5c08fa72d..85da2a201 100644 --- a/services/src/main/java/io/scalecube/services/Scalecube.java +++ b/services/src/main/java/io/scalecube/services/Scalecube.java @@ -26,7 +26,16 @@ import io.scalecube.services.transport.api.ServiceTransport; import java.lang.management.ManagementFactory; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.StringJoiner; +import java.util.UUID; import java.util.concurrent.CopyOnWriteArrayList; import java.util.function.Function; import java.util.function.Supplier; diff --git a/services/src/main/java/io/scalecube/services/inject/ScaleCubeServicesProvider.java b/services/src/main/java/io/scalecube/services/inject/ScaleCubeServicesProvider.java index 5b4c5b693..1ed0a899c 100644 --- a/services/src/main/java/io/scalecube/services/inject/ScaleCubeServicesProvider.java +++ b/services/src/main/java/io/scalecube/services/inject/ScaleCubeServicesProvider.java @@ -13,7 +13,9 @@ import reactor.core.publisher.Mono; -/** Default {@link ServicesProvider}. Thread-safe. */ +/** + * Default {@link ServicesProvider}. Thread-safe. + */ public class ScaleCubeServicesProvider implements ServicesProvider { private final Function> serviceFactory; From 5b98d7cdf202b70c5cd35fb350bd889b1f36737e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=95=D0=B2=D0=B3=D0=B5=D0=BD=D0=B8=D0=B9=20=D0=A3=D1=82?= =?UTF-8?q?=D0=BA=D0=B8=D0=BD?= Date: Fri, 13 Mar 2020 16:34:28 +0300 Subject: [PATCH 26/61] ISSUE 708, fix check style --- .../inject/ScaleCubeServicesProvider.java | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/services/src/main/java/io/scalecube/services/inject/ScaleCubeServicesProvider.java b/services/src/main/java/io/scalecube/services/inject/ScaleCubeServicesProvider.java index 1ed0a899c..bc3752a7a 100644 --- a/services/src/main/java/io/scalecube/services/inject/ScaleCubeServicesProvider.java +++ b/services/src/main/java/io/scalecube/services/inject/ScaleCubeServicesProvider.java @@ -94,14 +94,13 @@ public Mono> provideService(Microservices micr @Override public Mono shutDown(Microservices microservices) { return Mono.fromRunnable( - () -> { - if (this.services.get() != null) { - this.services - .get() - .forEach(service -> Injector.processBeforeDestroy(microservices, service)); - } - }) - .thenReturn(microservices); + () -> { + if (this.services.get() != null) { + this.services + .get() + .forEach(service -> Injector.processBeforeDestroy(microservices, service)); + } + }).thenReturn(microservices); } private Collection services(Microservices microservices) { From 22b88fc230c2ba1c24f46263c2d379609bcad1e8 Mon Sep 17 00:00:00 2001 From: artem-v Date: Sun, 15 Mar 2020 01:39:09 +0200 Subject: [PATCH 27/61] Fixed style --- .../java/io/scalecube/services/Reflect.java | 1 - .../scalecube/services/ServicesProvider.java | 1 - .../services/annotations/BeforeDestroy.java | 3 +-- .../transport/api/DefaultHeadersCodec.java | 9 --------- .../spring/SpringServicesProvider.java | 3 --- .../spring/SpringServicesProviderTest.java | 10 +++++----- .../java/io/scalecube/services/Scalecube.java | 5 ----- .../scalecube/services/inject/Injector.java | 2 -- .../inject/ScaleCubeServicesProvider.java | 20 +++++++------------ .../services/routings/RoutersTest.java | 2 +- .../services/sut/GreetingServiceImpl.java | 3 +-- 11 files changed, 15 insertions(+), 44 deletions(-) diff --git a/services-api/src/main/java/io/scalecube/services/Reflect.java b/services-api/src/main/java/io/scalecube/services/Reflect.java index ea6df6528..140fbdd3f 100644 --- a/services-api/src/main/java/io/scalecube/services/Reflect.java +++ b/services-api/src/main/java/io/scalecube/services/Reflect.java @@ -25,7 +25,6 @@ import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; - import org.reactivestreams.Publisher; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; diff --git a/services-api/src/main/java/io/scalecube/services/ServicesProvider.java b/services-api/src/main/java/io/scalecube/services/ServicesProvider.java index cb654bdda..ace69092c 100644 --- a/services-api/src/main/java/io/scalecube/services/ServicesProvider.java +++ b/services-api/src/main/java/io/scalecube/services/ServicesProvider.java @@ -1,7 +1,6 @@ package io.scalecube.services; import java.util.Collection; - import reactor.core.publisher.Mono; /** Manages the life cycle of all services registered with Scale Cube Services. */ diff --git a/services-api/src/main/java/io/scalecube/services/annotations/BeforeDestroy.java b/services-api/src/main/java/io/scalecube/services/annotations/BeforeDestroy.java index bb37bb57f..8d0d94008 100644 --- a/services-api/src/main/java/io/scalecube/services/annotations/BeforeDestroy.java +++ b/services-api/src/main/java/io/scalecube/services/annotations/BeforeDestroy.java @@ -8,8 +8,7 @@ import java.lang.annotation.Target; /** - * This annotation is used to mark the method which will be executed before shutdown of service - *
+ * This annotation is used to mark the method which will be executed before shutdown of service
* Scalecube services doesn't support {@link javax.annotation.PreDestroy} since Java API * * Specification for it has strict limitation for annotated method. */ diff --git a/services-bytebuf-codec/src/main/java/io/scalecube/services/transport/api/DefaultHeadersCodec.java b/services-bytebuf-codec/src/main/java/io/scalecube/services/transport/api/DefaultHeadersCodec.java index 7be169a35..fedc3198c 100644 --- a/services-bytebuf-codec/src/main/java/io/scalecube/services/transport/api/DefaultHeadersCodec.java +++ b/services-bytebuf-codec/src/main/java/io/scalecube/services/transport/api/DefaultHeadersCodec.java @@ -13,17 +13,11 @@ /** Simple binary codec for headers service message. */ public class DefaultHeadersCodec implements HeadersCodec { - /** - * {@inheritDoc} - */ @Override public String contentType() { return "application/octet-stream"; } - /** - * {@inheritDoc} - */ @Override public void encode(OutputStream stream, Map headers) throws IOException { if (headers.isEmpty()) { @@ -40,9 +34,6 @@ public void encode(OutputStream stream, Map headers) throws IOEx } } - /** - * {@inheritDoc} - */ @Override public Map decode(InputStream stream) throws IOException { if (stream.available() < 1) { diff --git a/services-examples-parent/scalecube-examples-spring/src/main/java/io/scalecube/spring/SpringServicesProvider.java b/services-examples-parent/scalecube-examples-spring/src/main/java/io/scalecube/spring/SpringServicesProvider.java index 2021d70d2..ddae5995c 100644 --- a/services-examples-parent/scalecube-examples-spring/src/main/java/io/scalecube/spring/SpringServicesProvider.java +++ b/services-examples-parent/scalecube-examples-spring/src/main/java/io/scalecube/spring/SpringServicesProvider.java @@ -7,7 +7,6 @@ import io.scalecube.services.ServicesProvider; import io.scalecube.services.annotations.Service; import io.scalecube.services.discovery.api.ServiceDiscovery; - import java.util.Collection; import java.util.Collections; import java.util.List; @@ -15,11 +14,9 @@ import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; - import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.support.GenericBeanDefinition; import org.springframework.context.annotation.AnnotationConfigApplicationContext; - import org.springframework.util.ClassUtils; import reactor.core.publisher.Mono; diff --git a/services-examples-parent/scalecube-examples-spring/src/test/java/io/scalecube/spring/SpringServicesProviderTest.java b/services-examples-parent/scalecube-examples-spring/src/test/java/io/scalecube/spring/SpringServicesProviderTest.java index b306958d6..9e528c9b0 100644 --- a/services-examples-parent/scalecube-examples-spring/src/test/java/io/scalecube/spring/SpringServicesProviderTest.java +++ b/services-examples-parent/scalecube-examples-spring/src/test/java/io/scalecube/spring/SpringServicesProviderTest.java @@ -1,5 +1,7 @@ package io.scalecube.spring; +import static org.junit.jupiter.api.Assertions.assertEquals; + import io.scalecube.services.Scalecube; import io.scalecube.services.ServiceCall; import io.scalecube.services.ServiceEndpoint; @@ -8,6 +10,7 @@ import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.discovery.api.ServiceDiscovery; import io.scalecube.services.transport.rsocket.RSocketServiceTransport; +import java.time.Duration; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -16,10 +19,6 @@ import reactor.core.publisher.Hooks; import reactor.core.publisher.Mono; -import java.time.Duration; - -import static org.junit.jupiter.api.Assertions.assertEquals; - class SpringServicesProviderTest { private static Scalecube microserviceWithSpring; @@ -82,7 +81,8 @@ private static ServiceDiscovery serviceDiscovery(ServiceEndpoint endpoint) { @Configuration static class Beans { @Bean - public LocalService localServiceBean(ServiceCall serviceCall, ServiceDiscovery serviceDiscovery) { + public LocalService localServiceBean( + ServiceCall serviceCall, ServiceDiscovery serviceDiscovery) { return new LocalServiceBean(serviceCall, serviceDiscovery); } } diff --git a/services/src/main/java/io/scalecube/services/Scalecube.java b/services/src/main/java/io/scalecube/services/Scalecube.java index 85da2a201..a1f8bd962 100644 --- a/services/src/main/java/io/scalecube/services/Scalecube.java +++ b/services/src/main/java/io/scalecube/services/Scalecube.java @@ -24,7 +24,6 @@ import io.scalecube.services.transport.api.ServerTransport; import io.scalecube.services.transport.api.ServiceMessageDataDecoder; import io.scalecube.services.transport.api.ServiceTransport; - import java.lang.management.ManagementFactory; import java.util.ArrayList; import java.util.Arrays; @@ -41,21 +40,17 @@ import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; - import javax.management.MBeanServer; import javax.management.ObjectName; import javax.management.StandardMBean; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import reactor.core.Disposable; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.core.publisher.MonoProcessor; import reactor.core.scheduler.Scheduler; import reactor.core.scheduler.Schedulers; - import sun.misc.Signal; import sun.misc.SignalHandler; diff --git a/services/src/main/java/io/scalecube/services/inject/Injector.java b/services/src/main/java/io/scalecube/services/inject/Injector.java index 94c00c588..fa46c191c 100644 --- a/services/src/main/java/io/scalecube/services/inject/Injector.java +++ b/services/src/main/java/io/scalecube/services/inject/Injector.java @@ -9,12 +9,10 @@ import io.scalecube.services.annotations.BeforeDestroy; import io.scalecube.services.annotations.Inject; import io.scalecube.services.routing.Router; - import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Arrays; - import reactor.core.Exceptions; /** Service Injector scan and injects beans to a given Microservices instance. */ diff --git a/services/src/main/java/io/scalecube/services/inject/ScaleCubeServicesProvider.java b/services/src/main/java/io/scalecube/services/inject/ScaleCubeServicesProvider.java index bc3752a7a..4658978ce 100644 --- a/services/src/main/java/io/scalecube/services/inject/ScaleCubeServicesProvider.java +++ b/services/src/main/java/io/scalecube/services/inject/ScaleCubeServicesProvider.java @@ -5,17 +5,12 @@ import io.scalecube.services.ServiceInfo; import io.scalecube.services.ServiceProvider; import io.scalecube.services.ServicesProvider; - import java.util.Collection; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; import java.util.stream.Collectors; - import reactor.core.publisher.Mono; -/** - * Default {@link ServicesProvider}. Thread-safe. - */ public class ScaleCubeServicesProvider implements ServicesProvider { private final Function> serviceFactory; @@ -93,14 +88,13 @@ public Mono> provideService(Microservices micr */ @Override public Mono shutDown(Microservices microservices) { - return Mono.fromRunnable( - () -> { - if (this.services.get() != null) { - this.services - .get() - .forEach(service -> Injector.processBeforeDestroy(microservices, service)); - } - }).thenReturn(microservices); + return Mono.fromRunnable(() -> shutdown0(microservices)).thenReturn(microservices); + } + + private void shutdown0(Microservices microservices) { + if (this.services.get() != null) { + this.services.get().forEach(service -> Injector.processBeforeDestroy(microservices, service)); + } } private Collection services(Microservices microservices) { diff --git a/services/src/test/java/io/scalecube/services/routings/RoutersTest.java b/services/src/test/java/io/scalecube/services/routings/RoutersTest.java index 7b092c314..143000d07 100644 --- a/services/src/test/java/io/scalecube/services/routings/RoutersTest.java +++ b/services/src/test/java/io/scalecube/services/routings/RoutersTest.java @@ -11,8 +11,8 @@ import io.scalecube.net.Address; import io.scalecube.services.BaseTest; -import io.scalecube.services.Scalecube; import io.scalecube.services.Reflect; +import io.scalecube.services.Scalecube; import io.scalecube.services.ServiceCall; import io.scalecube.services.ServiceInfo; import io.scalecube.services.ServiceReference; diff --git a/services/src/test/java/io/scalecube/services/sut/GreetingServiceImpl.java b/services/src/test/java/io/scalecube/services/sut/GreetingServiceImpl.java index 5cd7c6412..583ac2aaa 100644 --- a/services/src/test/java/io/scalecube/services/sut/GreetingServiceImpl.java +++ b/services/src/test/java/io/scalecube/services/sut/GreetingServiceImpl.java @@ -12,8 +12,7 @@ public final class GreetingServiceImpl implements GreetingService { - @Inject - Scalecube ms; + @Inject Scalecube ms; private int instanceId; From 8e48b228b5a9a4611062840c27bcbce55140a98d Mon Sep 17 00:00:00 2001 From: eutkin Date: Mon, 16 Mar 2020 19:15:34 +0300 Subject: [PATCH 28/61] ISSUE-708 fix code style --- ...vicesProvider.java => ServiceFactory.java} | 11 +- .../io/scalecube/services/ServiceInfo.java | 21 ++-- .../scalecube/services/ServiceProvider.java | 2 +- services-examples-parent/pom.xml | 1 - .../scalecube-examples-spring/pom.xml | 55 -------- .../spring/SpringServicesProvider.java | 100 --------------- .../spring/SpringServicesProviderTest.java | 118 ------------------ .../java/io/scalecube/services/Scalecube.java | 111 ++++++++-------- ...ider.java => ScaleCubeServiceFactory.java} | 18 +-- 9 files changed, 83 insertions(+), 354 deletions(-) rename services-api/src/main/java/io/scalecube/services/{ServicesProvider.java => ServiceFactory.java} (64%) delete mode 100644 services-examples-parent/scalecube-examples-spring/pom.xml delete mode 100644 services-examples-parent/scalecube-examples-spring/src/main/java/io/scalecube/spring/SpringServicesProvider.java delete mode 100644 services-examples-parent/scalecube-examples-spring/src/test/java/io/scalecube/spring/SpringServicesProviderTest.java rename services/src/main/java/io/scalecube/services/inject/{ScaleCubeServicesProvider.java => ScaleCubeServiceFactory.java} (82%) diff --git a/services-api/src/main/java/io/scalecube/services/ServicesProvider.java b/services-api/src/main/java/io/scalecube/services/ServiceFactory.java similarity index 64% rename from services-api/src/main/java/io/scalecube/services/ServicesProvider.java rename to services-api/src/main/java/io/scalecube/services/ServiceFactory.java index ace69092c..804799ae4 100644 --- a/services-api/src/main/java/io/scalecube/services/ServicesProvider.java +++ b/services-api/src/main/java/io/scalecube/services/ServiceFactory.java @@ -4,17 +4,16 @@ import reactor.core.publisher.Mono; /** Manages the life cycle of all services registered with Scale Cube Services. */ -public interface ServicesProvider { +public interface ServiceFactory { /** * Provide service definitions. * * @param microservices scale cube instance. - * @return collection of service definitions - service type&tags. + * @return collection of service definitions - service type and tags. * @see ServiceDefinition */ - Mono> provideServiceDefinitions( - Microservices microservices); + Mono> getServiceDefinitions(Microservices microservices); /** * Initialize instances of services. @@ -22,7 +21,7 @@ Mono> provideServiceDefinitions( * @param microservices scale cube instance. * @return Completed Mono if initialization was successful for all services. */ - Mono> provideService(Microservices microservices); + Mono> initializeServices(Microservices microservices); /** * Finalization of service instances. @@ -30,5 +29,5 @@ Mono> provideServiceDefinitions( * @param microservices scale cube instance. * @return completed Mono if finalization was successful for all services. */ - Mono shutDown(Microservices microservices); + Mono shutdownServices(Microservices microservices); } diff --git a/services-api/src/main/java/io/scalecube/services/ServiceInfo.java b/services-api/src/main/java/io/scalecube/services/ServiceInfo.java index 1cff854ce..deb1405ba 100644 --- a/services-api/src/main/java/io/scalecube/services/ServiceInfo.java +++ b/services-api/src/main/java/io/scalecube/services/ServiceInfo.java @@ -6,6 +6,7 @@ import java.util.Collections; import java.util.HashMap; import java.util.Map; +import java.util.Objects; import java.util.StringJoiner; @SuppressWarnings("rawtypes") @@ -126,10 +127,7 @@ public Builder dataDecoder(ServiceMessageDataDecoder dataDecoder) { * @return current builder's state. */ public Builder errorMapperIfAbsent(ServiceProviderErrorMapper errorMapper) { - if (this.errorMapper == null) { - this.errorMapper = errorMapper; - } - return this; + return Objects.isNull(this.errorMapper) ? this.errorMapper(errorMapper) : this; } /** @@ -139,10 +137,7 @@ public Builder errorMapperIfAbsent(ServiceProviderErrorMapper errorMapper) { * @return current builder's state. */ public Builder dataDecoderIfAbsent(ServiceMessageDataDecoder dataDecoder) { - if (this.dataDecoder == null) { - this.dataDecoder = dataDecoder; - } - return this; + return Objects.isNull(this.dataDecoder) ? this.dataDecoder(dataDecoder) : this; } /** @@ -156,6 +151,16 @@ public Builder authenticator(Authenticator authenticator) { return this; } + /** + * Set up {@link Authenticator} if it hasn't been set up before. + * + * @param authenticator authenticator. + * @return current builder's state. + */ + public Builder authenticatorIfAbsent(Authenticator authenticator) { + return Objects.isNull(this.authenticator) ? this.authenticator(authenticator) : this; + } + /** * Build service info. * diff --git a/services-api/src/main/java/io/scalecube/services/ServiceProvider.java b/services-api/src/main/java/io/scalecube/services/ServiceProvider.java index 92faa6f1e..6e7f1ce23 100644 --- a/services-api/src/main/java/io/scalecube/services/ServiceProvider.java +++ b/services-api/src/main/java/io/scalecube/services/ServiceProvider.java @@ -5,7 +5,7 @@ /** * Provide service instances. * - * @deprecated use {@link ServicesProvider} + * @deprecated use {@link ServiceFactory} */ @FunctionalInterface @Deprecated diff --git a/services-examples-parent/pom.xml b/services-examples-parent/pom.xml index 22cb00a51..51c4ea328 100644 --- a/services-examples-parent/pom.xml +++ b/services-examples-parent/pom.xml @@ -14,7 +14,6 @@ services-examples services-examples-runner - scalecube-examples-spring diff --git a/services-examples-parent/scalecube-examples-spring/pom.xml b/services-examples-parent/scalecube-examples-spring/pom.xml deleted file mode 100644 index f3296f257..000000000 --- a/services-examples-parent/scalecube-examples-spring/pom.xml +++ /dev/null @@ -1,55 +0,0 @@ - - - - scalecube-services-examples-parent - io.scalecube - 2.8.10-SNAPSHOT - - 4.0.0 - - scalecube-examples-spring - - - - io.scalecube - scalecube-services - ${project.version} - - - io.scalecube - scalecube-services-discovery - ${project.version} - - - io.scalecube - scalecube-services-transport-rsocket - ${project.version} - - - io.scalecube - scalecube-services-transport-jackson - ${project.version} - - - org.springframework - spring-core - ${spring.version} - - - org.springframework - spring-beans - ${spring.version} - - - org.springframework - spring-context - ${spring.version} - - - - 5.2.4.RELEASE - - - \ No newline at end of file diff --git a/services-examples-parent/scalecube-examples-spring/src/main/java/io/scalecube/spring/SpringServicesProvider.java b/services-examples-parent/scalecube-examples-spring/src/main/java/io/scalecube/spring/SpringServicesProvider.java deleted file mode 100644 index ddae5995c..000000000 --- a/services-examples-parent/scalecube-examples-spring/src/main/java/io/scalecube/spring/SpringServicesProvider.java +++ /dev/null @@ -1,100 +0,0 @@ -package io.scalecube.spring; - -import io.scalecube.services.Microservices; -import io.scalecube.services.ServiceCall; -import io.scalecube.services.ServiceDefinition; -import io.scalecube.services.ServiceInfo; -import io.scalecube.services.ServicesProvider; -import io.scalecube.services.annotations.Service; -import io.scalecube.services.discovery.api.ServiceDiscovery; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.Objects; -import java.util.function.Supplier; -import java.util.stream.Collectors; -import java.util.stream.Stream; -import org.springframework.beans.factory.config.BeanDefinition; -import org.springframework.beans.factory.support.GenericBeanDefinition; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.springframework.util.ClassUtils; -import reactor.core.publisher.Mono; - -public class SpringServicesProvider implements ServicesProvider { - - private final Class[] configurations; - - // lazy init - private AnnotationConfigApplicationContext ctx; - - /** - * Create the instance from Spring Context. - * - * @param configurations spring configurations. - */ - public SpringServicesProvider(Class... configurations) { - this.configurations = configurations; - } - - @Override - public Mono> provideServiceDefinitions( - Microservices microservices) { - - this.ctx = new AnnotationConfigApplicationContext(); - String id = microservices.id(); - this.ctx.registerBeanDefinition( - "discovery-" + id, createBeanDef(ServiceDiscovery.class, microservices::discovery)); - this.ctx.registerBeanDefinition( - "serviceCall-" + id, createBeanDef(ServiceCall.class, microservices::call)); - - Stream.of(this.configurations).forEach(this.ctx::register); - - String[] serviceBeanNames = this.ctx.getBeanDefinitionNames(); - List serviceDefinitions = - Stream.of(serviceBeanNames) - .map(serviceBeanName -> this.ctx.getBeanDefinition(serviceBeanName)) - .map(BeanDefinition::getBeanClassName) - .filter(Objects::nonNull) - .map(className -> ClassUtils.resolveClassName(className, ctx.getClassLoader())) - .filter(type -> type.getAnnotation(Service.class) != null) - .map(type -> new ServiceDefinition(type, Collections.emptyMap())) - .collect(Collectors.toList()); - return Mono.defer(() -> Mono.just(serviceDefinitions)); - } - - private GenericBeanDefinition createBeanDef(Class type, Supplier instanceSupplier) { - GenericBeanDefinition discoveryBd = new GenericBeanDefinition(); - discoveryBd.setBeanClass(type); - discoveryBd.setLazyInit(true); - discoveryBd.setSynthetic(true); - discoveryBd.setInstanceSupplier(instanceSupplier); - discoveryBd.setSource(this); - return discoveryBd; - } - - @Override - public Mono> provideService(Microservices microservices) { - return Mono.defer( - () -> { - this.ctx.refresh(); - this.ctx.start(); - List services = - this.ctx.getBeansWithAnnotation(Service.class).values().stream() - .map(bean -> ServiceInfo.fromServiceInstance(bean).build()) - .collect(Collectors.toList()); - return Mono.just(services); - }); - } - - @Override - public Mono shutDown(Microservices microservices) { - return Mono.defer( - () -> - Mono.fromCallable( - () -> { - this.ctx.stop(); - this.ctx.close(); - return microservices; - })); - } -} diff --git a/services-examples-parent/scalecube-examples-spring/src/test/java/io/scalecube/spring/SpringServicesProviderTest.java b/services-examples-parent/scalecube-examples-spring/src/test/java/io/scalecube/spring/SpringServicesProviderTest.java deleted file mode 100644 index 9e528c9b0..000000000 --- a/services-examples-parent/scalecube-examples-spring/src/test/java/io/scalecube/spring/SpringServicesProviderTest.java +++ /dev/null @@ -1,118 +0,0 @@ -package io.scalecube.spring; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import io.scalecube.services.Scalecube; -import io.scalecube.services.ServiceCall; -import io.scalecube.services.ServiceEndpoint; -import io.scalecube.services.annotations.Service; -import io.scalecube.services.annotations.ServiceMethod; -import io.scalecube.services.discovery.ScalecubeServiceDiscovery; -import io.scalecube.services.discovery.api.ServiceDiscovery; -import io.scalecube.services.transport.rsocket.RSocketServiceTransport; -import java.time.Duration; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import reactor.core.publisher.Hooks; -import reactor.core.publisher.Mono; - -class SpringServicesProviderTest { - - private static Scalecube microserviceWithSpring; - private static Scalecube microserviceWithoutSpring; - - @BeforeAll - public static void setUp() { - Hooks.onOperatorDebug(); - microserviceWithSpring = microserviceWithSpring(); - microserviceWithoutSpring = microserviceWithoutSpring(); - } - - @AfterAll - public static void tearDown() { - try { - microserviceWithSpring.shutdown().block(); - } catch (Exception ignore) { - // no-op - } - - try { - microserviceWithoutSpring.shutdown().block(); - } catch (Exception ignore) { - // no-op - } - } - - private static Scalecube microserviceWithSpring() { - return Scalecube.builder() - .discovery(ScalecubeServiceDiscovery::new) - .transport(RSocketServiceTransport::new) - .serviceProvider(new SpringServicesProvider(Beans.class)) - .startAwait(); - } - - private static Scalecube microserviceWithoutSpring() { - return Scalecube.builder() - .discovery(SpringServicesProviderTest::serviceDiscovery) - .transport(RSocketServiceTransport::new) - .services((SimpleService) () -> Mono.just(1L)) - .startAwait(); - } - - @Test - public void testWithSpringServicesProvider() { - - LocalService service = microserviceWithSpring.call().api(LocalService.class); - - // call the service. - Mono result = service.get(); - Long block = result.block(Duration.ofSeconds(10)); - assertEquals(-1L, block.longValue()); - } - - private static ServiceDiscovery serviceDiscovery(ServiceEndpoint endpoint) { - return new ScalecubeServiceDiscovery(endpoint) - .membership(cfg -> cfg.seedMembers(microserviceWithSpring.discovery().address())); - } - - @Configuration - static class Beans { - @Bean - public LocalService localServiceBean( - ServiceCall serviceCall, ServiceDiscovery serviceDiscovery) { - return new LocalServiceBean(serviceCall, serviceDiscovery); - } - } - - @Service - public interface SimpleService { - - @ServiceMethod - Mono get(); - } - - @Service - public interface LocalService { - - @ServiceMethod - Mono get(); - } - - public static class LocalServiceBean implements LocalService { - - private final SimpleService serviceCall; - - public LocalServiceBean(ServiceCall serviceCall, ServiceDiscovery serviceDiscovery) { - this.serviceCall = serviceCall.api(SimpleService.class); - this.serviceCall.get().subscribe(System.out::println); - serviceDiscovery.listenDiscovery().subscribe(); - } - - public Mono get() { - return serviceCall.get().map(n -> n * -1); - } - } -} diff --git a/services/src/main/java/io/scalecube/services/Scalecube.java b/services/src/main/java/io/scalecube/services/Scalecube.java index a1f8bd962..c7cf78f8f 100644 --- a/services/src/main/java/io/scalecube/services/Scalecube.java +++ b/services/src/main/java/io/scalecube/services/Scalecube.java @@ -9,7 +9,7 @@ import io.scalecube.services.exceptions.ServiceProviderErrorMapper; import io.scalecube.services.gateway.Gateway; import io.scalecube.services.gateway.GatewayOptions; -import io.scalecube.services.inject.ScaleCubeServicesProvider; +import io.scalecube.services.inject.ScaleCubeServiceFactory; import io.scalecube.services.methods.MethodInfo; import io.scalecube.services.methods.ServiceMethodInvoker; import io.scalecube.services.methods.ServiceMethodRegistry; @@ -124,15 +124,15 @@ public final class Scalecube implements Microservices { private final String id = generateId(); private final Metrics metrics; private final Map tags; - private final ServicesProvider servicesProvider; + private final ServiceFactory serviceFactory; private final ServiceRegistry serviceRegistry; private final ServiceMethodRegistry methodRegistry; - private final Authenticator authenticator; + private final Authenticator defaultAuthenticator; private final ServiceTransportBootstrap transportBootstrap; private final GatewayBootstrap gatewayBootstrap; private final ServiceDiscoveryBootstrap discoveryBootstrap; - private final ServiceProviderErrorMapper errorMapper; - private final ServiceMessageDataDecoder dataDecoder; + private final ServiceProviderErrorMapper defaultErrorMapper; + private final ServiceMessageDataDecoder defaultDataDecoder; private final MonoProcessor shutdown = MonoProcessor.create(); private final MonoProcessor onShutdown = MonoProcessor.create(); @@ -140,16 +140,16 @@ private Scalecube(Builder builder) { this.metrics = builder.metrics; this.tags = new HashMap<>(builder.tags); - this.servicesProvider = builder.servicesProvider; + this.serviceFactory = builder.serviceFactory; this.serviceRegistry = builder.serviceRegistry; this.methodRegistry = builder.methodRegistry; - this.authenticator = builder.authenticator; + this.defaultAuthenticator = builder.authenticator; this.gatewayBootstrap = builder.gatewayBootstrap; this.discoveryBootstrap = builder.discoveryBootstrap; this.transportBootstrap = builder.transportBootstrap; - this.errorMapper = builder.errorMapper; - this.dataDecoder = builder.dataDecoder; + this.defaultErrorMapper = builder.errorMapper; + this.defaultDataDecoder = builder.dataDecoder; // Setup cleanup shutdown @@ -189,7 +189,7 @@ private Mono start() { .flatMap(this::initializeServiceEndpoint) .flatMap(this.discoveryBootstrap::createInstance) .publishOn(scheduler) - .then(this.servicesProvider.provideService(this)) + .then(this.serviceFactory.initializeServices(this)) .doOnNext(this::registerInMethodRegistry) .publishOn(scheduler) .then(startGateway()) @@ -209,35 +209,34 @@ private Mono start() { } private Mono initializeServiceEndpoint(Supplier
serviceAddress) { - return this.servicesProvider - .provideServiceDefinitions(this) - .map( - serviceDefinitions -> { - final ServiceEndpoint.Builder serviceEndpointBuilder = - ServiceEndpoint.builder() - .id(this.id) - .address(serviceAddress.get()) - .contentTypes(DataCodec.getAllContentTypes()) - .tags(this.tags); - serviceDefinitions.forEach( - serviceDefinition -> - serviceEndpointBuilder.appendServiceRegistrations( - ServiceScanner.scanServiceDefinition(serviceDefinition))); - return serviceEndpointBuilder.build(); - }); + Mono> serviceDefinitionsMono = + Mono.defer(() -> this.serviceFactory.getServiceDefinitions(this)); + return serviceDefinitionsMono.map( + serviceDefinitions -> { + final ServiceEndpoint.Builder serviceEndpointBuilder = + ServiceEndpoint.builder() + .id(this.id) + .address(serviceAddress.get()) + .contentTypes(DataCodec.getAllContentTypes()) + .tags(this.tags); + serviceDefinitions.forEach( + serviceDefinition -> + serviceEndpointBuilder.appendServiceRegistrations( + ServiceScanner.scanServiceDefinition(serviceDefinition))); + return serviceEndpointBuilder.build(); + }); } private void registerInMethodRegistry(Collection services) { - services.forEach( - serviceInfo -> { - methodRegistry.registerService( - ServiceInfo.from(serviceInfo) - .errorMapperIfAbsent(this.errorMapper) - .dataDecoderIfAbsent(this.dataDecoder) - .authenticator( - Optional.ofNullable(serviceInfo.authenticator()).orElse(this.authenticator)) - .build()); - }); + services.stream() + .map( + serviceInfo -> + ServiceInfo.from(serviceInfo) + .errorMapperIfAbsent(this.defaultErrorMapper) + .dataDecoderIfAbsent(this.defaultDataDecoder) + .authenticatorIfAbsent(this.defaultAuthenticator) + .build()) + .forEach(methodRegistry::registerService); } private Mono startGateway() { @@ -318,7 +317,7 @@ private Mono doShutdown() { } private Mono processBeforeDestroy() { - return servicesProvider.shutDown(this); + return serviceFactory.shutdownServices(this); } public static final class Builder { @@ -327,7 +326,7 @@ public static final class Builder { private Map tags = new HashMap<>(); private List services = new ArrayList<>(); private List serviceProviders = new ArrayList<>(); - private ServicesProvider servicesProvider; + private ServiceFactory serviceFactory; private ServiceRegistry serviceRegistry = new ServiceRegistryImpl(); private ServiceMethodRegistry methodRegistry = new ServiceMethodRegistryImpl(); private Authenticator authenticator = null; @@ -353,10 +352,10 @@ private void build() { Collectors.toList(), services -> (ServiceProvider) call -> services)); this.serviceProviders.add(serviceProvider); List serviceProviders = Collections.unmodifiableList(this.serviceProviders); - this.servicesProvider = - this.servicesProvider == null - ? ScaleCubeServicesProvider.create(serviceProviders) - : this.servicesProvider; + this.serviceFactory = + this.serviceFactory == null + ? ScaleCubeServiceFactory.create(serviceProviders) + : this.serviceFactory; } public Mono start() { @@ -371,13 +370,13 @@ public Scalecube startAwait() { /** * Adds service instance to microservice. * - *

WARNING This service will be ignored if custom {@link ServicesProvider} - * is installed. This method has been left for backward compatibility only and will be removed - * in future releases. + *

WARNING This service will be ignored if custom {@link ServiceFactory} is + * installed. This method has been left for backward compatibility only and will be removed in + * future releases. * * @param services service info instance. * @return builder - * @deprecated use {@link this#serviceProvider(ServicesProvider)} + * @deprecated use {@link this#serviceProvider(ServiceFactory)} */ @Deprecated public Builder services(ServiceInfo... services) { @@ -388,13 +387,13 @@ public Builder services(ServiceInfo... services) { /** * Adds service instance to microservice. * - *

WARNING This service will be ignored if custom {@link ServicesProvider} - * is installed. This method has been left for backward compatibility only and will be removed - * in future releases. + *

WARNING This service will be ignored if custom {@link ServiceFactory} is + * installed. This method has been left for backward compatibility only and will be removed in + * future releases. * * @param services service instance. * @return builder - * @deprecated use {@link this#serviceProvider(ServicesProvider)} + * @deprecated use {@link this#serviceProvider(ServiceFactory)} */ @Deprecated public Builder services(Object... services) { @@ -407,13 +406,13 @@ public Builder services(Object... services) { /** * Set up service provider. * - *

WARNING This service will be ignored if custom {@link ServicesProvider} - * is installed. This method has been left for backward compatibility only and will be removed - * in future releases. + *

WARNING This service will be ignored if custom {@link ServiceFactory} is + * installed. This method has been left for backward compatibility only and will be removed in + * future releases. * * @param serviceProvider - old service provider * @return this - * @deprecated use {@link this#serviceProvider(ServicesProvider)} + * @deprecated use {@link this#serviceProvider(ServiceFactory)} */ @Deprecated public Builder services(ServiceProvider serviceProvider) { @@ -421,8 +420,8 @@ public Builder services(ServiceProvider serviceProvider) { return this; } - public Builder serviceProvider(ServicesProvider serviceProvider) { - this.servicesProvider = serviceProvider; + public Builder serviceProvider(ServiceFactory serviceProvider) { + this.serviceFactory = serviceProvider; return this; } diff --git a/services/src/main/java/io/scalecube/services/inject/ScaleCubeServicesProvider.java b/services/src/main/java/io/scalecube/services/inject/ScaleCubeServiceFactory.java similarity index 82% rename from services/src/main/java/io/scalecube/services/inject/ScaleCubeServicesProvider.java rename to services/src/main/java/io/scalecube/services/inject/ScaleCubeServiceFactory.java index 4658978ce..8ec5172d0 100644 --- a/services/src/main/java/io/scalecube/services/inject/ScaleCubeServicesProvider.java +++ b/services/src/main/java/io/scalecube/services/inject/ScaleCubeServiceFactory.java @@ -4,14 +4,14 @@ import io.scalecube.services.ServiceDefinition; import io.scalecube.services.ServiceInfo; import io.scalecube.services.ServiceProvider; -import io.scalecube.services.ServicesProvider; +import io.scalecube.services.ServiceFactory; import java.util.Collection; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; import java.util.stream.Collectors; import reactor.core.publisher.Mono; -public class ScaleCubeServicesProvider implements ServicesProvider { +public class ScaleCubeServiceFactory implements ServiceFactory { private final Function> serviceFactory; @@ -24,11 +24,11 @@ public class ScaleCubeServicesProvider implements ServicesProvider { * @param serviceProviders old service providers. * @return default services provider. */ - public static ServicesProvider create(Collection serviceProviders) { - return new ScaleCubeServicesProvider(serviceProviders); + public static ServiceFactory create(Collection serviceProviders) { + return new ScaleCubeServiceFactory(serviceProviders); } - private ScaleCubeServicesProvider(Collection serviceProviders) { + private ScaleCubeServiceFactory(Collection serviceProviders) { this.serviceFactory = microservices -> serviceProviders.stream() @@ -42,7 +42,7 @@ private ScaleCubeServicesProvider(Collection serviceProviders) * Since the service instance factory ({@link ServiceProvider}) we have to leave behind does not * provide us with information about the types of services produced, there is nothing left for us * to do but start creating all the services and then retrieve the type of service, previously - * saving it as a {@link ScaleCubeServicesProvider} state. + * saving it as a {@link ScaleCubeServiceFactory} state. * *

{@inheritDoc} * @@ -53,7 +53,7 @@ private ScaleCubeServicesProvider(Collection serviceProviders) * @see ServiceDefinition */ @Override - public Mono> provideServiceDefinitions( + public Mono> getServiceDefinitions( Microservices microservices) { return Mono.fromCallable( () -> @@ -72,7 +72,7 @@ public Mono> provideServiceDefinitions( * instance. */ @Override - public Mono> provideService(Microservices microservices) { + public Mono> initializeServices(Microservices microservices) { return Mono.fromCallable( () -> this.services(microservices).stream() @@ -87,7 +87,7 @@ public Mono> provideService(Microservices micr * instance. */ @Override - public Mono shutDown(Microservices microservices) { + public Mono shutdownServices(Microservices microservices) { return Mono.fromRunnable(() -> shutdown0(microservices)).thenReturn(microservices); } From 5dcfa3073a04ed91d0cfdd6b1407c37189990a41 Mon Sep 17 00:00:00 2001 From: eutkin Date: Mon, 16 Mar 2020 19:50:27 +0300 Subject: [PATCH 29/61] ISSUE-708 fix code style --- .../io/scalecube/services/inject/ScaleCubeServiceFactory.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/src/main/java/io/scalecube/services/inject/ScaleCubeServiceFactory.java b/services/src/main/java/io/scalecube/services/inject/ScaleCubeServiceFactory.java index 8ec5172d0..7006a5253 100644 --- a/services/src/main/java/io/scalecube/services/inject/ScaleCubeServiceFactory.java +++ b/services/src/main/java/io/scalecube/services/inject/ScaleCubeServiceFactory.java @@ -2,9 +2,9 @@ import io.scalecube.services.Microservices; import io.scalecube.services.ServiceDefinition; +import io.scalecube.services.ServiceFactory; import io.scalecube.services.ServiceInfo; import io.scalecube.services.ServiceProvider; -import io.scalecube.services.ServiceFactory; import java.util.Collection; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; From 8145b059e7f74ee12495b2dae2677c878f45f3e0 Mon Sep 17 00:00:00 2001 From: Eugene_Utkin Date: Mon, 4 May 2020 19:47:28 +0300 Subject: [PATCH 30/61] ISSUE-708 merge with develop --- .../io/scalecube/services/examples/ExamplesRunner.java | 2 +- .../io/scalecube/services/examples/codecs/Example1.java | 9 +++++---- .../java/io/scalecube/services/ServiceRegistryTest.java | 2 +- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/services-examples-parent/services-examples-runner/src/main/java/io/scalecube/services/examples/ExamplesRunner.java b/services-examples-parent/services-examples-runner/src/main/java/io/scalecube/services/examples/ExamplesRunner.java index 2c888333e..cdfd9f50c 100644 --- a/services-examples-parent/services-examples-runner/src/main/java/io/scalecube/services/examples/ExamplesRunner.java +++ b/services-examples-parent/services-examples-runner/src/main/java/io/scalecube/services/examples/ExamplesRunner.java @@ -53,7 +53,7 @@ public static void main(String[] args) { .orElse(Runtime.getRuntime().availableProcessors()); LOGGER.info("Number of worker threads: " + numOfThreads); - Microservices microservices = Scalecube.builder() + Scalecube microservices = Scalecube.builder() .discovery(endpoint -> serviceDiscovery(endpoint, config)) .transport( () -> diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/codecs/Example1.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/codecs/Example1.java index 92456ac93..80d286495 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/codecs/Example1.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/codecs/Example1.java @@ -2,6 +2,7 @@ import io.scalecube.net.Address; import io.scalecube.services.Microservices; +import io.scalecube.services.Scalecube; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.examples.helloworld.service.GreetingServiceImpl; import io.scalecube.services.examples.helloworld.service.api.GreetingsService; @@ -18,8 +19,8 @@ public class Example1 { */ public static void main(String[] args) { // ScaleCube Node node with no members - Microservices seed = - Microservices.builder() + Scalecube seed = + Scalecube.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) .contentType(CONTENT_TYPE) // need to send with non-default data format @@ -28,8 +29,8 @@ public static void main(String[] args) { final Address seedAddress = seed.discovery().address(); // Construct a ScaleCube node which joins the cluster hosting the Greeting Service - Microservices ms = - Microservices.builder() + Scalecube ms = + Scalecube.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) diff --git a/services/src/test/java/io/scalecube/services/ServiceRegistryTest.java b/services/src/test/java/io/scalecube/services/ServiceRegistryTest.java index 8a96db8f3..11abf79b9 100644 --- a/services/src/test/java/io/scalecube/services/ServiceRegistryTest.java +++ b/services/src/test/java/io/scalecube/services/ServiceRegistryTest.java @@ -200,7 +200,7 @@ public void test_delayed_listen_to_discovery_events(MetadataCodec metadataCodec) .thenCancel() .verify(TIMEOUT); - Mono.whenDelayError(cluster.stream().map(Microservices::shutdown).toArray(Mono[]::new)) + Mono.whenDelayError(cluster.stream().map(Scalecube::shutdown).toArray(Mono[]::new)) .block(TIMEOUT); } From a22dcbe5dd1eccf89870b826a12bd93983ecda34 Mon Sep 17 00:00:00 2001 From: Eugene_Utkin Date: Thu, 14 May 2020 22:26:24 +0300 Subject: [PATCH 31/61] ISSUE-708 merge with develop and add MicroservicesContext --- ...ervices.java => MicroservicesContext.java} | 3 +- .../io/scalecube/services/ServiceFactory.java | 7 +- .../io/scalecube/services/ServiceInfo.java | 22 ++---- .../transport/BenchmarkServiceState.java | 12 +-- .../services/examples/ExamplesRunner.java | 3 +- .../services/examples/codecs/Example1.java | 9 +-- .../exceptions/ExceptionMapperExample.java | 10 +-- .../examples/helloworld/Example1.java | 10 +-- .../examples/helloworld/Example2.java | 10 +-- .../examples/helloworld/Example3.java | 10 +-- .../services/examples/orderbook/Example1.java | 10 +-- .../services/examples/services/Example1.java | 14 ++-- .../services/examples/services/Example2.java | 14 ++-- .../{Scalecube.java => Microservices.java} | 75 ++++++++++++------- .../scalecube/services/inject/Injector.java | 17 +++-- .../inject/ScaleCubeServiceFactory.java | 18 +++-- .../io/scalecube/services/ErrorFlowTest.java | 8 +- .../services/ServiceAuthRemoteTest.java | 25 ++++--- .../services/ServiceCallLocalTest.java | 6 +- .../services/ServiceCallRemoteTest.java | 14 ++-- .../ServiceLifecycleAnnotationsTest.java | 6 +- .../scalecube/services/ServiceLocalTest.java | 6 +- .../services/ServiceRegistryTest.java | 44 +++++------ .../scalecube/services/ServiceRemoteTest.java | 32 ++++---- .../services/StreamingServiceTest.java | 8 +- .../services/routings/RoutersTest.java | 18 ++--- .../services/routings/ServiceTagsExample.java | 14 ++-- .../services/sut/AnnotationServiceImpl.java | 5 +- .../sut/CoarseGrainedServiceImpl.java | 5 +- .../services/sut/GreetingServiceImpl.java | 6 +- ...ocketNettyColocatedEventLoopGroupTest.java | 24 +++--- .../rsocket/RSocketServiceTransportTest.java | 14 ++-- 32 files changed, 249 insertions(+), 230 deletions(-) rename services-api/src/main/java/io/scalecube/services/{Microservices.java => MicroservicesContext.java} (84%) rename services/src/main/java/io/scalecube/services/{Scalecube.java => Microservices.java} (94%) diff --git a/services-api/src/main/java/io/scalecube/services/Microservices.java b/services-api/src/main/java/io/scalecube/services/MicroservicesContext.java similarity index 84% rename from services-api/src/main/java/io/scalecube/services/Microservices.java rename to services-api/src/main/java/io/scalecube/services/MicroservicesContext.java index f700f672f..cdf7f5e97 100644 --- a/services-api/src/main/java/io/scalecube/services/Microservices.java +++ b/services-api/src/main/java/io/scalecube/services/MicroservicesContext.java @@ -3,7 +3,7 @@ import io.scalecube.net.Address; import io.scalecube.services.discovery.api.ServiceDiscovery; -public interface Microservices { +public interface MicroservicesContext { String id(); @@ -12,4 +12,5 @@ public interface Microservices { Address serviceAddress(); ServiceDiscovery discovery(); + } diff --git a/services-api/src/main/java/io/scalecube/services/ServiceFactory.java b/services-api/src/main/java/io/scalecube/services/ServiceFactory.java index 804799ae4..6bb0a975d 100644 --- a/services-api/src/main/java/io/scalecube/services/ServiceFactory.java +++ b/services-api/src/main/java/io/scalecube/services/ServiceFactory.java @@ -13,7 +13,8 @@ public interface ServiceFactory { * @return collection of service definitions - service type and tags. * @see ServiceDefinition */ - Mono> getServiceDefinitions(Microservices microservices); + Mono> getServiceDefinitions( + MicroservicesContext microservices); /** * Initialize instances of services. @@ -21,7 +22,7 @@ public interface ServiceFactory { * @param microservices scale cube instance. * @return Completed Mono if initialization was successful for all services. */ - Mono> initializeServices(Microservices microservices); + Mono> initializeServices(MicroservicesContext microservices); /** * Finalization of service instances. @@ -29,5 +30,5 @@ public interface ServiceFactory { * @param microservices scale cube instance. * @return completed Mono if finalization was successful for all services. */ - Mono shutdownServices(Microservices microservices); + Mono shutdownServices(MicroservicesContext microservices); } diff --git a/services-api/src/main/java/io/scalecube/services/ServiceInfo.java b/services-api/src/main/java/io/scalecube/services/ServiceInfo.java index cf8fdd2f4..3fcae4f56 100644 --- a/services-api/src/main/java/io/scalecube/services/ServiceInfo.java +++ b/services-api/src/main/java/io/scalecube/services/ServiceInfo.java @@ -160,12 +160,6 @@ Builder errorMapperIfAbsent(ServiceProviderErrorMapper errorMapper) { return this; } - /** - * Set up {@link ServiceProviderErrorMapper} if it hasn't been set up before. - * - * @param errorMapper error mapper. - * @return current builder's state. - */ Builder dataDecoderIfAbsent(ServiceMessageDataDecoder dataDecoder) { if (this.dataDecoder == null) { this.dataDecoder = dataDecoder; @@ -173,6 +167,12 @@ Builder dataDecoderIfAbsent(ServiceMessageDataDecoder dataDecoder) { return this; } + /** + * Set up {@link Authenticator} if it hasn't been set up before. + * + * @param authenticator authenticator. + * @return current builder's state. + */ Builder authenticatorIfAbsent(Authenticator authenticator) { if (this.authenticator == null) { this.authenticator = authenticator; @@ -187,16 +187,6 @@ Builder principalMapperIfAbsent(PrincipalMapper principalMapper) return this; } - /** - * Set up {@link Authenticator} if it hasn't been set up before. - * - * @param authenticator authenticator. - * @return current builder's state. - */ - public Builder authenticatorIfAbsent(Authenticator authenticator) { - return Objects.isNull(this.authenticator) ? this.authenticator(authenticator) : this; - } - /** * Build service info. * diff --git a/services-benchmarks/src/main/java/io/scalecube/services/benchmarks/transport/BenchmarkServiceState.java b/services-benchmarks/src/main/java/io/scalecube/services/benchmarks/transport/BenchmarkServiceState.java index 1d01782e6..83eeb5da1 100644 --- a/services-benchmarks/src/main/java/io/scalecube/services/benchmarks/transport/BenchmarkServiceState.java +++ b/services-benchmarks/src/main/java/io/scalecube/services/benchmarks/transport/BenchmarkServiceState.java @@ -3,7 +3,7 @@ import io.scalecube.benchmarks.BenchmarkSettings; import io.scalecube.benchmarks.BenchmarkState; import io.scalecube.net.Address; -import io.scalecube.services.Scalecube; +import io.scalecube.services.Microservices; import io.scalecube.services.ServiceCall; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.transport.rsocket.RSocketServiceTransport; @@ -20,8 +20,8 @@ public class BenchmarkServiceState extends BenchmarkState private final Object[] services; - private Scalecube seed; - private Scalecube node; + private Microservices seed; + private Microservices node; public BenchmarkServiceState(BenchmarkSettings settings, Object... services) { super(settings); @@ -31,7 +31,7 @@ public BenchmarkServiceState(BenchmarkSettings settings, Object... services) { @Override public void beforeAll() { seed = - Scalecube.builder() + Microservices.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) .startAwait(); @@ -39,7 +39,7 @@ public void beforeAll() { final Address seedAddress = seed.discovery().address(); node = - Scalecube.builder() + Microservices.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) @@ -64,7 +64,7 @@ public void afterAll() { } } - public Scalecube seed() { + public Microservices seed() { return seed; } diff --git a/services-examples-parent/services-examples-runner/src/main/java/io/scalecube/services/examples/ExamplesRunner.java b/services-examples-parent/services-examples-runner/src/main/java/io/scalecube/services/examples/ExamplesRunner.java index cdfd9f50c..be149c885 100644 --- a/services-examples-parent/services-examples-runner/src/main/java/io/scalecube/services/examples/ExamplesRunner.java +++ b/services-examples-parent/services-examples-runner/src/main/java/io/scalecube/services/examples/ExamplesRunner.java @@ -9,7 +9,6 @@ import io.scalecube.net.Address; import io.scalecube.runners.Runners; import io.scalecube.services.Microservices; -import io.scalecube.services.Scalecube; import io.scalecube.services.ServiceEndpoint; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.discovery.api.ServiceDiscovery; @@ -53,7 +52,7 @@ public static void main(String[] args) { .orElse(Runtime.getRuntime().availableProcessors()); LOGGER.info("Number of worker threads: " + numOfThreads); - Scalecube microservices = Scalecube.builder() + Microservices microservices = Microservices.builder() .discovery(endpoint -> serviceDiscovery(endpoint, config)) .transport( () -> diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/codecs/Example1.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/codecs/Example1.java index 80d286495..92456ac93 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/codecs/Example1.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/codecs/Example1.java @@ -2,7 +2,6 @@ import io.scalecube.net.Address; import io.scalecube.services.Microservices; -import io.scalecube.services.Scalecube; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.examples.helloworld.service.GreetingServiceImpl; import io.scalecube.services.examples.helloworld.service.api.GreetingsService; @@ -19,8 +18,8 @@ public class Example1 { */ public static void main(String[] args) { // ScaleCube Node node with no members - Scalecube seed = - Scalecube.builder() + Microservices seed = + Microservices.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) .contentType(CONTENT_TYPE) // need to send with non-default data format @@ -29,8 +28,8 @@ public static void main(String[] args) { final Address seedAddress = seed.discovery().address(); // Construct a ScaleCube node which joins the cluster hosting the Greeting Service - Scalecube ms = - Scalecube.builder() + Microservices ms = + Microservices.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/exceptions/ExceptionMapperExample.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/exceptions/ExceptionMapperExample.java index e1394629f..bafd07b87 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/exceptions/ExceptionMapperExample.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/exceptions/ExceptionMapperExample.java @@ -1,7 +1,7 @@ package io.scalecube.services.examples.exceptions; import io.scalecube.net.Address; -import io.scalecube.services.Scalecube; +import io.scalecube.services.Microservices; import io.scalecube.services.ServiceInfo; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.transport.rsocket.RSocketServiceTransport; @@ -16,8 +16,8 @@ public class ExceptionMapperExample { * @throws InterruptedException exception. */ public static void main(String[] args) throws InterruptedException { - Scalecube ms1 = - Scalecube.builder() + Microservices ms1 = + Microservices.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) .defaultErrorMapper(new ServiceAProviderErrorMapper()) // default mapper for whole node @@ -31,8 +31,8 @@ public static void main(String[] args) throws InterruptedException { final Address address1 = ms1.discovery().address(); - Scalecube ms2 = - Scalecube.builder() + Microservices ms2 = + Microservices.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example1.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example1.java index c511a9755..1ca40f956 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example1.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example1.java @@ -1,7 +1,7 @@ package io.scalecube.services.examples.helloworld; import io.scalecube.net.Address; -import io.scalecube.services.Scalecube; +import io.scalecube.services.Microservices; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.examples.helloworld.service.GreetingServiceImpl; import io.scalecube.services.examples.helloworld.service.api.GreetingsService; @@ -24,8 +24,8 @@ public class Example1 { */ public static void main(String[] args) { // ScaleCube Node node with no members - Scalecube seed = - Scalecube.builder() + Microservices seed = + Microservices.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) .startAwait(); @@ -33,8 +33,8 @@ public static void main(String[] args) { final Address seedAddress = seed.discovery().address(); // Construct a ScaleCube node which joins the cluster hosting the Greeting Service - Scalecube ms = - Scalecube.builder() + Microservices ms = + Microservices.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example2.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example2.java index 4ec20d086..fc20274db 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example2.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example2.java @@ -1,7 +1,7 @@ package io.scalecube.services.examples.helloworld; import io.scalecube.net.Address; -import io.scalecube.services.Scalecube; +import io.scalecube.services.Microservices; import io.scalecube.services.ServiceCall; import io.scalecube.services.api.ServiceMessage; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; @@ -32,8 +32,8 @@ public class Example2 { */ public static void main(String[] args) { // ScaleCube Node node with no members - Scalecube seed = - Scalecube.builder() + Microservices seed = + Microservices.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) .startAwait(); @@ -41,8 +41,8 @@ public static void main(String[] args) { // Construct a ScaleCube node which joins the cluster hosting the Greeting Service final Address seedAddress = seed.discovery().address(); - Scalecube ms = - Scalecube.builder() + Microservices ms = + Microservices.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example3.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example3.java index 8e6c1dad7..8891ffa1e 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example3.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example3.java @@ -1,7 +1,7 @@ package io.scalecube.services.examples.helloworld; import io.scalecube.net.Address; -import io.scalecube.services.Scalecube; +import io.scalecube.services.Microservices; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.examples.helloworld.service.BidiGreetingImpl; import io.scalecube.services.examples.helloworld.service.api.BidiGreetingService; @@ -25,8 +25,8 @@ public class Example3 { */ public static void main(String[] args) { // ScaleCube Node node with no members - Scalecube seed = - Scalecube.builder() + Microservices seed = + Microservices.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) .startAwait(); @@ -34,8 +34,8 @@ public static void main(String[] args) { final Address seedAddress = seed.discovery().address(); // Construct a ScaleCube node which joins the cluster hosting the Greeting Service - Scalecube ms = - Scalecube.builder() + Microservices ms = + Microservices.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/orderbook/Example1.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/orderbook/Example1.java index 4b7a86b5a..b2bd1b737 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/orderbook/Example1.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/orderbook/Example1.java @@ -1,7 +1,7 @@ package io.scalecube.services.examples.orderbook; import io.scalecube.net.Address; -import io.scalecube.services.Scalecube; +import io.scalecube.services.Microservices; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.examples.orderbook.service.DefaultMarketDataService; import io.scalecube.services.examples.orderbook.service.OrderBookSnapshoot; @@ -32,16 +32,16 @@ public class Example1 { */ public static void main(String[] args) throws InterruptedException { - Scalecube gateway = - Scalecube.builder() + Microservices gateway = + Microservices.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) .startAwait(); final Address gatewayAddress = gateway.discovery().address(); - Scalecube ms = - Scalecube.builder() + Microservices ms = + Microservices.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example1.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example1.java index 7a294bb04..b6b039151 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example1.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example1.java @@ -1,7 +1,7 @@ package io.scalecube.services.examples.services; import io.scalecube.net.Address; -import io.scalecube.services.Scalecube; +import io.scalecube.services.Microservices; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.transport.rsocket.RSocketServiceTransport; import reactor.core.publisher.Mono; @@ -15,16 +15,16 @@ public class Example1 { * @param args - program arguments */ public static void main(String[] args) { - Scalecube gateway = - Scalecube.builder() + Microservices gateway = + Microservices.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) .startAwait(); final Address gatewayAddress = gateway.discovery().address(); - Scalecube service2Node = - Scalecube.builder() + Microservices service2Node = + Microservices.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) @@ -33,8 +33,8 @@ public static void main(String[] args) { .services(new Service2Impl()) .startAwait(); - Scalecube service1Node = - Scalecube.builder() + Microservices service1Node = + Microservices.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example2.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example2.java index b27521c34..a5c528d20 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example2.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example2.java @@ -1,7 +1,7 @@ package io.scalecube.services.examples.services; import io.scalecube.net.Address; -import io.scalecube.services.Scalecube; +import io.scalecube.services.Microservices; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.transport.rsocket.RSocketServiceTransport; import reactor.core.publisher.Mono; @@ -15,16 +15,16 @@ public class Example2 { * @param args - program arguments */ public static void main(String[] args) { - Scalecube gateway = - Scalecube.builder() + Microservices gateway = + Microservices.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) .startAwait(); final Address gatewayAddress = gateway.discovery().address(); - Scalecube service2Node = - Scalecube.builder() + Microservices service2Node = + Microservices.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) @@ -33,8 +33,8 @@ public static void main(String[] args) { .services(new Service2Impl()) .startAwait(); - Scalecube service1Node = - Scalecube.builder() + Microservices service1Node = + Microservices.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) diff --git a/services/src/main/java/io/scalecube/services/Scalecube.java b/services/src/main/java/io/scalecube/services/Microservices.java similarity index 94% rename from services/src/main/java/io/scalecube/services/Scalecube.java rename to services/src/main/java/io/scalecube/services/Microservices.java index 5c6464639..9ef871ba9 100644 --- a/services/src/main/java/io/scalecube/services/Scalecube.java +++ b/services/src/main/java/io/scalecube/services/Microservices.java @@ -114,12 +114,13 @@ * * } */ -public final class Scalecube implements Microservices { +public final class Microservices { - public static final Logger LOGGER = LoggerFactory.getLogger(Scalecube.class); + public static final Logger LOGGER = LoggerFactory.getLogger(Microservices.class); private final String id = generateId(); private final Map tags; + private final MicroservicesContext context; private final ServiceFactory serviceFactory; private final ServiceRegistry serviceRegistry; private final ServiceMethodRegistry methodRegistry; @@ -134,7 +135,7 @@ public final class Scalecube implements Microservices { private final MonoProcessor shutdown = MonoProcessor.create(); private final MonoProcessor onShutdown = MonoProcessor.create(); - private Scalecube(Builder builder) { + private Microservices(Builder builder) { this.tags = new HashMap<>(builder.tags); this.serviceFactory = builder.serviceFactory; @@ -149,6 +150,7 @@ private Scalecube(Builder builder) { this.defaultDataDecoder = builder.dataDecoder; this.contentType = builder.contentType; this.principalMapper = builder.principalMapper; + this.context = new Context(); // Setup cleanup shutdown @@ -162,7 +164,6 @@ public static Builder builder() { return new Builder(); } - @Override public String id() { return this.id; } @@ -176,7 +177,7 @@ public String toString() { return "Microservices@" + id; } - private Mono start() { + private Mono start() { LOGGER.info("[{}][start] Starting", id); // Create bootstrap scheduler @@ -188,7 +189,7 @@ private Mono start() { .flatMap(this::initializeServiceEndpoint) .flatMap(this.discoveryBootstrap::createInstance) .publishOn(scheduler) - .then(this.serviceFactory.initializeServices(this)) + .then(this.serviceFactory.initializeServices(this.context)) .doOnNext(this::registerInMethodRegistry) .publishOn(scheduler) .then(startGateway()) @@ -200,7 +201,7 @@ private Mono start() { .onErrorResume( ex -> { // return original error then shutdown - return Mono.whenDelayError(Mono.error(ex), shutdown()).cast(Scalecube.class); + return Mono.whenDelayError(Mono.error(ex), shutdown()).cast(Microservices.class); }) .doOnSuccess(m -> LOGGER.info("[{}][start] Started", id)) .doOnTerminate(scheduler::dispose); @@ -208,7 +209,7 @@ private Mono start() { private Mono initializeServiceEndpoint(Supplier
serviceAddress) { Mono> serviceDefinitionsMono = - Mono.defer(() -> this.serviceFactory.getServiceDefinitions(this)); + Mono.defer(() -> this.serviceFactory.getServiceDefinitions(this.context)); return serviceDefinitionsMono.map( serviceDefinitions -> { final ServiceEndpoint.Builder serviceEndpointBuilder = @@ -239,14 +240,9 @@ private void registerInMethodRegistry(Collection services) { } private Mono startGateway() { - return gatewayBootstrap.start(this, new GatewayOptions().call(this.call()).metrics(metrics)); - } - - public Metrics metrics() { - return this.metrics; + return gatewayBootstrap.start(this, new GatewayOptions().call(this.call())); } - @Override public Address serviceAddress() { return transportBootstrap.transportAddress; } @@ -256,7 +252,6 @@ public Address serviceAddress() { * * @return new {@code ServiceCall} instance. */ - @Override public ServiceCall call() { return new ServiceCall() .transport(transportBootstrap.clientTransport) @@ -275,7 +270,6 @@ public Gateway gateway(String id) { return gatewayBootstrap.gateway(id); } - @Override public ServiceDiscovery discovery() { return discoveryBootstrap.discovery; } @@ -311,8 +305,31 @@ private Mono doShutdown() { }); } - private Mono processBeforeDestroy() { - return serviceFactory.shutdownServices(this); + private Mono processBeforeDestroy() { + return serviceFactory.shutdownServices(this.context).then(); + } + + public final class Context implements MicroservicesContext { + + @Override + public String id() { + return Microservices.this.id(); + } + + @Override + public ServiceCall call() { + return Microservices.this.call(); + } + + @Override + public Address serviceAddress() { + return Microservices.this.serviceAddress(); + } + + @Override + public ServiceDiscovery discovery() { + return Microservices.this.discovery(); + } } public static final class Builder { @@ -354,12 +371,12 @@ private void build() { : this.serviceFactory; } - public Mono start() { + public Mono start() { build(); - return Mono.defer(() -> new Scalecube(this).start()); + return Mono.defer(() -> new Microservices(this).start()); } - public Scalecube startAwait() { + public Microservices startAwait() { return start().block(); } @@ -561,7 +578,7 @@ private Mono createInstance(ServiceEndpoint serviceEndpoint) { : Mono.defer(() -> Mono.just(discovery = factory.apply(serviceEndpoint))); } - private Mono startListen(Scalecube microservices) { + private Mono startListen(Microservices microservices) { return Mono.defer( () -> { if (this.discovery == null) { @@ -594,7 +611,7 @@ private Mono startListen(Scalecube microservices) { }); } - private void onDiscoveryEvent(Scalecube microservices, ServiceDiscoveryEvent event) { + private void onDiscoveryEvent(Microservices microservices, ServiceDiscoveryEvent event) { if (event.isEndpointAdded()) { microservices.serviceRegistry.registerService(event.serviceEndpoint()); } @@ -624,7 +641,7 @@ private GatewayBootstrap addFactory(Function factory) { return this; } - private Mono start(Scalecube microservices, GatewayOptions options) { + private Mono start(Microservices microservices, GatewayOptions options) { return Flux.fromIterable(factories) .flatMap( factory -> { @@ -693,7 +710,7 @@ public ServiceTransportBootstrap(Supplier transportSupplier) { this.transportSupplier = transportSupplier; } - private Mono start(Scalecube microservices) { + private Mono start(Microservices microservices) { if (transportSupplier == NULL_SUPPLIER || (serviceTransport = transportSupplier.get()) == null) { LOGGER.info("[{}] ServiceTransport not set", microservices.id()); @@ -732,7 +749,7 @@ private Mono start(Scalecube microservices) { } public Address address() { - return address; + return transportAddress; } private Mono shutdown() { @@ -763,9 +780,9 @@ public interface MonitorMBean { private static class JmxMonitorMBean implements MonitorMBean { - private final Scalecube microservices; + private final Microservices microservices; - private static JmxMonitorMBean start(Scalecube instance) throws Exception { + private static JmxMonitorMBean start(Microservices instance) throws Exception { MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer(); JmxMonitorMBean jmxMBean = new JmxMonitorMBean(instance); ObjectName objectName = new ObjectName("io.scalecube.services:name=" + instance.toString()); @@ -774,7 +791,7 @@ private static JmxMonitorMBean start(Scalecube instance) throws Exception { return jmxMBean; } - private JmxMonitorMBean(Scalecube microservices) { + private JmxMonitorMBean(Microservices microservices) { this.microservices = microservices; } diff --git a/services/src/main/java/io/scalecube/services/inject/Injector.java b/services/src/main/java/io/scalecube/services/inject/Injector.java index fa46c191c..92e4b16c2 100644 --- a/services/src/main/java/io/scalecube/services/inject/Injector.java +++ b/services/src/main/java/io/scalecube/services/inject/Injector.java @@ -1,8 +1,8 @@ package io.scalecube.services.inject; import io.scalecube.services.Microservices; +import io.scalecube.services.MicroservicesContext; import io.scalecube.services.Reflect; -import io.scalecube.services.Scalecube; import io.scalecube.services.ServiceCall; import io.scalecube.services.ServiceInfo; import io.scalecube.services.annotations.AfterConstruct; @@ -30,15 +30,15 @@ private Injector() { * @param service service * @return service instance */ - public static ServiceInfo inject(Microservices microservices, ServiceInfo service) { + public static ServiceInfo inject(MicroservicesContext microservices, ServiceInfo service) { Object serviceInstance = service.serviceInstance(); Arrays.stream(serviceInstance.getClass().getDeclaredFields()) .forEach(field -> injectField(microservices, field, serviceInstance)); return service; } - private static void injectField(Microservices microservices, Field field, Object service) { - if (field.isAnnotationPresent(Inject.class) && field.getType().equals(Scalecube.class)) { + private static void injectField(MicroservicesContext microservices, Field field, Object service) { + if (field.isAnnotationPresent(Inject.class) && field.getType().equals(MicroservicesContext.class)) { setField(field, service, microservices); } else if (field.isAnnotationPresent(Inject.class) && Reflect.isService(field.getType())) { Inject injection = field.getAnnotation(Inject.class); @@ -69,17 +69,18 @@ private static void setField(Field field, Object object, Object value) { * @return service info with modified service's instance. */ public static ServiceInfo processAfterConstruct( - Microservices microservices, ServiceInfo serviceInfo) { + MicroservicesContext microservices, ServiceInfo serviceInfo) { processMethodWithAnnotation(microservices, serviceInfo.serviceInstance(), AfterConstruct.class); return serviceInfo; } - public static void processBeforeDestroy(Microservices microservices, ServiceInfo serviceInfo) { + public static void processBeforeDestroy( + MicroservicesContext microservices, ServiceInfo serviceInfo) { processMethodWithAnnotation(microservices, serviceInfo.serviceInstance(), BeforeDestroy.class); } private static void processMethodWithAnnotation( - Microservices microservices, Object targetInstance, Class annotation) { + MicroservicesContext microservices, Object targetInstance, Class annotation) { Method[] declaredMethods = targetInstance.getClass().getDeclaredMethods(); Arrays.stream(declaredMethods) .filter(method -> method.isAnnotationPresent(annotation)) @@ -91,7 +92,7 @@ private static void processMethodWithAnnotation( Arrays.stream(targetMethod.getParameters()) .map( mapper -> { - if (mapper.getType().equals(Scalecube.class)) { + if (mapper.getType().equals(MicroservicesContext.class)) { return microservices; } else if (Reflect.isService(mapper.getType())) { return microservices.call().api(mapper.getType()); diff --git a/services/src/main/java/io/scalecube/services/inject/ScaleCubeServiceFactory.java b/services/src/main/java/io/scalecube/services/inject/ScaleCubeServiceFactory.java index 7006a5253..65705e9e0 100644 --- a/services/src/main/java/io/scalecube/services/inject/ScaleCubeServiceFactory.java +++ b/services/src/main/java/io/scalecube/services/inject/ScaleCubeServiceFactory.java @@ -1,6 +1,7 @@ package io.scalecube.services.inject; import io.scalecube.services.Microservices; +import io.scalecube.services.MicroservicesContext; import io.scalecube.services.ServiceDefinition; import io.scalecube.services.ServiceFactory; import io.scalecube.services.ServiceInfo; @@ -13,7 +14,7 @@ public class ScaleCubeServiceFactory implements ServiceFactory { - private final Function> serviceFactory; + private final Function> serviceFactory; // lazy init private AtomicReference> services = new AtomicReference<>(); @@ -54,7 +55,7 @@ private ScaleCubeServiceFactory(Collection serviceProviders) { */ @Override public Mono> getServiceDefinitions( - Microservices microservices) { + MicroservicesContext microservices) { return Mono.fromCallable( () -> this.services(microservices).stream() @@ -72,7 +73,8 @@ public Mono> getServiceDefinitions( * instance. */ @Override - public Mono> initializeServices(Microservices microservices) { + public Mono> initializeServices( + MicroservicesContext microservices) { return Mono.fromCallable( () -> this.services(microservices).stream() @@ -85,19 +87,21 @@ public Mono> initializeServices(Microservices * *

Use {@link io.scalecube.services.annotations.BeforeDestroy} for finilization service's * instance. + * + * @return */ @Override - public Mono shutdownServices(Microservices microservices) { - return Mono.fromRunnable(() -> shutdown0(microservices)).thenReturn(microservices); + public Mono shutdownServices(MicroservicesContext microservices) { + return Mono.fromRunnable(() -> shutdown0(microservices)); } - private void shutdown0(Microservices microservices) { + private void shutdown0(MicroservicesContext microservices) { if (this.services.get() != null) { this.services.get().forEach(service -> Injector.processBeforeDestroy(microservices, service)); } } - private Collection services(Microservices microservices) { + private Collection services(MicroservicesContext microservices) { return this.services.updateAndGet( currentValue -> currentValue == null ? this.serviceFactory.apply(microservices) : currentValue); diff --git a/services/src/test/java/io/scalecube/services/ErrorFlowTest.java b/services/src/test/java/io/scalecube/services/ErrorFlowTest.java index 55d357719..bd6f56ef0 100644 --- a/services/src/test/java/io/scalecube/services/ErrorFlowTest.java +++ b/services/src/test/java/io/scalecube/services/ErrorFlowTest.java @@ -23,13 +23,13 @@ public class ErrorFlowTest extends BaseTest { private static AtomicInteger port = new AtomicInteger(4000); - private static Scalecube provider; - private static Scalecube consumer; + private static Microservices provider; + private static Microservices consumer; @BeforeAll public static void initNodes() { provider = - Scalecube.builder() + Microservices.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) @@ -41,7 +41,7 @@ public static void initNodes() { final Address seedAddress = provider.discovery().address(); consumer = - Scalecube.builder() + Microservices.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) diff --git a/services/src/test/java/io/scalecube/services/ServiceAuthRemoteTest.java b/services/src/test/java/io/scalecube/services/ServiceAuthRemoteTest.java index 7c9dccf55..4ed7d98b2 100644 --- a/services/src/test/java/io/scalecube/services/ServiceAuthRemoteTest.java +++ b/services/src/test/java/io/scalecube/services/ServiceAuthRemoteTest.java @@ -50,8 +50,8 @@ final class ServiceAuthRemoteTest extends BaseTest { return Mono.error(new UnauthorizedException("Authentication failed")); }; - private static Scalecube caller; - private static Scalecube service; + private static Microservices caller; + private static Microservices service; public static PrincipalMapper, UserProfile> principalMapper; @BeforeAll @@ -59,7 +59,7 @@ static void beforeAll() { StepVerifier.setDefaultTimeout(TIMEOUT); caller = - Scalecube.builder() + Microservices.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) .startAwait(); @@ -67,11 +67,14 @@ static void beforeAll() { principalMapper = authData -> new UserProfile(authData.get("name"), authData.get("role")); service = - Scalecube.builder() + Microservices.builder() .discovery(ServiceAuthRemoteTest::serviceDiscovery) .transport(RSocketServiceTransport::new) .defaultAuthenticator(authenticator) - .services(new SecuredServiceImpl()) + .services( + ServiceInfo.fromServiceInstance(new SecuredServiceImpl()) + .principalMapper(principalMapper) + .build()) .startAwait(); } @@ -108,8 +111,8 @@ void successfulAuthentication() { @Test @DisplayName("Authentication failed if authenticator not provided") void failedAuthenticationWhenAuthenticatorNotProvided() { - Scalecube service = - Scalecube.builder() + Microservices service = + Microservices.builder() .discovery(ServiceAuthRemoteTest::serviceDiscovery) .transport(RSocketServiceTransport::new) .services( @@ -169,8 +172,8 @@ void failedAuthenticationWithInvalidOrEmptyCredentials() { @Test @DisplayName("Successful authentication of partially secured service") void successfulAuthenticationOnPartiallySecuredService() { - Scalecube service = - Scalecube.builder() + Microservices service = + Microservices.builder() .discovery(ServiceAuthRemoteTest::serviceDiscovery) .transport(RSocketServiceTransport::new) .defaultAuthenticator(authenticator) @@ -193,8 +196,8 @@ void successfulAuthenticationOnPartiallySecuredService() { @Test @DisplayName("Successful call public method of partially secured service without authentication") void successfulCallOfPublicMethodWithoutAuthentication() { - Scalecube service = - Scalecube.builder() + Microservices service = + Microservices.builder() .discovery(ServiceAuthRemoteTest::serviceDiscovery) .transport(RSocketServiceTransport::new) .services( diff --git a/services/src/test/java/io/scalecube/services/ServiceCallLocalTest.java b/services/src/test/java/io/scalecube/services/ServiceCallLocalTest.java index ff1737594..e39bfda6a 100644 --- a/services/src/test/java/io/scalecube/services/ServiceCallLocalTest.java +++ b/services/src/test/java/io/scalecube/services/ServiceCallLocalTest.java @@ -37,7 +37,7 @@ public class ServiceCallLocalTest extends BaseTest { public static final int TIMEOUT = 3; private Duration timeout = Duration.ofSeconds(TIMEOUT); - private static Scalecube provider; + private static Microservices provider; @BeforeAll public static void setup() { @@ -63,8 +63,8 @@ public void test_local_async_no_params() { GREETING_NO_PARAMS_REQUEST.qualifier(), message.qualifier(), "Didn't get desired response"); } - private static Scalecube serviceProvider() { - return Scalecube.builder() + private static Microservices serviceProvider() { + return Microservices.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) .services(new GreetingServiceImpl()) diff --git a/services/src/test/java/io/scalecube/services/ServiceCallRemoteTest.java b/services/src/test/java/io/scalecube/services/ServiceCallRemoteTest.java index 578123217..4143c90db 100644 --- a/services/src/test/java/io/scalecube/services/ServiceCallRemoteTest.java +++ b/services/src/test/java/io/scalecube/services/ServiceCallRemoteTest.java @@ -40,8 +40,8 @@ public class ServiceCallRemoteTest extends BaseTest { public static final int TIMEOUT = 3; private Duration timeout = Duration.ofSeconds(TIMEOUT); - private static Scalecube gateway; - private static Scalecube provider; + private static Microservices gateway; + private static Microservices provider; @BeforeAll public static void setup() { @@ -64,8 +64,8 @@ public static void tearDown() { } } - private static Scalecube serviceProvider(Object service) { - return Scalecube.builder() + private static Microservices serviceProvider(Object service) { + return Microservices.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) @@ -226,7 +226,7 @@ public void test_service_address_lookup_occur_only_after_subscription() { // Add service to cluster AFTER creating a call object. // (prove address lookup occur only after subscription) - Scalecube quotesService = serviceProvider(new SimpleQuoteService()); + Microservices quotesService = serviceProvider(new SimpleQuoteService()); StepVerifier.create(quotes.take(1)).expectNextCount(1).expectComplete().verify(timeout); @@ -255,8 +255,8 @@ public void test_many_stream_block_first() { } } - private static Scalecube gateway() { - return Scalecube.builder() + private static Microservices gateway() { + return Microservices.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) .startAwait(); diff --git a/services/src/test/java/io/scalecube/services/ServiceLifecycleAnnotationsTest.java b/services/src/test/java/io/scalecube/services/ServiceLifecycleAnnotationsTest.java index df68065db..0255e28d9 100644 --- a/services/src/test/java/io/scalecube/services/ServiceLifecycleAnnotationsTest.java +++ b/services/src/test/java/io/scalecube/services/ServiceLifecycleAnnotationsTest.java @@ -18,8 +18,8 @@ void testAfterConstructThenBeforeDestroy() throws Exception { final CountDownLatch afterConstruct = new CountDownLatch(1); final CountDownLatch beforeDestroy = new CountDownLatch(1); - Scalecube microservices = - Scalecube.builder() + Microservices microservices = + Microservices.builder() .services( ServiceInfo.fromServiceInstance( new TestService() { @@ -55,7 +55,7 @@ void testAfterConstructFailsThenBeforeDestroy() throws Exception { Assertions.assertThrows( Exception.class, () -> - Scalecube.builder() + Microservices.builder() .services( ServiceInfo.fromServiceInstance( new TestService() { diff --git a/services/src/test/java/io/scalecube/services/ServiceLocalTest.java b/services/src/test/java/io/scalecube/services/ServiceLocalTest.java index bcfdc692c..16c62d3f2 100644 --- a/services/src/test/java/io/scalecube/services/ServiceLocalTest.java +++ b/services/src/test/java/io/scalecube/services/ServiceLocalTest.java @@ -23,11 +23,11 @@ public class ServiceLocalTest extends BaseTest { private static final Duration timeout = Duration.ofSeconds(3); - private Scalecube microservices; + private Microservices microservices; @BeforeEach public void setUp() { - microservices = Scalecube.builder().services(new GreetingServiceImpl()).startAwait(); + microservices = Microservices.builder().services(new GreetingServiceImpl()).startAwait(); } @AfterEach @@ -304,7 +304,7 @@ public void test_local_bidi_greeting_expect_GreetingResponse() { .verify(Duration.ofSeconds(3)); } - private GreetingService createProxy(Scalecube gateway) { + private GreetingService createProxy(Microservices gateway) { return gateway.call().api(GreetingService.class); // create proxy for GreetingService API } } diff --git a/services/src/test/java/io/scalecube/services/ServiceRegistryTest.java b/services/src/test/java/io/scalecube/services/ServiceRegistryTest.java index 11abf79b9..d1c503ecf 100644 --- a/services/src/test/java/io/scalecube/services/ServiceRegistryTest.java +++ b/services/src/test/java/io/scalecube/services/ServiceRegistryTest.java @@ -45,8 +45,8 @@ private static Stream metadataCodecSource() { public void test_added_removed_registration_events(MetadataCodec metadataCodec) { ReplayProcessor events = ReplayProcessor.create(); - Scalecube seed = - Scalecube.builder() + Microservices seed = + Microservices.builder() .discovery(defServiceDiscovery(metadataCodec)) .transport(RSocketServiceTransport::new) .startAwait(); @@ -55,15 +55,15 @@ public void test_added_removed_registration_events(MetadataCodec metadataCodec) Address seedAddress = seed.discovery().address(); - Scalecube ms1 = - Scalecube.builder() + Microservices ms1 = + Microservices.builder() .discovery(defServiceDiscovery(seedAddress, metadataCodec)) .transport(RSocketServiceTransport::new) .services(new GreetingServiceImpl()) .startAwait(); - Scalecube ms2 = - Scalecube.builder() + Microservices ms2 = + Microservices.builder() .discovery(defServiceDiscovery(seedAddress, metadataCodec)) .transport(RSocketServiceTransport::new) .services(new GreetingServiceImpl()) @@ -87,10 +87,10 @@ public void test_added_removed_registration_events(MetadataCodec metadataCodec) public void test_listen_to_discovery_events(MetadataCodec metadataCodec) { ReplayProcessor processor = ReplayProcessor.create(); - List cluster = new CopyOnWriteArrayList<>(); + List cluster = new CopyOnWriteArrayList<>(); - Scalecube seed = - Scalecube.builder() + Microservices seed = + Microservices.builder() .discovery(defServiceDiscovery(metadataCodec)) .transport(RSocketServiceTransport::new) .services(new AnnotationServiceImpl()) @@ -104,8 +104,8 @@ public void test_listen_to_discovery_events(MetadataCodec metadataCodec) { StepVerifier.create(processor) .then( () -> { - Scalecube ms1 = - Scalecube.builder() + Microservices ms1 = + Microservices.builder() .discovery(defServiceDiscovery(seedAddress, metadataCodec)) .transport(RSocketServiceTransport::new) .services(new GreetingServiceImpl()) @@ -115,8 +115,8 @@ public void test_listen_to_discovery_events(MetadataCodec metadataCodec) { .assertNext(event -> assertEquals(ENDPOINT_ADDED, event.type())) .then( () -> { - Scalecube ms2 = - Scalecube.builder() + Microservices ms2 = + Microservices.builder() .discovery(defServiceDiscovery(seedAddress, metadataCodec)) .transport(RSocketServiceTransport::new) .services(new GreetingServiceImpl()) @@ -145,7 +145,7 @@ public void test_listen_to_discovery_events(MetadataCodec metadataCodec) { .thenCancel() .verify(TIMEOUT); - Mono.whenDelayError(cluster.stream().map(Scalecube::shutdown).toArray(Mono[]::new)) + Mono.whenDelayError(cluster.stream().map(Microservices::shutdown).toArray(Mono[]::new)) .block(TIMEOUT); } @@ -154,10 +154,10 @@ public void test_listen_to_discovery_events(MetadataCodec metadataCodec) { public void test_delayed_listen_to_discovery_events(MetadataCodec metadataCodec) { ReplayProcessor processor = ReplayProcessor.create(); - List cluster = new CopyOnWriteArrayList<>(); + List cluster = new CopyOnWriteArrayList<>(); - Scalecube seed = - Scalecube.builder() + Microservices seed = + Microservices.builder() .discovery(defServiceDiscovery(metadataCodec)) .transport(RSocketServiceTransport::new) .services(new GreetingServiceImpl()) @@ -171,8 +171,8 @@ public void test_delayed_listen_to_discovery_events(MetadataCodec metadataCodec) StepVerifier.create(processor) .then( () -> { - Scalecube ms1 = - Scalecube.builder() + Microservices ms1 = + Microservices.builder() .discovery(defServiceDiscovery(seedAddress, metadataCodec)) .transport(RSocketServiceTransport::new) .services(new GreetingServiceImpl(), new AnnotationServiceImpl()) @@ -182,8 +182,8 @@ public void test_delayed_listen_to_discovery_events(MetadataCodec metadataCodec) .assertNext(event -> assertEquals(ENDPOINT_ADDED, event.type())) .then( () -> { - Scalecube ms2 = - Scalecube.builder() + Microservices ms2 = + Microservices.builder() .discovery(defServiceDiscovery(seedAddress, metadataCodec)) .transport(RSocketServiceTransport::new) .services(new GreetingServiceImpl()) @@ -200,7 +200,7 @@ public void test_delayed_listen_to_discovery_events(MetadataCodec metadataCodec) .thenCancel() .verify(TIMEOUT); - Mono.whenDelayError(cluster.stream().map(Scalecube::shutdown).toArray(Mono[]::new)) + Mono.whenDelayError(cluster.stream().map(Microservices::shutdown).toArray(Mono[]::new)) .block(TIMEOUT); } diff --git a/services/src/test/java/io/scalecube/services/ServiceRemoteTest.java b/services/src/test/java/io/scalecube/services/ServiceRemoteTest.java index aafe3dbf2..03ddfb7ca 100644 --- a/services/src/test/java/io/scalecube/services/ServiceRemoteTest.java +++ b/services/src/test/java/io/scalecube/services/ServiceRemoteTest.java @@ -36,8 +36,8 @@ public class ServiceRemoteTest extends BaseTest { private static final Duration TIMEOUT = Duration.ofSeconds(10); public static final Duration TIMEOUT2 = Duration.ofSeconds(6); - private static Scalecube gateway; - private static Scalecube provider; + private static Microservices gateway; + private static Microservices provider; @BeforeAll public static void setup() { @@ -61,15 +61,15 @@ public static void tearDown() { } } - private static Scalecube gateway() { - return Scalecube.builder() + private static Microservices gateway() { + return Microservices.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) .startAwait(); } - private static Scalecube serviceProvider() { - return Scalecube.builder() + private static Microservices serviceProvider() { + return Microservices.builder() .discovery(ServiceRemoteTest::serviceDiscovery) .transport(RSocketServiceTransport::new) .services(new GreetingServiceImpl()) @@ -264,8 +264,8 @@ public void test_remote_serviceA_calls_serviceB_using_setter() { // Create microservices instance cluster. // noinspection unused - Scalecube provider = - Scalecube.builder() + Microservices provider = + Microservices.builder() .discovery(ServiceRemoteTest::serviceDiscovery) .transport(RSocketServiceTransport::new) .services(new CoarseGrainedServiceImpl()) // add service a and b @@ -287,8 +287,8 @@ public void test_remote_serviceA_calls_serviceB() { // Create microservices instance cluster. // noinspection unused - Scalecube provider = - Scalecube.builder() + Microservices provider = + Microservices.builder() .discovery(ServiceRemoteTest::serviceDiscovery) .transport(RSocketServiceTransport::new) .services(another) @@ -307,8 +307,8 @@ public void test_remote_serviceA_calls_serviceB_with_timeout() { CoarseGrainedServiceImpl another = new CoarseGrainedServiceImpl(); // Create microservices instance cluster. - Scalecube ms = - Scalecube.builder() + Microservices ms = + Microservices.builder() .discovery(ServiceRemoteTest::serviceDiscovery) .transport(RSocketServiceTransport::new) .services(another) // add service a and b @@ -332,8 +332,8 @@ public void test_remote_serviceA_calls_serviceB_with_dispatcher() { CoarseGrainedServiceImpl another = new CoarseGrainedServiceImpl(); // Create microservices instance cluster. - Scalecube provider = - Scalecube.builder() + Microservices provider = + Microservices.builder() .discovery(ServiceRemoteTest::serviceDiscovery) .transport(RSocketServiceTransport::new) .services(another) // add service a and b @@ -416,8 +416,8 @@ public void test_services_contribute_to_cluster_metadata() { Map tags = new HashMap<>(); tags.put("HOSTNAME", "host1"); - Scalecube ms = - Scalecube.builder() + Microservices ms = + Microservices.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) .tags(tags) diff --git a/services/src/test/java/io/scalecube/services/StreamingServiceTest.java b/services/src/test/java/io/scalecube/services/StreamingServiceTest.java index 56e0b3c72..db4c56a8b 100644 --- a/services/src/test/java/io/scalecube/services/StreamingServiceTest.java +++ b/services/src/test/java/io/scalecube/services/StreamingServiceTest.java @@ -21,20 +21,20 @@ public class StreamingServiceTest extends BaseTest { - private static Scalecube gateway; - private static Scalecube node; + private static Microservices gateway; + private static Microservices node; @BeforeAll public static void setup() { gateway = - Scalecube.builder() + Microservices.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) .defaultDataDecoder(ServiceMessageCodec::decodeData) .startAwait(); node = - Scalecube.builder() + Microservices.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) diff --git a/services/src/test/java/io/scalecube/services/routings/RoutersTest.java b/services/src/test/java/io/scalecube/services/routings/RoutersTest.java index 143000d07..718de3cac 100644 --- a/services/src/test/java/io/scalecube/services/routings/RoutersTest.java +++ b/services/src/test/java/io/scalecube/services/routings/RoutersTest.java @@ -12,7 +12,7 @@ import io.scalecube.net.Address; import io.scalecube.services.BaseTest; import io.scalecube.services.Reflect; -import io.scalecube.services.Scalecube; +import io.scalecube.services.Microservices; import io.scalecube.services.ServiceCall; import io.scalecube.services.ServiceInfo; import io.scalecube.services.ServiceReference; @@ -47,16 +47,16 @@ public class RoutersTest extends BaseTest { public static final int TIMEOUT = 10; private Duration timeout = Duration.ofSeconds(TIMEOUT); - private static Scalecube gateway; + private static Microservices gateway; private static Address gatewayAddress; - private static Scalecube provider1; - private static Scalecube provider2; - private static Scalecube provider3; + private static Microservices provider1; + private static Microservices provider2; + private static Microservices provider3; @BeforeAll public static void setup() { gateway = - Scalecube.builder() // + Microservices.builder() // .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) .startAwait(); @@ -65,7 +65,7 @@ public static void setup() { // Create microservices instance cluster. provider1 = - Scalecube.builder() + Microservices.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) @@ -83,7 +83,7 @@ public static void setup() { // Create microservices instance cluster. provider2 = - Scalecube.builder() + Microservices.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) @@ -101,7 +101,7 @@ public static void setup() { TagService tagService = input -> input.map(String::toUpperCase); provider3 = - Scalecube.builder() + Microservices.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) diff --git a/services/src/test/java/io/scalecube/services/routings/ServiceTagsExample.java b/services/src/test/java/io/scalecube/services/routings/ServiceTagsExample.java index 3aed21031..1151880c8 100644 --- a/services/src/test/java/io/scalecube/services/routings/ServiceTagsExample.java +++ b/services/src/test/java/io/scalecube/services/routings/ServiceTagsExample.java @@ -1,7 +1,7 @@ package io.scalecube.services.routings; import io.scalecube.net.Address; -import io.scalecube.services.Scalecube; +import io.scalecube.services.Microservices; import io.scalecube.services.ServiceInfo; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.routings.sut.CanaryService; @@ -20,16 +20,16 @@ public class ServiceTagsExample { * @param args arguments */ public static void main(String[] args) { - Scalecube gateway = - Scalecube.builder() + Microservices gateway = + Microservices.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) .startAwait(); Address seedAddress = gateway.discovery().address(); - Scalecube services1 = - Scalecube.builder() + Microservices services1 = + Microservices.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) @@ -41,8 +41,8 @@ public static void main(String[] args) { .build()) .startAwait(); - Scalecube services2 = - Scalecube.builder() + Microservices services2 = + Microservices.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) diff --git a/services/src/test/java/io/scalecube/services/sut/AnnotationServiceImpl.java b/services/src/test/java/io/scalecube/services/sut/AnnotationServiceImpl.java index 6aa6ec115..e1fba79d4 100644 --- a/services/src/test/java/io/scalecube/services/sut/AnnotationServiceImpl.java +++ b/services/src/test/java/io/scalecube/services/sut/AnnotationServiceImpl.java @@ -1,6 +1,7 @@ package io.scalecube.services.sut; -import io.scalecube.services.Scalecube; +import io.scalecube.services.Microservices; +import io.scalecube.services.MicroservicesContext; import io.scalecube.services.annotations.AfterConstruct; import io.scalecube.services.discovery.api.ServiceDiscoveryEvent; import reactor.core.publisher.Flux; @@ -11,7 +12,7 @@ public class AnnotationServiceImpl implements AnnotationService { private ReplayProcessor serviceDiscoveryEvents; @AfterConstruct - void init(Scalecube microservices) { + void init(MicroservicesContext microservices) { this.serviceDiscoveryEvents = ReplayProcessor.create(); microservices.discovery().listenDiscovery().subscribe(serviceDiscoveryEvents); } diff --git a/services/src/test/java/io/scalecube/services/sut/CoarseGrainedServiceImpl.java b/services/src/test/java/io/scalecube/services/sut/CoarseGrainedServiceImpl.java index 1d4af8091..10fb067c2 100644 --- a/services/src/test/java/io/scalecube/services/sut/CoarseGrainedServiceImpl.java +++ b/services/src/test/java/io/scalecube/services/sut/CoarseGrainedServiceImpl.java @@ -1,6 +1,7 @@ package io.scalecube.services.sut; -import io.scalecube.services.Scalecube; +import io.scalecube.services.Microservices; +import io.scalecube.services.MicroservicesContext; import io.scalecube.services.annotations.Inject; import io.scalecube.services.api.ServiceMessage; import java.time.Duration; @@ -12,7 +13,7 @@ public class CoarseGrainedServiceImpl implements CoarseGrainedService { @Inject private GreetingService greetingService; - @Inject private Scalecube microservices; + @Inject private MicroservicesContext microservices; @Override public Mono callGreeting(String name) { diff --git a/services/src/test/java/io/scalecube/services/sut/GreetingServiceImpl.java b/services/src/test/java/io/scalecube/services/sut/GreetingServiceImpl.java index 583ac2aaa..938ba222e 100644 --- a/services/src/test/java/io/scalecube/services/sut/GreetingServiceImpl.java +++ b/services/src/test/java/io/scalecube/services/sut/GreetingServiceImpl.java @@ -1,6 +1,7 @@ package io.scalecube.services.sut; -import io.scalecube.services.Scalecube; +import io.scalecube.services.Microservices; +import io.scalecube.services.MicroservicesContext; import io.scalecube.services.annotations.Inject; import io.scalecube.services.api.ServiceMessage; import io.scalecube.services.exceptions.UnauthorizedException; @@ -12,7 +13,8 @@ public final class GreetingServiceImpl implements GreetingService { - @Inject Scalecube ms; + @Inject + MicroservicesContext ms; private int instanceId; diff --git a/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketNettyColocatedEventLoopGroupTest.java b/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketNettyColocatedEventLoopGroupTest.java index cb54e0f62..d333a1b93 100644 --- a/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketNettyColocatedEventLoopGroupTest.java +++ b/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketNettyColocatedEventLoopGroupTest.java @@ -3,7 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import io.scalecube.services.BaseTest; -import io.scalecube.services.Scalecube; +import io.scalecube.services.Microservices; import io.scalecube.services.ServiceCall; import io.scalecube.services.annotations.Inject; import io.scalecube.services.annotations.Service; @@ -19,20 +19,20 @@ public class RSocketNettyColocatedEventLoopGroupTest extends BaseTest { - private Scalecube ping; - private Scalecube pong; - private Scalecube gateway; + private Microservices ping; + private Microservices pong; + private Microservices gateway; @BeforeEach public void setUp() { this.gateway = - Scalecube.builder() + Microservices.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) .startAwait(); - Scalecube facade = - Scalecube.builder() + Microservices facade = + Microservices.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) @@ -42,7 +42,7 @@ public void setUp() { .startAwait(); this.ping = - Scalecube.builder() + Microservices.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) @@ -52,7 +52,7 @@ public void setUp() { .startAwait(); this.pong = - Scalecube.builder() + Microservices.builder() .discovery( endpoint -> new ScalecubeServiceDiscovery(endpoint) @@ -80,9 +80,9 @@ public void testColocatedEventLoopGroup() { public void tearDown() { try { Mono.whenDelayError( - Optional.ofNullable(gateway).map(Scalecube::shutdown).orElse(Mono.empty()), - Optional.ofNullable(ping).map(Scalecube::shutdown).orElse(Mono.empty()), - Optional.ofNullable(pong).map(Scalecube::shutdown).orElse(Mono.empty())) + Optional.ofNullable(gateway).map(Microservices::shutdown).orElse(Mono.empty()), + Optional.ofNullable(ping).map(Microservices::shutdown).orElse(Mono.empty()), + Optional.ofNullable(pong).map(Microservices::shutdown).orElse(Mono.empty())) .block(); } catch (Throwable ignore) { // no-op diff --git a/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketServiceTransportTest.java b/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketServiceTransportTest.java index 4a4941b11..ac042a89d 100644 --- a/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketServiceTransportTest.java +++ b/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketServiceTransportTest.java @@ -4,7 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import io.scalecube.services.BaseTest; -import io.scalecube.services.Scalecube; +import io.scalecube.services.Microservices; import io.scalecube.services.ServiceCall; import io.scalecube.services.api.ServiceMessage; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; @@ -32,19 +32,19 @@ public class RSocketServiceTransportTest extends BaseTest { private static final ServiceMessage ONLY_ONE_AND_THEN_NEVER = ServiceMessage.builder().qualifier(QuoteService.NAME, "onlyOneAndThenNever").build(); - private Scalecube gateway; - private Scalecube serviceNode; + private Microservices gateway; + private Microservices serviceNode; @BeforeEach public void setUp() { gateway = - Scalecube.builder() + Microservices.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) .startAwait(); serviceNode = - Scalecube.builder() + Microservices.builder() .discovery( serviceEndpoint -> new ScalecubeServiceDiscovery(serviceEndpoint) @@ -58,8 +58,8 @@ public void setUp() { public void cleanUp() { try { Mono.whenDelayError( - Optional.ofNullable(gateway).map(Scalecube::shutdown).orElse(Mono.empty()), - Optional.ofNullable(serviceNode).map(Scalecube::shutdown).orElse(Mono.empty())) + Optional.ofNullable(gateway).map(Microservices::shutdown).orElse(Mono.empty()), + Optional.ofNullable(serviceNode).map(Microservices::shutdown).orElse(Mono.empty())) .block(); } catch (Throwable ignore) { // no-op From cc4711d4fc83d11cc6a927fc95bafa19670aef68 Mon Sep 17 00:00:00 2001 From: Eugene_Utkin Date: Thu, 14 May 2020 22:34:03 +0300 Subject: [PATCH 32/61] code style checks --- .../src/main/java/io/scalecube/services/inject/Injector.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/services/src/main/java/io/scalecube/services/inject/Injector.java b/services/src/main/java/io/scalecube/services/inject/Injector.java index 92e4b16c2..95b2c7cf7 100644 --- a/services/src/main/java/io/scalecube/services/inject/Injector.java +++ b/services/src/main/java/io/scalecube/services/inject/Injector.java @@ -38,7 +38,8 @@ public static ServiceInfo inject(MicroservicesContext microservices, ServiceInfo } private static void injectField(MicroservicesContext microservices, Field field, Object service) { - if (field.isAnnotationPresent(Inject.class) && field.getType().equals(MicroservicesContext.class)) { + if (field.isAnnotationPresent(Inject.class) + && field.getType().equals(MicroservicesContext.class)) { setField(field, service, microservices); } else if (field.isAnnotationPresent(Inject.class) && Reflect.isService(field.getType())) { Inject injection = field.getAnnotation(Inject.class); From 50c3cc71188d254287647065f0186f022d6c48c8 Mon Sep 17 00:00:00 2001 From: "e.utkin" Date: Sun, 7 Jun 2020 15:34:09 +0300 Subject: [PATCH 33/61] Fix tests and examples --- README.md | 7 +++- .../scalecube/services/ServiceDefinition.java | 5 +++ .../io/scalecube/services/ServiceFactory.java | 4 +- .../transport/BenchmarkServiceState.java | 6 ++- .../services/examples/ExamplesRunner.java | 6 ++- .../services/examples/codecs/Example1.java | 7 +++- .../services/examples/codecs/Example2.java | 7 +++- .../exceptions/ExceptionMapperExample.java | 42 ++++++++++++++----- .../examples/helloworld/Example1.java | 7 +++- .../examples/helloworld/Example2.java | 7 +++- .../examples/helloworld/Example3.java | 7 +++- .../services/examples/orderbook/Example1.java | 6 ++- .../services/examples/services/Example1.java | 10 ++++- .../services/examples/services/Example2.java | 10 ++++- .../io/scalecube/services/Microservices.java | 14 +++---- ...tory.java => ScalecubeServiceFactory.java} | 37 +++++++++++++--- .../io/scalecube/services/ErrorFlowTest.java | 3 +- .../services/ServiceCallLocalTest.java | 3 +- .../services/ServiceCallRemoteTest.java | 3 +- .../scalecube/services/ServiceLocalTest.java | 20 +++++---- .../services/ServiceRegistryTest.java | 19 +++++---- .../scalecube/services/ServiceRemoteTest.java | 13 +++--- .../services/StreamingServiceTest.java | 3 +- ...ocketNettyColocatedEventLoopGroupTest.java | 10 +++-- .../rsocket/RSocketServiceTransportTest.java | 3 +- 25 files changed, 191 insertions(+), 68 deletions(-) rename services/src/main/java/io/scalecube/services/inject/{ScaleCubeServiceFactory.java => ScalecubeServiceFactory.java} (73%) diff --git a/README.md b/README.md index aee02a40b..8423c1445 100644 --- a/README.md +++ b/README.md @@ -63,7 +63,10 @@ The example provisions 2 cluster nodes and making a remote interaction. //1. ScaleCube Node node with no members Microservices seed = Microservices.builder().startAwait(); - //2. Construct a ScaleCube node which joins the cluster hosting the Greeting Service + //2. Create ServiceFactory + ServiceFactory serviceFactory = ScaleCubeServiceFactory.from(new GreetingServiceImpl()); + + //3. Construct a ScaleCube node which joins the cluster hosting the Greeting Service Microservices microservices = Microservices.builder() .discovery( @@ -71,7 +74,7 @@ The example provisions 2 cluster nodes and making a remote interaction. new ScalecubeServiceDiscovery(self) .options(opts -> opts.seedMembers(toAddress(seed.discovery().address())))) .transport(ServiceTransports::rsocketServiceTransport) - .services(new GreetingServiceImpl()) + .serviceFactory(serviceFactory) .startAwait(); //3. Create service proxy diff --git a/services-api/src/main/java/io/scalecube/services/ServiceDefinition.java b/services-api/src/main/java/io/scalecube/services/ServiceDefinition.java index 0e33ac152..cc8ecd9f8 100644 --- a/services-api/src/main/java/io/scalecube/services/ServiceDefinition.java +++ b/services-api/src/main/java/io/scalecube/services/ServiceDefinition.java @@ -1,5 +1,6 @@ package io.scalecube.services; +import java.util.Collections; import java.util.Map; /** Definition of service - type and tags. */ @@ -13,6 +14,10 @@ public ServiceDefinition(Class serviceType, Map tags) { this.tags = tags; } + public ServiceDefinition(Class serviceType) { + this(serviceType, Collections.emptyMap()); + } + public Class type() { return serviceType; } diff --git a/services-api/src/main/java/io/scalecube/services/ServiceFactory.java b/services-api/src/main/java/io/scalecube/services/ServiceFactory.java index 6bb0a975d..ac6cee528 100644 --- a/services-api/src/main/java/io/scalecube/services/ServiceFactory.java +++ b/services-api/src/main/java/io/scalecube/services/ServiceFactory.java @@ -30,5 +30,7 @@ Mono> getServiceDefinitions( * @param microservices scale cube instance. * @return completed Mono if finalization was successful for all services. */ - Mono shutdownServices(MicroservicesContext microservices); + default Mono shutdownServices(MicroservicesContext microservices) { + return Mono.defer(Mono::empty); + } } diff --git a/services-benchmarks/src/main/java/io/scalecube/services/benchmarks/transport/BenchmarkServiceState.java b/services-benchmarks/src/main/java/io/scalecube/services/benchmarks/transport/BenchmarkServiceState.java index 83eeb5da1..f2b221cfb 100644 --- a/services-benchmarks/src/main/java/io/scalecube/services/benchmarks/transport/BenchmarkServiceState.java +++ b/services-benchmarks/src/main/java/io/scalecube/services/benchmarks/transport/BenchmarkServiceState.java @@ -5,7 +5,9 @@ import io.scalecube.net.Address; import io.scalecube.services.Microservices; import io.scalecube.services.ServiceCall; +import io.scalecube.services.ServiceFactory; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; +import io.scalecube.services.inject.ScalecubeServiceFactory; import io.scalecube.services.transport.rsocket.RSocketServiceTransport; import java.time.Duration; import org.slf4j.Logger; @@ -38,6 +40,8 @@ public void beforeAll() { final Address seedAddress = seed.discovery().address(); + ServiceFactory serviceFactory = ScalecubeServiceFactory.from(services); + node = Microservices.builder() .discovery( @@ -45,7 +49,7 @@ public void beforeAll() { new ScalecubeServiceDiscovery(endpoint) .membership(cfg -> cfg.seedMembers(seedAddress))) .transport(RSocketServiceTransport::new) - .services(services) + .serviceFactory(serviceFactory) .startAwait(); LOGGER.info( diff --git a/services-examples-parent/services-examples-runner/src/main/java/io/scalecube/services/examples/ExamplesRunner.java b/services-examples-parent/services-examples-runner/src/main/java/io/scalecube/services/examples/ExamplesRunner.java index be149c885..bd162996a 100644 --- a/services-examples-parent/services-examples-runner/src/main/java/io/scalecube/services/examples/ExamplesRunner.java +++ b/services-examples-parent/services-examples-runner/src/main/java/io/scalecube/services/examples/ExamplesRunner.java @@ -10,8 +10,10 @@ import io.scalecube.runners.Runners; import io.scalecube.services.Microservices; import io.scalecube.services.ServiceEndpoint; +import io.scalecube.services.ServiceFactory; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.discovery.api.ServiceDiscovery; +import io.scalecube.services.inject.ScalecubeServiceFactory; import io.scalecube.services.transport.rsocket.RSocketServiceTransport; import java.nio.file.Path; import java.util.List; @@ -52,6 +54,8 @@ public static void main(String[] args) { .orElse(Runtime.getRuntime().availableProcessors()); LOGGER.info("Number of worker threads: " + numOfThreads); + ServiceFactory serviceFactory = + ScalecubeServiceFactory.from(new BenchmarkServiceImpl(), new GreetingServiceImpl()); Microservices microservices = Microservices.builder() .discovery(endpoint -> serviceDiscovery(endpoint, config)) .transport( @@ -71,7 +75,7 @@ public static void main(String[] args) { .port(config.servicePort()) .runOn(loopResources) .noSSL())) - .services(new BenchmarkServiceImpl(), new GreetingServiceImpl()) + .serviceFactory(serviceFactory) .startAwait(); Runners.onShutdown(() -> microservices.shutdown().subscribe()); diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/codecs/Example1.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/codecs/Example1.java index 92456ac93..d3ac79390 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/codecs/Example1.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/codecs/Example1.java @@ -2,9 +2,11 @@ import io.scalecube.net.Address; import io.scalecube.services.Microservices; +import io.scalecube.services.ServiceFactory; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.examples.helloworld.service.GreetingServiceImpl; import io.scalecube.services.examples.helloworld.service.api.GreetingsService; +import io.scalecube.services.inject.ScalecubeServiceFactory; import io.scalecube.services.transport.rsocket.RSocketServiceTransport; public class Example1 { @@ -27,6 +29,9 @@ public static void main(String[] args) { final Address seedAddress = seed.discovery().address(); + // Create service factory for GreetingService + ServiceFactory serviceFactory = ScalecubeServiceFactory.from(new GreetingServiceImpl()); + // Construct a ScaleCube node which joins the cluster hosting the Greeting Service Microservices ms = Microservices.builder() @@ -35,7 +40,7 @@ public static void main(String[] args) { new ScalecubeServiceDiscovery(endpoint) .membership(cfg -> cfg.seedMembers(seedAddress))) .transport(RSocketServiceTransport::new) - .services(new GreetingServiceImpl()) + .serviceFactory(serviceFactory) .startAwait(); // Create service proxy diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/codecs/Example2.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/codecs/Example2.java index f7349af55..e244dbeae 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/codecs/Example2.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/codecs/Example2.java @@ -2,9 +2,11 @@ import io.scalecube.net.Address; import io.scalecube.services.Microservices; +import io.scalecube.services.ServiceFactory; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.examples.helloworld.service.GreetingServiceImpl; import io.scalecube.services.examples.helloworld.service.api.GreetingsService; +import io.scalecube.services.inject.ScalecubeServiceFactory; import io.scalecube.services.transport.rsocket.RSocketServiceTransport; public class Example2 { @@ -27,6 +29,9 @@ public static void main(String[] args) { final Address seedAddress = seed.discovery().address(); + // Create serviceFactory for Greeting Service + ServiceFactory serviceFactory = ScalecubeServiceFactory.from(new GreetingServiceImpl()); + // Construct a ScaleCube node which joins the cluster hosting the Greeting Service Microservices ms = Microservices.builder() @@ -35,7 +40,7 @@ public static void main(String[] args) { new ScalecubeServiceDiscovery(endpoint) .membership(cfg -> cfg.seedMembers(seedAddress))) .transport(RSocketServiceTransport::new) - .services(new GreetingServiceImpl()) + .serviceFactory(serviceFactory) .startAwait(); // Create service proxy diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/exceptions/ExceptionMapperExample.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/exceptions/ExceptionMapperExample.java index bafd07b87..51576a418 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/exceptions/ExceptionMapperExample.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/exceptions/ExceptionMapperExample.java @@ -2,10 +2,19 @@ import io.scalecube.net.Address; import io.scalecube.services.Microservices; +import io.scalecube.services.MicroservicesContext; +import io.scalecube.services.ServiceCall; +import io.scalecube.services.ServiceDefinition; +import io.scalecube.services.ServiceFactory; import io.scalecube.services.ServiceInfo; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.transport.rsocket.RSocketServiceTransport; + +import java.util.Collection; import java.util.Collections; +import java.util.List; + +import reactor.core.publisher.Mono; public class ExceptionMapperExample { @@ -31,6 +40,27 @@ public static void main(String[] args) throws InterruptedException { final Address address1 = ms1.discovery().address(); + ServiceFactory serviceFactory = + new ServiceFactory() { + @Override + public Mono> getServiceDefinitions( + MicroservicesContext microservices) { + ServiceDefinition serviceA = new ServiceDefinition(ServiceA.class); + ServiceDefinition serviceB = new ServiceDefinition(ServiceB.class); + return Mono.just(List.of(serviceA, serviceB)); + } + + @Override + public Mono> initializeServices( + MicroservicesContext microservices) { + ServiceCall call = microservices.call(); + ServiceA serviceA = + call.errorMapper(new ServiceAClientErrorMapper()).api(ServiceA.class); + ServiceB serviceB = new ServiceBImpl(serviceA); + ServiceInfo serviceInfoB = ServiceInfo.fromServiceInstance(serviceB).build(); + return Mono.just(Collections.singletonList(serviceInfoB)); + } + }; Microservices ms2 = Microservices.builder() .discovery( @@ -38,17 +68,7 @@ public static void main(String[] args) throws InterruptedException { new ScalecubeServiceDiscovery(endpoint) .membership(cfg -> cfg.seedMembers(address1))) .transport(RSocketServiceTransport::new) - .services( - call -> { - ServiceA serviceA = - call.errorMapper( - new ServiceAClientErrorMapper()) // service client error mapper - .api(ServiceA.class); - - ServiceB serviceB = new ServiceBImpl(serviceA); - - return Collections.singleton(ServiceInfo.fromServiceInstance(serviceB).build()); - }) + .serviceFactory(serviceFactory) .startAwait(); System.err.println("ms2 started: " + ms2.serviceAddress()); diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example1.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example1.java index 1ca40f956..7f9c64cf2 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example1.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example1.java @@ -2,9 +2,11 @@ import io.scalecube.net.Address; import io.scalecube.services.Microservices; +import io.scalecube.services.ServiceFactory; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.examples.helloworld.service.GreetingServiceImpl; import io.scalecube.services.examples.helloworld.service.api.GreetingsService; +import io.scalecube.services.inject.ScalecubeServiceFactory; import io.scalecube.services.transport.rsocket.RSocketServiceTransport; /** @@ -32,6 +34,9 @@ public static void main(String[] args) { final Address seedAddress = seed.discovery().address(); + // Create service factory for Greeting Service + ServiceFactory serviceFactory = ScalecubeServiceFactory.from(new GreetingServiceImpl()); + // Construct a ScaleCube node which joins the cluster hosting the Greeting Service Microservices ms = Microservices.builder() @@ -40,7 +45,7 @@ public static void main(String[] args) { new ScalecubeServiceDiscovery(endpoint) .membership(cfg -> cfg.seedMembers(seedAddress))) .transport(RSocketServiceTransport::new) - .services(new GreetingServiceImpl()) + .serviceFactory(serviceFactory) .startAwait(); // Create service proxy diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example2.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example2.java index fc20274db..55a6cb5a2 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example2.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example2.java @@ -3,10 +3,12 @@ import io.scalecube.net.Address; import io.scalecube.services.Microservices; import io.scalecube.services.ServiceCall; +import io.scalecube.services.ServiceFactory; import io.scalecube.services.api.ServiceMessage; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.examples.helloworld.service.GreetingServiceImpl; import io.scalecube.services.examples.helloworld.service.api.Greeting; +import io.scalecube.services.inject.ScalecubeServiceFactory; import io.scalecube.services.transport.rsocket.RSocketServiceTransport; import org.reactivestreams.Publisher; import reactor.core.publisher.Mono; @@ -41,6 +43,9 @@ public static void main(String[] args) { // Construct a ScaleCube node which joins the cluster hosting the Greeting Service final Address seedAddress = seed.discovery().address(); + // Create service factory for Greeting Service + ServiceFactory serviceFactory = ScalecubeServiceFactory.from(new GreetingServiceImpl()); + Microservices ms = Microservices.builder() .discovery( @@ -48,7 +53,7 @@ public static void main(String[] args) { new ScalecubeServiceDiscovery(endpoint) .membership(cfg -> cfg.seedMembers(seedAddress))) .transport(RSocketServiceTransport::new) - .services(new GreetingServiceImpl()) + .serviceFactory(serviceFactory) .startAwait(); // Create a proxy to the seed service node diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example3.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example3.java index 8891ffa1e..eb200f7c5 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example3.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example3.java @@ -2,9 +2,11 @@ import io.scalecube.net.Address; import io.scalecube.services.Microservices; +import io.scalecube.services.ServiceFactory; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.examples.helloworld.service.BidiGreetingImpl; import io.scalecube.services.examples.helloworld.service.api.BidiGreetingService; +import io.scalecube.services.inject.ScalecubeServiceFactory; import io.scalecube.services.transport.rsocket.RSocketServiceTransport; import reactor.core.publisher.Flux; @@ -33,6 +35,9 @@ public static void main(String[] args) { final Address seedAddress = seed.discovery().address(); + // Create service factory for Bid Greeting Service + ServiceFactory serviceFactory = ScalecubeServiceFactory.from(new BidiGreetingImpl()); + // Construct a ScaleCube node which joins the cluster hosting the Greeting Service Microservices ms = Microservices.builder() @@ -41,7 +46,7 @@ public static void main(String[] args) { new ScalecubeServiceDiscovery(endpoint) .membership(cfg -> cfg.seedMembers(seedAddress))) .transport(RSocketServiceTransport::new) - .services(new BidiGreetingImpl()) + .serviceFactory(serviceFactory) .startAwait(); // Create service proxy diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/orderbook/Example1.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/orderbook/Example1.java index b2bd1b737..cfa02a856 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/orderbook/Example1.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/orderbook/Example1.java @@ -2,6 +2,7 @@ import io.scalecube.net.Address; import io.scalecube.services.Microservices; +import io.scalecube.services.ServiceFactory; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.examples.orderbook.service.DefaultMarketDataService; import io.scalecube.services.examples.orderbook.service.OrderBookSnapshoot; @@ -10,6 +11,7 @@ import io.scalecube.services.examples.orderbook.service.engine.Order; import io.scalecube.services.examples.orderbook.service.engine.PriceLevel; import io.scalecube.services.examples.orderbook.service.engine.events.Side; +import io.scalecube.services.inject.ScalecubeServiceFactory; import io.scalecube.services.transport.rsocket.RSocketServiceTransport; import java.util.Collections; import java.util.Random; @@ -40,6 +42,8 @@ public static void main(String[] args) throws InterruptedException { final Address gatewayAddress = gateway.discovery().address(); + ServiceFactory serviceFactory = ScalecubeServiceFactory.from(new DefaultMarketDataService()); + Microservices ms = Microservices.builder() .discovery( @@ -47,7 +51,7 @@ public static void main(String[] args) throws InterruptedException { new ScalecubeServiceDiscovery(endpoint) .membership(cfg -> cfg.seedMembers(gatewayAddress))) .transport(RSocketServiceTransport::new) - .services(new DefaultMarketDataService()) + .serviceFactory(serviceFactory) .startAwait(); MarketDataService marketService = ms.call().api(MarketDataService.class); diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example1.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example1.java index b6b039151..a0ac7ba04 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example1.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example1.java @@ -2,7 +2,9 @@ import io.scalecube.net.Address; import io.scalecube.services.Microservices; +import io.scalecube.services.ServiceFactory; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; +import io.scalecube.services.inject.ScalecubeServiceFactory; import io.scalecube.services.transport.rsocket.RSocketServiceTransport; import reactor.core.publisher.Mono; import reactor.core.scheduler.Schedulers; @@ -23,6 +25,8 @@ public static void main(String[] args) { final Address gatewayAddress = gateway.discovery().address(); + ServiceFactory serviceFactory2 = ScalecubeServiceFactory.from(new Service2Impl()); + Microservices service2Node = Microservices.builder() .discovery( @@ -30,9 +34,11 @@ public static void main(String[] args) { new ScalecubeServiceDiscovery(endpoint) .membership(cfg -> cfg.seedMembers(gatewayAddress))) .transport(RSocketServiceTransport::new) - .services(new Service2Impl()) + .serviceFactory(serviceFactory2) .startAwait(); + ServiceFactory serviceFactory1 = ScalecubeServiceFactory.from(new Service1Impl()); + Microservices service1Node = Microservices.builder() .discovery( @@ -40,7 +46,7 @@ public static void main(String[] args) { new ScalecubeServiceDiscovery(endpoint) .membership(cfg -> cfg.seedMembers(gatewayAddress))) .transport(RSocketServiceTransport::new) - .services(new Service1Impl()) + .serviceFactory(serviceFactory1) .startAwait(); gateway diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example2.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example2.java index a5c528d20..1ac6384df 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example2.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example2.java @@ -2,7 +2,9 @@ import io.scalecube.net.Address; import io.scalecube.services.Microservices; +import io.scalecube.services.ServiceFactory; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; +import io.scalecube.services.inject.ScalecubeServiceFactory; import io.scalecube.services.transport.rsocket.RSocketServiceTransport; import reactor.core.publisher.Mono; import reactor.core.scheduler.Schedulers; @@ -23,6 +25,8 @@ public static void main(String[] args) { final Address gatewayAddress = gateway.discovery().address(); + ServiceFactory serviceFactory2 = ScalecubeServiceFactory.from(new Service2Impl()); + Microservices service2Node = Microservices.builder() .discovery( @@ -30,9 +34,11 @@ public static void main(String[] args) { new ScalecubeServiceDiscovery(endpoint) .membership(cfg -> cfg.seedMembers(gatewayAddress))) .transport(RSocketServiceTransport::new) - .services(new Service2Impl()) + .serviceFactory(serviceFactory2) .startAwait(); + ServiceFactory serviceFactory1 = ScalecubeServiceFactory.from(new Service1Impl()); + Microservices service1Node = Microservices.builder() .discovery( @@ -40,7 +46,7 @@ public static void main(String[] args) { new ScalecubeServiceDiscovery(endpoint) .membership(cfg -> cfg.seedMembers(gatewayAddress))) .transport(RSocketServiceTransport::new) - .services(new Service1Impl()) + .serviceFactory(serviceFactory1) .startAwait(); gateway diff --git a/services/src/main/java/io/scalecube/services/Microservices.java b/services/src/main/java/io/scalecube/services/Microservices.java index 9ef871ba9..3bd64cdc9 100644 --- a/services/src/main/java/io/scalecube/services/Microservices.java +++ b/services/src/main/java/io/scalecube/services/Microservices.java @@ -9,7 +9,7 @@ import io.scalecube.services.exceptions.ServiceProviderErrorMapper; import io.scalecube.services.gateway.Gateway; import io.scalecube.services.gateway.GatewayOptions; -import io.scalecube.services.inject.ScaleCubeServiceFactory; +import io.scalecube.services.inject.ScalecubeServiceFactory; import io.scalecube.services.methods.MethodInfo; import io.scalecube.services.methods.ServiceMethodInvoker; import io.scalecube.services.methods.ServiceMethodRegistry; @@ -367,7 +367,7 @@ private void build() { List serviceProviders = Collections.unmodifiableList(this.serviceProviders); this.serviceFactory = this.serviceFactory == null - ? ScaleCubeServiceFactory.create(serviceProviders) + ? ScalecubeServiceFactory.create(serviceProviders) : this.serviceFactory; } @@ -389,7 +389,7 @@ public Microservices startAwait() { * * @param services service info instance. * @return builder - * @deprecated use {@link this#serviceProvider(ServiceFactory)} + * @deprecated use {@link this#serviceFactory(ServiceFactory)} */ @Deprecated public Builder services(ServiceInfo... services) { @@ -406,7 +406,7 @@ public Builder services(ServiceInfo... services) { * * @param services service instance. * @return builder - * @deprecated use {@link this#serviceProvider(ServiceFactory)} + * @deprecated use {@link this#serviceFactory(ServiceFactory)} */ @Deprecated public Builder services(Object... services) { @@ -425,7 +425,7 @@ public Builder services(Object... services) { * * @param serviceProvider - old service provider * @return this - * @deprecated use {@link this#serviceProvider(ServiceFactory)} + * @deprecated use {@link this#serviceFactory(ServiceFactory)} */ @Deprecated public Builder services(ServiceProvider serviceProvider) { @@ -433,8 +433,8 @@ public Builder services(ServiceProvider serviceProvider) { return this; } - public Builder serviceProvider(ServiceFactory serviceProvider) { - this.serviceFactory = serviceProvider; + public Builder serviceFactory(ServiceFactory serviceFactory) { + this.serviceFactory = serviceFactory; return this; } diff --git a/services/src/main/java/io/scalecube/services/inject/ScaleCubeServiceFactory.java b/services/src/main/java/io/scalecube/services/inject/ScalecubeServiceFactory.java similarity index 73% rename from services/src/main/java/io/scalecube/services/inject/ScaleCubeServiceFactory.java rename to services/src/main/java/io/scalecube/services/inject/ScalecubeServiceFactory.java index 65705e9e0..b1ee47f2d 100644 --- a/services/src/main/java/io/scalecube/services/inject/ScaleCubeServiceFactory.java +++ b/services/src/main/java/io/scalecube/services/inject/ScalecubeServiceFactory.java @@ -7,29 +7,54 @@ import io.scalecube.services.ServiceInfo; import io.scalecube.services.ServiceProvider; import java.util.Collection; +import java.util.Collections; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; import java.util.stream.Collectors; +import java.util.stream.Stream; + import reactor.core.publisher.Mono; -public class ScaleCubeServiceFactory implements ServiceFactory { +public class ScalecubeServiceFactory implements ServiceFactory { private final Function> serviceFactory; // lazy init - private AtomicReference> services = new AtomicReference<>(); + private final AtomicReference> services = new AtomicReference<>(); /** * Create the instance from {@link ServiceProvider}. * * @param serviceProviders old service providers. - * @return default services provider. + * @return default services factory. + * @deprecated use {@link this#from(Object...)} */ public static ServiceFactory create(Collection serviceProviders) { - return new ScaleCubeServiceFactory(serviceProviders); + return new ScalecubeServiceFactory(serviceProviders); + } + + /** + * Create the instance {@link ServiceFactory} with pre-installed services. + * + * @param services user's services + * @return service factory + */ + public static ServiceFactory from(Object... services) { + ServiceProvider provider = call -> Stream.of(services) + .map(service -> { + ServiceInfo.Builder builder; + if (service instanceof ServiceInfo) { + builder = ServiceInfo.from((ServiceInfo) service); + } else { + builder = ServiceInfo.fromServiceInstance(service); + } + return builder.build(); + }) + .collect(Collectors.toList()); + return new ScalecubeServiceFactory(Collections.singleton(provider)); } - private ScaleCubeServiceFactory(Collection serviceProviders) { + private ScalecubeServiceFactory(Collection serviceProviders) { this.serviceFactory = microservices -> serviceProviders.stream() @@ -43,7 +68,7 @@ private ScaleCubeServiceFactory(Collection serviceProviders) { * Since the service instance factory ({@link ServiceProvider}) we have to leave behind does not * provide us with information about the types of services produced, there is nothing left for us * to do but start creating all the services and then retrieve the type of service, previously - * saving it as a {@link ScaleCubeServiceFactory} state. + * saving it as a {@link ScalecubeServiceFactory} state. * *

{@inheritDoc} * diff --git a/services/src/test/java/io/scalecube/services/ErrorFlowTest.java b/services/src/test/java/io/scalecube/services/ErrorFlowTest.java index bd6f56ef0..7f129eb3f 100644 --- a/services/src/test/java/io/scalecube/services/ErrorFlowTest.java +++ b/services/src/test/java/io/scalecube/services/ErrorFlowTest.java @@ -10,6 +10,7 @@ import io.scalecube.services.exceptions.InternalServiceException; import io.scalecube.services.exceptions.ServiceUnavailableException; import io.scalecube.services.exceptions.UnauthorizedException; +import io.scalecube.services.inject.ScalecubeServiceFactory; import io.scalecube.services.sut.GreetingResponse; import io.scalecube.services.sut.GreetingServiceImpl; import io.scalecube.services.transport.rsocket.RSocketServiceTransport; @@ -35,7 +36,7 @@ public static void initNodes() { new ScalecubeServiceDiscovery(endpoint) .transport(cfg -> cfg.port(port.incrementAndGet()))) .transport(RSocketServiceTransport::new) - .services(new GreetingServiceImpl()) + .serviceFactory(ScalecubeServiceFactory.from(new GreetingServiceImpl())) .startAwait(); final Address seedAddress = provider.discovery().address(); diff --git a/services/src/test/java/io/scalecube/services/ServiceCallLocalTest.java b/services/src/test/java/io/scalecube/services/ServiceCallLocalTest.java index e39bfda6a..ca7dcd2a2 100644 --- a/services/src/test/java/io/scalecube/services/ServiceCallLocalTest.java +++ b/services/src/test/java/io/scalecube/services/ServiceCallLocalTest.java @@ -19,6 +19,7 @@ import io.scalecube.services.api.ServiceMessage; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.exceptions.ServiceException; +import io.scalecube.services.inject.ScalecubeServiceFactory; import io.scalecube.services.routing.RoundRobinServiceRouter; import io.scalecube.services.sut.EmptyGreetingResponse; import io.scalecube.services.sut.GreetingResponse; @@ -67,7 +68,7 @@ private static Microservices serviceProvider() { return Microservices.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) - .services(new GreetingServiceImpl()) + .serviceFactory(ScalecubeServiceFactory.from(new GreetingServiceImpl())) .startAwait(); } diff --git a/services/src/test/java/io/scalecube/services/ServiceCallRemoteTest.java b/services/src/test/java/io/scalecube/services/ServiceCallRemoteTest.java index 4143c90db..eedb7bcc1 100644 --- a/services/src/test/java/io/scalecube/services/ServiceCallRemoteTest.java +++ b/services/src/test/java/io/scalecube/services/ServiceCallRemoteTest.java @@ -20,6 +20,7 @@ import io.scalecube.services.api.ServiceMessage; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.exceptions.ServiceException; +import io.scalecube.services.inject.ScalecubeServiceFactory; import io.scalecube.services.sut.EmptyGreetingResponse; import io.scalecube.services.sut.GreetingResponse; import io.scalecube.services.sut.GreetingServiceImpl; @@ -71,7 +72,7 @@ private static Microservices serviceProvider(Object service) { new ScalecubeServiceDiscovery(endpoint) .membership(cfg -> cfg.seedMembers(gateway.discovery().address()))) .transport(RSocketServiceTransport::new) - .services(service) + .serviceFactory(ScalecubeServiceFactory.from(service)) .startAwait(); } diff --git a/services/src/test/java/io/scalecube/services/ServiceLocalTest.java b/services/src/test/java/io/scalecube/services/ServiceLocalTest.java index 16c62d3f2..85bd68732 100644 --- a/services/src/test/java/io/scalecube/services/ServiceLocalTest.java +++ b/services/src/test/java/io/scalecube/services/ServiceLocalTest.java @@ -5,12 +5,15 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import io.scalecube.services.api.ServiceMessage; +import io.scalecube.services.inject.ScalecubeServiceFactory; import io.scalecube.services.sut.GreetingRequest; import io.scalecube.services.sut.GreetingResponse; import io.scalecube.services.sut.GreetingService; import io.scalecube.services.sut.GreetingServiceImpl; + import java.time.Duration; import java.util.concurrent.atomic.AtomicReference; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -27,7 +30,10 @@ public class ServiceLocalTest extends BaseTest { @BeforeEach public void setUp() { - microservices = Microservices.builder().services(new GreetingServiceImpl()).startAwait(); + microservices = + Microservices.builder() + .serviceFactory(ScalecubeServiceFactory.from(new GreetingServiceImpl())) + .startAwait(); } @AfterEach @@ -212,9 +218,9 @@ void test_local_greeting_message() { ServiceCall serviceCall = microservices.call(); StepVerifier.create( - serviceCall.requestOne( - ServiceMessage.from(request).qualifier("/greetings/greetingMessage").build(), - GreetingResponse.class)) + serviceCall.requestOne( + ServiceMessage.from(request).qualifier("/greetings/greetingMessage").build(), + GreetingResponse.class)) .assertNext( message -> { assertEquals(GreetingResponse.class, message.data().getClass()); @@ -228,9 +234,9 @@ void test_local_greeting_message() { .verify(timeout); StepVerifier.create( - serviceCall.requestOne( - ServiceMessage.from(request).qualifier("/greetings/greetingMessage2").build(), - GreetingResponse.class)) + serviceCall.requestOne( + ServiceMessage.from(request).qualifier("/greetings/greetingMessage2").build(), + GreetingResponse.class)) .assertNext( message -> { assertEquals(GreetingResponse.class, message.data().getClass()); diff --git a/services/src/test/java/io/scalecube/services/ServiceRegistryTest.java b/services/src/test/java/io/scalecube/services/ServiceRegistryTest.java index d1c503ecf..cec954f9d 100644 --- a/services/src/test/java/io/scalecube/services/ServiceRegistryTest.java +++ b/services/src/test/java/io/scalecube/services/ServiceRegistryTest.java @@ -13,6 +13,7 @@ import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.discovery.api.ServiceDiscovery; import io.scalecube.services.discovery.api.ServiceDiscoveryEvent; +import io.scalecube.services.inject.ScalecubeServiceFactory; import io.scalecube.services.sut.AnnotationService; import io.scalecube.services.sut.AnnotationServiceImpl; import io.scalecube.services.sut.GreetingServiceImpl; @@ -59,14 +60,14 @@ public void test_added_removed_registration_events(MetadataCodec metadataCodec) Microservices.builder() .discovery(defServiceDiscovery(seedAddress, metadataCodec)) .transport(RSocketServiceTransport::new) - .services(new GreetingServiceImpl()) + .serviceFactory(ScalecubeServiceFactory.from(new GreetingServiceImpl())) .startAwait(); Microservices ms2 = Microservices.builder() .discovery(defServiceDiscovery(seedAddress, metadataCodec)) .transport(RSocketServiceTransport::new) - .services(new GreetingServiceImpl()) + .serviceFactory(ScalecubeServiceFactory.from(new GreetingServiceImpl())) .startAwait(); StepVerifier.create(events) @@ -93,7 +94,7 @@ public void test_listen_to_discovery_events(MetadataCodec metadataCodec) { Microservices.builder() .discovery(defServiceDiscovery(metadataCodec)) .transport(RSocketServiceTransport::new) - .services(new AnnotationServiceImpl()) + .serviceFactory(ScalecubeServiceFactory.from(new AnnotationServiceImpl())) .startAwait(); cluster.add(seed); @@ -108,7 +109,7 @@ public void test_listen_to_discovery_events(MetadataCodec metadataCodec) { Microservices.builder() .discovery(defServiceDiscovery(seedAddress, metadataCodec)) .transport(RSocketServiceTransport::new) - .services(new GreetingServiceImpl()) + .serviceFactory(ScalecubeServiceFactory.from(new GreetingServiceImpl())) .startAwait(); cluster.add(ms1); }) @@ -119,7 +120,7 @@ public void test_listen_to_discovery_events(MetadataCodec metadataCodec) { Microservices.builder() .discovery(defServiceDiscovery(seedAddress, metadataCodec)) .transport(RSocketServiceTransport::new) - .services(new GreetingServiceImpl()) + .serviceFactory(ScalecubeServiceFactory.from(new GreetingServiceImpl())) .startAwait(); cluster.add(ms2); }) @@ -160,7 +161,7 @@ public void test_delayed_listen_to_discovery_events(MetadataCodec metadataCodec) Microservices.builder() .discovery(defServiceDiscovery(metadataCodec)) .transport(RSocketServiceTransport::new) - .services(new GreetingServiceImpl()) + .serviceFactory(ScalecubeServiceFactory.from(new GreetingServiceImpl())) .startAwait(); cluster.add(seed); @@ -175,7 +176,9 @@ public void test_delayed_listen_to_discovery_events(MetadataCodec metadataCodec) Microservices.builder() .discovery(defServiceDiscovery(seedAddress, metadataCodec)) .transport(RSocketServiceTransport::new) - .services(new GreetingServiceImpl(), new AnnotationServiceImpl()) + .serviceFactory( + ScalecubeServiceFactory.from( + new GreetingServiceImpl(), new AnnotationServiceImpl())) .startAwait(); cluster.add(ms1); }) @@ -186,7 +189,7 @@ public void test_delayed_listen_to_discovery_events(MetadataCodec metadataCodec) Microservices.builder() .discovery(defServiceDiscovery(seedAddress, metadataCodec)) .transport(RSocketServiceTransport::new) - .services(new GreetingServiceImpl()) + .serviceFactory(ScalecubeServiceFactory.from(new GreetingServiceImpl())) .startAwait(); cluster.add(ms2); }) diff --git a/services/src/test/java/io/scalecube/services/ServiceRemoteTest.java b/services/src/test/java/io/scalecube/services/ServiceRemoteTest.java index 03ddfb7ca..02d43c421 100644 --- a/services/src/test/java/io/scalecube/services/ServiceRemoteTest.java +++ b/services/src/test/java/io/scalecube/services/ServiceRemoteTest.java @@ -8,6 +8,7 @@ import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.discovery.api.ServiceDiscovery; import io.scalecube.services.exceptions.InternalServiceException; +import io.scalecube.services.inject.ScalecubeServiceFactory; import io.scalecube.services.sut.CoarseGrainedService; import io.scalecube.services.sut.CoarseGrainedServiceImpl; import io.scalecube.services.sut.EmptyGreetingRequest; @@ -72,7 +73,7 @@ private static Microservices serviceProvider() { return Microservices.builder() .discovery(ServiceRemoteTest::serviceDiscovery) .transport(RSocketServiceTransport::new) - .services(new GreetingServiceImpl()) + .serviceFactory(ScalecubeServiceFactory.from(new GreetingServiceImpl())) .startAwait(); } @@ -268,7 +269,7 @@ public void test_remote_serviceA_calls_serviceB_using_setter() { Microservices.builder() .discovery(ServiceRemoteTest::serviceDiscovery) .transport(RSocketServiceTransport::new) - .services(new CoarseGrainedServiceImpl()) // add service a and b + .serviceFactory(ScalecubeServiceFactory.from(new CoarseGrainedServiceImpl())) // add service a and b .startAwait(); // Get a proxy to the service api. @@ -291,7 +292,7 @@ public void test_remote_serviceA_calls_serviceB() { Microservices.builder() .discovery(ServiceRemoteTest::serviceDiscovery) .transport(RSocketServiceTransport::new) - .services(another) + .serviceFactory(ScalecubeServiceFactory.from(another)) .startAwait(); // Get a proxy to the service api. @@ -311,7 +312,7 @@ public void test_remote_serviceA_calls_serviceB_with_timeout() { Microservices.builder() .discovery(ServiceRemoteTest::serviceDiscovery) .transport(RSocketServiceTransport::new) - .services(another) // add service a and b + .serviceFactory(ScalecubeServiceFactory.from(another)) // add service a and b .startAwait(); // Get a proxy to the service api. @@ -336,7 +337,7 @@ public void test_remote_serviceA_calls_serviceB_with_dispatcher() { Microservices.builder() .discovery(ServiceRemoteTest::serviceDiscovery) .transport(RSocketServiceTransport::new) - .services(another) // add service a and b + .serviceFactory(ScalecubeServiceFactory.from(another)) // add service a and b .startAwait(); // Get a proxy to the service api. @@ -421,7 +422,7 @@ public void test_services_contribute_to_cluster_metadata() { .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) .tags(tags) - .services(new GreetingServiceImpl()) + .serviceFactory(ScalecubeServiceFactory.from(new GreetingServiceImpl())) .startAwait(); assertTrue(ms.discovery().serviceEndpoint().tags().containsKey("HOSTNAME")); diff --git a/services/src/test/java/io/scalecube/services/StreamingServiceTest.java b/services/src/test/java/io/scalecube/services/StreamingServiceTest.java index db4c56a8b..d1bdb7dbe 100644 --- a/services/src/test/java/io/scalecube/services/StreamingServiceTest.java +++ b/services/src/test/java/io/scalecube/services/StreamingServiceTest.java @@ -7,6 +7,7 @@ import io.scalecube.services.api.ServiceMessage; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; +import io.scalecube.services.inject.ScalecubeServiceFactory; import io.scalecube.services.sut.QuoteService; import io.scalecube.services.sut.SimpleQuoteService; import io.scalecube.services.transport.api.ServiceMessageCodec; @@ -41,7 +42,7 @@ public static void setup() { .membership(cfg -> cfg.seedMembers(gateway.discovery().address()))) .transport(RSocketServiceTransport::new) .defaultDataDecoder(ServiceMessageCodec::decodeData) - .services(new SimpleQuoteService()) + .serviceFactory(ScalecubeServiceFactory.from(new SimpleQuoteService())) .startAwait(); } diff --git a/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketNettyColocatedEventLoopGroupTest.java b/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketNettyColocatedEventLoopGroupTest.java index d333a1b93..affdd15cf 100644 --- a/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketNettyColocatedEventLoopGroupTest.java +++ b/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketNettyColocatedEventLoopGroupTest.java @@ -11,6 +11,8 @@ import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import java.util.Optional; import java.util.concurrent.atomic.AtomicBoolean; + +import io.scalecube.services.inject.ScalecubeServiceFactory; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -38,9 +40,10 @@ public void setUp() { new ScalecubeServiceDiscovery(endpoint) .membership(cfg -> cfg.seedMembers(gateway.discovery().address()))) .transport(RSocketServiceTransport::new) - .services(new Facade()) + .serviceFactory(ScalecubeServiceFactory.from(new Facade())) .startAwait(); + PingService pingService = () -> Mono.just(Thread.currentThread().getName()); this.ping = Microservices.builder() .discovery( @@ -48,9 +51,10 @@ public void setUp() { new ScalecubeServiceDiscovery(endpoint) .membership(cfg -> cfg.seedMembers(facade.discovery().address()))) .transport(RSocketServiceTransport::new) - .services((PingService) () -> Mono.just(Thread.currentThread().getName())) + .serviceFactory(ScalecubeServiceFactory.from(pingService)) .startAwait(); + PongService pongService = () -> Mono.just(Thread.currentThread().getName()); this.pong = Microservices.builder() .discovery( @@ -58,7 +62,7 @@ public void setUp() { new ScalecubeServiceDiscovery(endpoint) .membership(cfg -> cfg.seedMembers(facade.discovery().address()))) .transport(RSocketServiceTransport::new) - .services((PongService) () -> Mono.just(Thread.currentThread().getName())) + .serviceFactory(ScalecubeServiceFactory.from(pongService)) .startAwait(); } diff --git a/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketServiceTransportTest.java b/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketServiceTransportTest.java index ac042a89d..d6f7b1a1c 100644 --- a/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketServiceTransportTest.java +++ b/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketServiceTransportTest.java @@ -10,6 +10,7 @@ import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.discovery.api.ServiceDiscoveryEvent; import io.scalecube.services.exceptions.ConnectionClosedException; +import io.scalecube.services.inject.ScalecubeServiceFactory; import io.scalecube.services.sut.QuoteService; import io.scalecube.services.sut.SimpleQuoteService; import java.time.Duration; @@ -50,7 +51,7 @@ public void setUp() { new ScalecubeServiceDiscovery(serviceEndpoint) .membership(cfg -> cfg.seedMembers(gateway.discovery().address()))) .transport(RSocketServiceTransport::new) - .services(new SimpleQuoteService()) + .serviceFactory(ScalecubeServiceFactory.from(new SimpleQuoteService())) .startAwait(); } From 13b2403aebd9b9f2e57383b4f1bf3d0ebda7e1c0 Mon Sep 17 00:00:00 2001 From: "e.utkin" Date: Sun, 7 Jun 2020 22:27:53 +0300 Subject: [PATCH 34/61] Fix code review checks --- .../services/MicroservicesContext.java | 33 +++++++++++++++++-- .../exceptions/ExceptionMapperExample.java | 2 +- 2 files changed, 31 insertions(+), 4 deletions(-) diff --git a/services-api/src/main/java/io/scalecube/services/MicroservicesContext.java b/services-api/src/main/java/io/scalecube/services/MicroservicesContext.java index cdf7f5e97..0d2b75f9d 100644 --- a/services-api/src/main/java/io/scalecube/services/MicroservicesContext.java +++ b/services-api/src/main/java/io/scalecube/services/MicroservicesContext.java @@ -3,14 +3,41 @@ import io.scalecube.net.Address; import io.scalecube.services.discovery.api.ServiceDiscovery; +/** + * Context of Scale Cube node. Used in {@link ServiceFactory}. + * + * @see ServiceFactory + */ public interface MicroservicesContext { + /** + * Id of Scale Cube node. + * + * @return id + */ String id(); - ServiceCall call(); + /** + * Used for remote service call. + * + * @return service call + * @see ServiceCall + */ + ServiceCall serviceCall(); + /** + * Network address of Scale Cube node. + * + * @return address of node + * @see Address + */ Address serviceAddress(); - ServiceDiscovery discovery(); - + /** + * Service discovery for services localed in other nodes. + * + * @return service discovery + * @see ServiceDiscovery + */ + ServiceDiscovery serviceDiscovery(); } diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/exceptions/ExceptionMapperExample.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/exceptions/ExceptionMapperExample.java index 51576a418..967dc666c 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/exceptions/ExceptionMapperExample.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/exceptions/ExceptionMapperExample.java @@ -53,7 +53,7 @@ public Mono> getServiceDefinitions( @Override public Mono> initializeServices( MicroservicesContext microservices) { - ServiceCall call = microservices.call(); + ServiceCall call = microservices.serviceCall(); ServiceA serviceA = call.errorMapper(new ServiceAClientErrorMapper()).api(ServiceA.class); ServiceB serviceB = new ServiceBImpl(serviceA); From 1895d8f66b3720b3bbc6eba2e3c65fcbc9048b8c Mon Sep 17 00:00:00 2001 From: "e.utkin" Date: Mon, 8 Jun 2020 14:36:53 +0300 Subject: [PATCH 35/61] add spring & guice review --- .../java/io/scalecube/services/Reflect.java | 3 + .../io/scalecube/services/RemoteService.java | 4 + .../io/scalecube/services/ServiceCall.java | 2 +- .../services-examples/pom.xml | 15 ++ .../factory/GuiceServiceFactoryExample.java | 161 ++++++++++++++++++ .../factory/SpringServiceFactoryExample.java | 142 +++++++++++++++ .../factory/service/BidiGreetingImpl.java | 31 ++++ .../factory/service/GreetingServiceImpl.java | 12 ++ .../service/api/BidiGreetingService.java | 13 ++ .../factory/service/api/Greeting.java | 18 ++ .../factory/service/api/GreetingsService.java | 23 +++ .../io/scalecube/services/Microservices.java | 4 +- .../scalecube/services/inject/Injector.java | 5 +- .../inject/ScalecubeServiceFactory.java | 2 +- .../services/sut/AnnotationServiceImpl.java | 3 +- .../sut/CoarseGrainedServiceImpl.java | 3 +- 16 files changed, 430 insertions(+), 11 deletions(-) create mode 100644 services-api/src/main/java/io/scalecube/services/RemoteService.java create mode 100644 services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/GuiceServiceFactoryExample.java create mode 100644 services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/SpringServiceFactoryExample.java create mode 100644 services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/service/BidiGreetingImpl.java create mode 100644 services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/service/GreetingServiceImpl.java create mode 100644 services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/service/api/BidiGreetingService.java create mode 100644 services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/service/api/Greeting.java create mode 100644 services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/service/api/GreetingsService.java diff --git a/services-api/src/main/java/io/scalecube/services/Reflect.java b/services-api/src/main/java/io/scalecube/services/Reflect.java index 270c41958..54a6a2674 100644 --- a/services-api/src/main/java/io/scalecube/services/Reflect.java +++ b/services-api/src/main/java/io/scalecube/services/Reflect.java @@ -257,6 +257,9 @@ public static Stream> serviceInterfaces(Object serviceObject) { * @return service interface class. */ public static Stream> serviceInterfaces(Class serviceType) { + if (serviceType.isInterface() && serviceType.isAnnotationPresent(Service.class)) { + return Stream.of(serviceType); + } Class[] interfaces = serviceType.getInterfaces(); return Arrays.stream(interfaces) .filter(interfaceClass -> interfaceClass.isAnnotationPresent(Service.class)); diff --git a/services-api/src/main/java/io/scalecube/services/RemoteService.java b/services-api/src/main/java/io/scalecube/services/RemoteService.java new file mode 100644 index 000000000..0b0b407c6 --- /dev/null +++ b/services-api/src/main/java/io/scalecube/services/RemoteService.java @@ -0,0 +1,4 @@ +package io.scalecube.services; + +public interface RemoteService { +} diff --git a/services-api/src/main/java/io/scalecube/services/ServiceCall.java b/services-api/src/main/java/io/scalecube/services/ServiceCall.java index 6b7f99819..b04953192 100644 --- a/services-api/src/main/java/io/scalecube/services/ServiceCall.java +++ b/services-api/src/main/java/io/scalecube/services/ServiceCall.java @@ -367,7 +367,7 @@ public T api(Class serviceInterface) { return (T) Proxy.newProxyInstance( getClass().getClassLoader(), - new Class[] {serviceInterface}, + new Class[] {serviceInterface, RemoteService.class}, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] params) { diff --git a/services-examples-parent/services-examples/pom.xml b/services-examples-parent/services-examples/pom.xml index 5ef7e3d99..a5724c785 100644 --- a/services-examples-parent/services-examples/pom.xml +++ b/services-examples-parent/services-examples/pom.xml @@ -57,6 +57,21 @@ org.apache.logging.log4j log4j-core + + org.springframework + spring-core + 5.2.6.RELEASE + + + org.springframework + spring-context + 5.2.6.RELEASE + + + com.google.inject + guice + 4.1.0 + diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/GuiceServiceFactoryExample.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/GuiceServiceFactoryExample.java new file mode 100644 index 000000000..2b2508da4 --- /dev/null +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/GuiceServiceFactoryExample.java @@ -0,0 +1,161 @@ +package io.scalecube.services.examples.services.factory; + +import com.google.inject.AbstractModule; +import com.google.inject.Guice; +import com.google.inject.Inject; +import com.google.inject.Injector; +import com.google.inject.Module; +import com.google.inject.Provider; +import com.google.inject.Scopes; +import io.scalecube.services.Microservices; +import io.scalecube.services.MicroservicesContext; +import io.scalecube.services.Reflect; +import io.scalecube.services.RemoteService; +import io.scalecube.services.ServiceCall; +import io.scalecube.services.ServiceDefinition; +import io.scalecube.services.ServiceFactory; +import io.scalecube.services.ServiceInfo; +import io.scalecube.services.discovery.ScalecubeServiceDiscovery; +import io.scalecube.services.discovery.api.ServiceDiscovery; +import io.scalecube.services.examples.helloworld.service.GreetingServiceImpl; +import io.scalecube.services.examples.services.factory.service.BidiGreetingImpl; +import io.scalecube.services.examples.services.factory.service.api.BidiGreetingService; +import io.scalecube.services.examples.services.factory.service.api.GreetingsService; +import io.scalecube.services.inject.ScalecubeServiceFactory; +import io.scalecube.services.transport.rsocket.RSocketServiceTransport; +import java.lang.reflect.Constructor; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.Objects; +import java.util.function.Predicate; +import java.util.stream.Collectors; +import reactor.core.publisher.Mono; + +public class GuiceServiceFactoryExample { + + /** + * Main method. + * + * @param args - program arguments + */ + public static void main(String[] args) { + ServiceFactory serviceFactory2 = ScalecubeServiceFactory.from(new GreetingServiceImpl()); + + Microservices service2Node = + Microservices.builder() + .serviceFactory(serviceFactory2) + .discovery(ScalecubeServiceDiscovery::new) + .transport(RSocketServiceTransport::new) + .startAwait(); + + ServiceFactory serviceFactory1 = new GuiceServiceFactory(new SampleModule()); + + Microservices service1Node = + Microservices.builder() + .discovery( + endpoint -> + new ScalecubeServiceDiscovery(endpoint) + .membership(cfg -> cfg.seedMembers(service2Node.discovery().address()))) + .serviceFactory(serviceFactory1) + .transport(RSocketServiceTransport::new) + .startAwait(); + + service1Node + .call() + .api(BidiGreetingService.class) + .greeting() + .log("receive |") + .log() + .log("complete |") + .block(); + + Mono.whenDelayError(service1Node.shutdown(), service2Node.shutdown()).block(); + } + + public static class SampleModule extends AbstractModule { + + @Override + protected void configure() { + try { + bind(GreetingsService.class) + .toProvider( + new Provider<>() { + + @Inject private ServiceCall serviceCall; + + @Override + public GreetingsService get() { + return serviceCall.api(GreetingsService.class); + } + }); + Constructor constructor = + BidiGreetingImpl1.class.getConstructor(GreetingsService.class); + bind(BidiGreetingService.class).toConstructor(constructor).in(Scopes.SINGLETON); + } catch (Exception ex) { + throw new RuntimeException(ex); + } + } + } + + public static class BidiGreetingImpl1 extends BidiGreetingImpl implements BidiGreetingService { + + @Inject + public BidiGreetingImpl1(GreetingsService greetingsService) { + super(greetingsService); + } + } + + public static class GuiceServiceFactory implements ServiceFactory { + + private final List modules; + private final List beans = new ArrayList<>(); + + private GuiceServiceFactory(Module... modules) { + this.modules = Arrays.asList(modules); + } + + @Override + public Mono> getServiceDefinitions( + MicroservicesContext microservices) { + return Mono.fromCallable( + () -> { + AbstractModule baseModule = + new AbstractModule() { + + @Override + protected void configure() { + bind(MicroservicesContext.class).toInstance(microservices); + bind(ServiceCall.class).toProvider(microservices::serviceCall); + bind(ServiceDiscovery.class).toProvider(microservices::serviceDiscovery); + } + }; + List modules = new ArrayList<>(); + modules.add(baseModule); + modules.addAll(this.modules); + Injector injector = Guice.createInjector(modules); + return injector.getAllBindings().values().stream() + .map(binding -> binding.getProvider().get()) + .filter(Objects::nonNull) + .filter( + Predicate.not(bean -> RemoteService.class.isAssignableFrom(bean.getClass()))) + .filter(bean -> Reflect.serviceInterfaces(bean).findAny().isPresent()) + .peek(this.beans::add) + .map(Object::getClass) + .map(ServiceDefinition::new) + .collect(Collectors.toList()); + }); + } + + @Override + public Mono> initializeServices( + MicroservicesContext microservices) { + return Mono.fromCallable( + () -> + this.beans.stream() + .map(bean -> ServiceInfo.fromServiceInstance(bean).build()) + .collect(Collectors.toList())); + } + } +} diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/SpringServiceFactoryExample.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/SpringServiceFactoryExample.java new file mode 100644 index 000000000..34564963a --- /dev/null +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/SpringServiceFactoryExample.java @@ -0,0 +1,142 @@ +package io.scalecube.services.examples.services.factory; + +import io.scalecube.services.Microservices; +import io.scalecube.services.MicroservicesContext; +import io.scalecube.services.RemoteService; +import io.scalecube.services.ServiceCall; +import io.scalecube.services.ServiceDefinition; +import io.scalecube.services.ServiceFactory; +import io.scalecube.services.ServiceInfo; +import io.scalecube.services.annotations.Service; +import io.scalecube.services.discovery.ScalecubeServiceDiscovery; +import io.scalecube.services.discovery.api.ServiceDiscovery; +import io.scalecube.services.examples.helloworld.service.GreetingServiceImpl; +import io.scalecube.services.examples.services.factory.service.BidiGreetingImpl; +import io.scalecube.services.examples.services.factory.service.api.BidiGreetingService; +import io.scalecube.services.examples.services.factory.service.api.GreetingsService; +import io.scalecube.services.inject.ScalecubeServiceFactory; +import io.scalecube.services.transport.rsocket.RSocketServiceTransport; + +import java.util.Collection; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import reactor.core.publisher.Mono; + +public class SpringServiceFactoryExample { + + /** + * Main method. + * + * @param args - program arguments + */ + public static void main(String[] args) { + ServiceFactory serviceFactory2 = ScalecubeServiceFactory.from(new GreetingServiceImpl()); + + Microservices service2Node = + Microservices.builder() + .serviceFactory(serviceFactory2) + .discovery(ScalecubeServiceDiscovery::new) + .transport(RSocketServiceTransport::new) + .startAwait(); + + ServiceFactory serviceFactory1 = + AnnotatedSpringServiceFactory.configurations(ExampleConfiguration.class); + + Microservices service1Node = + Microservices.builder() + .discovery( + endpoint -> + new ScalecubeServiceDiscovery(endpoint) + .membership(cfg -> cfg.seedMembers(service2Node.discovery().address()))) + .serviceFactory(serviceFactory1) + .transport(RSocketServiceTransport::new) + .startAwait(); + + service1Node + .call() + .api(BidiGreetingService.class) + .greeting() + .log("receive |") + .log() + .log("complete |") + .block(); + + Mono.whenDelayError(service1Node.shutdown(), service2Node.shutdown()).block(); + } + + @Configuration + static class ExampleConfiguration { + + @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection") + @Bean + public GreetingsService greetingService(ServiceCall serviceCall) { + return serviceCall.api(GreetingsService.class); + } + + @Bean + public BidiGreetingService bidiGreetingService(GreetingsService greetingsService) { + return new BidiGreetingImpl(greetingsService); + } + } + + private static class AnnotatedSpringServiceFactory implements ServiceFactory { + + private final AnnotationConfigApplicationContext context; + private final Class[] configuration; + + public static ServiceFactory configurations(Class... configurations) { + return new AnnotatedSpringServiceFactory(configurations); + } + + private AnnotatedSpringServiceFactory(Class... configurations) { + this.context = new AnnotationConfigApplicationContext(); + this.configuration = configurations; + } + + @Override + public Mono> getServiceDefinitions( + MicroservicesContext microservices) { + return Mono.fromCallable( + () -> { + this.context.registerBean(MicroservicesContext.class, () -> microservices); + this.context.registerBean(ServiceCall.class, microservices::serviceCall); + this.context.registerBean(ServiceDiscovery.class, microservices::serviceDiscovery); + this.context.register(this.configuration); + this.context.refresh(); + return this.context.getBeansWithAnnotation(Service.class).values().stream() + .map(Object::getClass) + .filter(Predicate.not(RemoteService.class::isAssignableFrom)) + .map(ServiceDefinition::new) + .collect(Collectors.toList()); + }); + } + + @Override + public Mono> initializeServices( + MicroservicesContext microservices) { + return Mono.fromCallable( + () -> { + this.context.start(); + return this.context.getBeansWithAnnotation(Service.class).values().stream() + .filter( + Predicate.not(bean -> RemoteService.class.isAssignableFrom(bean.getClass()))) + .map(bean -> ServiceInfo.fromServiceInstance(bean).build()) + .collect(Collectors.toList()); + }); + } + + @Override + public Mono shutdownServices(MicroservicesContext microservices) { + return Mono.fromCallable( + () -> { + this.context.stop(); + return this.context; + }) + .then(); + } + } +} diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/service/BidiGreetingImpl.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/service/BidiGreetingImpl.java new file mode 100644 index 000000000..b3c1f972b --- /dev/null +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/service/BidiGreetingImpl.java @@ -0,0 +1,31 @@ +package io.scalecube.services.examples.services.factory.service; + +import io.scalecube.services.examples.services.factory.service.api.BidiGreetingService; +import io.scalecube.services.examples.services.factory.service.api.Greeting; +import io.scalecube.services.examples.services.factory.service.api.GreetingsService; +import reactor.core.publisher.Mono; + +/** + * Greeting is an act of communication in which human beings intentionally make their presence known + * to each other, to show attention to, and to suggest a type of relationship (usually cordial) or + * social status (formal or informal) between individuals or groups of people coming in contact with + * each other. + */ +public class BidiGreetingImpl implements BidiGreetingService { + + private final GreetingsService greetingsService; + + public BidiGreetingImpl(GreetingsService greetingsService) { + this.greetingsService = greetingsService; + } + + /** + * Call this method to be greeted by the this ScaleCube service. + * + * @return service greeting + */ + @Override + public Mono greeting() { + return this.greetingsService.sayHello("Jack").map(Greeting::message); + } +} diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/service/GreetingServiceImpl.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/service/GreetingServiceImpl.java new file mode 100644 index 000000000..e330ba992 --- /dev/null +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/service/GreetingServiceImpl.java @@ -0,0 +1,12 @@ +package io.scalecube.services.examples.services.factory.service; + +import io.scalecube.services.examples.services.factory.service.api.Greeting; +import io.scalecube.services.examples.services.factory.service.api.GreetingsService; +import reactor.core.publisher.Mono; + +public class GreetingServiceImpl implements GreetingsService { + @Override + public Mono sayHello(String name) { + return Mono.just(new Greeting("Nice to meet you " + name + " and welcome to ScaleCube")); + } +} diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/service/api/BidiGreetingService.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/service/api/BidiGreetingService.java new file mode 100644 index 000000000..e9c8f9609 --- /dev/null +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/service/api/BidiGreetingService.java @@ -0,0 +1,13 @@ +package io.scalecube.services.examples.services.factory.service.api; + +import io.scalecube.services.annotations.Service; +import io.scalecube.services.annotations.ServiceMethod; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +@Service("BidiGreeting") +public interface BidiGreetingService { + + @ServiceMethod() + Mono greeting(); +} diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/service/api/Greeting.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/service/api/Greeting.java new file mode 100644 index 000000000..a873e3155 --- /dev/null +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/service/api/Greeting.java @@ -0,0 +1,18 @@ +package io.scalecube.services.examples.services.factory.service.api; + +import java.io.Serializable; + +public class Greeting implements Serializable { + + String message; + + public Greeting() {} + + public Greeting(String message) { + this.message = message; + } + + public String message() { + return message; + } +} diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/service/api/GreetingsService.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/service/api/GreetingsService.java new file mode 100644 index 000000000..0c46a98e4 --- /dev/null +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/service/api/GreetingsService.java @@ -0,0 +1,23 @@ +package io.scalecube.services.examples.services.factory.service.api; + +import io.scalecube.services.annotations.Service; +import io.scalecube.services.annotations.ServiceMethod; +import reactor.core.publisher.Mono; + +/** + * Greeting is an act of communication in which human beings intentionally make their presence known + * to each other, to show attention to, and to suggest a type of relationship (usually cordial) or + * social status (formal or informal) between individuals or groups of people coming in contact with + * each other. + */ +@Service("io.scalecube.Greetings") +public interface GreetingsService { + /** + * Call this method to be greeted by the this ScaleCube service. + * + * @param name name of the caller + * @return service greeting + */ + @ServiceMethod("sayHello") + Mono sayHello(String name); +} diff --git a/services/src/main/java/io/scalecube/services/Microservices.java b/services/src/main/java/io/scalecube/services/Microservices.java index 55339d1e0..39f982543 100644 --- a/services/src/main/java/io/scalecube/services/Microservices.java +++ b/services/src/main/java/io/scalecube/services/Microservices.java @@ -320,7 +320,7 @@ public String id() { } @Override - public ServiceCall call() { + public ServiceCall serviceCall() { return Microservices.this.call(); } @@ -330,7 +330,7 @@ public Address serviceAddress() { } @Override - public ServiceDiscovery discovery() { + public ServiceDiscovery serviceDiscovery() { return Microservices.this.discovery(); } } diff --git a/services/src/main/java/io/scalecube/services/inject/Injector.java b/services/src/main/java/io/scalecube/services/inject/Injector.java index 95b2c7cf7..085054c58 100644 --- a/services/src/main/java/io/scalecube/services/inject/Injector.java +++ b/services/src/main/java/io/scalecube/services/inject/Injector.java @@ -1,6 +1,5 @@ package io.scalecube.services.inject; -import io.scalecube.services.Microservices; import io.scalecube.services.MicroservicesContext; import io.scalecube.services.Reflect; import io.scalecube.services.ServiceCall; @@ -44,7 +43,7 @@ private static void injectField(MicroservicesContext microservices, Field field, } else if (field.isAnnotationPresent(Inject.class) && Reflect.isService(field.getType())) { Inject injection = field.getAnnotation(Inject.class); Class routerClass = injection.router(); - final ServiceCall call = microservices.call(); + final ServiceCall call = microservices.serviceCall(); if (!routerClass.isInterface()) { call.router(routerClass); } @@ -96,7 +95,7 @@ private static void processMethodWithAnnotation( if (mapper.getType().equals(MicroservicesContext.class)) { return microservices; } else if (Reflect.isService(mapper.getType())) { - return microservices.call().api(mapper.getType()); + return microservices.serviceCall().api(mapper.getType()); } else { return null; } diff --git a/services/src/main/java/io/scalecube/services/inject/ScalecubeServiceFactory.java b/services/src/main/java/io/scalecube/services/inject/ScalecubeServiceFactory.java index b1ee47f2d..3f0919aa7 100644 --- a/services/src/main/java/io/scalecube/services/inject/ScalecubeServiceFactory.java +++ b/services/src/main/java/io/scalecube/services/inject/ScalecubeServiceFactory.java @@ -58,7 +58,7 @@ private ScalecubeServiceFactory(Collection serviceProviders) { this.serviceFactory = microservices -> serviceProviders.stream() - .map(serviceProvider -> serviceProvider.provide(microservices.call())) + .map(serviceProvider -> serviceProvider.provide(microservices.serviceCall())) .flatMap(Collection::stream) .map(service -> Injector.inject(microservices, service)) .collect(Collectors.toList()); diff --git a/services/src/test/java/io/scalecube/services/sut/AnnotationServiceImpl.java b/services/src/test/java/io/scalecube/services/sut/AnnotationServiceImpl.java index e1fba79d4..ac4a4a780 100644 --- a/services/src/test/java/io/scalecube/services/sut/AnnotationServiceImpl.java +++ b/services/src/test/java/io/scalecube/services/sut/AnnotationServiceImpl.java @@ -1,6 +1,5 @@ package io.scalecube.services.sut; -import io.scalecube.services.Microservices; import io.scalecube.services.MicroservicesContext; import io.scalecube.services.annotations.AfterConstruct; import io.scalecube.services.discovery.api.ServiceDiscoveryEvent; @@ -14,7 +13,7 @@ public class AnnotationServiceImpl implements AnnotationService { @AfterConstruct void init(MicroservicesContext microservices) { this.serviceDiscoveryEvents = ReplayProcessor.create(); - microservices.discovery().listenDiscovery().subscribe(serviceDiscoveryEvents); + microservices.serviceDiscovery().listenDiscovery().subscribe(serviceDiscoveryEvents); } @Override diff --git a/services/src/test/java/io/scalecube/services/sut/CoarseGrainedServiceImpl.java b/services/src/test/java/io/scalecube/services/sut/CoarseGrainedServiceImpl.java index 10fb067c2..61bcf05d7 100644 --- a/services/src/test/java/io/scalecube/services/sut/CoarseGrainedServiceImpl.java +++ b/services/src/test/java/io/scalecube/services/sut/CoarseGrainedServiceImpl.java @@ -1,6 +1,5 @@ package io.scalecube.services.sut; -import io.scalecube.services.Microservices; import io.scalecube.services.MicroservicesContext; import io.scalecube.services.annotations.Inject; import io.scalecube.services.api.ServiceMessage; @@ -33,7 +32,7 @@ public Mono callGreetingTimeout(String request) { @Override public Mono callGreetingWithDispatcher(String request) { return microservices - .call() + .serviceCall() .requestOne( ServiceMessage.builder() .qualifier(GreetingService.SERVICE_NAME, "greeting") From 117fb118bb5d34102d2c0eca5f91a34b95fe8f78 Mon Sep 17 00:00:00 2001 From: "e.utkin" Date: Tue, 9 Jun 2020 13:49:51 +0300 Subject: [PATCH 36/61] Add marker interface for Service Proxy --- .../io/scalecube/services/RemoteService.java | 4 +- .../factory/SpringServiceFactoryExample.java | 72 +++++++++++++++---- 2 files changed, 61 insertions(+), 15 deletions(-) diff --git a/services-api/src/main/java/io/scalecube/services/RemoteService.java b/services-api/src/main/java/io/scalecube/services/RemoteService.java index 0b0b407c6..fec11ddfb 100644 --- a/services-api/src/main/java/io/scalecube/services/RemoteService.java +++ b/services-api/src/main/java/io/scalecube/services/RemoteService.java @@ -1,4 +1,4 @@ package io.scalecube.services; -public interface RemoteService { -} +/** Interface-marker for Proxy of remote services. */ +public interface RemoteService {} diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/SpringServiceFactoryExample.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/SpringServiceFactoryExample.java index 34564963a..16b9e614e 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/SpringServiceFactoryExample.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/SpringServiceFactoryExample.java @@ -2,6 +2,7 @@ import io.scalecube.services.Microservices; import io.scalecube.services.MicroservicesContext; +import io.scalecube.services.Reflect; import io.scalecube.services.RemoteService; import io.scalecube.services.ServiceCall; import io.scalecube.services.ServiceDefinition; @@ -16,14 +17,23 @@ import io.scalecube.services.examples.services.factory.service.api.GreetingsService; import io.scalecube.services.inject.ScalecubeServiceFactory; import io.scalecube.services.transport.rsocket.RSocketServiceTransport; - +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; import java.util.Collection; +import java.util.Objects; import java.util.function.Predicate; import java.util.stream.Collectors; - +import java.util.stream.Stream; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.support.AbstractBeanDefinition; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.core.ResolvableType; +import org.springframework.core.annotation.AliasFor; +import org.springframework.stereotype.Component; import reactor.core.publisher.Mono; public class SpringServiceFactoryExample { @@ -77,12 +87,50 @@ public GreetingsService greetingService(ServiceCall serviceCall) { return serviceCall.api(GreetingsService.class); } - @Bean + @ScalecubeBean public BidiGreetingService bidiGreetingService(GreetingsService greetingsService) { return new BidiGreetingImpl(greetingsService); } } + @Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE}) + @Retention(RetentionPolicy.RUNTIME) + @Bean + @interface ScalecubeBean { + + /** + * {@link Bean#value()}. + * + * @return name + */ + @AliasFor(annotation = Bean.class, attribute = "name") + String[] value() default {}; + + /** + * {@link Bean#name()}. + * + * @return name + */ + @AliasFor(annotation = Bean.class, attribute = "value") + String[] name() default {}; + + /** + * {@link Bean#initMethod()} ()}. + * + * @return init method + */ + @AliasFor(annotation = Bean.class, attribute = "initMethod") + String initMethod() default ""; + + /** + * {@link Bean#destroyMethod()} ()}. + * + * @return destroy method + */ + @AliasFor(annotation = Bean.class, attribute = "destroyMethod") + String destroyMethod() default AbstractBeanDefinition.INFER_METHOD; + } + private static class AnnotatedSpringServiceFactory implements ServiceFactory { private final AnnotationConfigApplicationContext context; @@ -104,12 +152,15 @@ public Mono> getServiceDefinitions( () -> { this.context.registerBean(MicroservicesContext.class, () -> microservices); this.context.registerBean(ServiceCall.class, microservices::serviceCall); - this.context.registerBean(ServiceDiscovery.class, microservices::serviceDiscovery); this.context.register(this.configuration); this.context.refresh(); - return this.context.getBeansWithAnnotation(Service.class).values().stream() - .map(Object::getClass) - .filter(Predicate.not(RemoteService.class::isAssignableFrom)) + String[] beanNames = this.context.getBeanNamesForAnnotation(ScalecubeBean.class); + return Stream.of(beanNames) + .map(this.context::getBeanDefinition) + .map(BeanDefinition::getResolvableType) + .map(ResolvableType::resolve) + .filter(Objects::nonNull) + .filter(Reflect::isService) .map(ServiceDefinition::new) .collect(Collectors.toList()); }); @@ -131,12 +182,7 @@ public Mono> initializeServices( @Override public Mono shutdownServices(MicroservicesContext microservices) { - return Mono.fromCallable( - () -> { - this.context.stop(); - return this.context; - }) - .then(); + return Mono.fromRunnable(this.context::stop).then(); } } } From e6d17bd7c870f77d7c74693628500e686c3e6874 Mon Sep 17 00:00:00 2001 From: "e.utkin" Date: Tue, 9 Jun 2020 13:56:28 +0300 Subject: [PATCH 37/61] Rename static constructor --- README.md | 2 +- .../transport/BenchmarkServiceState.java | 2 +- .../services/examples/ExamplesRunner.java | 2 +- .../services/examples/codecs/Example1.java | 2 +- .../services/examples/helloworld/Example1.java | 2 +- .../services/examples/helloworld/Example2.java | 2 +- .../services/examples/helloworld/Example3.java | 2 +- .../services/examples/orderbook/Example1.java | 2 +- .../services/examples/services/Example1.java | 4 ++-- .../services/examples/services/Example2.java | 4 ++-- .../factory/GuiceServiceFactoryExample.java | 2 +- .../factory/SpringServiceFactoryExample.java | 4 +--- .../services/inject/ScalecubeServiceFactory.java | 4 ++-- .../io/scalecube/services/ErrorFlowTest.java | 3 +-- .../scalecube/services/ServiceCallLocalTest.java | 2 +- .../services/ServiceCallRemoteTest.java | 2 +- .../io/scalecube/services/ServiceLocalTest.java | 2 +- .../scalecube/services/ServiceRegistryTest.java | 16 ++++++++-------- .../io/scalecube/services/ServiceRemoteTest.java | 12 ++++++------ .../scalecube/services/StreamingServiceTest.java | 2 +- .../RSocketNettyColocatedEventLoopGroupTest.java | 6 +++--- .../rsocket/RSocketServiceTransportTest.java | 2 +- 22 files changed, 39 insertions(+), 42 deletions(-) diff --git a/README.md b/README.md index a84c544bc..8b1840f75 100644 --- a/README.md +++ b/README.md @@ -65,7 +65,7 @@ The example provisions 2 cluster nodes and making a remote interaction. Microservices seed = Microservices.builder().startAwait(); //2. Create ServiceFactory - ServiceFactory serviceFactory = ScaleCubeServiceFactory.from(new GreetingServiceImpl()); + ServiceFactory serviceFactory = ScalecubeServiceFactory.fromInstances(new GreetingServiceImpl()); //3. Construct a ScaleCube node which joins the cluster hosting the Greeting Service Microservices microservices = diff --git a/services-benchmarks/src/main/java/io/scalecube/services/benchmarks/transport/BenchmarkServiceState.java b/services-benchmarks/src/main/java/io/scalecube/services/benchmarks/transport/BenchmarkServiceState.java index f2b221cfb..e4b099ab8 100644 --- a/services-benchmarks/src/main/java/io/scalecube/services/benchmarks/transport/BenchmarkServiceState.java +++ b/services-benchmarks/src/main/java/io/scalecube/services/benchmarks/transport/BenchmarkServiceState.java @@ -40,7 +40,7 @@ public void beforeAll() { final Address seedAddress = seed.discovery().address(); - ServiceFactory serviceFactory = ScalecubeServiceFactory.from(services); + ServiceFactory serviceFactory = ScalecubeServiceFactory.fromInstances(services); node = Microservices.builder() diff --git a/services-examples-parent/services-examples-runner/src/main/java/io/scalecube/services/examples/ExamplesRunner.java b/services-examples-parent/services-examples-runner/src/main/java/io/scalecube/services/examples/ExamplesRunner.java index bd162996a..b10766f15 100644 --- a/services-examples-parent/services-examples-runner/src/main/java/io/scalecube/services/examples/ExamplesRunner.java +++ b/services-examples-parent/services-examples-runner/src/main/java/io/scalecube/services/examples/ExamplesRunner.java @@ -55,7 +55,7 @@ public static void main(String[] args) { LOGGER.info("Number of worker threads: " + numOfThreads); ServiceFactory serviceFactory = - ScalecubeServiceFactory.from(new BenchmarkServiceImpl(), new GreetingServiceImpl()); + ScalecubeServiceFactory.fromInstances(new BenchmarkServiceImpl(), new GreetingServiceImpl()); Microservices microservices = Microservices.builder() .discovery(endpoint -> serviceDiscovery(endpoint, config)) .transport( diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/codecs/Example1.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/codecs/Example1.java index a46176d66..e4eda0c16 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/codecs/Example1.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/codecs/Example1.java @@ -32,7 +32,7 @@ public static void main(String[] args) { final Address seedAddress = seed.discovery().address(); // Create service factory for GreetingService - ServiceFactory serviceFactory = ScalecubeServiceFactory.from(new GreetingServiceImpl()); + ServiceFactory serviceFactory = ScalecubeServiceFactory.fromInstances(new GreetingServiceImpl()); // Construct a ScaleCube node which joins the cluster hosting the Greeting Service Microservices ms = diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example1.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example1.java index 7f9c64cf2..7835a4a47 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example1.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example1.java @@ -35,7 +35,7 @@ public static void main(String[] args) { final Address seedAddress = seed.discovery().address(); // Create service factory for Greeting Service - ServiceFactory serviceFactory = ScalecubeServiceFactory.from(new GreetingServiceImpl()); + ServiceFactory serviceFactory = ScalecubeServiceFactory.fromInstances(new GreetingServiceImpl()); // Construct a ScaleCube node which joins the cluster hosting the Greeting Service Microservices ms = diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example2.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example2.java index 55a6cb5a2..464e44970 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example2.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example2.java @@ -44,7 +44,7 @@ public static void main(String[] args) { final Address seedAddress = seed.discovery().address(); // Create service factory for Greeting Service - ServiceFactory serviceFactory = ScalecubeServiceFactory.from(new GreetingServiceImpl()); + ServiceFactory serviceFactory = ScalecubeServiceFactory.fromInstances(new GreetingServiceImpl()); Microservices ms = Microservices.builder() diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example3.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example3.java index eb200f7c5..5b9b6236b 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example3.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example3.java @@ -36,7 +36,7 @@ public static void main(String[] args) { final Address seedAddress = seed.discovery().address(); // Create service factory for Bid Greeting Service - ServiceFactory serviceFactory = ScalecubeServiceFactory.from(new BidiGreetingImpl()); + ServiceFactory serviceFactory = ScalecubeServiceFactory.fromInstances(new BidiGreetingImpl()); // Construct a ScaleCube node which joins the cluster hosting the Greeting Service Microservices ms = diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/orderbook/Example1.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/orderbook/Example1.java index cfa02a856..737a9f4e3 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/orderbook/Example1.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/orderbook/Example1.java @@ -42,7 +42,7 @@ public static void main(String[] args) throws InterruptedException { final Address gatewayAddress = gateway.discovery().address(); - ServiceFactory serviceFactory = ScalecubeServiceFactory.from(new DefaultMarketDataService()); + ServiceFactory serviceFactory = ScalecubeServiceFactory.fromInstances(new DefaultMarketDataService()); Microservices ms = Microservices.builder() diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example1.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example1.java index a0ac7ba04..57fa29a30 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example1.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example1.java @@ -25,7 +25,7 @@ public static void main(String[] args) { final Address gatewayAddress = gateway.discovery().address(); - ServiceFactory serviceFactory2 = ScalecubeServiceFactory.from(new Service2Impl()); + ServiceFactory serviceFactory2 = ScalecubeServiceFactory.fromInstances(new Service2Impl()); Microservices service2Node = Microservices.builder() @@ -37,7 +37,7 @@ public static void main(String[] args) { .serviceFactory(serviceFactory2) .startAwait(); - ServiceFactory serviceFactory1 = ScalecubeServiceFactory.from(new Service1Impl()); + ServiceFactory serviceFactory1 = ScalecubeServiceFactory.fromInstances(new Service1Impl()); Microservices service1Node = Microservices.builder() diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example2.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example2.java index 1ac6384df..559e88ed5 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example2.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example2.java @@ -25,7 +25,7 @@ public static void main(String[] args) { final Address gatewayAddress = gateway.discovery().address(); - ServiceFactory serviceFactory2 = ScalecubeServiceFactory.from(new Service2Impl()); + ServiceFactory serviceFactory2 = ScalecubeServiceFactory.fromInstances(new Service2Impl()); Microservices service2Node = Microservices.builder() @@ -37,7 +37,7 @@ public static void main(String[] args) { .serviceFactory(serviceFactory2) .startAwait(); - ServiceFactory serviceFactory1 = ScalecubeServiceFactory.from(new Service1Impl()); + ServiceFactory serviceFactory1 = ScalecubeServiceFactory.fromInstances(new Service1Impl()); Microservices service1Node = Microservices.builder() diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/GuiceServiceFactoryExample.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/GuiceServiceFactoryExample.java index 2b2508da4..b1934e558 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/GuiceServiceFactoryExample.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/GuiceServiceFactoryExample.java @@ -41,7 +41,7 @@ public class GuiceServiceFactoryExample { * @param args - program arguments */ public static void main(String[] args) { - ServiceFactory serviceFactory2 = ScalecubeServiceFactory.from(new GreetingServiceImpl()); + ServiceFactory serviceFactory2 = ScalecubeServiceFactory.fromInstances(new GreetingServiceImpl()); Microservices service2Node = Microservices.builder() diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/SpringServiceFactoryExample.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/SpringServiceFactoryExample.java index 16b9e614e..bd304cfa6 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/SpringServiceFactoryExample.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/SpringServiceFactoryExample.java @@ -10,7 +10,6 @@ import io.scalecube.services.ServiceInfo; import io.scalecube.services.annotations.Service; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; -import io.scalecube.services.discovery.api.ServiceDiscovery; import io.scalecube.services.examples.helloworld.service.GreetingServiceImpl; import io.scalecube.services.examples.services.factory.service.BidiGreetingImpl; import io.scalecube.services.examples.services.factory.service.api.BidiGreetingService; @@ -33,7 +32,6 @@ import org.springframework.context.annotation.Configuration; import org.springframework.core.ResolvableType; import org.springframework.core.annotation.AliasFor; -import org.springframework.stereotype.Component; import reactor.core.publisher.Mono; public class SpringServiceFactoryExample { @@ -44,7 +42,7 @@ public class SpringServiceFactoryExample { * @param args - program arguments */ public static void main(String[] args) { - ServiceFactory serviceFactory2 = ScalecubeServiceFactory.from(new GreetingServiceImpl()); + ServiceFactory serviceFactory2 = ScalecubeServiceFactory.fromInstances(new GreetingServiceImpl()); Microservices service2Node = Microservices.builder() diff --git a/services/src/main/java/io/scalecube/services/inject/ScalecubeServiceFactory.java b/services/src/main/java/io/scalecube/services/inject/ScalecubeServiceFactory.java index 3f0919aa7..4ae31b070 100644 --- a/services/src/main/java/io/scalecube/services/inject/ScalecubeServiceFactory.java +++ b/services/src/main/java/io/scalecube/services/inject/ScalecubeServiceFactory.java @@ -27,7 +27,7 @@ public class ScalecubeServiceFactory implements ServiceFactory { * * @param serviceProviders old service providers. * @return default services factory. - * @deprecated use {@link this#from(Object...)} + * @deprecated use {@link this#fromInstances(Object...)} */ public static ServiceFactory create(Collection serviceProviders) { return new ScalecubeServiceFactory(serviceProviders); @@ -39,7 +39,7 @@ public static ServiceFactory create(Collection serviceProviders * @param services user's services * @return service factory */ - public static ServiceFactory from(Object... services) { + public static ServiceFactory fromInstances(Object... services) { ServiceProvider provider = call -> Stream.of(services) .map(service -> { ServiceInfo.Builder builder; diff --git a/services/src/test/java/io/scalecube/services/ErrorFlowTest.java b/services/src/test/java/io/scalecube/services/ErrorFlowTest.java index f88f0e134..4f65f74bd 100644 --- a/services/src/test/java/io/scalecube/services/ErrorFlowTest.java +++ b/services/src/test/java/io/scalecube/services/ErrorFlowTest.java @@ -10,7 +10,6 @@ import io.scalecube.services.exceptions.ForbiddenException; import io.scalecube.services.exceptions.InternalServiceException; import io.scalecube.services.exceptions.ServiceUnavailableException; -import io.scalecube.services.exceptions.UnauthorizedException; import io.scalecube.services.inject.ScalecubeServiceFactory; import io.scalecube.services.sut.GreetingResponse; import io.scalecube.services.sut.GreetingServiceImpl; @@ -37,7 +36,7 @@ public static void initNodes() { new ScalecubeServiceDiscovery(endpoint) .transport(cfg -> cfg.port(port.incrementAndGet()))) .transport(RSocketServiceTransport::new) - .serviceFactory(ScalecubeServiceFactory.from(new GreetingServiceImpl())) + .serviceFactory(ScalecubeServiceFactory.fromInstances(new GreetingServiceImpl())) .startAwait(); final Address seedAddress = provider.discovery().address(); diff --git a/services/src/test/java/io/scalecube/services/ServiceCallLocalTest.java b/services/src/test/java/io/scalecube/services/ServiceCallLocalTest.java index ca7dcd2a2..1dca2fa76 100644 --- a/services/src/test/java/io/scalecube/services/ServiceCallLocalTest.java +++ b/services/src/test/java/io/scalecube/services/ServiceCallLocalTest.java @@ -68,7 +68,7 @@ private static Microservices serviceProvider() { return Microservices.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) - .serviceFactory(ScalecubeServiceFactory.from(new GreetingServiceImpl())) + .serviceFactory(ScalecubeServiceFactory.fromInstances(new GreetingServiceImpl())) .startAwait(); } diff --git a/services/src/test/java/io/scalecube/services/ServiceCallRemoteTest.java b/services/src/test/java/io/scalecube/services/ServiceCallRemoteTest.java index e4ad01204..a53267908 100644 --- a/services/src/test/java/io/scalecube/services/ServiceCallRemoteTest.java +++ b/services/src/test/java/io/scalecube/services/ServiceCallRemoteTest.java @@ -73,7 +73,7 @@ private static Microservices serviceProvider(Object service) { new ScalecubeServiceDiscovery(endpoint) .membership(cfg -> cfg.seedMembers(gateway.discovery().address()))) .transport(RSocketServiceTransport::new) - .serviceFactory(ScalecubeServiceFactory.from(service)) + .serviceFactory(ScalecubeServiceFactory.fromInstances(service)) .startAwait(); } diff --git a/services/src/test/java/io/scalecube/services/ServiceLocalTest.java b/services/src/test/java/io/scalecube/services/ServiceLocalTest.java index e45ab211d..8664911db 100644 --- a/services/src/test/java/io/scalecube/services/ServiceLocalTest.java +++ b/services/src/test/java/io/scalecube/services/ServiceLocalTest.java @@ -32,7 +32,7 @@ public class ServiceLocalTest extends BaseTest { public void setUp() { microservices = Microservices.builder() - .serviceFactory(ScalecubeServiceFactory.from(new GreetingServiceImpl())) + .serviceFactory(ScalecubeServiceFactory.fromInstances(new GreetingServiceImpl())) .startAwait(); } diff --git a/services/src/test/java/io/scalecube/services/ServiceRegistryTest.java b/services/src/test/java/io/scalecube/services/ServiceRegistryTest.java index cec954f9d..f5af598bc 100644 --- a/services/src/test/java/io/scalecube/services/ServiceRegistryTest.java +++ b/services/src/test/java/io/scalecube/services/ServiceRegistryTest.java @@ -60,14 +60,14 @@ public void test_added_removed_registration_events(MetadataCodec metadataCodec) Microservices.builder() .discovery(defServiceDiscovery(seedAddress, metadataCodec)) .transport(RSocketServiceTransport::new) - .serviceFactory(ScalecubeServiceFactory.from(new GreetingServiceImpl())) + .serviceFactory(ScalecubeServiceFactory.fromInstances(new GreetingServiceImpl())) .startAwait(); Microservices ms2 = Microservices.builder() .discovery(defServiceDiscovery(seedAddress, metadataCodec)) .transport(RSocketServiceTransport::new) - .serviceFactory(ScalecubeServiceFactory.from(new GreetingServiceImpl())) + .serviceFactory(ScalecubeServiceFactory.fromInstances(new GreetingServiceImpl())) .startAwait(); StepVerifier.create(events) @@ -94,7 +94,7 @@ public void test_listen_to_discovery_events(MetadataCodec metadataCodec) { Microservices.builder() .discovery(defServiceDiscovery(metadataCodec)) .transport(RSocketServiceTransport::new) - .serviceFactory(ScalecubeServiceFactory.from(new AnnotationServiceImpl())) + .serviceFactory(ScalecubeServiceFactory.fromInstances(new AnnotationServiceImpl())) .startAwait(); cluster.add(seed); @@ -109,7 +109,7 @@ public void test_listen_to_discovery_events(MetadataCodec metadataCodec) { Microservices.builder() .discovery(defServiceDiscovery(seedAddress, metadataCodec)) .transport(RSocketServiceTransport::new) - .serviceFactory(ScalecubeServiceFactory.from(new GreetingServiceImpl())) + .serviceFactory(ScalecubeServiceFactory.fromInstances(new GreetingServiceImpl())) .startAwait(); cluster.add(ms1); }) @@ -120,7 +120,7 @@ public void test_listen_to_discovery_events(MetadataCodec metadataCodec) { Microservices.builder() .discovery(defServiceDiscovery(seedAddress, metadataCodec)) .transport(RSocketServiceTransport::new) - .serviceFactory(ScalecubeServiceFactory.from(new GreetingServiceImpl())) + .serviceFactory(ScalecubeServiceFactory.fromInstances(new GreetingServiceImpl())) .startAwait(); cluster.add(ms2); }) @@ -161,7 +161,7 @@ public void test_delayed_listen_to_discovery_events(MetadataCodec metadataCodec) Microservices.builder() .discovery(defServiceDiscovery(metadataCodec)) .transport(RSocketServiceTransport::new) - .serviceFactory(ScalecubeServiceFactory.from(new GreetingServiceImpl())) + .serviceFactory(ScalecubeServiceFactory.fromInstances(new GreetingServiceImpl())) .startAwait(); cluster.add(seed); @@ -177,7 +177,7 @@ public void test_delayed_listen_to_discovery_events(MetadataCodec metadataCodec) .discovery(defServiceDiscovery(seedAddress, metadataCodec)) .transport(RSocketServiceTransport::new) .serviceFactory( - ScalecubeServiceFactory.from( + ScalecubeServiceFactory.fromInstances( new GreetingServiceImpl(), new AnnotationServiceImpl())) .startAwait(); cluster.add(ms1); @@ -189,7 +189,7 @@ public void test_delayed_listen_to_discovery_events(MetadataCodec metadataCodec) Microservices.builder() .discovery(defServiceDiscovery(seedAddress, metadataCodec)) .transport(RSocketServiceTransport::new) - .serviceFactory(ScalecubeServiceFactory.from(new GreetingServiceImpl())) + .serviceFactory(ScalecubeServiceFactory.fromInstances(new GreetingServiceImpl())) .startAwait(); cluster.add(ms2); }) diff --git a/services/src/test/java/io/scalecube/services/ServiceRemoteTest.java b/services/src/test/java/io/scalecube/services/ServiceRemoteTest.java index 784a716c6..e0807b13a 100644 --- a/services/src/test/java/io/scalecube/services/ServiceRemoteTest.java +++ b/services/src/test/java/io/scalecube/services/ServiceRemoteTest.java @@ -74,7 +74,7 @@ private static Microservices serviceProvider() { return Microservices.builder() .discovery(ServiceRemoteTest::serviceDiscovery) .transport(RSocketServiceTransport::new) - .serviceFactory(ScalecubeServiceFactory.from(new GreetingServiceImpl())) + .serviceFactory(ScalecubeServiceFactory.fromInstances(new GreetingServiceImpl())) .startAwait(); } @@ -270,7 +270,7 @@ public void test_remote_serviceA_calls_serviceB_using_setter() { Microservices.builder() .discovery(ServiceRemoteTest::serviceDiscovery) .transport(RSocketServiceTransport::new) - .serviceFactory(ScalecubeServiceFactory.from(new CoarseGrainedServiceImpl())) // add service a and b + .serviceFactory(ScalecubeServiceFactory.fromInstances(new CoarseGrainedServiceImpl())) // add service a and b .startAwait(); // Get a proxy to the service api. @@ -293,7 +293,7 @@ public void test_remote_serviceA_calls_serviceB() { Microservices.builder() .discovery(ServiceRemoteTest::serviceDiscovery) .transport(RSocketServiceTransport::new) - .serviceFactory(ScalecubeServiceFactory.from(another)) + .serviceFactory(ScalecubeServiceFactory.fromInstances(another)) .startAwait(); // Get a proxy to the service api. @@ -313,7 +313,7 @@ public void test_remote_serviceA_calls_serviceB_with_timeout() { Microservices.builder() .discovery(ServiceRemoteTest::serviceDiscovery) .transport(RSocketServiceTransport::new) - .serviceFactory(ScalecubeServiceFactory.from(another)) // add service a and b + .serviceFactory(ScalecubeServiceFactory.fromInstances(another)) // add service a and b .startAwait(); // Get a proxy to the service api. @@ -338,7 +338,7 @@ public void test_remote_serviceA_calls_serviceB_with_dispatcher() { Microservices.builder() .discovery(ServiceRemoteTest::serviceDiscovery) .transport(RSocketServiceTransport::new) - .serviceFactory(ScalecubeServiceFactory.from(another)) // add service a and b + .serviceFactory(ScalecubeServiceFactory.fromInstances(another)) // add service a and b .startAwait(); // Get a proxy to the service api. @@ -423,7 +423,7 @@ public void test_services_contribute_to_cluster_metadata() { .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) .tags(tags) - .serviceFactory(ScalecubeServiceFactory.from(new GreetingServiceImpl())) + .serviceFactory(ScalecubeServiceFactory.fromInstances(new GreetingServiceImpl())) .startAwait(); assertTrue(ms.discovery().serviceEndpoint().tags().containsKey("HOSTNAME")); diff --git a/services/src/test/java/io/scalecube/services/StreamingServiceTest.java b/services/src/test/java/io/scalecube/services/StreamingServiceTest.java index d1bdb7dbe..d5ea00780 100644 --- a/services/src/test/java/io/scalecube/services/StreamingServiceTest.java +++ b/services/src/test/java/io/scalecube/services/StreamingServiceTest.java @@ -42,7 +42,7 @@ public static void setup() { .membership(cfg -> cfg.seedMembers(gateway.discovery().address()))) .transport(RSocketServiceTransport::new) .defaultDataDecoder(ServiceMessageCodec::decodeData) - .serviceFactory(ScalecubeServiceFactory.from(new SimpleQuoteService())) + .serviceFactory(ScalecubeServiceFactory.fromInstances(new SimpleQuoteService())) .startAwait(); } diff --git a/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketNettyColocatedEventLoopGroupTest.java b/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketNettyColocatedEventLoopGroupTest.java index affdd15cf..5cd290b37 100644 --- a/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketNettyColocatedEventLoopGroupTest.java +++ b/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketNettyColocatedEventLoopGroupTest.java @@ -40,7 +40,7 @@ public void setUp() { new ScalecubeServiceDiscovery(endpoint) .membership(cfg -> cfg.seedMembers(gateway.discovery().address()))) .transport(RSocketServiceTransport::new) - .serviceFactory(ScalecubeServiceFactory.from(new Facade())) + .serviceFactory(ScalecubeServiceFactory.fromInstances(new Facade())) .startAwait(); PingService pingService = () -> Mono.just(Thread.currentThread().getName()); @@ -51,7 +51,7 @@ public void setUp() { new ScalecubeServiceDiscovery(endpoint) .membership(cfg -> cfg.seedMembers(facade.discovery().address()))) .transport(RSocketServiceTransport::new) - .serviceFactory(ScalecubeServiceFactory.from(pingService)) + .serviceFactory(ScalecubeServiceFactory.fromInstances(pingService)) .startAwait(); PongService pongService = () -> Mono.just(Thread.currentThread().getName()); @@ -62,7 +62,7 @@ public void setUp() { new ScalecubeServiceDiscovery(endpoint) .membership(cfg -> cfg.seedMembers(facade.discovery().address()))) .transport(RSocketServiceTransport::new) - .serviceFactory(ScalecubeServiceFactory.from(pongService)) + .serviceFactory(ScalecubeServiceFactory.fromInstances(pongService)) .startAwait(); } diff --git a/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketServiceTransportTest.java b/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketServiceTransportTest.java index d6f7b1a1c..fbfde1f6f 100644 --- a/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketServiceTransportTest.java +++ b/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketServiceTransportTest.java @@ -51,7 +51,7 @@ public void setUp() { new ScalecubeServiceDiscovery(serviceEndpoint) .membership(cfg -> cfg.seedMembers(gateway.discovery().address()))) .transport(RSocketServiceTransport::new) - .serviceFactory(ScalecubeServiceFactory.from(new SimpleQuoteService())) + .serviceFactory(ScalecubeServiceFactory.fromInstances(new SimpleQuoteService())) .startAwait(); } From 096c14a4a96512666e42cf735cab3102c5e191d4 Mon Sep 17 00:00:00 2001 From: "e.utkin" Date: Tue, 9 Jun 2020 13:56:28 +0300 Subject: [PATCH 38/61] Rename static constructor --- README.md | 2 +- .../transport/BenchmarkServiceState.java | 2 +- .../services/examples/ExamplesRunner.java | 2 +- .../services/examples/codecs/Example1.java | 3 ++- .../services/examples/helloworld/Example1.java | 3 ++- .../services/examples/helloworld/Example2.java | 3 ++- .../services/examples/helloworld/Example3.java | 2 +- .../services/examples/orderbook/Example1.java | 3 ++- .../services/examples/services/Example1.java | 4 ++-- .../services/examples/services/Example2.java | 4 ++-- .../factory/GuiceServiceFactoryExample.java | 3 ++- .../factory/SpringServiceFactoryExample.java | 5 ++--- .../services/inject/ScalecubeServiceFactory.java | 4 ++-- .../io/scalecube/services/ErrorFlowTest.java | 3 +-- .../scalecube/services/ServiceCallLocalTest.java | 2 +- .../services/ServiceCallRemoteTest.java | 2 +- .../io/scalecube/services/ServiceLocalTest.java | 2 +- .../scalecube/services/ServiceRegistryTest.java | 16 ++++++++-------- .../io/scalecube/services/ServiceRemoteTest.java | 12 ++++++------ .../scalecube/services/StreamingServiceTest.java | 2 +- .../RSocketNettyColocatedEventLoopGroupTest.java | 6 +++--- .../rsocket/RSocketServiceTransportTest.java | 2 +- 22 files changed, 45 insertions(+), 42 deletions(-) diff --git a/README.md b/README.md index a84c544bc..8b1840f75 100644 --- a/README.md +++ b/README.md @@ -65,7 +65,7 @@ The example provisions 2 cluster nodes and making a remote interaction. Microservices seed = Microservices.builder().startAwait(); //2. Create ServiceFactory - ServiceFactory serviceFactory = ScaleCubeServiceFactory.from(new GreetingServiceImpl()); + ServiceFactory serviceFactory = ScalecubeServiceFactory.fromInstances(new GreetingServiceImpl()); //3. Construct a ScaleCube node which joins the cluster hosting the Greeting Service Microservices microservices = diff --git a/services-benchmarks/src/main/java/io/scalecube/services/benchmarks/transport/BenchmarkServiceState.java b/services-benchmarks/src/main/java/io/scalecube/services/benchmarks/transport/BenchmarkServiceState.java index f2b221cfb..e4b099ab8 100644 --- a/services-benchmarks/src/main/java/io/scalecube/services/benchmarks/transport/BenchmarkServiceState.java +++ b/services-benchmarks/src/main/java/io/scalecube/services/benchmarks/transport/BenchmarkServiceState.java @@ -40,7 +40,7 @@ public void beforeAll() { final Address seedAddress = seed.discovery().address(); - ServiceFactory serviceFactory = ScalecubeServiceFactory.from(services); + ServiceFactory serviceFactory = ScalecubeServiceFactory.fromInstances(services); node = Microservices.builder() diff --git a/services-examples-parent/services-examples-runner/src/main/java/io/scalecube/services/examples/ExamplesRunner.java b/services-examples-parent/services-examples-runner/src/main/java/io/scalecube/services/examples/ExamplesRunner.java index bd162996a..b10766f15 100644 --- a/services-examples-parent/services-examples-runner/src/main/java/io/scalecube/services/examples/ExamplesRunner.java +++ b/services-examples-parent/services-examples-runner/src/main/java/io/scalecube/services/examples/ExamplesRunner.java @@ -55,7 +55,7 @@ public static void main(String[] args) { LOGGER.info("Number of worker threads: " + numOfThreads); ServiceFactory serviceFactory = - ScalecubeServiceFactory.from(new BenchmarkServiceImpl(), new GreetingServiceImpl()); + ScalecubeServiceFactory.fromInstances(new BenchmarkServiceImpl(), new GreetingServiceImpl()); Microservices microservices = Microservices.builder() .discovery(endpoint -> serviceDiscovery(endpoint, config)) .transport( diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/codecs/Example1.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/codecs/Example1.java index a46176d66..ded0b31da 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/codecs/Example1.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/codecs/Example1.java @@ -32,7 +32,8 @@ public static void main(String[] args) { final Address seedAddress = seed.discovery().address(); // Create service factory for GreetingService - ServiceFactory serviceFactory = ScalecubeServiceFactory.from(new GreetingServiceImpl()); + ServiceFactory serviceFactory = + ScalecubeServiceFactory.fromInstances(new GreetingServiceImpl()); // Construct a ScaleCube node which joins the cluster hosting the Greeting Service Microservices ms = diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example1.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example1.java index 7f9c64cf2..c8ae3c804 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example1.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example1.java @@ -35,7 +35,8 @@ public static void main(String[] args) { final Address seedAddress = seed.discovery().address(); // Create service factory for Greeting Service - ServiceFactory serviceFactory = ScalecubeServiceFactory.from(new GreetingServiceImpl()); + ServiceFactory serviceFactory = + ScalecubeServiceFactory.fromInstances(new GreetingServiceImpl()); // Construct a ScaleCube node which joins the cluster hosting the Greeting Service Microservices ms = diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example2.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example2.java index 55a6cb5a2..5cd4ccf67 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example2.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example2.java @@ -44,7 +44,8 @@ public static void main(String[] args) { final Address seedAddress = seed.discovery().address(); // Create service factory for Greeting Service - ServiceFactory serviceFactory = ScalecubeServiceFactory.from(new GreetingServiceImpl()); + ServiceFactory serviceFactory = + ScalecubeServiceFactory.fromInstances(new GreetingServiceImpl()); Microservices ms = Microservices.builder() diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example3.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example3.java index eb200f7c5..5b9b6236b 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example3.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example3.java @@ -36,7 +36,7 @@ public static void main(String[] args) { final Address seedAddress = seed.discovery().address(); // Create service factory for Bid Greeting Service - ServiceFactory serviceFactory = ScalecubeServiceFactory.from(new BidiGreetingImpl()); + ServiceFactory serviceFactory = ScalecubeServiceFactory.fromInstances(new BidiGreetingImpl()); // Construct a ScaleCube node which joins the cluster hosting the Greeting Service Microservices ms = diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/orderbook/Example1.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/orderbook/Example1.java index cfa02a856..1569dae7e 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/orderbook/Example1.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/orderbook/Example1.java @@ -42,7 +42,8 @@ public static void main(String[] args) throws InterruptedException { final Address gatewayAddress = gateway.discovery().address(); - ServiceFactory serviceFactory = ScalecubeServiceFactory.from(new DefaultMarketDataService()); + ServiceFactory serviceFactory = + ScalecubeServiceFactory.fromInstances(new DefaultMarketDataService()); Microservices ms = Microservices.builder() diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example1.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example1.java index a0ac7ba04..57fa29a30 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example1.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example1.java @@ -25,7 +25,7 @@ public static void main(String[] args) { final Address gatewayAddress = gateway.discovery().address(); - ServiceFactory serviceFactory2 = ScalecubeServiceFactory.from(new Service2Impl()); + ServiceFactory serviceFactory2 = ScalecubeServiceFactory.fromInstances(new Service2Impl()); Microservices service2Node = Microservices.builder() @@ -37,7 +37,7 @@ public static void main(String[] args) { .serviceFactory(serviceFactory2) .startAwait(); - ServiceFactory serviceFactory1 = ScalecubeServiceFactory.from(new Service1Impl()); + ServiceFactory serviceFactory1 = ScalecubeServiceFactory.fromInstances(new Service1Impl()); Microservices service1Node = Microservices.builder() diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example2.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example2.java index 1ac6384df..559e88ed5 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example2.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example2.java @@ -25,7 +25,7 @@ public static void main(String[] args) { final Address gatewayAddress = gateway.discovery().address(); - ServiceFactory serviceFactory2 = ScalecubeServiceFactory.from(new Service2Impl()); + ServiceFactory serviceFactory2 = ScalecubeServiceFactory.fromInstances(new Service2Impl()); Microservices service2Node = Microservices.builder() @@ -37,7 +37,7 @@ public static void main(String[] args) { .serviceFactory(serviceFactory2) .startAwait(); - ServiceFactory serviceFactory1 = ScalecubeServiceFactory.from(new Service1Impl()); + ServiceFactory serviceFactory1 = ScalecubeServiceFactory.fromInstances(new Service1Impl()); Microservices service1Node = Microservices.builder() diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/GuiceServiceFactoryExample.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/GuiceServiceFactoryExample.java index 2b2508da4..d673b009c 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/GuiceServiceFactoryExample.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/GuiceServiceFactoryExample.java @@ -41,7 +41,8 @@ public class GuiceServiceFactoryExample { * @param args - program arguments */ public static void main(String[] args) { - ServiceFactory serviceFactory2 = ScalecubeServiceFactory.from(new GreetingServiceImpl()); + ServiceFactory serviceFactory2 = + ScalecubeServiceFactory.fromInstances(new GreetingServiceImpl()); Microservices service2Node = Microservices.builder() diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/SpringServiceFactoryExample.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/SpringServiceFactoryExample.java index 16b9e614e..392d2b5f6 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/SpringServiceFactoryExample.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/SpringServiceFactoryExample.java @@ -10,7 +10,6 @@ import io.scalecube.services.ServiceInfo; import io.scalecube.services.annotations.Service; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; -import io.scalecube.services.discovery.api.ServiceDiscovery; import io.scalecube.services.examples.helloworld.service.GreetingServiceImpl; import io.scalecube.services.examples.services.factory.service.BidiGreetingImpl; import io.scalecube.services.examples.services.factory.service.api.BidiGreetingService; @@ -33,7 +32,6 @@ import org.springframework.context.annotation.Configuration; import org.springframework.core.ResolvableType; import org.springframework.core.annotation.AliasFor; -import org.springframework.stereotype.Component; import reactor.core.publisher.Mono; public class SpringServiceFactoryExample { @@ -44,7 +42,8 @@ public class SpringServiceFactoryExample { * @param args - program arguments */ public static void main(String[] args) { - ServiceFactory serviceFactory2 = ScalecubeServiceFactory.from(new GreetingServiceImpl()); + ServiceFactory serviceFactory2 = + ScalecubeServiceFactory.fromInstances(new GreetingServiceImpl()); Microservices service2Node = Microservices.builder() diff --git a/services/src/main/java/io/scalecube/services/inject/ScalecubeServiceFactory.java b/services/src/main/java/io/scalecube/services/inject/ScalecubeServiceFactory.java index 3f0919aa7..4ae31b070 100644 --- a/services/src/main/java/io/scalecube/services/inject/ScalecubeServiceFactory.java +++ b/services/src/main/java/io/scalecube/services/inject/ScalecubeServiceFactory.java @@ -27,7 +27,7 @@ public class ScalecubeServiceFactory implements ServiceFactory { * * @param serviceProviders old service providers. * @return default services factory. - * @deprecated use {@link this#from(Object...)} + * @deprecated use {@link this#fromInstances(Object...)} */ public static ServiceFactory create(Collection serviceProviders) { return new ScalecubeServiceFactory(serviceProviders); @@ -39,7 +39,7 @@ public static ServiceFactory create(Collection serviceProviders * @param services user's services * @return service factory */ - public static ServiceFactory from(Object... services) { + public static ServiceFactory fromInstances(Object... services) { ServiceProvider provider = call -> Stream.of(services) .map(service -> { ServiceInfo.Builder builder; diff --git a/services/src/test/java/io/scalecube/services/ErrorFlowTest.java b/services/src/test/java/io/scalecube/services/ErrorFlowTest.java index f88f0e134..4f65f74bd 100644 --- a/services/src/test/java/io/scalecube/services/ErrorFlowTest.java +++ b/services/src/test/java/io/scalecube/services/ErrorFlowTest.java @@ -10,7 +10,6 @@ import io.scalecube.services.exceptions.ForbiddenException; import io.scalecube.services.exceptions.InternalServiceException; import io.scalecube.services.exceptions.ServiceUnavailableException; -import io.scalecube.services.exceptions.UnauthorizedException; import io.scalecube.services.inject.ScalecubeServiceFactory; import io.scalecube.services.sut.GreetingResponse; import io.scalecube.services.sut.GreetingServiceImpl; @@ -37,7 +36,7 @@ public static void initNodes() { new ScalecubeServiceDiscovery(endpoint) .transport(cfg -> cfg.port(port.incrementAndGet()))) .transport(RSocketServiceTransport::new) - .serviceFactory(ScalecubeServiceFactory.from(new GreetingServiceImpl())) + .serviceFactory(ScalecubeServiceFactory.fromInstances(new GreetingServiceImpl())) .startAwait(); final Address seedAddress = provider.discovery().address(); diff --git a/services/src/test/java/io/scalecube/services/ServiceCallLocalTest.java b/services/src/test/java/io/scalecube/services/ServiceCallLocalTest.java index ca7dcd2a2..1dca2fa76 100644 --- a/services/src/test/java/io/scalecube/services/ServiceCallLocalTest.java +++ b/services/src/test/java/io/scalecube/services/ServiceCallLocalTest.java @@ -68,7 +68,7 @@ private static Microservices serviceProvider() { return Microservices.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) - .serviceFactory(ScalecubeServiceFactory.from(new GreetingServiceImpl())) + .serviceFactory(ScalecubeServiceFactory.fromInstances(new GreetingServiceImpl())) .startAwait(); } diff --git a/services/src/test/java/io/scalecube/services/ServiceCallRemoteTest.java b/services/src/test/java/io/scalecube/services/ServiceCallRemoteTest.java index e4ad01204..a53267908 100644 --- a/services/src/test/java/io/scalecube/services/ServiceCallRemoteTest.java +++ b/services/src/test/java/io/scalecube/services/ServiceCallRemoteTest.java @@ -73,7 +73,7 @@ private static Microservices serviceProvider(Object service) { new ScalecubeServiceDiscovery(endpoint) .membership(cfg -> cfg.seedMembers(gateway.discovery().address()))) .transport(RSocketServiceTransport::new) - .serviceFactory(ScalecubeServiceFactory.from(service)) + .serviceFactory(ScalecubeServiceFactory.fromInstances(service)) .startAwait(); } diff --git a/services/src/test/java/io/scalecube/services/ServiceLocalTest.java b/services/src/test/java/io/scalecube/services/ServiceLocalTest.java index e45ab211d..8664911db 100644 --- a/services/src/test/java/io/scalecube/services/ServiceLocalTest.java +++ b/services/src/test/java/io/scalecube/services/ServiceLocalTest.java @@ -32,7 +32,7 @@ public class ServiceLocalTest extends BaseTest { public void setUp() { microservices = Microservices.builder() - .serviceFactory(ScalecubeServiceFactory.from(new GreetingServiceImpl())) + .serviceFactory(ScalecubeServiceFactory.fromInstances(new GreetingServiceImpl())) .startAwait(); } diff --git a/services/src/test/java/io/scalecube/services/ServiceRegistryTest.java b/services/src/test/java/io/scalecube/services/ServiceRegistryTest.java index cec954f9d..f5af598bc 100644 --- a/services/src/test/java/io/scalecube/services/ServiceRegistryTest.java +++ b/services/src/test/java/io/scalecube/services/ServiceRegistryTest.java @@ -60,14 +60,14 @@ public void test_added_removed_registration_events(MetadataCodec metadataCodec) Microservices.builder() .discovery(defServiceDiscovery(seedAddress, metadataCodec)) .transport(RSocketServiceTransport::new) - .serviceFactory(ScalecubeServiceFactory.from(new GreetingServiceImpl())) + .serviceFactory(ScalecubeServiceFactory.fromInstances(new GreetingServiceImpl())) .startAwait(); Microservices ms2 = Microservices.builder() .discovery(defServiceDiscovery(seedAddress, metadataCodec)) .transport(RSocketServiceTransport::new) - .serviceFactory(ScalecubeServiceFactory.from(new GreetingServiceImpl())) + .serviceFactory(ScalecubeServiceFactory.fromInstances(new GreetingServiceImpl())) .startAwait(); StepVerifier.create(events) @@ -94,7 +94,7 @@ public void test_listen_to_discovery_events(MetadataCodec metadataCodec) { Microservices.builder() .discovery(defServiceDiscovery(metadataCodec)) .transport(RSocketServiceTransport::new) - .serviceFactory(ScalecubeServiceFactory.from(new AnnotationServiceImpl())) + .serviceFactory(ScalecubeServiceFactory.fromInstances(new AnnotationServiceImpl())) .startAwait(); cluster.add(seed); @@ -109,7 +109,7 @@ public void test_listen_to_discovery_events(MetadataCodec metadataCodec) { Microservices.builder() .discovery(defServiceDiscovery(seedAddress, metadataCodec)) .transport(RSocketServiceTransport::new) - .serviceFactory(ScalecubeServiceFactory.from(new GreetingServiceImpl())) + .serviceFactory(ScalecubeServiceFactory.fromInstances(new GreetingServiceImpl())) .startAwait(); cluster.add(ms1); }) @@ -120,7 +120,7 @@ public void test_listen_to_discovery_events(MetadataCodec metadataCodec) { Microservices.builder() .discovery(defServiceDiscovery(seedAddress, metadataCodec)) .transport(RSocketServiceTransport::new) - .serviceFactory(ScalecubeServiceFactory.from(new GreetingServiceImpl())) + .serviceFactory(ScalecubeServiceFactory.fromInstances(new GreetingServiceImpl())) .startAwait(); cluster.add(ms2); }) @@ -161,7 +161,7 @@ public void test_delayed_listen_to_discovery_events(MetadataCodec metadataCodec) Microservices.builder() .discovery(defServiceDiscovery(metadataCodec)) .transport(RSocketServiceTransport::new) - .serviceFactory(ScalecubeServiceFactory.from(new GreetingServiceImpl())) + .serviceFactory(ScalecubeServiceFactory.fromInstances(new GreetingServiceImpl())) .startAwait(); cluster.add(seed); @@ -177,7 +177,7 @@ public void test_delayed_listen_to_discovery_events(MetadataCodec metadataCodec) .discovery(defServiceDiscovery(seedAddress, metadataCodec)) .transport(RSocketServiceTransport::new) .serviceFactory( - ScalecubeServiceFactory.from( + ScalecubeServiceFactory.fromInstances( new GreetingServiceImpl(), new AnnotationServiceImpl())) .startAwait(); cluster.add(ms1); @@ -189,7 +189,7 @@ public void test_delayed_listen_to_discovery_events(MetadataCodec metadataCodec) Microservices.builder() .discovery(defServiceDiscovery(seedAddress, metadataCodec)) .transport(RSocketServiceTransport::new) - .serviceFactory(ScalecubeServiceFactory.from(new GreetingServiceImpl())) + .serviceFactory(ScalecubeServiceFactory.fromInstances(new GreetingServiceImpl())) .startAwait(); cluster.add(ms2); }) diff --git a/services/src/test/java/io/scalecube/services/ServiceRemoteTest.java b/services/src/test/java/io/scalecube/services/ServiceRemoteTest.java index 784a716c6..e0807b13a 100644 --- a/services/src/test/java/io/scalecube/services/ServiceRemoteTest.java +++ b/services/src/test/java/io/scalecube/services/ServiceRemoteTest.java @@ -74,7 +74,7 @@ private static Microservices serviceProvider() { return Microservices.builder() .discovery(ServiceRemoteTest::serviceDiscovery) .transport(RSocketServiceTransport::new) - .serviceFactory(ScalecubeServiceFactory.from(new GreetingServiceImpl())) + .serviceFactory(ScalecubeServiceFactory.fromInstances(new GreetingServiceImpl())) .startAwait(); } @@ -270,7 +270,7 @@ public void test_remote_serviceA_calls_serviceB_using_setter() { Microservices.builder() .discovery(ServiceRemoteTest::serviceDiscovery) .transport(RSocketServiceTransport::new) - .serviceFactory(ScalecubeServiceFactory.from(new CoarseGrainedServiceImpl())) // add service a and b + .serviceFactory(ScalecubeServiceFactory.fromInstances(new CoarseGrainedServiceImpl())) // add service a and b .startAwait(); // Get a proxy to the service api. @@ -293,7 +293,7 @@ public void test_remote_serviceA_calls_serviceB() { Microservices.builder() .discovery(ServiceRemoteTest::serviceDiscovery) .transport(RSocketServiceTransport::new) - .serviceFactory(ScalecubeServiceFactory.from(another)) + .serviceFactory(ScalecubeServiceFactory.fromInstances(another)) .startAwait(); // Get a proxy to the service api. @@ -313,7 +313,7 @@ public void test_remote_serviceA_calls_serviceB_with_timeout() { Microservices.builder() .discovery(ServiceRemoteTest::serviceDiscovery) .transport(RSocketServiceTransport::new) - .serviceFactory(ScalecubeServiceFactory.from(another)) // add service a and b + .serviceFactory(ScalecubeServiceFactory.fromInstances(another)) // add service a and b .startAwait(); // Get a proxy to the service api. @@ -338,7 +338,7 @@ public void test_remote_serviceA_calls_serviceB_with_dispatcher() { Microservices.builder() .discovery(ServiceRemoteTest::serviceDiscovery) .transport(RSocketServiceTransport::new) - .serviceFactory(ScalecubeServiceFactory.from(another)) // add service a and b + .serviceFactory(ScalecubeServiceFactory.fromInstances(another)) // add service a and b .startAwait(); // Get a proxy to the service api. @@ -423,7 +423,7 @@ public void test_services_contribute_to_cluster_metadata() { .discovery(ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) .tags(tags) - .serviceFactory(ScalecubeServiceFactory.from(new GreetingServiceImpl())) + .serviceFactory(ScalecubeServiceFactory.fromInstances(new GreetingServiceImpl())) .startAwait(); assertTrue(ms.discovery().serviceEndpoint().tags().containsKey("HOSTNAME")); diff --git a/services/src/test/java/io/scalecube/services/StreamingServiceTest.java b/services/src/test/java/io/scalecube/services/StreamingServiceTest.java index d1bdb7dbe..d5ea00780 100644 --- a/services/src/test/java/io/scalecube/services/StreamingServiceTest.java +++ b/services/src/test/java/io/scalecube/services/StreamingServiceTest.java @@ -42,7 +42,7 @@ public static void setup() { .membership(cfg -> cfg.seedMembers(gateway.discovery().address()))) .transport(RSocketServiceTransport::new) .defaultDataDecoder(ServiceMessageCodec::decodeData) - .serviceFactory(ScalecubeServiceFactory.from(new SimpleQuoteService())) + .serviceFactory(ScalecubeServiceFactory.fromInstances(new SimpleQuoteService())) .startAwait(); } diff --git a/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketNettyColocatedEventLoopGroupTest.java b/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketNettyColocatedEventLoopGroupTest.java index affdd15cf..5cd290b37 100644 --- a/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketNettyColocatedEventLoopGroupTest.java +++ b/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketNettyColocatedEventLoopGroupTest.java @@ -40,7 +40,7 @@ public void setUp() { new ScalecubeServiceDiscovery(endpoint) .membership(cfg -> cfg.seedMembers(gateway.discovery().address()))) .transport(RSocketServiceTransport::new) - .serviceFactory(ScalecubeServiceFactory.from(new Facade())) + .serviceFactory(ScalecubeServiceFactory.fromInstances(new Facade())) .startAwait(); PingService pingService = () -> Mono.just(Thread.currentThread().getName()); @@ -51,7 +51,7 @@ public void setUp() { new ScalecubeServiceDiscovery(endpoint) .membership(cfg -> cfg.seedMembers(facade.discovery().address()))) .transport(RSocketServiceTransport::new) - .serviceFactory(ScalecubeServiceFactory.from(pingService)) + .serviceFactory(ScalecubeServiceFactory.fromInstances(pingService)) .startAwait(); PongService pongService = () -> Mono.just(Thread.currentThread().getName()); @@ -62,7 +62,7 @@ public void setUp() { new ScalecubeServiceDiscovery(endpoint) .membership(cfg -> cfg.seedMembers(facade.discovery().address()))) .transport(RSocketServiceTransport::new) - .serviceFactory(ScalecubeServiceFactory.from(pongService)) + .serviceFactory(ScalecubeServiceFactory.fromInstances(pongService)) .startAwait(); } diff --git a/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketServiceTransportTest.java b/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketServiceTransportTest.java index d6f7b1a1c..fbfde1f6f 100644 --- a/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketServiceTransportTest.java +++ b/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketServiceTransportTest.java @@ -51,7 +51,7 @@ public void setUp() { new ScalecubeServiceDiscovery(serviceEndpoint) .membership(cfg -> cfg.seedMembers(gateway.discovery().address()))) .transport(RSocketServiceTransport::new) - .serviceFactory(ScalecubeServiceFactory.from(new SimpleQuoteService())) + .serviceFactory(ScalecubeServiceFactory.fromInstances(new SimpleQuoteService())) .startAwait(); } From c1a2842d316b0f99036e30fe297b8aea5dd0ea52 Mon Sep 17 00:00:00 2001 From: "e.utkin" Date: Tue, 9 Jun 2020 14:41:17 +0300 Subject: [PATCH 39/61] Rename static constructor --- .../services/examples/ExamplesRunner.java | 46 ++++++++++--------- 1 file changed, 24 insertions(+), 22 deletions(-) diff --git a/services-examples-parent/services-examples-runner/src/main/java/io/scalecube/services/examples/ExamplesRunner.java b/services-examples-parent/services-examples-runner/src/main/java/io/scalecube/services/examples/ExamplesRunner.java index b10766f15..30249c5d7 100644 --- a/services-examples-parent/services-examples-runner/src/main/java/io/scalecube/services/examples/ExamplesRunner.java +++ b/services-examples-parent/services-examples-runner/src/main/java/io/scalecube/services/examples/ExamplesRunner.java @@ -55,28 +55,30 @@ public static void main(String[] args) { LOGGER.info("Number of worker threads: " + numOfThreads); ServiceFactory serviceFactory = - ScalecubeServiceFactory.fromInstances(new BenchmarkServiceImpl(), new GreetingServiceImpl()); - Microservices microservices = Microservices.builder() - .discovery(endpoint -> serviceDiscovery(endpoint, config)) - .transport( - () -> - new RSocketServiceTransport() - .tcpClient( - loopResources -> - TcpClient.newConnection() - .runOn(loopResources) - .wiretap(false) - .noProxy() - .noSSL()) - .tcpServer( - loopResources -> - TcpServer.create() - .wiretap(false) - .port(config.servicePort()) - .runOn(loopResources) - .noSSL())) - .serviceFactory(serviceFactory) - .startAwait(); + ScalecubeServiceFactory.fromInstances( + new BenchmarkServiceImpl(), new GreetingServiceImpl()); + Microservices microservices = + Microservices.builder() + .discovery(endpoint -> serviceDiscovery(endpoint, config)) + .transport( + () -> + new RSocketServiceTransport() + .tcpClient( + loopResources -> + TcpClient.newConnection() + .runOn(loopResources) + .wiretap(false) + .noProxy() + .noSSL()) + .tcpServer( + loopResources -> + TcpServer.create() + .wiretap(false) + .port(config.servicePort()) + .runOn(loopResources) + .noSSL())) + .serviceFactory(serviceFactory) + .startAwait(); Runners.onShutdown(() -> microservices.shutdown().subscribe()); From f81d2c99cdcadeba28fa7ab4821cd4f2a542072a Mon Sep 17 00:00:00 2001 From: "e.utkin" Date: Tue, 9 Jun 2020 19:21:10 +0300 Subject: [PATCH 40/61] add TIMEOUT --- .../java/io/scalecube/services/ServiceRegistryTest.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/services/src/test/java/io/scalecube/services/ServiceRegistryTest.java b/services/src/test/java/io/scalecube/services/ServiceRegistryTest.java index f5af598bc..9fb78c129 100644 --- a/services/src/test/java/io/scalecube/services/ServiceRegistryTest.java +++ b/services/src/test/java/io/scalecube/services/ServiceRegistryTest.java @@ -120,16 +120,17 @@ public void test_listen_to_discovery_events(MetadataCodec metadataCodec) { Microservices.builder() .discovery(defServiceDiscovery(seedAddress, metadataCodec)) .transport(RSocketServiceTransport::new) - .serviceFactory(ScalecubeServiceFactory.fromInstances(new GreetingServiceImpl())) + .serviceFactory( + ScalecubeServiceFactory.fromInstances(new GreetingServiceImpl())) .startAwait(); cluster.add(ms2); }) .assertNext(event -> assertEquals(ENDPOINT_ADDED, event.type())) - .then(() -> cluster.remove(2).shutdown().block()) + .then(() -> cluster.remove(2).shutdown().block(TIMEOUT)) .assertNext(event -> assertEquals(ENDPOINT_LEAVING, event.type())) .thenAwait(TIMEOUT) .assertNext(event -> assertEquals(ENDPOINT_REMOVED, event.type())) - .then(() -> cluster.remove(1).shutdown().block()) + .then(() -> cluster.remove(1).shutdown().block(TIMEOUT)) .assertNext(event -> assertEquals(ENDPOINT_LEAVING, event.type())) .thenAwait(TIMEOUT) .assertNext(event -> assertEquals(ENDPOINT_REMOVED, event.type())) From cec7371968a88f63240d068ba01202f265378bca Mon Sep 17 00:00:00 2001 From: "e.utkin" Date: Tue, 9 Jun 2020 21:57:18 +0300 Subject: [PATCH 41/61] remove RemoteService --- .../io/scalecube/services/RemoteService.java | 4 -- .../io/scalecube/services/ServiceCall.java | 2 +- .../factory/GuiceServiceFactoryExample.java | 49 +++++++++++++------ .../factory/SpringServiceFactoryExample.java | 9 ++-- .../factory/service/BidiGreetingImpl.java | 5 ++ 5 files changed, 42 insertions(+), 27 deletions(-) delete mode 100644 services-api/src/main/java/io/scalecube/services/RemoteService.java diff --git a/services-api/src/main/java/io/scalecube/services/RemoteService.java b/services-api/src/main/java/io/scalecube/services/RemoteService.java deleted file mode 100644 index fec11ddfb..000000000 --- a/services-api/src/main/java/io/scalecube/services/RemoteService.java +++ /dev/null @@ -1,4 +0,0 @@ -package io.scalecube.services; - -/** Interface-marker for Proxy of remote services. */ -public interface RemoteService {} diff --git a/services-api/src/main/java/io/scalecube/services/ServiceCall.java b/services-api/src/main/java/io/scalecube/services/ServiceCall.java index b04953192..4194ac77a 100644 --- a/services-api/src/main/java/io/scalecube/services/ServiceCall.java +++ b/services-api/src/main/java/io/scalecube/services/ServiceCall.java @@ -367,7 +367,7 @@ public T api(Class serviceInterface) { return (T) Proxy.newProxyInstance( getClass().getClassLoader(), - new Class[] {serviceInterface, RemoteService.class}, + new Class[]{serviceInterface}, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] params) { diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/GuiceServiceFactoryExample.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/GuiceServiceFactoryExample.java index d673b009c..af9973f29 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/GuiceServiceFactoryExample.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/GuiceServiceFactoryExample.java @@ -1,16 +1,18 @@ package io.scalecube.services.examples.services.factory; import com.google.inject.AbstractModule; +import com.google.inject.Binding; +import com.google.inject.BindingAnnotation; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; +import com.google.inject.Key; import com.google.inject.Module; import com.google.inject.Provider; import com.google.inject.Scopes; +import com.google.inject.TypeLiteral; import io.scalecube.services.Microservices; import io.scalecube.services.MicroservicesContext; -import io.scalecube.services.Reflect; -import io.scalecube.services.RemoteService; import io.scalecube.services.ServiceCall; import io.scalecube.services.ServiceDefinition; import io.scalecube.services.ServiceFactory; @@ -23,13 +25,15 @@ import io.scalecube.services.examples.services.factory.service.api.GreetingsService; import io.scalecube.services.inject.ScalecubeServiceFactory; import io.scalecube.services.transport.rsocket.RSocketServiceTransport; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; -import java.util.Objects; -import java.util.function.Predicate; import java.util.stream.Collectors; import reactor.core.publisher.Mono; @@ -75,6 +79,13 @@ public static void main(String[] args) { Mono.whenDelayError(service1Node.shutdown(), service2Node.shutdown()).block(); } + @Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE}) + @Retention(RetentionPolicy.RUNTIME) + @BindingAnnotation + @interface ScalecubeBean { + + } + public static class SampleModule extends AbstractModule { @Override @@ -84,7 +95,8 @@ protected void configure() { .toProvider( new Provider<>() { - @Inject private ServiceCall serviceCall; + @Inject + private ServiceCall serviceCall; @Override public GreetingsService get() { @@ -93,13 +105,17 @@ public GreetingsService get() { }); Constructor constructor = BidiGreetingImpl1.class.getConstructor(GreetingsService.class); - bind(BidiGreetingService.class).toConstructor(constructor).in(Scopes.SINGLETON); + bind(BidiGreetingService.class) + .annotatedWith(ScalecubeBean.class) + .toConstructor(constructor) + .in(Scopes.SINGLETON); } catch (Exception ex) { throw new RuntimeException(ex); } } } + @ScalecubeBean public static class BidiGreetingImpl1 extends BidiGreetingImpl implements BidiGreetingService { @Inject @@ -111,7 +127,7 @@ public BidiGreetingImpl1(GreetingsService greetingsService) { public static class GuiceServiceFactory implements ServiceFactory { private final List modules; - private final List beans = new ArrayList<>(); + private Injector injector; private GuiceServiceFactory(Module... modules) { this.modules = Arrays.asList(modules); @@ -136,14 +152,12 @@ protected void configure() { modules.add(baseModule); modules.addAll(this.modules); Injector injector = Guice.createInjector(modules); - return injector.getAllBindings().values().stream() - .map(binding -> binding.getProvider().get()) - .filter(Objects::nonNull) - .filter( - Predicate.not(bean -> RemoteService.class.isAssignableFrom(bean.getClass()))) - .filter(bean -> Reflect.serviceInterfaces(bean).findAny().isPresent()) - .peek(this.beans::add) - .map(Object::getClass) + + this.injector = injector; + return injector.getAllBindings().keySet().stream() + .filter(key -> key.getAnnotationType() == ScalecubeBean.class) + .map(Key::getTypeLiteral) + .map(TypeLiteral::getRawType) .map(ServiceDefinition::new) .collect(Collectors.toList()); }); @@ -154,7 +168,10 @@ public Mono> initializeServices( MicroservicesContext microservices) { return Mono.fromCallable( () -> - this.beans.stream() + this.injector.getAllBindings().values().stream() + .filter(binding -> binding.getKey().getAnnotationType() == ScalecubeBean.class) + .map(Binding::getProvider) + .map(Provider::get) .map(bean -> ServiceInfo.fromServiceInstance(bean).build()) .collect(Collectors.toList())); } diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/SpringServiceFactoryExample.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/SpringServiceFactoryExample.java index 392d2b5f6..299726207 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/SpringServiceFactoryExample.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/SpringServiceFactoryExample.java @@ -3,12 +3,10 @@ import io.scalecube.services.Microservices; import io.scalecube.services.MicroservicesContext; import io.scalecube.services.Reflect; -import io.scalecube.services.RemoteService; import io.scalecube.services.ServiceCall; import io.scalecube.services.ServiceDefinition; import io.scalecube.services.ServiceFactory; import io.scalecube.services.ServiceInfo; -import io.scalecube.services.annotations.Service; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.examples.helloworld.service.GreetingServiceImpl; import io.scalecube.services.examples.services.factory.service.BidiGreetingImpl; @@ -22,10 +20,11 @@ import java.lang.annotation.Target; import java.util.Collection; import java.util.Objects; -import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; +import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.beans.factory.support.AbstractBeanDefinition; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; @@ -171,9 +170,7 @@ public Mono> initializeServices( return Mono.fromCallable( () -> { this.context.start(); - return this.context.getBeansWithAnnotation(Service.class).values().stream() - .filter( - Predicate.not(bean -> RemoteService.class.isAssignableFrom(bean.getClass()))) + return this.context.getBeansWithAnnotation(ScalecubeBean.class).values().stream() .map(bean -> ServiceInfo.fromServiceInstance(bean).build()) .collect(Collectors.toList()); }); diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/service/BidiGreetingImpl.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/service/BidiGreetingImpl.java index b3c1f972b..ce3d518a8 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/service/BidiGreetingImpl.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/service/BidiGreetingImpl.java @@ -1,8 +1,12 @@ package io.scalecube.services.examples.services.factory.service; +import io.scalecube.services.Microservices; +import io.scalecube.services.MicroservicesContext; +import io.scalecube.services.discovery.api.ServiceDiscovery; import io.scalecube.services.examples.services.factory.service.api.BidiGreetingService; import io.scalecube.services.examples.services.factory.service.api.Greeting; import io.scalecube.services.examples.services.factory.service.api.GreetingsService; +import org.springframework.beans.factory.annotation.Autowired; import reactor.core.publisher.Mono; /** @@ -28,4 +32,5 @@ public BidiGreetingImpl(GreetingsService greetingsService) { public Mono greeting() { return this.greetingsService.sayHello("Jack").map(Greeting::message); } + } From f3eee6c36bbb3f41785cfc22ef799f29044fbd7b Mon Sep 17 00:00:00 2001 From: "e.utkin" Date: Wed, 10 Jun 2020 13:11:46 +0300 Subject: [PATCH 42/61] separate MicroservicesContext to MicroservicesContext without ServiceDiscovery and ExtendedMicroservicesContext with service discovery. Because, we can get service discovery only ServiceFactory#initializeServices, but can't get this in ServiceFactory#getServiceDefinitions --- .../ExtendedMicroservicesContext.java | 21 +++++++++++++++++++ .../services/MicroservicesContext.java | 8 ------- .../io/scalecube/services/ServiceFactory.java | 5 +++-- .../exceptions/ExceptionMapperExample.java | 3 ++- .../factory/GuiceServiceFactoryExample.java | 3 ++- .../factory/SpringServiceFactoryExample.java | 14 +++++++++++-- .../io/scalecube/services/Microservices.java | 4 ++-- .../inject/ScalecubeServiceFactory.java | 7 +++++-- 8 files changed, 47 insertions(+), 18 deletions(-) create mode 100644 services-api/src/main/java/io/scalecube/services/ExtendedMicroservicesContext.java diff --git a/services-api/src/main/java/io/scalecube/services/ExtendedMicroservicesContext.java b/services-api/src/main/java/io/scalecube/services/ExtendedMicroservicesContext.java new file mode 100644 index 000000000..f2bbaea9f --- /dev/null +++ b/services-api/src/main/java/io/scalecube/services/ExtendedMicroservicesContext.java @@ -0,0 +1,21 @@ +package io.scalecube.services; + +import io.scalecube.net.Address; +import io.scalecube.services.discovery.api.ServiceDiscovery; + +/** + * Context of Scale Cube node. Used in {@link ServiceFactory}. Compared to MicroservicesContext, it + * gives access to ServiceDiscovery. + * + * @see ServiceFactory + */ +public interface ExtendedMicroservicesContext extends MicroservicesContext { + + /** + * Service discovery for services localed in other nodes. + * + * @return service discovery + * @see ServiceDiscovery + */ + ServiceDiscovery serviceDiscovery(); +} diff --git a/services-api/src/main/java/io/scalecube/services/MicroservicesContext.java b/services-api/src/main/java/io/scalecube/services/MicroservicesContext.java index 0d2b75f9d..5cba898da 100644 --- a/services-api/src/main/java/io/scalecube/services/MicroservicesContext.java +++ b/services-api/src/main/java/io/scalecube/services/MicroservicesContext.java @@ -32,12 +32,4 @@ public interface MicroservicesContext { * @see Address */ Address serviceAddress(); - - /** - * Service discovery for services localed in other nodes. - * - * @return service discovery - * @see ServiceDiscovery - */ - ServiceDiscovery serviceDiscovery(); } diff --git a/services-api/src/main/java/io/scalecube/services/ServiceFactory.java b/services-api/src/main/java/io/scalecube/services/ServiceFactory.java index ac6cee528..414614bb6 100644 --- a/services-api/src/main/java/io/scalecube/services/ServiceFactory.java +++ b/services-api/src/main/java/io/scalecube/services/ServiceFactory.java @@ -22,7 +22,8 @@ Mono> getServiceDefinitions( * @param microservices scale cube instance. * @return Completed Mono if initialization was successful for all services. */ - Mono> initializeServices(MicroservicesContext microservices); + Mono> initializeServices( + ExtendedMicroservicesContext microservices); /** * Finalization of service instances. @@ -30,7 +31,7 @@ Mono> getServiceDefinitions( * @param microservices scale cube instance. * @return completed Mono if finalization was successful for all services. */ - default Mono shutdownServices(MicroservicesContext microservices) { + default Mono shutdownServices(ExtendedMicroservicesContext microservices) { return Mono.defer(Mono::empty); } } diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/exceptions/ExceptionMapperExample.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/exceptions/ExceptionMapperExample.java index 967dc666c..5307553cf 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/exceptions/ExceptionMapperExample.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/exceptions/ExceptionMapperExample.java @@ -1,6 +1,7 @@ package io.scalecube.services.examples.exceptions; import io.scalecube.net.Address; +import io.scalecube.services.ExtendedMicroservicesContext; import io.scalecube.services.Microservices; import io.scalecube.services.MicroservicesContext; import io.scalecube.services.ServiceCall; @@ -52,7 +53,7 @@ public Mono> getServiceDefinitions( @Override public Mono> initializeServices( - MicroservicesContext microservices) { + ExtendedMicroservicesContext microservices) { ServiceCall call = microservices.serviceCall(); ServiceA serviceA = call.errorMapper(new ServiceAClientErrorMapper()).api(ServiceA.class); diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/GuiceServiceFactoryExample.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/GuiceServiceFactoryExample.java index af9973f29..e38310d7e 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/GuiceServiceFactoryExample.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/GuiceServiceFactoryExample.java @@ -11,6 +11,7 @@ import com.google.inject.Provider; import com.google.inject.Scopes; import com.google.inject.TypeLiteral; +import io.scalecube.services.ExtendedMicroservicesContext; import io.scalecube.services.Microservices; import io.scalecube.services.MicroservicesContext; import io.scalecube.services.ServiceCall; @@ -165,7 +166,7 @@ protected void configure() { @Override public Mono> initializeServices( - MicroservicesContext microservices) { + ExtendedMicroservicesContext microservices) { return Mono.fromCallable( () -> this.injector.getAllBindings().values().stream() diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/SpringServiceFactoryExample.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/SpringServiceFactoryExample.java index 299726207..bbe415aa1 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/SpringServiceFactoryExample.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/SpringServiceFactoryExample.java @@ -1,5 +1,6 @@ package io.scalecube.services.examples.services.factory; +import io.scalecube.services.ExtendedMicroservicesContext; import io.scalecube.services.Microservices; import io.scalecube.services.MicroservicesContext; import io.scalecube.services.Reflect; @@ -8,6 +9,7 @@ import io.scalecube.services.ServiceFactory; import io.scalecube.services.ServiceInfo; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; +import io.scalecube.services.discovery.api.ServiceDiscovery; import io.scalecube.services.examples.helloworld.service.GreetingServiceImpl; import io.scalecube.services.examples.services.factory.service.BidiGreetingImpl; import io.scalecube.services.examples.services.factory.service.api.BidiGreetingService; @@ -25,10 +27,14 @@ import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.BeanPostProcessor; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.support.AbstractBeanDefinition; +import org.springframework.beans.factory.support.BeanDefinitionRegistry; +import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Lazy; import org.springframework.core.ResolvableType; import org.springframework.core.annotation.AliasFor; import reactor.core.publisher.Mono; @@ -94,6 +100,8 @@ public BidiGreetingService bidiGreetingService(GreetingsService greetingsService @Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE}) @Retention(RetentionPolicy.RUNTIME) @Bean + @Lazy + // need for access to ServiceDiscovery @interface ScalecubeBean { /** @@ -166,9 +174,11 @@ public Mono> getServiceDefinitions( @Override public Mono> initializeServices( - MicroservicesContext microservices) { + ExtendedMicroservicesContext microservices) { return Mono.fromCallable( () -> { + this.context.registerBean(ServiceDiscovery.class, microservices::serviceDiscovery); + this.context.registerBean(ExtendedMicroservicesContext.class, () -> microservices); this.context.start(); return this.context.getBeansWithAnnotation(ScalecubeBean.class).values().stream() .map(bean -> ServiceInfo.fromServiceInstance(bean).build()) @@ -177,7 +187,7 @@ public Mono> initializeServices( } @Override - public Mono shutdownServices(MicroservicesContext microservices) { + public Mono shutdownServices(ExtendedMicroservicesContext microservices) { return Mono.fromRunnable(this.context::stop).then(); } } diff --git a/services/src/main/java/io/scalecube/services/Microservices.java b/services/src/main/java/io/scalecube/services/Microservices.java index 52f09070d..865f7b4ef 100644 --- a/services/src/main/java/io/scalecube/services/Microservices.java +++ b/services/src/main/java/io/scalecube/services/Microservices.java @@ -123,7 +123,7 @@ public final class Microservices { private final String id = generateId(); private final Map tags; - private final MicroservicesContext context; + private final ExtendedMicroservicesContext context; private final ServiceFactory serviceFactory; private final ServiceRegistry serviceRegistry; private final ServiceMethodRegistry methodRegistry; @@ -314,7 +314,7 @@ private Mono processBeforeDestroy() { return serviceFactory.shutdownServices(this.context).then(); } - public final class Context implements MicroservicesContext { + public final class Context implements ExtendedMicroservicesContext { @Override public String id() { diff --git a/services/src/main/java/io/scalecube/services/inject/ScalecubeServiceFactory.java b/services/src/main/java/io/scalecube/services/inject/ScalecubeServiceFactory.java index 4ae31b070..247cdd0cb 100644 --- a/services/src/main/java/io/scalecube/services/inject/ScalecubeServiceFactory.java +++ b/services/src/main/java/io/scalecube/services/inject/ScalecubeServiceFactory.java @@ -1,5 +1,6 @@ package io.scalecube.services.inject; +import io.scalecube.services.ExtendedMicroservicesContext; import io.scalecube.services.Microservices; import io.scalecube.services.MicroservicesContext; import io.scalecube.services.ServiceDefinition; @@ -96,10 +97,12 @@ public Mono> getServiceDefinitions( * *

Use {@link io.scalecube.services.annotations.AfterConstruct} for initialization service's * instance. + * + * @param microservices */ @Override public Mono> initializeServices( - MicroservicesContext microservices) { + ExtendedMicroservicesContext microservices) { return Mono.fromCallable( () -> this.services(microservices).stream() @@ -116,7 +119,7 @@ public Mono> initializeServices( * @return */ @Override - public Mono shutdownServices(MicroservicesContext microservices) { + public Mono shutdownServices(ExtendedMicroservicesContext microservices) { return Mono.fromRunnable(() -> shutdown0(microservices)); } From ccff07741180d09ef9d5b56e961c98339e9fdaa3 Mon Sep 17 00:00:00 2001 From: "e.utkin" Date: Wed, 10 Jun 2020 13:39:27 +0300 Subject: [PATCH 43/61] fix code style --- .../inject/ScalecubeServiceFactory.java | 25 +++++++++++-------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/services/src/main/java/io/scalecube/services/inject/ScalecubeServiceFactory.java b/services/src/main/java/io/scalecube/services/inject/ScalecubeServiceFactory.java index 247cdd0cb..8d835e733 100644 --- a/services/src/main/java/io/scalecube/services/inject/ScalecubeServiceFactory.java +++ b/services/src/main/java/io/scalecube/services/inject/ScalecubeServiceFactory.java @@ -41,17 +41,20 @@ public static ServiceFactory create(Collection serviceProviders * @return service factory */ public static ServiceFactory fromInstances(Object... services) { - ServiceProvider provider = call -> Stream.of(services) - .map(service -> { - ServiceInfo.Builder builder; - if (service instanceof ServiceInfo) { - builder = ServiceInfo.from((ServiceInfo) service); - } else { - builder = ServiceInfo.fromServiceInstance(service); - } - return builder.build(); - }) - .collect(Collectors.toList()); + ServiceProvider provider = + call -> + Stream.of(services) + .map( + service -> { + ServiceInfo.Builder builder; + if (service instanceof ServiceInfo) { + builder = ServiceInfo.from((ServiceInfo) service); + } else { + builder = ServiceInfo.fromServiceInstance(service); + } + return builder.build(); + }) + .collect(Collectors.toList()); return new ScalecubeServiceFactory(Collections.singleton(provider)); } From 51796af3dcbcc86cdf9754ed218e765d69f6f976 Mon Sep 17 00:00:00 2001 From: "e.utkin" Date: Wed, 10 Jun 2020 13:45:47 +0300 Subject: [PATCH 44/61] fix code style --- .../src/main/java/io/scalecube/services/ServiceFactory.java | 6 +++--- .../scalecube/services/inject/ScalecubeServiceFactory.java | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/services-api/src/main/java/io/scalecube/services/ServiceFactory.java b/services-api/src/main/java/io/scalecube/services/ServiceFactory.java index 414614bb6..2745b03b3 100644 --- a/services-api/src/main/java/io/scalecube/services/ServiceFactory.java +++ b/services-api/src/main/java/io/scalecube/services/ServiceFactory.java @@ -9,7 +9,7 @@ public interface ServiceFactory { /** * Provide service definitions. * - * @param microservices scale cube instance. + * @param microservices microservices context * @return collection of service definitions - service type and tags. * @see ServiceDefinition */ @@ -19,7 +19,7 @@ Mono> getServiceDefinitions( /** * Initialize instances of services. * - * @param microservices scale cube instance. + * @param microservices microservices context * @return Completed Mono if initialization was successful for all services. */ Mono> initializeServices( @@ -28,7 +28,7 @@ Mono> initializeServices( /** * Finalization of service instances. * - * @param microservices scale cube instance. + * @param microservices microservices context * @return completed Mono if finalization was successful for all services. */ default Mono shutdownServices(ExtendedMicroservicesContext microservices) { diff --git a/services/src/main/java/io/scalecube/services/inject/ScalecubeServiceFactory.java b/services/src/main/java/io/scalecube/services/inject/ScalecubeServiceFactory.java index 8d835e733..f6e462889 100644 --- a/services/src/main/java/io/scalecube/services/inject/ScalecubeServiceFactory.java +++ b/services/src/main/java/io/scalecube/services/inject/ScalecubeServiceFactory.java @@ -101,7 +101,7 @@ public Mono> getServiceDefinitions( *

Use {@link io.scalecube.services.annotations.AfterConstruct} for initialization service's * instance. * - * @param microservices + * @param microservices microservices context */ @Override public Mono> initializeServices( From d07e90aab33c5f79e37f46c05c3a052afb4f4189 Mon Sep 17 00:00:00 2001 From: "e.utkin" Date: Wed, 10 Jun 2020 15:07:51 +0300 Subject: [PATCH 45/61] fix code style and add lightweight spring factory --- .../factory/GuiceServiceFactoryExample.java | 2 - ...ightweightSpringServiceFactoryExample.java | 144 ++++++++++++++++++ .../factory/SpringServiceFactoryExample.java | 7 +- .../scalecube/services/inject/Injector.java | 21 +-- .../inject/ScalecubeServiceFactory.java | 21 +-- .../services/sut/AnnotationServiceImpl.java | 3 +- 6 files changed, 171 insertions(+), 27 deletions(-) create mode 100644 services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/LightweightSpringServiceFactoryExample.java diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/GuiceServiceFactoryExample.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/GuiceServiceFactoryExample.java index e38310d7e..4e322c486 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/GuiceServiceFactoryExample.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/GuiceServiceFactoryExample.java @@ -19,7 +19,6 @@ import io.scalecube.services.ServiceFactory; import io.scalecube.services.ServiceInfo; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; -import io.scalecube.services.discovery.api.ServiceDiscovery; import io.scalecube.services.examples.helloworld.service.GreetingServiceImpl; import io.scalecube.services.examples.services.factory.service.BidiGreetingImpl; import io.scalecube.services.examples.services.factory.service.api.BidiGreetingService; @@ -146,7 +145,6 @@ public Mono> getServiceDefinitions( protected void configure() { bind(MicroservicesContext.class).toInstance(microservices); bind(ServiceCall.class).toProvider(microservices::serviceCall); - bind(ServiceDiscovery.class).toProvider(microservices::serviceDiscovery); } }; List modules = new ArrayList<>(); diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/LightweightSpringServiceFactoryExample.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/LightweightSpringServiceFactoryExample.java new file mode 100644 index 000000000..ab9696600 --- /dev/null +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/LightweightSpringServiceFactoryExample.java @@ -0,0 +1,144 @@ +package io.scalecube.services.examples.services.factory; + +import io.scalecube.services.ExtendedMicroservicesContext; +import io.scalecube.services.Microservices; +import io.scalecube.services.MicroservicesContext; +import io.scalecube.services.ServiceCall; +import io.scalecube.services.ServiceDefinition; +import io.scalecube.services.ServiceFactory; +import io.scalecube.services.ServiceInfo; +import io.scalecube.services.discovery.ScalecubeServiceDiscovery; +import io.scalecube.services.examples.helloworld.service.GreetingServiceImpl; +import io.scalecube.services.examples.services.factory.service.BidiGreetingImpl; +import io.scalecube.services.examples.services.factory.service.api.BidiGreetingService; +import io.scalecube.services.examples.services.factory.service.api.GreetingsService; +import io.scalecube.services.inject.ScalecubeServiceFactory; +import io.scalecube.services.transport.rsocket.RSocketServiceTransport; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.function.Predicate; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.config.BeanDefinitionCustomizer; +import org.springframework.context.ApplicationContextInitializer; +import org.springframework.context.support.GenericApplicationContext; +import org.springframework.core.ResolvableType; +import reactor.core.publisher.Mono; + +public class LightweightSpringServiceFactoryExample { + + /** + * Main method. + * + * @param args - program arguments + */ + public static void main(String[] args) { + ServiceFactory serviceFactory2 = + ScalecubeServiceFactory.fromInstances(new GreetingServiceImpl()); + + Microservices service2Node = + Microservices.builder() + .serviceFactory(serviceFactory2) + .discovery(ScalecubeServiceDiscovery::new) + .transport(RSocketServiceTransport::new) + .startAwait(); + + ServiceFactory serviceFactory1 = + LightweightSpringServiceFactory.initialize( + ctx -> { + ctx.registerBean( + GreetingsService.class, + () -> ctx.getBean(ServiceCall.class).api(GreetingsService.class)); + + ctx.registerBean(BidiGreetingImpl.class, Customizers.LOCAL); + }); + + Microservices service1Node = + Microservices.builder() + .discovery( + endpoint -> + new ScalecubeServiceDiscovery(endpoint) + .membership(cfg -> cfg.seedMembers(service2Node.discovery().address()))) + .serviceFactory(serviceFactory1) + .transport(RSocketServiceTransport::new) + .startAwait(); + + service1Node + .call() + .api(BidiGreetingService.class) + .greeting() + .log("receive |") + .log() + .log("complete |") + .block(); + + Mono.whenDelayError(service1Node.shutdown(), service2Node.shutdown()).block(); + } + + private static class LightweightSpringServiceFactory implements ServiceFactory { + + private final GenericApplicationContext context; + private final List localServiceBeanNames = new ArrayList<>(); + + public LightweightSpringServiceFactory( + ApplicationContextInitializer initializer) { + this.context = new GenericApplicationContext(); + initializer.initialize(this.context); + } + + public static ServiceFactory initialize( + ApplicationContextInitializer initializer) { + return new LightweightSpringServiceFactory(initializer); + } + + @Override + public Mono> getServiceDefinitions( + MicroservicesContext microservices) { + return Mono.fromCallable( + () -> { + this.context.registerBean(ServiceCall.class, microservices::serviceCall); + return Stream.of(this.context.getBeanDefinitionNames()) + .map( + beanName -> { + BeanDefinition bd = this.context.getBeanDefinition(beanName); + bd.setAttribute("name", beanName); + return bd; + }) + .filter(Customizers.IS_LOCAL) + .peek(bd -> this.localServiceBeanNames.add((String) bd.getAttribute("name"))) + .map(BeanDefinition::getResolvableType) + .map(ResolvableType::resolve) + .map(ServiceDefinition::new) + .collect(Collectors.toList()); + }); + } + + @Override + public Mono> initializeServices( + ExtendedMicroservicesContext microservices) { + return Mono.fromCallable( + () -> { + this.context.refresh(); + this.context.start(); + return this.localServiceBeanNames.stream() + .map(this.context::getBean) + .map(bean -> ServiceInfo.fromServiceInstance(bean).build()) + .collect(Collectors.toList()); + }); + } + + @Override + public Mono shutdownServices(ExtendedMicroservicesContext microservices) { + return Mono.fromRunnable(this.context::stop); + } + } + + private static class Customizers { + + public static final BeanDefinitionCustomizer LOCAL = bd -> bd.setAttribute("_LOCAL", true); + public static final Predicate IS_LOCAL = + bd -> bd.hasAttribute("_LOCAL") && (boolean) bd.getAttribute("_LOCAL"); + } +} diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/SpringServiceFactoryExample.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/SpringServiceFactoryExample.java index bbe415aa1..2ceb7f567 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/SpringServiceFactoryExample.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/SpringServiceFactoryExample.java @@ -24,13 +24,8 @@ import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.Stream; -import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanDefinition; -import org.springframework.beans.factory.config.BeanPostProcessor; -import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.support.AbstractBeanDefinition; -import org.springframework.beans.factory.support.BeanDefinitionRegistry; -import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -101,7 +96,7 @@ public BidiGreetingService bidiGreetingService(GreetingsService greetingsService @Retention(RetentionPolicy.RUNTIME) @Bean @Lazy - // need for access to ServiceDiscovery + // need for access to ServiceDiscovery @interface ScalecubeBean { /** diff --git a/services/src/main/java/io/scalecube/services/inject/Injector.java b/services/src/main/java/io/scalecube/services/inject/Injector.java index 085054c58..ff2c489a6 100644 --- a/services/src/main/java/io/scalecube/services/inject/Injector.java +++ b/services/src/main/java/io/scalecube/services/inject/Injector.java @@ -1,5 +1,6 @@ package io.scalecube.services.inject; +import io.scalecube.services.ExtendedMicroservicesContext; import io.scalecube.services.MicroservicesContext; import io.scalecube.services.Reflect; import io.scalecube.services.ServiceCall; @@ -26,19 +27,21 @@ private Injector() { * local service instances and inject a service proxy. * * @param microservices microservices instance - * @param service service + * @param service service * @return service instance */ - public static ServiceInfo inject(MicroservicesContext microservices, ServiceInfo service) { + public static ServiceInfo inject( + ExtendedMicroservicesContext microservices, ServiceInfo service) { Object serviceInstance = service.serviceInstance(); Arrays.stream(serviceInstance.getClass().getDeclaredFields()) .forEach(field -> injectField(microservices, field, serviceInstance)); return service; } - private static void injectField(MicroservicesContext microservices, Field field, Object service) { + private static void injectField( + ExtendedMicroservicesContext microservices, Field field, Object service) { if (field.isAnnotationPresent(Inject.class) - && field.getType().equals(MicroservicesContext.class)) { + && MicroservicesContext.class.isAssignableFrom(field.getType())) { setField(field, service, microservices); } else if (field.isAnnotationPresent(Inject.class) && Reflect.isService(field.getType())) { Inject injection = field.getAnnotation(Inject.class); @@ -65,22 +68,22 @@ private static void setField(Field field, Object object, Object value) { * Run methods with {@link AfterConstruct} annotations. * * @param microservices scale cube instance. - * @param serviceInfo service info. + * @param serviceInfo service info. * @return service info with modified service's instance. */ public static ServiceInfo processAfterConstruct( - MicroservicesContext microservices, ServiceInfo serviceInfo) { + ExtendedMicroservicesContext microservices, ServiceInfo serviceInfo) { processMethodWithAnnotation(microservices, serviceInfo.serviceInstance(), AfterConstruct.class); return serviceInfo; } public static void processBeforeDestroy( - MicroservicesContext microservices, ServiceInfo serviceInfo) { + ExtendedMicroservicesContext microservices, ServiceInfo serviceInfo) { processMethodWithAnnotation(microservices, serviceInfo.serviceInstance(), BeforeDestroy.class); } private static void processMethodWithAnnotation( - MicroservicesContext microservices, Object targetInstance, Class annotation) { + ExtendedMicroservicesContext microservices, Object targetInstance, Class annotation) { Method[] declaredMethods = targetInstance.getClass().getDeclaredMethods(); Arrays.stream(declaredMethods) .filter(method -> method.isAnnotationPresent(annotation)) @@ -92,7 +95,7 @@ private static void processMethodWithAnnotation( Arrays.stream(targetMethod.getParameters()) .map( mapper -> { - if (mapper.getType().equals(MicroservicesContext.class)) { + if (MicroservicesContext.class.isAssignableFrom(mapper.getType())) { return microservices; } else if (Reflect.isService(mapper.getType())) { return microservices.serviceCall().api(mapper.getType()); diff --git a/services/src/main/java/io/scalecube/services/inject/ScalecubeServiceFactory.java b/services/src/main/java/io/scalecube/services/inject/ScalecubeServiceFactory.java index f6e462889..9e8a0ec20 100644 --- a/services/src/main/java/io/scalecube/services/inject/ScalecubeServiceFactory.java +++ b/services/src/main/java/io/scalecube/services/inject/ScalecubeServiceFactory.java @@ -3,10 +3,12 @@ import io.scalecube.services.ExtendedMicroservicesContext; import io.scalecube.services.Microservices; import io.scalecube.services.MicroservicesContext; +import io.scalecube.services.ServiceCall; import io.scalecube.services.ServiceDefinition; import io.scalecube.services.ServiceFactory; import io.scalecube.services.ServiceInfo; import io.scalecube.services.ServiceProvider; +import io.scalecube.services.annotations.Inject; import java.util.Collection; import java.util.Collections; import java.util.concurrent.atomic.AtomicReference; @@ -18,7 +20,7 @@ public class ScalecubeServiceFactory implements ServiceFactory { - private final Function> serviceFactory; + private final Function> serviceFactory; // lazy init private final AtomicReference> services = new AtomicReference<>(); @@ -60,11 +62,10 @@ public static ServiceFactory fromInstances(Object... services) { private ScalecubeServiceFactory(Collection serviceProviders) { this.serviceFactory = - microservices -> + serviceCall -> serviceProviders.stream() - .map(serviceProvider -> serviceProvider.provide(microservices.serviceCall())) + .map(serviceProvider -> serviceProvider.provide(serviceCall)) .flatMap(Collection::stream) - .map(service -> Injector.inject(microservices, service)) .collect(Collectors.toList()); } @@ -87,7 +88,8 @@ public Mono> getServiceDefinitions( MicroservicesContext microservices) { return Mono.fromCallable( () -> - this.services(microservices).stream() + this.services(microservices.serviceCall()) + .stream() .map( serviceInfo -> new ServiceDefinition( @@ -108,7 +110,8 @@ public Mono> initializeServices( ExtendedMicroservicesContext microservices) { return Mono.fromCallable( () -> - this.services(microservices).stream() + this.services(microservices.serviceCall()).stream() + .map(service -> Injector.inject(microservices, service)) .map(service -> Injector.processAfterConstruct(microservices, service)) .collect(Collectors.toList())); } @@ -126,15 +129,15 @@ public Mono shutdownServices(ExtendedMicroservicesContext microservices) { return Mono.fromRunnable(() -> shutdown0(microservices)); } - private void shutdown0(MicroservicesContext microservices) { + private void shutdown0(ExtendedMicroservicesContext microservices) { if (this.services.get() != null) { this.services.get().forEach(service -> Injector.processBeforeDestroy(microservices, service)); } } - private Collection services(MicroservicesContext microservices) { + private Collection services(ServiceCall serviceCall) { return this.services.updateAndGet( currentValue -> - currentValue == null ? this.serviceFactory.apply(microservices) : currentValue); + currentValue == null ? this.serviceFactory.apply(serviceCall) : currentValue); } } diff --git a/services/src/test/java/io/scalecube/services/sut/AnnotationServiceImpl.java b/services/src/test/java/io/scalecube/services/sut/AnnotationServiceImpl.java index ac4a4a780..071ea9763 100644 --- a/services/src/test/java/io/scalecube/services/sut/AnnotationServiceImpl.java +++ b/services/src/test/java/io/scalecube/services/sut/AnnotationServiceImpl.java @@ -1,5 +1,6 @@ package io.scalecube.services.sut; +import io.scalecube.services.ExtendedMicroservicesContext; import io.scalecube.services.MicroservicesContext; import io.scalecube.services.annotations.AfterConstruct; import io.scalecube.services.discovery.api.ServiceDiscoveryEvent; @@ -11,7 +12,7 @@ public class AnnotationServiceImpl implements AnnotationService { private ReplayProcessor serviceDiscoveryEvents; @AfterConstruct - void init(MicroservicesContext microservices) { + void init(ExtendedMicroservicesContext microservices) { this.serviceDiscoveryEvents = ReplayProcessor.create(); microservices.serviceDiscovery().listenDiscovery().subscribe(serviceDiscoveryEvents); } From f51d0b612a71bc9bf36ed93ca29192112e8c5a3b Mon Sep 17 00:00:00 2001 From: Eugene_Utkin Date: Sat, 13 Jun 2020 15:47:04 +0300 Subject: [PATCH 46/61] minor fix --- .../scalecube/services/ExtendedMicroservicesContext.java | 3 +-- .../java/io/scalecube/services/MicroservicesContext.java | 7 +++---- .../main/java/io/scalecube/services/ServiceFactory.java | 2 +- 3 files changed, 5 insertions(+), 7 deletions(-) diff --git a/services-api/src/main/java/io/scalecube/services/ExtendedMicroservicesContext.java b/services-api/src/main/java/io/scalecube/services/ExtendedMicroservicesContext.java index f2bbaea9f..50db3586d 100644 --- a/services-api/src/main/java/io/scalecube/services/ExtendedMicroservicesContext.java +++ b/services-api/src/main/java/io/scalecube/services/ExtendedMicroservicesContext.java @@ -1,10 +1,9 @@ package io.scalecube.services; -import io.scalecube.net.Address; import io.scalecube.services.discovery.api.ServiceDiscovery; /** - * Context of Scale Cube node. Used in {@link ServiceFactory}. Compared to MicroservicesContext, it + * Context of Scalecube node. Used in {@link ServiceFactory}. Compared to MicroservicesContext, it * gives access to ServiceDiscovery. * * @see ServiceFactory diff --git a/services-api/src/main/java/io/scalecube/services/MicroservicesContext.java b/services-api/src/main/java/io/scalecube/services/MicroservicesContext.java index 5cba898da..9b24c5fcd 100644 --- a/services-api/src/main/java/io/scalecube/services/MicroservicesContext.java +++ b/services-api/src/main/java/io/scalecube/services/MicroservicesContext.java @@ -1,17 +1,16 @@ package io.scalecube.services; import io.scalecube.net.Address; -import io.scalecube.services.discovery.api.ServiceDiscovery; /** - * Context of Scale Cube node. Used in {@link ServiceFactory}. + * Context of Scalecube node. Used in {@link ServiceFactory}. * * @see ServiceFactory */ public interface MicroservicesContext { /** - * Id of Scale Cube node. + * Id of Scalecube node. * * @return id */ @@ -26,7 +25,7 @@ public interface MicroservicesContext { ServiceCall serviceCall(); /** - * Network address of Scale Cube node. + * Network address of Scalecube node. * * @return address of node * @see Address diff --git a/services-api/src/main/java/io/scalecube/services/ServiceFactory.java b/services-api/src/main/java/io/scalecube/services/ServiceFactory.java index 2745b03b3..a71bd0d38 100644 --- a/services-api/src/main/java/io/scalecube/services/ServiceFactory.java +++ b/services-api/src/main/java/io/scalecube/services/ServiceFactory.java @@ -3,7 +3,7 @@ import java.util.Collection; import reactor.core.publisher.Mono; -/** Manages the life cycle of all services registered with Scale Cube Services. */ +/** Manages the life cycle of all services registered with Scalecube Services. */ public interface ServiceFactory { /** From 2de26b889ff9038216ee05c5872a48254ca7d49c Mon Sep 17 00:00:00 2001 From: Eugene_Utkin Date: Sat, 13 Jun 2020 17:31:56 +0300 Subject: [PATCH 47/61] merge MicroservicesContext and ExtendedMicroservicesContext and remove MicroservicesContext from ServiceFactory#getServiceDefinitions --- .../ExtendedMicroservicesContext.java | 20 ----- .../services/MicroservicesContext.java | 9 ++ .../io/scalecube/services/ServiceFactory.java | 8 +- .../transport/BenchmarkServiceState.java | 2 +- .../services/examples/ExamplesRunner.java | 2 +- .../services/examples/codecs/Example1.java | 2 +- .../exceptions/ExceptionMapperExample.java | 10 +-- .../examples/helloworld/Example1.java | 2 +- .../examples/helloworld/Example2.java | 2 +- .../examples/helloworld/Example3.java | 2 +- .../services/examples/orderbook/Example1.java | 2 +- .../services/examples/services/Example1.java | 2 +- .../services/examples/services/Example2.java | 2 +- .../factory/GuiceServiceFactoryExample.java | 87 +++++++++---------- ...ightweightSpringServiceFactoryExample.java | 43 ++++----- .../factory/SpringServiceFactoryExample.java | 54 ++++++------ .../io/scalecube/services/Microservices.java | 24 ++--- .../{inject => }/ScalecubeServiceFactory.java | 81 ++++++++--------- .../scalecube/services/inject/Injector.java | 11 ++- .../io/scalecube/services/ErrorFlowTest.java | 1 - .../services/ServiceCallLocalTest.java | 1 - .../services/ServiceCallRemoteTest.java | 1 - .../scalecube/services/ServiceLocalTest.java | 1 - .../services/ServiceRegistryTest.java | 1 - .../scalecube/services/ServiceRemoteTest.java | 1 - .../services/StreamingServiceTest.java | 1 - .../services/sut/AnnotationServiceImpl.java | 3 +- ...ocketNettyColocatedEventLoopGroupTest.java | 2 +- .../rsocket/RSocketServiceTransportTest.java | 2 +- 29 files changed, 175 insertions(+), 204 deletions(-) delete mode 100644 services-api/src/main/java/io/scalecube/services/ExtendedMicroservicesContext.java rename services/src/main/java/io/scalecube/services/{inject => }/ScalecubeServiceFactory.java (66%) diff --git a/services-api/src/main/java/io/scalecube/services/ExtendedMicroservicesContext.java b/services-api/src/main/java/io/scalecube/services/ExtendedMicroservicesContext.java deleted file mode 100644 index 50db3586d..000000000 --- a/services-api/src/main/java/io/scalecube/services/ExtendedMicroservicesContext.java +++ /dev/null @@ -1,20 +0,0 @@ -package io.scalecube.services; - -import io.scalecube.services.discovery.api.ServiceDiscovery; - -/** - * Context of Scalecube node. Used in {@link ServiceFactory}. Compared to MicroservicesContext, it - * gives access to ServiceDiscovery. - * - * @see ServiceFactory - */ -public interface ExtendedMicroservicesContext extends MicroservicesContext { - - /** - * Service discovery for services localed in other nodes. - * - * @return service discovery - * @see ServiceDiscovery - */ - ServiceDiscovery serviceDiscovery(); -} diff --git a/services-api/src/main/java/io/scalecube/services/MicroservicesContext.java b/services-api/src/main/java/io/scalecube/services/MicroservicesContext.java index 9b24c5fcd..7bece3886 100644 --- a/services-api/src/main/java/io/scalecube/services/MicroservicesContext.java +++ b/services-api/src/main/java/io/scalecube/services/MicroservicesContext.java @@ -1,6 +1,7 @@ package io.scalecube.services; import io.scalecube.net.Address; +import io.scalecube.services.discovery.api.ServiceDiscovery; /** * Context of Scalecube node. Used in {@link ServiceFactory}. @@ -31,4 +32,12 @@ public interface MicroservicesContext { * @see Address */ Address serviceAddress(); + + /** + * Service discovery for services localed in other nodes. + * + * @return service discovery + * @see ServiceDiscovery + */ + ServiceDiscovery serviceDiscovery(); } diff --git a/services-api/src/main/java/io/scalecube/services/ServiceFactory.java b/services-api/src/main/java/io/scalecube/services/ServiceFactory.java index a71bd0d38..252c6cb3d 100644 --- a/services-api/src/main/java/io/scalecube/services/ServiceFactory.java +++ b/services-api/src/main/java/io/scalecube/services/ServiceFactory.java @@ -9,12 +9,10 @@ public interface ServiceFactory { /** * Provide service definitions. * - * @param microservices microservices context * @return collection of service definitions - service type and tags. * @see ServiceDefinition */ - Mono> getServiceDefinitions( - MicroservicesContext microservices); + Collection getServiceDefinitions(); /** * Initialize instances of services. @@ -23,7 +21,7 @@ Mono> getServiceDefinitions( * @return Completed Mono if initialization was successful for all services. */ Mono> initializeServices( - ExtendedMicroservicesContext microservices); + MicroservicesContext microservices); /** * Finalization of service instances. @@ -31,7 +29,7 @@ Mono> initializeServices( * @param microservices microservices context * @return completed Mono if finalization was successful for all services. */ - default Mono shutdownServices(ExtendedMicroservicesContext microservices) { + default Mono shutdownServices(MicroservicesContext microservices) { return Mono.defer(Mono::empty); } } diff --git a/services-benchmarks/src/main/java/io/scalecube/services/benchmarks/transport/BenchmarkServiceState.java b/services-benchmarks/src/main/java/io/scalecube/services/benchmarks/transport/BenchmarkServiceState.java index e4b099ab8..21a2a3e52 100644 --- a/services-benchmarks/src/main/java/io/scalecube/services/benchmarks/transport/BenchmarkServiceState.java +++ b/services-benchmarks/src/main/java/io/scalecube/services/benchmarks/transport/BenchmarkServiceState.java @@ -7,7 +7,7 @@ import io.scalecube.services.ServiceCall; import io.scalecube.services.ServiceFactory; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; -import io.scalecube.services.inject.ScalecubeServiceFactory; +import io.scalecube.services.ScalecubeServiceFactory; import io.scalecube.services.transport.rsocket.RSocketServiceTransport; import java.time.Duration; import org.slf4j.Logger; diff --git a/services-examples-parent/services-examples-runner/src/main/java/io/scalecube/services/examples/ExamplesRunner.java b/services-examples-parent/services-examples-runner/src/main/java/io/scalecube/services/examples/ExamplesRunner.java index 30249c5d7..58645eeda 100644 --- a/services-examples-parent/services-examples-runner/src/main/java/io/scalecube/services/examples/ExamplesRunner.java +++ b/services-examples-parent/services-examples-runner/src/main/java/io/scalecube/services/examples/ExamplesRunner.java @@ -13,7 +13,7 @@ import io.scalecube.services.ServiceFactory; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.discovery.api.ServiceDiscovery; -import io.scalecube.services.inject.ScalecubeServiceFactory; +import io.scalecube.services.ScalecubeServiceFactory; import io.scalecube.services.transport.rsocket.RSocketServiceTransport; import java.nio.file.Path; import java.util.List; diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/codecs/Example1.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/codecs/Example1.java index ded0b31da..1244d36b4 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/codecs/Example1.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/codecs/Example1.java @@ -6,7 +6,7 @@ import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.examples.helloworld.service.GreetingServiceImpl; import io.scalecube.services.examples.helloworld.service.api.GreetingsService; -import io.scalecube.services.inject.ScalecubeServiceFactory; +import io.scalecube.services.ScalecubeServiceFactory; import io.scalecube.services.transport.rsocket.RSocketServiceTransport; public class Example1 { diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/exceptions/ExceptionMapperExample.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/exceptions/ExceptionMapperExample.java index 5307553cf..e3cc9a3d9 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/exceptions/ExceptionMapperExample.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/exceptions/ExceptionMapperExample.java @@ -1,9 +1,8 @@ package io.scalecube.services.examples.exceptions; import io.scalecube.net.Address; -import io.scalecube.services.ExtendedMicroservicesContext; -import io.scalecube.services.Microservices; import io.scalecube.services.MicroservicesContext; +import io.scalecube.services.Microservices; import io.scalecube.services.ServiceCall; import io.scalecube.services.ServiceDefinition; import io.scalecube.services.ServiceFactory; @@ -44,16 +43,15 @@ public static void main(String[] args) throws InterruptedException { ServiceFactory serviceFactory = new ServiceFactory() { @Override - public Mono> getServiceDefinitions( - MicroservicesContext microservices) { + public Collection getServiceDefinitions() { ServiceDefinition serviceA = new ServiceDefinition(ServiceA.class); ServiceDefinition serviceB = new ServiceDefinition(ServiceB.class); - return Mono.just(List.of(serviceA, serviceB)); + return List.of(serviceA, serviceB); } @Override public Mono> initializeServices( - ExtendedMicroservicesContext microservices) { + MicroservicesContext microservices) { ServiceCall call = microservices.serviceCall(); ServiceA serviceA = call.errorMapper(new ServiceAClientErrorMapper()).api(ServiceA.class); diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example1.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example1.java index c8ae3c804..e3b7f1cb0 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example1.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example1.java @@ -6,7 +6,7 @@ import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.examples.helloworld.service.GreetingServiceImpl; import io.scalecube.services.examples.helloworld.service.api.GreetingsService; -import io.scalecube.services.inject.ScalecubeServiceFactory; +import io.scalecube.services.ScalecubeServiceFactory; import io.scalecube.services.transport.rsocket.RSocketServiceTransport; /** diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example2.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example2.java index 5cd4ccf67..5967c6d86 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example2.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example2.java @@ -8,7 +8,7 @@ import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.examples.helloworld.service.GreetingServiceImpl; import io.scalecube.services.examples.helloworld.service.api.Greeting; -import io.scalecube.services.inject.ScalecubeServiceFactory; +import io.scalecube.services.ScalecubeServiceFactory; import io.scalecube.services.transport.rsocket.RSocketServiceTransport; import org.reactivestreams.Publisher; import reactor.core.publisher.Mono; diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example3.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example3.java index 5b9b6236b..f23e6e7c4 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example3.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example3.java @@ -6,7 +6,7 @@ import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.examples.helloworld.service.BidiGreetingImpl; import io.scalecube.services.examples.helloworld.service.api.BidiGreetingService; -import io.scalecube.services.inject.ScalecubeServiceFactory; +import io.scalecube.services.ScalecubeServiceFactory; import io.scalecube.services.transport.rsocket.RSocketServiceTransport; import reactor.core.publisher.Flux; diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/orderbook/Example1.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/orderbook/Example1.java index 1569dae7e..e6919b7e6 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/orderbook/Example1.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/orderbook/Example1.java @@ -11,7 +11,7 @@ import io.scalecube.services.examples.orderbook.service.engine.Order; import io.scalecube.services.examples.orderbook.service.engine.PriceLevel; import io.scalecube.services.examples.orderbook.service.engine.events.Side; -import io.scalecube.services.inject.ScalecubeServiceFactory; +import io.scalecube.services.ScalecubeServiceFactory; import io.scalecube.services.transport.rsocket.RSocketServiceTransport; import java.util.Collections; import java.util.Random; diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example1.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example1.java index 57fa29a30..34890beef 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example1.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example1.java @@ -4,7 +4,7 @@ import io.scalecube.services.Microservices; import io.scalecube.services.ServiceFactory; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; -import io.scalecube.services.inject.ScalecubeServiceFactory; +import io.scalecube.services.ScalecubeServiceFactory; import io.scalecube.services.transport.rsocket.RSocketServiceTransport; import reactor.core.publisher.Mono; import reactor.core.scheduler.Schedulers; diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example2.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example2.java index 559e88ed5..887b0d92c 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example2.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example2.java @@ -4,7 +4,7 @@ import io.scalecube.services.Microservices; import io.scalecube.services.ServiceFactory; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; -import io.scalecube.services.inject.ScalecubeServiceFactory; +import io.scalecube.services.ScalecubeServiceFactory; import io.scalecube.services.transport.rsocket.RSocketServiceTransport; import reactor.core.publisher.Mono; import reactor.core.scheduler.Schedulers; diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/GuiceServiceFactoryExample.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/GuiceServiceFactoryExample.java index 4e322c486..2ab2580ea 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/GuiceServiceFactoryExample.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/GuiceServiceFactoryExample.java @@ -9,21 +9,20 @@ import com.google.inject.Key; import com.google.inject.Module; import com.google.inject.Provider; -import com.google.inject.Scopes; import com.google.inject.TypeLiteral; -import io.scalecube.services.ExtendedMicroservicesContext; import io.scalecube.services.Microservices; import io.scalecube.services.MicroservicesContext; +import io.scalecube.services.ScalecubeServiceFactory; import io.scalecube.services.ServiceCall; import io.scalecube.services.ServiceDefinition; import io.scalecube.services.ServiceFactory; import io.scalecube.services.ServiceInfo; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; +import io.scalecube.services.discovery.api.ServiceDiscovery; import io.scalecube.services.examples.helloworld.service.GreetingServiceImpl; import io.scalecube.services.examples.services.factory.service.BidiGreetingImpl; import io.scalecube.services.examples.services.factory.service.api.BidiGreetingService; import io.scalecube.services.examples.services.factory.service.api.GreetingsService; -import io.scalecube.services.inject.ScalecubeServiceFactory; import io.scalecube.services.transport.rsocket.RSocketServiceTransport; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; @@ -34,6 +33,7 @@ import java.util.Arrays; import java.util.Collection; import java.util.List; +import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Collectors; import reactor.core.publisher.Mono; @@ -82,9 +82,7 @@ public static void main(String[] args) { @Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE}) @Retention(RetentionPolicy.RUNTIME) @BindingAnnotation - @interface ScalecubeBean { - - } + @interface ScalecubeBean {} public static class SampleModule extends AbstractModule { @@ -95,20 +93,18 @@ protected void configure() { .toProvider( new Provider<>() { - @Inject - private ServiceCall serviceCall; + @Inject private Provider serviceCall; @Override public GreetingsService get() { - return serviceCall.api(GreetingsService.class); + return serviceCall.get().api(GreetingsService.class); } }); Constructor constructor = BidiGreetingImpl1.class.getConstructor(GreetingsService.class); bind(BidiGreetingService.class) .annotatedWith(ScalecubeBean.class) - .toConstructor(constructor) - .in(Scopes.SINGLETON); + .toConstructor(constructor); } catch (Exception ex) { throw new RuntimeException(ex); } @@ -128,51 +124,50 @@ public static class GuiceServiceFactory implements ServiceFactory { private final List modules; private Injector injector; + private final AtomicReference lazyContext; private GuiceServiceFactory(Module... modules) { - this.modules = Arrays.asList(modules); + this.lazyContext = new AtomicReference<>(); + this.modules = new ArrayList<>(Arrays.asList(modules)); + this.modules.add( + new AbstractModule() { + @Override + protected void configure() { + AtomicReference context = GuiceServiceFactory.this.lazyContext; + bind(MicroservicesContext.class).toProvider(context::get); + bind(ServiceCall.class).toProvider(() -> context.get().serviceCall()); + bind(ServiceDiscovery.class).toProvider(() -> context.get().serviceDiscovery()); + } + }); } @Override - public Mono> getServiceDefinitions( - MicroservicesContext microservices) { - return Mono.fromCallable( - () -> { - AbstractModule baseModule = - new AbstractModule() { - - @Override - protected void configure() { - bind(MicroservicesContext.class).toInstance(microservices); - bind(ServiceCall.class).toProvider(microservices::serviceCall); - } - }; - List modules = new ArrayList<>(); - modules.add(baseModule); - modules.addAll(this.modules); - Injector injector = Guice.createInjector(modules); - - this.injector = injector; - return injector.getAllBindings().keySet().stream() - .filter(key -> key.getAnnotationType() == ScalecubeBean.class) - .map(Key::getTypeLiteral) - .map(TypeLiteral::getRawType) - .map(ServiceDefinition::new) - .collect(Collectors.toList()); - }); + public Collection getServiceDefinitions() { + Injector injector = Guice.createInjector(this.modules); + this.injector = injector; + return injector.getAllBindings().keySet().stream() + .filter(key -> key.getAnnotationType() == ScalecubeBean.class) + .map(Key::getTypeLiteral) + .map(TypeLiteral::getRawType) + .map(ServiceDefinition::new) + .collect(Collectors.toList()); } @Override public Mono> initializeServices( - ExtendedMicroservicesContext microservices) { + MicroservicesContext microservices) { return Mono.fromCallable( - () -> - this.injector.getAllBindings().values().stream() - .filter(binding -> binding.getKey().getAnnotationType() == ScalecubeBean.class) - .map(Binding::getProvider) - .map(Provider::get) - .map(bean -> ServiceInfo.fromServiceInstance(bean).build()) - .collect(Collectors.toList())); + () -> { + this.lazyContext.set(microservices); + List collect = + this.injector.getAllBindings().values().stream() + .filter(binding -> binding.getKey().getAnnotationType() == ScalecubeBean.class) + .map(Binding::getProvider) + .map(Provider::get) + .map(bean -> ServiceInfo.fromServiceInstance(bean).build()) + .collect(Collectors.toList()); + return collect; + }); } } } diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/LightweightSpringServiceFactoryExample.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/LightweightSpringServiceFactoryExample.java index ab9696600..7ab53e091 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/LightweightSpringServiceFactoryExample.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/LightweightSpringServiceFactoryExample.java @@ -1,8 +1,7 @@ package io.scalecube.services.examples.services.factory; -import io.scalecube.services.ExtendedMicroservicesContext; -import io.scalecube.services.Microservices; import io.scalecube.services.MicroservicesContext; +import io.scalecube.services.Microservices; import io.scalecube.services.ServiceCall; import io.scalecube.services.ServiceDefinition; import io.scalecube.services.ServiceFactory; @@ -12,7 +11,7 @@ import io.scalecube.services.examples.services.factory.service.BidiGreetingImpl; import io.scalecube.services.examples.services.factory.service.api.BidiGreetingService; import io.scalecube.services.examples.services.factory.service.api.GreetingsService; -import io.scalecube.services.inject.ScalecubeServiceFactory; +import io.scalecube.services.ScalecubeServiceFactory; import io.scalecube.services.transport.rsocket.RSocketServiceTransport; import java.util.ArrayList; import java.util.Collection; @@ -94,32 +93,28 @@ public static ServiceFactory initialize( } @Override - public Mono> getServiceDefinitions( - MicroservicesContext microservices) { - return Mono.fromCallable( - () -> { - this.context.registerBean(ServiceCall.class, microservices::serviceCall); - return Stream.of(this.context.getBeanDefinitionNames()) - .map( - beanName -> { - BeanDefinition bd = this.context.getBeanDefinition(beanName); - bd.setAttribute("name", beanName); - return bd; - }) - .filter(Customizers.IS_LOCAL) - .peek(bd -> this.localServiceBeanNames.add((String) bd.getAttribute("name"))) - .map(BeanDefinition::getResolvableType) - .map(ResolvableType::resolve) - .map(ServiceDefinition::new) - .collect(Collectors.toList()); - }); + public Collection getServiceDefinitions() { + return Stream.of(this.context.getBeanDefinitionNames()) + .map( + beanName -> { + BeanDefinition bd = this.context.getBeanDefinition(beanName); + bd.setAttribute("name", beanName); + return bd; + }) + .filter(Customizers.IS_LOCAL) + .peek(bd -> this.localServiceBeanNames.add((String) bd.getAttribute("name"))) + .map(BeanDefinition::getResolvableType) + .map(ResolvableType::resolve) + .map(ServiceDefinition::new) + .collect(Collectors.toList()); } @Override public Mono> initializeServices( - ExtendedMicroservicesContext microservices) { + MicroservicesContext microservices) { return Mono.fromCallable( () -> { + this.context.registerBean(ServiceCall.class, microservices::serviceCall); this.context.refresh(); this.context.start(); return this.localServiceBeanNames.stream() @@ -130,7 +125,7 @@ public Mono> initializeServices( } @Override - public Mono shutdownServices(ExtendedMicroservicesContext microservices) { + public Mono shutdownServices(MicroservicesContext microservices) { return Mono.fromRunnable(this.context::stop); } } diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/SpringServiceFactoryExample.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/SpringServiceFactoryExample.java index 2ceb7f567..b4f434299 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/SpringServiceFactoryExample.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/SpringServiceFactoryExample.java @@ -1,8 +1,9 @@ package io.scalecube.services.examples.services.factory; -import io.scalecube.services.ExtendedMicroservicesContext; -import io.scalecube.services.Microservices; +import static org.springframework.beans.factory.config.BeanDefinition.SCOPE_PROTOTYPE; + import io.scalecube.services.MicroservicesContext; +import io.scalecube.services.Microservices; import io.scalecube.services.Reflect; import io.scalecube.services.ServiceCall; import io.scalecube.services.ServiceDefinition; @@ -14,7 +15,7 @@ import io.scalecube.services.examples.services.factory.service.BidiGreetingImpl; import io.scalecube.services.examples.services.factory.service.api.BidiGreetingService; import io.scalecube.services.examples.services.factory.service.api.GreetingsService; -import io.scalecube.services.inject.ScalecubeServiceFactory; +import io.scalecube.services.ScalecubeServiceFactory; import io.scalecube.services.transport.rsocket.RSocketServiceTransport; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; @@ -82,6 +83,7 @@ static class ExampleConfiguration { @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection") @Bean + @Lazy public GreetingsService greetingService(ServiceCall serviceCall) { return serviceCall.api(GreetingsService.class); } @@ -96,7 +98,6 @@ public BidiGreetingService bidiGreetingService(GreetingsService greetingsService @Retention(RetentionPolicy.RUNTIME) @Bean @Lazy - // need for access to ServiceDiscovery @interface ScalecubeBean { /** @@ -147,33 +148,34 @@ private AnnotatedSpringServiceFactory(Class... configurations) { } @Override - public Mono> getServiceDefinitions( - MicroservicesContext microservices) { - return Mono.fromCallable( - () -> { - this.context.registerBean(MicroservicesContext.class, () -> microservices); - this.context.registerBean(ServiceCall.class, microservices::serviceCall); - this.context.register(this.configuration); - this.context.refresh(); - String[] beanNames = this.context.getBeanNamesForAnnotation(ScalecubeBean.class); - return Stream.of(beanNames) - .map(this.context::getBeanDefinition) - .map(BeanDefinition::getResolvableType) - .map(ResolvableType::resolve) - .filter(Objects::nonNull) - .filter(Reflect::isService) - .map(ServiceDefinition::new) - .collect(Collectors.toList()); - }); + public Collection getServiceDefinitions() { + this.context.register(this.configuration); + this.context.refresh(); + String[] beanNames = this.context.getBeanNamesForAnnotation(ScalecubeBean.class); + return Stream.of(beanNames) + .map(this.context::getBeanDefinition) + .map(BeanDefinition::getResolvableType) + .map(ResolvableType::resolve) + .filter(Objects::nonNull) + .filter(Reflect::isService) + .map(ServiceDefinition::new) + .collect(Collectors.toList()); } @Override public Mono> initializeServices( - ExtendedMicroservicesContext microservices) { + MicroservicesContext microservices) { return Mono.fromCallable( () -> { - this.context.registerBean(ServiceDiscovery.class, microservices::serviceDiscovery); - this.context.registerBean(ExtendedMicroservicesContext.class, () -> microservices); + this.context.registerBean(MicroservicesContext.class, () -> microservices); + this.context.registerBean( + ServiceCall.class, + microservices::serviceCall, + beanDefinition -> beanDefinition.setScope(SCOPE_PROTOTYPE)); + this.context.registerBean( + ServiceDiscovery.class, + microservices::serviceDiscovery, + beanDefinition -> beanDefinition.setScope(SCOPE_PROTOTYPE)); this.context.start(); return this.context.getBeansWithAnnotation(ScalecubeBean.class).values().stream() .map(bean -> ServiceInfo.fromServiceInstance(bean).build()) @@ -182,7 +184,7 @@ public Mono> initializeServices( } @Override - public Mono shutdownServices(ExtendedMicroservicesContext microservices) { + public Mono shutdownServices(MicroservicesContext microservices) { return Mono.fromRunnable(this.context::stop).then(); } } diff --git a/services/src/main/java/io/scalecube/services/Microservices.java b/services/src/main/java/io/scalecube/services/Microservices.java index 865f7b4ef..6ce50277c 100644 --- a/services/src/main/java/io/scalecube/services/Microservices.java +++ b/services/src/main/java/io/scalecube/services/Microservices.java @@ -11,7 +11,6 @@ import io.scalecube.services.exceptions.ServiceProviderErrorMapper; import io.scalecube.services.gateway.Gateway; import io.scalecube.services.gateway.GatewayOptions; -import io.scalecube.services.inject.ScalecubeServiceFactory; import io.scalecube.services.methods.MethodInfo; import io.scalecube.services.methods.ServiceMethodInvoker; import io.scalecube.services.methods.ServiceMethodRegistry; @@ -29,7 +28,6 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; -import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -123,7 +121,7 @@ public final class Microservices { private final String id = generateId(); private final Map tags; - private final ExtendedMicroservicesContext context; + private final MicroservicesContext context; private final ServiceFactory serviceFactory; private final ServiceRegistry serviceRegistry; private final ServiceMethodRegistry methodRegistry; @@ -141,8 +139,6 @@ public final class Microservices { private Microservices(Builder builder) { this.tags = new HashMap<>(builder.tags); - this.serviceFactory = builder.serviceFactory; - this.serviceRegistry = builder.serviceRegistry; this.methodRegistry = builder.methodRegistry; this.defaultAuthenticator = builder.authenticator; @@ -155,6 +151,15 @@ private Microservices(Builder builder) { this.principalMapper = builder.principalMapper; this.context = new Context(); + this.serviceFactory = + builder.serviceFactory != null + ? builder.serviceFactory + : ScalecubeServiceFactory.create(builder.serviceProviders); + // for initialization services by deprecated ServiceProvider + if (this.serviceFactory instanceof ScalecubeServiceFactory) { + ((ScalecubeServiceFactory) this.serviceFactory).setServiceCall(this::call); + } + // Setup cleanup shutdown .then(doShutdown()) @@ -214,7 +219,7 @@ private Mono start() { private Mono initializeServiceEndpoint(Supplier

serviceAddress) { Mono> serviceDefinitionsMono = - Mono.defer(() -> this.serviceFactory.getServiceDefinitions(this.context)); + Mono.fromCallable(this.serviceFactory::getServiceDefinitions); return serviceDefinitionsMono.map( serviceDefinitions -> { final ServiceEndpoint.Builder serviceEndpointBuilder = @@ -314,7 +319,7 @@ private Mono processBeforeDestroy() { return serviceFactory.shutdownServices(this.context).then(); } - public final class Context implements ExtendedMicroservicesContext { + public final class Context implements MicroservicesContext { @Override public String id() { @@ -369,11 +374,6 @@ private void build() { Collectors.collectingAndThen( Collectors.toList(), services -> (ServiceProvider) call -> services)); this.serviceProviders.add(serviceProvider); - List serviceProviders = Collections.unmodifiableList(this.serviceProviders); - this.serviceFactory = - this.serviceFactory == null - ? ScalecubeServiceFactory.create(serviceProviders) - : this.serviceFactory; } public Mono start() { diff --git a/services/src/main/java/io/scalecube/services/inject/ScalecubeServiceFactory.java b/services/src/main/java/io/scalecube/services/ScalecubeServiceFactory.java similarity index 66% rename from services/src/main/java/io/scalecube/services/inject/ScalecubeServiceFactory.java rename to services/src/main/java/io/scalecube/services/ScalecubeServiceFactory.java index 9e8a0ec20..eb8c7de29 100644 --- a/services/src/main/java/io/scalecube/services/inject/ScalecubeServiceFactory.java +++ b/services/src/main/java/io/scalecube/services/ScalecubeServiceFactory.java @@ -1,18 +1,10 @@ -package io.scalecube.services.inject; +package io.scalecube.services; -import io.scalecube.services.ExtendedMicroservicesContext; -import io.scalecube.services.Microservices; -import io.scalecube.services.MicroservicesContext; -import io.scalecube.services.ServiceCall; -import io.scalecube.services.ServiceDefinition; -import io.scalecube.services.ServiceFactory; -import io.scalecube.services.ServiceInfo; -import io.scalecube.services.ServiceProvider; -import io.scalecube.services.annotations.Inject; +import io.scalecube.services.inject.Injector; import java.util.Collection; import java.util.Collections; import java.util.concurrent.atomic.AtomicReference; -import java.util.function.Function; +import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -20,10 +12,22 @@ public class ScalecubeServiceFactory implements ServiceFactory { - private final Function> serviceFactory; + private final Supplier> serviceFactory; // lazy init private final AtomicReference> services = new AtomicReference<>(); + private Supplier serviceCallSupplier; + + private ScalecubeServiceFactory(Collection serviceProviders) { + this.serviceFactory = + () -> { + final ServiceCall serviceCall = this.serviceCallSupplier.get(); + return serviceProviders.stream() + .map(serviceProvider -> serviceProvider.provide(serviceCall)) + .flatMap(Collection::stream) + .collect(Collectors.toList()); + }; + } /** * Create the instance from {@link ServiceProvider}. @@ -60,15 +64,6 @@ public static ServiceFactory fromInstances(Object... services) { return new ScalecubeServiceFactory(Collections.singleton(provider)); } - private ScalecubeServiceFactory(Collection serviceProviders) { - this.serviceFactory = - serviceCall -> - serviceProviders.stream() - .map(serviceProvider -> serviceProvider.provide(serviceCall)) - .flatMap(Collection::stream) - .collect(Collectors.toList()); - } - /** * Since the service instance factory ({@link ServiceProvider}) we have to leave behind does not * provide us with information about the types of services produced, there is nothing left for us @@ -82,19 +77,15 @@ private ScalecubeServiceFactory(Collection serviceProviders) { * * @see ServiceInfo * @see ServiceDefinition + * @return */ @Override - public Mono> getServiceDefinitions( - MicroservicesContext microservices) { - return Mono.fromCallable( - () -> - this.services(microservices.serviceCall()) - .stream() - .map( - serviceInfo -> - new ServiceDefinition( - serviceInfo.serviceInstance().getClass(), serviceInfo.tags())) - .collect(Collectors.toList())); + public Collection getServiceDefinitions() { + return this.services().stream() + .map( + serviceInfo -> + new ServiceDefinition(serviceInfo.serviceInstance().getClass(), serviceInfo.tags())) + .collect(Collectors.toList()); } /** @@ -107,10 +98,10 @@ public Mono> getServiceDefinitions( */ @Override public Mono> initializeServices( - ExtendedMicroservicesContext microservices) { + MicroservicesContext microservices) { return Mono.fromCallable( () -> - this.services(microservices.serviceCall()).stream() + this.services().stream() .map(service -> Injector.inject(microservices, service)) .map(service -> Injector.processAfterConstruct(microservices, service)) .collect(Collectors.toList())); @@ -125,19 +116,31 @@ public Mono> initializeServices( * @return */ @Override - public Mono shutdownServices(ExtendedMicroservicesContext microservices) { + public Mono shutdownServices(MicroservicesContext microservices) { return Mono.fromRunnable(() -> shutdown0(microservices)); } - private void shutdown0(ExtendedMicroservicesContext microservices) { + private void shutdown0(MicroservicesContext microservices) { if (this.services.get() != null) { this.services.get().forEach(service -> Injector.processBeforeDestroy(microservices, service)); } } - private Collection services(ServiceCall serviceCall) { + private Collection services() { return this.services.updateAndGet( - currentValue -> - currentValue == null ? this.serviceFactory.apply(serviceCall) : currentValue); + currentValue -> currentValue == null ? this.serviceFactory.get() : currentValue); + } + + /** + * Setting serviceCall supplier. + * + * @param serviceCallSupplier lazy serviceCall initialization function + * @return current instance scalecube service factory + * @deprecated see reason in {@link ServiceProvider} + */ + @Deprecated + ScalecubeServiceFactory setServiceCall(Supplier serviceCallSupplier) { + this.serviceCallSupplier = serviceCallSupplier; + return this; } } diff --git a/services/src/main/java/io/scalecube/services/inject/Injector.java b/services/src/main/java/io/scalecube/services/inject/Injector.java index ff2c489a6..f4dbc5a8b 100644 --- a/services/src/main/java/io/scalecube/services/inject/Injector.java +++ b/services/src/main/java/io/scalecube/services/inject/Injector.java @@ -1,6 +1,5 @@ package io.scalecube.services.inject; -import io.scalecube.services.ExtendedMicroservicesContext; import io.scalecube.services.MicroservicesContext; import io.scalecube.services.Reflect; import io.scalecube.services.ServiceCall; @@ -31,7 +30,7 @@ private Injector() { * @return service instance */ public static ServiceInfo inject( - ExtendedMicroservicesContext microservices, ServiceInfo service) { + MicroservicesContext microservices, ServiceInfo service) { Object serviceInstance = service.serviceInstance(); Arrays.stream(serviceInstance.getClass().getDeclaredFields()) .forEach(field -> injectField(microservices, field, serviceInstance)); @@ -39,7 +38,7 @@ public static ServiceInfo inject( } private static void injectField( - ExtendedMicroservicesContext microservices, Field field, Object service) { + MicroservicesContext microservices, Field field, Object service) { if (field.isAnnotationPresent(Inject.class) && MicroservicesContext.class.isAssignableFrom(field.getType())) { setField(field, service, microservices); @@ -72,18 +71,18 @@ private static void setField(Field field, Object object, Object value) { * @return service info with modified service's instance. */ public static ServiceInfo processAfterConstruct( - ExtendedMicroservicesContext microservices, ServiceInfo serviceInfo) { + MicroservicesContext microservices, ServiceInfo serviceInfo) { processMethodWithAnnotation(microservices, serviceInfo.serviceInstance(), AfterConstruct.class); return serviceInfo; } public static void processBeforeDestroy( - ExtendedMicroservicesContext microservices, ServiceInfo serviceInfo) { + MicroservicesContext microservices, ServiceInfo serviceInfo) { processMethodWithAnnotation(microservices, serviceInfo.serviceInstance(), BeforeDestroy.class); } private static void processMethodWithAnnotation( - ExtendedMicroservicesContext microservices, Object targetInstance, Class annotation) { + MicroservicesContext microservices, Object targetInstance, Class annotation) { Method[] declaredMethods = targetInstance.getClass().getDeclaredMethods(); Arrays.stream(declaredMethods) .filter(method -> method.isAnnotationPresent(annotation)) diff --git a/services/src/test/java/io/scalecube/services/ErrorFlowTest.java b/services/src/test/java/io/scalecube/services/ErrorFlowTest.java index 4f65f74bd..ec099779e 100644 --- a/services/src/test/java/io/scalecube/services/ErrorFlowTest.java +++ b/services/src/test/java/io/scalecube/services/ErrorFlowTest.java @@ -10,7 +10,6 @@ import io.scalecube.services.exceptions.ForbiddenException; import io.scalecube.services.exceptions.InternalServiceException; import io.scalecube.services.exceptions.ServiceUnavailableException; -import io.scalecube.services.inject.ScalecubeServiceFactory; import io.scalecube.services.sut.GreetingResponse; import io.scalecube.services.sut.GreetingServiceImpl; import io.scalecube.services.transport.rsocket.RSocketServiceTransport; diff --git a/services/src/test/java/io/scalecube/services/ServiceCallLocalTest.java b/services/src/test/java/io/scalecube/services/ServiceCallLocalTest.java index 1dca2fa76..9be95c8cf 100644 --- a/services/src/test/java/io/scalecube/services/ServiceCallLocalTest.java +++ b/services/src/test/java/io/scalecube/services/ServiceCallLocalTest.java @@ -19,7 +19,6 @@ import io.scalecube.services.api.ServiceMessage; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.exceptions.ServiceException; -import io.scalecube.services.inject.ScalecubeServiceFactory; import io.scalecube.services.routing.RoundRobinServiceRouter; import io.scalecube.services.sut.EmptyGreetingResponse; import io.scalecube.services.sut.GreetingResponse; diff --git a/services/src/test/java/io/scalecube/services/ServiceCallRemoteTest.java b/services/src/test/java/io/scalecube/services/ServiceCallRemoteTest.java index a53267908..43a67611c 100644 --- a/services/src/test/java/io/scalecube/services/ServiceCallRemoteTest.java +++ b/services/src/test/java/io/scalecube/services/ServiceCallRemoteTest.java @@ -20,7 +20,6 @@ import io.scalecube.services.api.ServiceMessage; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.exceptions.ServiceException; -import io.scalecube.services.inject.ScalecubeServiceFactory; import io.scalecube.services.sut.EmptyGreetingResponse; import io.scalecube.services.sut.GreetingResponse; import io.scalecube.services.sut.GreetingServiceImpl; diff --git a/services/src/test/java/io/scalecube/services/ServiceLocalTest.java b/services/src/test/java/io/scalecube/services/ServiceLocalTest.java index 8664911db..5cb3c672e 100644 --- a/services/src/test/java/io/scalecube/services/ServiceLocalTest.java +++ b/services/src/test/java/io/scalecube/services/ServiceLocalTest.java @@ -5,7 +5,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import io.scalecube.services.api.ServiceMessage; -import io.scalecube.services.inject.ScalecubeServiceFactory; import io.scalecube.services.sut.GreetingRequest; import io.scalecube.services.sut.GreetingResponse; import io.scalecube.services.sut.GreetingService; diff --git a/services/src/test/java/io/scalecube/services/ServiceRegistryTest.java b/services/src/test/java/io/scalecube/services/ServiceRegistryTest.java index 9fb78c129..aa12d2119 100644 --- a/services/src/test/java/io/scalecube/services/ServiceRegistryTest.java +++ b/services/src/test/java/io/scalecube/services/ServiceRegistryTest.java @@ -13,7 +13,6 @@ import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.discovery.api.ServiceDiscovery; import io.scalecube.services.discovery.api.ServiceDiscoveryEvent; -import io.scalecube.services.inject.ScalecubeServiceFactory; import io.scalecube.services.sut.AnnotationService; import io.scalecube.services.sut.AnnotationServiceImpl; import io.scalecube.services.sut.GreetingServiceImpl; diff --git a/services/src/test/java/io/scalecube/services/ServiceRemoteTest.java b/services/src/test/java/io/scalecube/services/ServiceRemoteTest.java index e0807b13a..0ad8d8c14 100644 --- a/services/src/test/java/io/scalecube/services/ServiceRemoteTest.java +++ b/services/src/test/java/io/scalecube/services/ServiceRemoteTest.java @@ -8,7 +8,6 @@ import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.discovery.api.ServiceDiscovery; import io.scalecube.services.exceptions.InternalServiceException; -import io.scalecube.services.inject.ScalecubeServiceFactory; import io.scalecube.services.sut.CoarseGrainedService; import io.scalecube.services.sut.CoarseGrainedServiceImpl; import io.scalecube.services.sut.EmptyGreetingRequest; diff --git a/services/src/test/java/io/scalecube/services/StreamingServiceTest.java b/services/src/test/java/io/scalecube/services/StreamingServiceTest.java index d5ea00780..2281e67a2 100644 --- a/services/src/test/java/io/scalecube/services/StreamingServiceTest.java +++ b/services/src/test/java/io/scalecube/services/StreamingServiceTest.java @@ -7,7 +7,6 @@ import io.scalecube.services.api.ServiceMessage; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; -import io.scalecube.services.inject.ScalecubeServiceFactory; import io.scalecube.services.sut.QuoteService; import io.scalecube.services.sut.SimpleQuoteService; import io.scalecube.services.transport.api.ServiceMessageCodec; diff --git a/services/src/test/java/io/scalecube/services/sut/AnnotationServiceImpl.java b/services/src/test/java/io/scalecube/services/sut/AnnotationServiceImpl.java index 071ea9763..ac4a4a780 100644 --- a/services/src/test/java/io/scalecube/services/sut/AnnotationServiceImpl.java +++ b/services/src/test/java/io/scalecube/services/sut/AnnotationServiceImpl.java @@ -1,6 +1,5 @@ package io.scalecube.services.sut; -import io.scalecube.services.ExtendedMicroservicesContext; import io.scalecube.services.MicroservicesContext; import io.scalecube.services.annotations.AfterConstruct; import io.scalecube.services.discovery.api.ServiceDiscoveryEvent; @@ -12,7 +11,7 @@ public class AnnotationServiceImpl implements AnnotationService { private ReplayProcessor serviceDiscoveryEvents; @AfterConstruct - void init(ExtendedMicroservicesContext microservices) { + void init(MicroservicesContext microservices) { this.serviceDiscoveryEvents = ReplayProcessor.create(); microservices.serviceDiscovery().listenDiscovery().subscribe(serviceDiscoveryEvents); } diff --git a/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketNettyColocatedEventLoopGroupTest.java b/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketNettyColocatedEventLoopGroupTest.java index 5cd290b37..ae12d73da 100644 --- a/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketNettyColocatedEventLoopGroupTest.java +++ b/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketNettyColocatedEventLoopGroupTest.java @@ -12,7 +12,7 @@ import java.util.Optional; import java.util.concurrent.atomic.AtomicBoolean; -import io.scalecube.services.inject.ScalecubeServiceFactory; +import io.scalecube.services.ScalecubeServiceFactory; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketServiceTransportTest.java b/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketServiceTransportTest.java index fbfde1f6f..fc867fd8c 100644 --- a/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketServiceTransportTest.java +++ b/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketServiceTransportTest.java @@ -10,7 +10,7 @@ import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.discovery.api.ServiceDiscoveryEvent; import io.scalecube.services.exceptions.ConnectionClosedException; -import io.scalecube.services.inject.ScalecubeServiceFactory; +import io.scalecube.services.ScalecubeServiceFactory; import io.scalecube.services.sut.QuoteService; import io.scalecube.services.sut.SimpleQuoteService; import java.time.Duration; From 03aa5e189959c716d1b7e09e1dcb3e9c60a75ae9 Mon Sep 17 00:00:00 2001 From: Eugene_Utkin Date: Sat, 13 Jun 2020 18:06:51 +0300 Subject: [PATCH 48/61] fix checkstyles --- .../services/benchmarks/transport/BenchmarkServiceState.java | 2 +- .../java/io/scalecube/services/examples/ExamplesRunner.java | 2 +- .../java/io/scalecube/services/examples/codecs/Example1.java | 2 +- .../services/examples/exceptions/ExceptionMapperExample.java | 2 +- .../io/scalecube/services/examples/helloworld/Example1.java | 2 +- .../io/scalecube/services/examples/helloworld/Example2.java | 2 +- .../io/scalecube/services/examples/helloworld/Example3.java | 2 +- .../io/scalecube/services/examples/orderbook/Example1.java | 2 +- .../io/scalecube/services/examples/services/Example1.java | 2 +- .../io/scalecube/services/examples/services/Example2.java | 2 +- .../factory/LightweightSpringServiceFactoryExample.java | 4 ++-- .../services/factory/SpringServiceFactoryExample.java | 4 ++-- 12 files changed, 14 insertions(+), 14 deletions(-) diff --git a/services-benchmarks/src/main/java/io/scalecube/services/benchmarks/transport/BenchmarkServiceState.java b/services-benchmarks/src/main/java/io/scalecube/services/benchmarks/transport/BenchmarkServiceState.java index 21a2a3e52..b29378019 100644 --- a/services-benchmarks/src/main/java/io/scalecube/services/benchmarks/transport/BenchmarkServiceState.java +++ b/services-benchmarks/src/main/java/io/scalecube/services/benchmarks/transport/BenchmarkServiceState.java @@ -4,10 +4,10 @@ import io.scalecube.benchmarks.BenchmarkState; import io.scalecube.net.Address; import io.scalecube.services.Microservices; +import io.scalecube.services.ScalecubeServiceFactory; import io.scalecube.services.ServiceCall; import io.scalecube.services.ServiceFactory; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; -import io.scalecube.services.ScalecubeServiceFactory; import io.scalecube.services.transport.rsocket.RSocketServiceTransport; import java.time.Duration; import org.slf4j.Logger; diff --git a/services-examples-parent/services-examples-runner/src/main/java/io/scalecube/services/examples/ExamplesRunner.java b/services-examples-parent/services-examples-runner/src/main/java/io/scalecube/services/examples/ExamplesRunner.java index 58645eeda..63568ba9b 100644 --- a/services-examples-parent/services-examples-runner/src/main/java/io/scalecube/services/examples/ExamplesRunner.java +++ b/services-examples-parent/services-examples-runner/src/main/java/io/scalecube/services/examples/ExamplesRunner.java @@ -9,11 +9,11 @@ import io.scalecube.net.Address; import io.scalecube.runners.Runners; import io.scalecube.services.Microservices; +import io.scalecube.services.ScalecubeServiceFactory; import io.scalecube.services.ServiceEndpoint; import io.scalecube.services.ServiceFactory; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.discovery.api.ServiceDiscovery; -import io.scalecube.services.ScalecubeServiceFactory; import io.scalecube.services.transport.rsocket.RSocketServiceTransport; import java.nio.file.Path; import java.util.List; diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/codecs/Example1.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/codecs/Example1.java index 1244d36b4..5b3373370 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/codecs/Example1.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/codecs/Example1.java @@ -2,11 +2,11 @@ import io.scalecube.net.Address; import io.scalecube.services.Microservices; +import io.scalecube.services.ScalecubeServiceFactory; import io.scalecube.services.ServiceFactory; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.examples.helloworld.service.GreetingServiceImpl; import io.scalecube.services.examples.helloworld.service.api.GreetingsService; -import io.scalecube.services.ScalecubeServiceFactory; import io.scalecube.services.transport.rsocket.RSocketServiceTransport; public class Example1 { diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/exceptions/ExceptionMapperExample.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/exceptions/ExceptionMapperExample.java index e3cc9a3d9..d151ecc16 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/exceptions/ExceptionMapperExample.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/exceptions/ExceptionMapperExample.java @@ -1,8 +1,8 @@ package io.scalecube.services.examples.exceptions; import io.scalecube.net.Address; -import io.scalecube.services.MicroservicesContext; import io.scalecube.services.Microservices; +import io.scalecube.services.MicroservicesContext; import io.scalecube.services.ServiceCall; import io.scalecube.services.ServiceDefinition; import io.scalecube.services.ServiceFactory; diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example1.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example1.java index e3b7f1cb0..bb97e8a6f 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example1.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example1.java @@ -2,11 +2,11 @@ import io.scalecube.net.Address; import io.scalecube.services.Microservices; +import io.scalecube.services.ScalecubeServiceFactory; import io.scalecube.services.ServiceFactory; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.examples.helloworld.service.GreetingServiceImpl; import io.scalecube.services.examples.helloworld.service.api.GreetingsService; -import io.scalecube.services.ScalecubeServiceFactory; import io.scalecube.services.transport.rsocket.RSocketServiceTransport; /** diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example2.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example2.java index 5967c6d86..a09364bd4 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example2.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example2.java @@ -2,13 +2,13 @@ import io.scalecube.net.Address; import io.scalecube.services.Microservices; +import io.scalecube.services.ScalecubeServiceFactory; import io.scalecube.services.ServiceCall; import io.scalecube.services.ServiceFactory; import io.scalecube.services.api.ServiceMessage; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.examples.helloworld.service.GreetingServiceImpl; import io.scalecube.services.examples.helloworld.service.api.Greeting; -import io.scalecube.services.ScalecubeServiceFactory; import io.scalecube.services.transport.rsocket.RSocketServiceTransport; import org.reactivestreams.Publisher; import reactor.core.publisher.Mono; diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example3.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example3.java index f23e6e7c4..fcab0fdc4 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example3.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example3.java @@ -2,11 +2,11 @@ import io.scalecube.net.Address; import io.scalecube.services.Microservices; +import io.scalecube.services.ScalecubeServiceFactory; import io.scalecube.services.ServiceFactory; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.examples.helloworld.service.BidiGreetingImpl; import io.scalecube.services.examples.helloworld.service.api.BidiGreetingService; -import io.scalecube.services.ScalecubeServiceFactory; import io.scalecube.services.transport.rsocket.RSocketServiceTransport; import reactor.core.publisher.Flux; diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/orderbook/Example1.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/orderbook/Example1.java index e6919b7e6..c9718d9f8 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/orderbook/Example1.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/orderbook/Example1.java @@ -2,6 +2,7 @@ import io.scalecube.net.Address; import io.scalecube.services.Microservices; +import io.scalecube.services.ScalecubeServiceFactory; import io.scalecube.services.ServiceFactory; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.examples.orderbook.service.DefaultMarketDataService; @@ -11,7 +12,6 @@ import io.scalecube.services.examples.orderbook.service.engine.Order; import io.scalecube.services.examples.orderbook.service.engine.PriceLevel; import io.scalecube.services.examples.orderbook.service.engine.events.Side; -import io.scalecube.services.ScalecubeServiceFactory; import io.scalecube.services.transport.rsocket.RSocketServiceTransport; import java.util.Collections; import java.util.Random; diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example1.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example1.java index 34890beef..f84c01a7f 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example1.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example1.java @@ -2,9 +2,9 @@ import io.scalecube.net.Address; import io.scalecube.services.Microservices; +import io.scalecube.services.ScalecubeServiceFactory; import io.scalecube.services.ServiceFactory; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; -import io.scalecube.services.ScalecubeServiceFactory; import io.scalecube.services.transport.rsocket.RSocketServiceTransport; import reactor.core.publisher.Mono; import reactor.core.scheduler.Schedulers; diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example2.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example2.java index 887b0d92c..097e6a3ca 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example2.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example2.java @@ -2,9 +2,9 @@ import io.scalecube.net.Address; import io.scalecube.services.Microservices; +import io.scalecube.services.ScalecubeServiceFactory; import io.scalecube.services.ServiceFactory; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; -import io.scalecube.services.ScalecubeServiceFactory; import io.scalecube.services.transport.rsocket.RSocketServiceTransport; import reactor.core.publisher.Mono; import reactor.core.scheduler.Schedulers; diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/LightweightSpringServiceFactoryExample.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/LightweightSpringServiceFactoryExample.java index 7ab53e091..7e1958bde 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/LightweightSpringServiceFactoryExample.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/LightweightSpringServiceFactoryExample.java @@ -1,7 +1,8 @@ package io.scalecube.services.examples.services.factory; -import io.scalecube.services.MicroservicesContext; import io.scalecube.services.Microservices; +import io.scalecube.services.MicroservicesContext; +import io.scalecube.services.ScalecubeServiceFactory; import io.scalecube.services.ServiceCall; import io.scalecube.services.ServiceDefinition; import io.scalecube.services.ServiceFactory; @@ -11,7 +12,6 @@ import io.scalecube.services.examples.services.factory.service.BidiGreetingImpl; import io.scalecube.services.examples.services.factory.service.api.BidiGreetingService; import io.scalecube.services.examples.services.factory.service.api.GreetingsService; -import io.scalecube.services.ScalecubeServiceFactory; import io.scalecube.services.transport.rsocket.RSocketServiceTransport; import java.util.ArrayList; import java.util.Collection; diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/SpringServiceFactoryExample.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/SpringServiceFactoryExample.java index b4f434299..4a99305d8 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/SpringServiceFactoryExample.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/SpringServiceFactoryExample.java @@ -2,9 +2,10 @@ import static org.springframework.beans.factory.config.BeanDefinition.SCOPE_PROTOTYPE; -import io.scalecube.services.MicroservicesContext; import io.scalecube.services.Microservices; +import io.scalecube.services.MicroservicesContext; import io.scalecube.services.Reflect; +import io.scalecube.services.ScalecubeServiceFactory; import io.scalecube.services.ServiceCall; import io.scalecube.services.ServiceDefinition; import io.scalecube.services.ServiceFactory; @@ -15,7 +16,6 @@ import io.scalecube.services.examples.services.factory.service.BidiGreetingImpl; import io.scalecube.services.examples.services.factory.service.api.BidiGreetingService; import io.scalecube.services.examples.services.factory.service.api.GreetingsService; -import io.scalecube.services.ScalecubeServiceFactory; import io.scalecube.services.transport.rsocket.RSocketServiceTransport; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; From 0d81eee414b40c41ac6a917735423044dee8a4e8 Mon Sep 17 00:00:00 2001 From: "e.utkin" Date: Sat, 13 Jun 2020 20:07:04 +0300 Subject: [PATCH 49/61] Context is private now --- services/src/main/java/io/scalecube/services/Microservices.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/src/main/java/io/scalecube/services/Microservices.java b/services/src/main/java/io/scalecube/services/Microservices.java index 6ce50277c..12dd475ed 100644 --- a/services/src/main/java/io/scalecube/services/Microservices.java +++ b/services/src/main/java/io/scalecube/services/Microservices.java @@ -319,7 +319,7 @@ private Mono processBeforeDestroy() { return serviceFactory.shutdownServices(this.context).then(); } - public final class Context implements MicroservicesContext { + private final class Context implements MicroservicesContext { @Override public String id() { From b25f026c5c2d9a9625cd0ba8ae51c540471ebef1 Mon Sep 17 00:00:00 2001 From: "e.utkin" Date: Sat, 13 Jun 2020 23:08:46 +0300 Subject: [PATCH 50/61] change MicroservicesContext signatures --- .../services/MicroservicesContext.java | 17 ++++++---- .../io/scalecube/services/ServiceFactory.java | 8 ++--- .../factory/GuiceServiceFactoryExample.java | 18 +++++----- .../factory/SpringServiceFactoryExample.java | 6 ++-- .../io/scalecube/services/Microservices.java | 33 +++++++++++++------ 5 files changed, 48 insertions(+), 34 deletions(-) diff --git a/services-api/src/main/java/io/scalecube/services/MicroservicesContext.java b/services-api/src/main/java/io/scalecube/services/MicroservicesContext.java index 7bece3886..2954a29d5 100644 --- a/services-api/src/main/java/io/scalecube/services/MicroservicesContext.java +++ b/services-api/src/main/java/io/scalecube/services/MicroservicesContext.java @@ -2,6 +2,8 @@ import io.scalecube.net.Address; import io.scalecube.services.discovery.api.ServiceDiscovery; +import io.scalecube.services.discovery.api.ServiceDiscoveryEvent; +import reactor.core.publisher.Flux; /** * Context of Scalecube node. Used in {@link ServiceFactory}. @@ -11,33 +13,34 @@ public interface MicroservicesContext { /** - * Id of Scalecube node. + * Service endpoint of current Scalecube node. * * @return id */ - String id(); + ServiceEndpoint serviceEndpoint(); /** * Used for remote service call. * - * @return service call + * @return new instance service call * @see ServiceCall */ ServiceCall serviceCall(); /** - * Network address of Scalecube node. + * Network address of service discovery in current Scalecube node. * * @return address of node * @see Address */ - Address serviceAddress(); + Address discoveryAddress(); /** - * Service discovery for services localed in other nodes. + * Flux of service discovery events. * * @return service discovery * @see ServiceDiscovery + * @see ServiceDiscoveryEvent */ - ServiceDiscovery serviceDiscovery(); + Flux listenDiscoveryEvents(); } diff --git a/services-api/src/main/java/io/scalecube/services/ServiceFactory.java b/services-api/src/main/java/io/scalecube/services/ServiceFactory.java index 252c6cb3d..bb65b9532 100644 --- a/services-api/src/main/java/io/scalecube/services/ServiceFactory.java +++ b/services-api/src/main/java/io/scalecube/services/ServiceFactory.java @@ -7,7 +7,7 @@ public interface ServiceFactory { /** - * Provide service definitions. + * Provide service definitions to be deployed on the current Scalecube node. * * @return collection of service definitions - service type and tags. * @see ServiceDefinition @@ -15,13 +15,13 @@ public interface ServiceFactory { Collection getServiceDefinitions(); /** - * Initialize instances of services. + * Creates instances of services declared in the method {@link this#getServiceDefinitions()} + * getServiceDefinitions. * * @param microservices microservices context * @return Completed Mono if initialization was successful for all services. */ - Mono> initializeServices( - MicroservicesContext microservices); + Mono> initializeServices(MicroservicesContext microservices); /** * Finalization of service instances. diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/GuiceServiceFactoryExample.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/GuiceServiceFactoryExample.java index 2ab2580ea..a1895a3ba 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/GuiceServiceFactoryExample.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/GuiceServiceFactoryExample.java @@ -15,10 +15,10 @@ import io.scalecube.services.ScalecubeServiceFactory; import io.scalecube.services.ServiceCall; import io.scalecube.services.ServiceDefinition; +import io.scalecube.services.ServiceEndpoint; import io.scalecube.services.ServiceFactory; import io.scalecube.services.ServiceInfo; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; -import io.scalecube.services.discovery.api.ServiceDiscovery; import io.scalecube.services.examples.helloworld.service.GreetingServiceImpl; import io.scalecube.services.examples.services.factory.service.BidiGreetingImpl; import io.scalecube.services.examples.services.factory.service.api.BidiGreetingService; @@ -136,7 +136,7 @@ protected void configure() { AtomicReference context = GuiceServiceFactory.this.lazyContext; bind(MicroservicesContext.class).toProvider(context::get); bind(ServiceCall.class).toProvider(() -> context.get().serviceCall()); - bind(ServiceDiscovery.class).toProvider(() -> context.get().serviceDiscovery()); + bind(ServiceEndpoint.class).toProvider(() -> context.get().serviceEndpoint()); } }); } @@ -159,14 +159,12 @@ public Mono> initializeServices( return Mono.fromCallable( () -> { this.lazyContext.set(microservices); - List collect = - this.injector.getAllBindings().values().stream() - .filter(binding -> binding.getKey().getAnnotationType() == ScalecubeBean.class) - .map(Binding::getProvider) - .map(Provider::get) - .map(bean -> ServiceInfo.fromServiceInstance(bean).build()) - .collect(Collectors.toList()); - return collect; + return this.injector.getAllBindings().values().stream() + .filter(binding -> binding.getKey().getAnnotationType() == ScalecubeBean.class) + .map(Binding::getProvider) + .map(Provider::get) + .map(bean -> ServiceInfo.fromServiceInstance(bean).build()) + .collect(Collectors.toList()); }); } } diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/SpringServiceFactoryExample.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/SpringServiceFactoryExample.java index 4a99305d8..766d33013 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/SpringServiceFactoryExample.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/SpringServiceFactoryExample.java @@ -8,10 +8,10 @@ import io.scalecube.services.ScalecubeServiceFactory; import io.scalecube.services.ServiceCall; import io.scalecube.services.ServiceDefinition; +import io.scalecube.services.ServiceEndpoint; import io.scalecube.services.ServiceFactory; import io.scalecube.services.ServiceInfo; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; -import io.scalecube.services.discovery.api.ServiceDiscovery; import io.scalecube.services.examples.helloworld.service.GreetingServiceImpl; import io.scalecube.services.examples.services.factory.service.BidiGreetingImpl; import io.scalecube.services.examples.services.factory.service.api.BidiGreetingService; @@ -173,8 +173,8 @@ public Mono> initializeServices( microservices::serviceCall, beanDefinition -> beanDefinition.setScope(SCOPE_PROTOTYPE)); this.context.registerBean( - ServiceDiscovery.class, - microservices::serviceDiscovery, + ServiceEndpoint.class, + microservices::serviceEndpoint, beanDefinition -> beanDefinition.setScope(SCOPE_PROTOTYPE)); this.context.start(); return this.context.getBeansWithAnnotation(ScalecubeBean.class).values().stream() diff --git a/services/src/main/java/io/scalecube/services/Microservices.java b/services/src/main/java/io/scalecube/services/Microservices.java index 12dd475ed..20bbabdd4 100644 --- a/services/src/main/java/io/scalecube/services/Microservices.java +++ b/services/src/main/java/io/scalecube/services/Microservices.java @@ -121,7 +121,6 @@ public final class Microservices { private final String id = generateId(); private final Map tags; - private final MicroservicesContext context; private final ServiceFactory serviceFactory; private final ServiceRegistry serviceRegistry; private final ServiceMethodRegistry methodRegistry; @@ -135,6 +134,7 @@ public final class Microservices { private final PrincipalMapper principalMapper; private final MonoProcessor shutdown = MonoProcessor.create(); private final MonoProcessor onShutdown = MonoProcessor.create(); + private MicroservicesContext context; private Microservices(Builder builder) { this.tags = new HashMap<>(builder.tags); @@ -149,7 +149,6 @@ private Microservices(Builder builder) { this.defaultDataDecoder = builder.dataDecoder; this.contentType = builder.contentType; this.principalMapper = builder.principalMapper; - this.context = new Context(); this.serviceFactory = builder.serviceFactory != null @@ -199,7 +198,9 @@ private Mono start() { .flatMap(this::initializeServiceEndpoint) .flatMap(this.discoveryBootstrap::createInstance) .publishOn(scheduler) - .then(this.serviceFactory.initializeServices(this.context)) + .map(serviceDiscovery -> new Context(serviceDiscovery, this::call)) + .doOnSuccess(context -> this.context = context) + .flatMap(this.serviceFactory::initializeServices) .doOnNext(this::registerInMethodRegistry) .publishOn(scheduler) .then(startGateway()) @@ -321,24 +322,36 @@ private Mono processBeforeDestroy() { private final class Context implements MicroservicesContext { + private final ServiceEndpoint serviceEndpoint; + private final Supplier serviceCallSupplier; + private final Address discoveryAddress; + private final Flux events; + + private Context(ServiceDiscovery serviceDiscovery, Supplier serviceCallSupplier) { + this.serviceEndpoint = serviceDiscovery.serviceEndpoint(); + this.serviceCallSupplier = serviceCallSupplier; + this.discoveryAddress = serviceDiscovery.address(); + this.events = serviceDiscovery.listenDiscovery(); + } + @Override - public String id() { - return Microservices.this.id(); + public ServiceEndpoint serviceEndpoint() { + return this.serviceEndpoint; } @Override public ServiceCall serviceCall() { - return Microservices.this.call(); + return this.serviceCallSupplier.get(); } @Override - public Address serviceAddress() { - return Microservices.this.serviceAddress(); + public Address discoveryAddress() { + return this.discoveryAddress; } @Override - public ServiceDiscovery serviceDiscovery() { - return Microservices.this.discovery(); + public Flux listenDiscoveryEvents() { + return this.events; } } From 1ecb7a722376ee8537d11d63a38054fa32e9e8b7 Mon Sep 17 00:00:00 2001 From: "e.utkin" Date: Sat, 13 Jun 2020 23:13:04 +0300 Subject: [PATCH 51/61] fix example --- .../examples/exceptions/ExceptionMapperExample.java | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/exceptions/ExceptionMapperExample.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/exceptions/ExceptionMapperExample.java index d151ecc16..2cb9fe07c 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/exceptions/ExceptionMapperExample.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/exceptions/ExceptionMapperExample.java @@ -9,11 +9,8 @@ import io.scalecube.services.ServiceInfo; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; import io.scalecube.services.transport.rsocket.RSocketServiceTransport; - import java.util.Collection; -import java.util.Collections; import java.util.List; - import reactor.core.publisher.Mono; public class ExceptionMapperExample { @@ -44,9 +41,8 @@ public static void main(String[] args) throws InterruptedException { new ServiceFactory() { @Override public Collection getServiceDefinitions() { - ServiceDefinition serviceA = new ServiceDefinition(ServiceA.class); ServiceDefinition serviceB = new ServiceDefinition(ServiceB.class); - return List.of(serviceA, serviceB); + return List.of(serviceB); } @Override @@ -57,7 +53,7 @@ public Mono> initializeServices( call.errorMapper(new ServiceAClientErrorMapper()).api(ServiceA.class); ServiceB serviceB = new ServiceBImpl(serviceA); ServiceInfo serviceInfoB = ServiceInfo.fromServiceInstance(serviceB).build(); - return Mono.just(Collections.singletonList(serviceInfoB)); + return Mono.just(List.of(serviceInfoB)); } }; Microservices ms2 = From b91d7497185b7f829085fdd5e9a41869dea479d2 Mon Sep 17 00:00:00 2001 From: "e.utkin" Date: Sat, 13 Jun 2020 23:22:34 +0300 Subject: [PATCH 52/61] fix example --- .../java/io/scalecube/services/sut/AnnotationServiceImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/src/test/java/io/scalecube/services/sut/AnnotationServiceImpl.java b/services/src/test/java/io/scalecube/services/sut/AnnotationServiceImpl.java index ac4a4a780..6ccb7569d 100644 --- a/services/src/test/java/io/scalecube/services/sut/AnnotationServiceImpl.java +++ b/services/src/test/java/io/scalecube/services/sut/AnnotationServiceImpl.java @@ -13,7 +13,7 @@ public class AnnotationServiceImpl implements AnnotationService { @AfterConstruct void init(MicroservicesContext microservices) { this.serviceDiscoveryEvents = ReplayProcessor.create(); - microservices.serviceDiscovery().listenDiscovery().subscribe(serviceDiscoveryEvents); + microservices.listenDiscoveryEvents().subscribe(serviceDiscoveryEvents); } @Override From 592c39889da6e2b341c5959dc2f0b5ed421b1c17 Mon Sep 17 00:00:00 2001 From: "e.utkin" Date: Sun, 14 Jun 2020 00:18:05 +0300 Subject: [PATCH 53/61] remove MicroservicesContext#discoveyAddress because it not yet initializes --- .../java/io/scalecube/services/MicroservicesContext.java | 9 --------- .../main/java/io/scalecube/services/Microservices.java | 5 ----- 2 files changed, 14 deletions(-) diff --git a/services-api/src/main/java/io/scalecube/services/MicroservicesContext.java b/services-api/src/main/java/io/scalecube/services/MicroservicesContext.java index 2954a29d5..33cafeef0 100644 --- a/services-api/src/main/java/io/scalecube/services/MicroservicesContext.java +++ b/services-api/src/main/java/io/scalecube/services/MicroservicesContext.java @@ -1,6 +1,5 @@ package io.scalecube.services; -import io.scalecube.net.Address; import io.scalecube.services.discovery.api.ServiceDiscovery; import io.scalecube.services.discovery.api.ServiceDiscoveryEvent; import reactor.core.publisher.Flux; @@ -27,14 +26,6 @@ public interface MicroservicesContext { */ ServiceCall serviceCall(); - /** - * Network address of service discovery in current Scalecube node. - * - * @return address of node - * @see Address - */ - Address discoveryAddress(); - /** * Flux of service discovery events. * diff --git a/services/src/main/java/io/scalecube/services/Microservices.java b/services/src/main/java/io/scalecube/services/Microservices.java index 20bbabdd4..9a3c22aac 100644 --- a/services/src/main/java/io/scalecube/services/Microservices.java +++ b/services/src/main/java/io/scalecube/services/Microservices.java @@ -344,11 +344,6 @@ public ServiceCall serviceCall() { return this.serviceCallSupplier.get(); } - @Override - public Address discoveryAddress() { - return this.discoveryAddress; - } - @Override public Flux listenDiscoveryEvents() { return this.events; From 4ee55fbbf1bb5ad3fc8f323bfbee612e5b872967 Mon Sep 17 00:00:00 2001 From: "e.utkin" Date: Sun, 14 Jun 2020 00:25:28 +0300 Subject: [PATCH 54/61] remove MicroservicesContext#discoveyAddress because it not yet initializes --- .../src/main/java/io/scalecube/services/Microservices.java | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/services/src/main/java/io/scalecube/services/Microservices.java b/services/src/main/java/io/scalecube/services/Microservices.java index 9a3c22aac..e284ebfbb 100644 --- a/services/src/main/java/io/scalecube/services/Microservices.java +++ b/services/src/main/java/io/scalecube/services/Microservices.java @@ -320,17 +320,15 @@ private Mono processBeforeDestroy() { return serviceFactory.shutdownServices(this.context).then(); } - private final class Context implements MicroservicesContext { + private static final class Context implements MicroservicesContext { private final ServiceEndpoint serviceEndpoint; private final Supplier serviceCallSupplier; - private final Address discoveryAddress; private final Flux events; private Context(ServiceDiscovery serviceDiscovery, Supplier serviceCallSupplier) { this.serviceEndpoint = serviceDiscovery.serviceEndpoint(); this.serviceCallSupplier = serviceCallSupplier; - this.discoveryAddress = serviceDiscovery.address(); this.events = serviceDiscovery.listenDiscovery(); } From 02eee19e26c1cf92ed5d8920602df0959a23bbaf Mon Sep 17 00:00:00 2001 From: "e.utkin" Date: Tue, 16 Jun 2020 15:43:44 +0300 Subject: [PATCH 55/61] Merge with develop and extract public api of Microservices to MicroservicesContext --- .../services/MicroservicesContext.java | 55 +- .../factory/GuiceServiceFactoryExample.java | 7 +- ...ightweightSpringServiceFactoryExample.java | 7 +- .../factory/SpringServiceFactoryExample.java | 7 +- .../io/scalecube/services/Microservices.java | 469 ++++++++++-------- .../io/scalecube/services/ErrorFlowTest.java | 15 +- .../services/ServiceAuthRemoteTest.java | 13 +- .../services/ServiceCallLocalTest.java | 32 +- .../services/ServiceCallRemoteTest.java | 47 +- .../scalecube/services/ServiceLocalTest.java | 9 +- .../services/ServiceRegistryTest.java | 24 +- .../scalecube/services/ServiceRemoteTest.java | 39 +- .../services/StreamingServiceTest.java | 23 +- .../services/routings/RoutersTest.java | 14 +- .../services/routings/ServiceTagsExample.java | 4 +- .../services/sut/AnnotationServiceImpl.java | 2 +- ...ocketNettyColocatedEventLoopGroupTest.java | 6 +- .../rsocket/RSocketServiceTransportTest.java | 11 +- 18 files changed, 473 insertions(+), 311 deletions(-) diff --git a/services-api/src/main/java/io/scalecube/services/MicroservicesContext.java b/services-api/src/main/java/io/scalecube/services/MicroservicesContext.java index 33cafeef0..b7ea87f77 100644 --- a/services-api/src/main/java/io/scalecube/services/MicroservicesContext.java +++ b/services-api/src/main/java/io/scalecube/services/MicroservicesContext.java @@ -1,11 +1,17 @@ package io.scalecube.services; -import io.scalecube.services.discovery.api.ServiceDiscovery; +import io.scalecube.net.Address; +import io.scalecube.services.discovery.api.ServiceDiscoveryContext; import io.scalecube.services.discovery.api.ServiceDiscoveryEvent; +import io.scalecube.services.gateway.Gateway; +import java.util.List; import reactor.core.publisher.Flux; /** - * Context of Scalecube node. Used in {@link ServiceFactory}. + * Context of Microservices node. Contain all public API of Microservices node, include gateways, + * service discoveries, etc. + * + *

Can be used in user services. * * @see ServiceFactory */ @@ -27,11 +33,46 @@ public interface MicroservicesContext { ServiceCall serviceCall(); /** - * Flux of service discovery events. + * Function to subscribe and listen on {@code ServiceDiscoveryEvent} events. + * + * @return stream of {@code ServiceDiscoveryEvent} events + */ + Flux listenDiscovery(); + + /** + * Returns service discovery context by id. + * + * @param id service discovery id + * @return service discovery context + */ + ServiceDiscoveryContext discovery(String id); + + /** + * All gateways registered on this Microservices node. + * + * @return list of gateway + */ + List gateways(); + + /** + * Return gateway by id. + * + * @param id gateway id + * @return gateway + */ + Gateway gateway(String id); + + /** + * Network address current Microservices node. * - * @return service discovery - * @see ServiceDiscovery - * @see ServiceDiscoveryEvent + * @return network address + */ + Address serviceAddress(); + + /** + * Unique id of this Microservices node. + * + * @return id */ - Flux listenDiscoveryEvents(); + String id(); } diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/GuiceServiceFactoryExample.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/GuiceServiceFactoryExample.java index a1895a3ba..ff1d4730d 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/GuiceServiceFactoryExample.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/GuiceServiceFactoryExample.java @@ -51,7 +51,7 @@ public static void main(String[] args) { Microservices service2Node = Microservices.builder() .serviceFactory(serviceFactory2) - .discovery(ScalecubeServiceDiscovery::new) + .discovery("s2", ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) .startAwait(); @@ -60,9 +60,12 @@ public static void main(String[] args) { Microservices service1Node = Microservices.builder() .discovery( + "s1", endpoint -> new ScalecubeServiceDiscovery(endpoint) - .membership(cfg -> cfg.seedMembers(service2Node.discovery().address()))) + .membership( + cfg -> + cfg.seedMembers(service2Node.context().discovery("s2").address()))) .serviceFactory(serviceFactory1) .transport(RSocketServiceTransport::new) .startAwait(); diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/LightweightSpringServiceFactoryExample.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/LightweightSpringServiceFactoryExample.java index 7e1958bde..a3ad1df95 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/LightweightSpringServiceFactoryExample.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/LightweightSpringServiceFactoryExample.java @@ -40,7 +40,7 @@ public static void main(String[] args) { Microservices service2Node = Microservices.builder() .serviceFactory(serviceFactory2) - .discovery(ScalecubeServiceDiscovery::new) + .discovery("s2", ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) .startAwait(); @@ -57,9 +57,12 @@ public static void main(String[] args) { Microservices service1Node = Microservices.builder() .discovery( + "s1", endpoint -> new ScalecubeServiceDiscovery(endpoint) - .membership(cfg -> cfg.seedMembers(service2Node.discovery().address()))) + .membership( + cfg -> + cfg.seedMembers(service2Node.context().discovery("s2").address()))) .serviceFactory(serviceFactory1) .transport(RSocketServiceTransport::new) .startAwait(); diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/SpringServiceFactoryExample.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/SpringServiceFactoryExample.java index 766d33013..a8854c780 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/SpringServiceFactoryExample.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/SpringServiceFactoryExample.java @@ -49,7 +49,7 @@ public static void main(String[] args) { Microservices service2Node = Microservices.builder() .serviceFactory(serviceFactory2) - .discovery(ScalecubeServiceDiscovery::new) + .discovery("s2", ScalecubeServiceDiscovery::new) .transport(RSocketServiceTransport::new) .startAwait(); @@ -59,9 +59,12 @@ public static void main(String[] args) { Microservices service1Node = Microservices.builder() .discovery( + "s1", endpoint -> new ScalecubeServiceDiscovery(endpoint) - .membership(cfg -> cfg.seedMembers(service2Node.discovery().address()))) + .membership( + cfg -> + cfg.seedMembers(service2Node.context().discovery("s2").address()))) .serviceFactory(serviceFactory1) .transport(RSocketServiceTransport::new) .startAwait(); diff --git a/services/src/main/java/io/scalecube/services/Microservices.java b/services/src/main/java/io/scalecube/services/Microservices.java index 7854b620f..9e9d85eda 100644 --- a/services/src/main/java/io/scalecube/services/Microservices.java +++ b/services/src/main/java/io/scalecube/services/Microservices.java @@ -144,7 +144,7 @@ public final class Microservices { private final PrincipalMapper principalMapper; private final MonoProcessor shutdown = MonoProcessor.create(); private final MonoProcessor onShutdown = MonoProcessor.create(); - private MicroservicesContext context; + private MicroservicesContext microservicesContext; private ServiceEndpoint serviceEndpoint; private Microservices(Builder builder) { @@ -182,10 +182,26 @@ public static Builder builder() { return new Builder(); } + /** + * Unique id of this Microservices node. + * + * @return id + * @deprecated use {@link MicroservicesContext#id()} by {@link Microservices#context()} + */ + @Deprecated public String id() { return this.id; } + /** + * Return microservices context with all public information about Microservices. + * + * @return microservices context + */ + public MicroservicesContext context() { + return microservicesContext; + } + @Override public String toString() { return "Microservices@" + id; @@ -201,26 +217,17 @@ private Mono start() { // because ServiceTransportBootstrap#address may return nullable value in local case .map(transport -> (Supplier

) transport::address) .flatMap(this::initializeServiceEndpoint) - .map(serviceEndpoint -> { - return createDiscovery(new ServiceDiscoveryOptions().serviceEndpoint(serviceEndpoint)) - .publishOn(scheduler) - .then(startGateway(new GatewayOptions().call(call))) - .publishOn(scheduler) - .then(Mono.fromCallable(() -> Injector.inject(this, serviceInstances))) - .then(Mono.fromCallable(() -> JmxMonitorMBean.start(this))) - .then(compositeDiscovery.startListen(this)) - .publishOn(scheduler) - .thenReturn(this); - }) - .map(serviceDiscovery -> new Context(serviceDiscovery, this::call)) - .doOnSuccess(context -> this.context = context) + .flatMap( + serviceEndpoint -> + createDiscovery(new ServiceDiscoveryOptions().serviceEndpoint(serviceEndpoint))) + .map(avoid -> this.microservicesContext = new MicroservicesContextImpl()) .flatMap(this.serviceFactory::initializeServices) .doOnNext(this::registerInMethodRegistry) .publishOn(scheduler) .then(startGateway()) .publishOn(scheduler) .then(Mono.fromCallable(() -> JmxMonitorMBean.start(this))) - .then(this.discoveryBootstrap.startListen(this)) + .then(this.compositeDiscovery.startListen(this)) .publishOn(scheduler) .thenReturn(this) .onErrorResume( @@ -230,17 +237,9 @@ private Mono start() { } private Mono createDiscovery(ServiceDiscoveryOptions options) { - return compositeDiscovery.createInstance(options); + return this.compositeDiscovery.createInstance(options); } - private void registerInMethodRegistry(ServiceInfo serviceInfo) { - methodRegistry.registerService( - ServiceInfo.from(serviceInfo) - .errorMapperIfAbsent(errorMapper) - .dataDecoderIfAbsent(dataDecoder) - .authenticatorIfAbsent(authenticator) - .principalMapperIfAbsent(principalMapper) - .build()); private Mono initializeServiceEndpoint(Supplier
serviceAddress) { Mono> serviceDefinitionsMono = Mono.fromCallable(this.serviceFactory::getServiceDefinitions); @@ -256,7 +255,9 @@ private Mono initializeServiceEndpoint(Supplier
servic serviceDefinition -> serviceEndpointBuilder.appendServiceRegistrations( ServiceScanner.scanServiceDefinition(serviceDefinition))); - return serviceEndpointBuilder.build(); + ServiceEndpoint serviceEndpoint = serviceEndpointBuilder.build(); + this.serviceEndpoint = serviceEndpoint; + return serviceEndpoint; }); } @@ -270,13 +271,20 @@ private void registerInMethodRegistry(Collection services) { .authenticatorIfAbsent(this.defaultAuthenticator) .principalMapperIfAbsent(this.principalMapper) .build()) - .forEach(methodRegistry::registerService); + .forEach(this.methodRegistry::registerService); } private Mono startGateway() { - return gatewayBootstrap.start(this, new GatewayOptions().call(this.call())); + return this.gatewayBootstrap.start(this, new GatewayOptions().call(this.call())); } + /** + * Network address of this Microservices node. + * + * @return network address + * @deprecated use {@link MicroservicesContext#serviceAddress()} )} by {@link + * Microservices#context()} + */ public Address serviceAddress() { return transportBootstrap.transportAddress; } @@ -285,25 +293,49 @@ public Address serviceAddress() { * Creates new instance {@code ServiceCall}. * * @return new {@code ServiceCall} instance. + * @deprecated use {@link MicroservicesContext#serviceCall()} by {@link Microservices#context()} */ + @Deprecated public ServiceCall call() { return new ServiceCall() - .transport(transportBootstrap.clientTransport) - .serviceRegistry(serviceRegistry) - .methodRegistry(methodRegistry) - .contentType(contentType) + .transport(this.transportBootstrap.clientTransport) + .serviceRegistry(this.serviceRegistry) + .methodRegistry(this.methodRegistry) + .contentType(this.contentType) .errorMapper(DefaultErrorMapper.INSTANCE) .router(Routers.getRouter(RoundRobinServiceRouter.class)); } + /** + * List of all gateway registered in this Microservices node. + * + * @return gateways + * @deprecated use {@link MicroservicesContext#gateways()} by {@link Microservices#context()} + */ + @Deprecated public List gateways() { return gatewayBootstrap.gateways(); } + /** + * Get gateway registered in this Microservices node by id. + * + * @return gateway + * @deprecated use {@link MicroservicesContext#gateway(String)} by {@link Microservices#context()} + */ + @Deprecated public Gateway gateway(String id) { return gatewayBootstrap.gateway(id); } + /** + * Service endpoint. + * + * @return service endpoint + * @deprecated use {@link MicroservicesContext#serviceEndpoint()} by {@link + * Microservices#context()} + */ + @Deprecated public ServiceEndpoint serviceEndpoint() { return serviceEndpoint; } @@ -313,7 +345,10 @@ public ServiceEndpoint serviceEndpoint() { * * @param id service discovery id * @return service discovery context + * @deprecated use {@link MicroservicesContext#discovery(String)} by {@link + * Microservices#context()} */ + @Deprecated public ServiceDiscoveryContext discovery(String id) { return Optional.ofNullable(compositeDiscovery.contextMap.get(id)) .orElseThrow(() -> new NoSuchElementException("[discovery] id: " + id)); @@ -323,7 +358,10 @@ public ServiceDiscoveryContext discovery(String id) { * Function to subscribe and listen on {@code ServiceDiscoveryEvent} events. * * @return stream of {@code ServiceDiscoveryEvent} events + * @deprecated use {@link MicroservicesContext#listenDiscovery()} by {@link + * Microservices#context()} */ + @Deprecated public Flux listenDiscovery() { return compositeDiscovery.listen(); } @@ -334,7 +372,7 @@ public Flux listenDiscovery() { * @return result of shutdown */ public Mono shutdown() { - return Mono.fromRunnable(shutdown::onComplete).then(onShutdown); + return Mono.fromRunnable(this.shutdown::onComplete).then(this.onShutdown); } /** @@ -343,7 +381,7 @@ public Mono shutdown() { * @return signal of when shutdown completed */ public Mono onShutdown() { - return onShutdown; + return this.onShutdown; } private Mono doShutdown() { @@ -351,43 +389,138 @@ private Mono doShutdown() { () -> { LOGGER.info("[{}][doShutdown] Shutting down", id); return Mono.whenDelayError( - processBeforeDestroy(), - compositeDiscovery.shutdown(), - gatewayBootstrap.shutdown(), - transportBootstrap.shutdown()) + processBeforeDestroy(), + compositeDiscovery.shutdown(), + gatewayBootstrap.shutdown(), + transportBootstrap.shutdown()) .doOnSuccess(s -> LOGGER.info("[{}][doShutdown] Shutdown", id)); }); } private Mono processBeforeDestroy() { - return serviceFactory.shutdownServices(this.context).then(); + return serviceFactory.shutdownServices(this.microservicesContext).then(); } - private static final class Context implements MicroservicesContext { + private static class CompositeServiceDiscovery implements ServiceDiscovery { + + private final List> operatorList = new ArrayList<>(); + private final Map discoveryMap = new HashMap<>(); + private final Map contextMap = new ConcurrentHashMap<>(); + + // Subject + private final DirectProcessor subject = DirectProcessor.create(); + private final FluxSink sink = subject.sink(); - private final ServiceEndpoint serviceEndpoint; - private final Supplier serviceCallSupplier; - private final Flux events; + private final Disposable.Composite disposables = Disposables.composite(); + private Scheduler scheduler; - private Context(ServiceDiscovery serviceDiscovery, Supplier serviceCallSupplier) { - this.serviceEndpoint = serviceDiscovery.serviceEndpoint(); - this.serviceCallSupplier = serviceCallSupplier; - this.events = serviceDiscovery.listenDiscovery(); + private CompositeServiceDiscovery addOperator(UnaryOperator operator) { + this.operatorList.add(operator); + return this; + } + + private Mono createInstance(ServiceDiscoveryOptions options) { + for (UnaryOperator operator : operatorList) { + final ServiceDiscoveryOptions finalOptions = operator.apply(options); + final ServiceEndpoint serviceEndpoint = finalOptions.serviceEndpoint(); + final String id = finalOptions.id(); + discoveryMap.put( + id, finalOptions.discoveryFactory().createServiceDiscovery(serviceEndpoint)); + } + + scheduler = Schedulers.newSingle("composite-discovery", true); + + return Mono.just(this); + } + + private Mono startListen(Microservices microservices) { + return Mono.deferWithContext(context -> start()) + .doOnSubscribe( + s -> LOGGER.info("[{}][startListen] Starting", microservices.id)) + .doOnSuccess( + discovery -> LOGGER.info("[{}][startListen] Started", microservices.id)) + .doOnError( + ex -> + LOGGER.error( + "[{}][startListen] Exception occurred: {}", + microservices.id, + ex.toString())) + .subscriberContext( + context -> reactor.util.context.Context.of(Microservices.class, microservices)); } @Override - public ServiceEndpoint serviceEndpoint() { - return this.serviceEndpoint; + public Flux listen() { + return subject.onBackpressureBuffer(); } @Override - public ServiceCall serviceCall() { - return this.serviceCallSupplier.get(); + public Mono start() { + return Flux.fromIterable(discoveryMap.entrySet()) + .flatMap( + entry -> { + final String id = entry.getKey(); + final ServiceDiscovery discovery = entry.getValue(); + + return Mono.deferWithContext(context -> start0(discovery, context)) + .doOnSubscribe(s -> LOGGER.info("[discovery][{}][start] Starting", id)) + .doOnSuccess(avoid -> LOGGER.info("[discovery][{}][start] Started", id)) + .doOnError( + ex -> + LOGGER.error( + "[discovery][{}][start] Exception occurred: {}", id, ex.toString())) + .subscriberContext( + context -> + context.put( + ServiceDiscoveryContext.Builder.class, + ServiceDiscoveryContext.builder().id(id).discovery(discovery))); + }) + .then(); + } + + private Mono start0( + ServiceDiscovery discovery, Context innerMicroservicesContext) { + final Microservices microservices = innerMicroservicesContext.get(Microservices.class); + ServiceDiscoveryContext.Builder builder = + innerMicroservicesContext.get(ServiceDiscoveryContext.Builder.class); + + disposables.add( + discovery + .listen() + .publishOn(scheduler) + .doOnNext(event -> onDiscoveryEvent(microservices, event)) + .doOnNext(sink::next) + .subscribe()); + + return discovery + .start() + .doOnSuccess( + avoid -> { + ServiceDiscoveryContext discoveryContext = builder.build(); + contextMap.put(discoveryContext.id(), discoveryContext); + }); + } + + private void onDiscoveryEvent(Microservices microservices, ServiceDiscoveryEvent event) { + if (event.isEndpointAdded()) { + microservices.serviceRegistry.registerService(event.serviceEndpoint()); + } + if (event.isEndpointLeaving() || event.isEndpointRemoved()) { + microservices.serviceRegistry.unregisterService(event.serviceEndpoint().id()); + } } @Override - public Flux listenDiscoveryEvents() { - return this.events; + public Mono shutdown() { + return Mono.defer( + () -> { + disposables.dispose(); + return Mono.whenDelayError( + discoveryMap.values().stream() + .map(ServiceDiscovery::shutdown) + .collect(Collectors.toList())) + .then(Mono.fromRunnable(() -> scheduler.dispose())); + }); } } @@ -614,125 +747,6 @@ public Builder defaultPrincipalMapper( } } - private static class CompositeServiceDiscovery implements ServiceDiscovery { - - private final List> operatorList = new ArrayList<>(); - private final Map discoveryMap = new HashMap<>(); - private final Map contextMap = new ConcurrentHashMap<>(); - - // Subject - private final DirectProcessor subject = DirectProcessor.create(); - private final FluxSink sink = subject.sink(); - - private final Disposable.Composite disposables = Disposables.composite(); - private Scheduler scheduler; - - private CompositeServiceDiscovery addOperator(UnaryOperator operator) { - this.operatorList.add(operator); - return this; - } - - private Mono createInstance(ServiceDiscoveryOptions options) { - for (UnaryOperator operator : operatorList) { - final ServiceDiscoveryOptions finalOptions = operator.apply(options); - final ServiceEndpoint serviceEndpoint = finalOptions.serviceEndpoint(); - final String id = finalOptions.id(); - discoveryMap.put( - id, finalOptions.discoveryFactory().createServiceDiscovery(serviceEndpoint)); - } - - scheduler = Schedulers.newSingle("composite-discovery", true); - - return Mono.just(this); - } - - private Mono startListen(Microservices microservices) { - return Mono.deferWithContext(context -> start()) - .doOnSubscribe(s -> LOGGER.info("[{}][startListen] Starting", microservices.id())) - .doOnSuccess(discovery -> LOGGER.info("[{}][startListen] Started", microservices.id())) - .doOnError( - ex -> - LOGGER.error( - "[{}][startListen] Exception occurred: {}", - microservices.id(), - ex.toString())) - .subscriberContext( - context -> reactor.util.context.Context.of(Microservices.class, microservices)); - } - - @Override - public Flux listen() { - return subject.onBackpressureBuffer(); - } - - @Override - public Mono start() { - return Flux.fromIterable(discoveryMap.entrySet()) - .flatMap( - entry -> { - final String id = entry.getKey(); - final ServiceDiscovery discovery = entry.getValue(); - - return Mono.deferWithContext(context -> start0(discovery, context)) - .doOnSubscribe(s -> LOGGER.info("[discovery][{}][start] Starting", id)) - .doOnSuccess(avoid -> LOGGER.info("[discovery][{}][start] Started", id)) - .doOnError( - ex -> - LOGGER.error( - "[discovery][{}][start] Exception occurred: {}", id, ex.toString())) - .subscriberContext( - context -> - context.put( - ServiceDiscoveryContext.Builder.class, - ServiceDiscoveryContext.builder().id(id).discovery(discovery))); - }) - .then(); - } - - private Mono start0(ServiceDiscovery discovery, Context context) { - final Microservices microservices = context.get(Microservices.class); - ServiceDiscoveryContext.Builder builder = context.get(ServiceDiscoveryContext.Builder.class); - - disposables.add( - discovery - .listen() - .publishOn(scheduler) - .doOnNext(event -> onDiscoveryEvent(microservices, event)) - .doOnNext(sink::next) - .subscribe()); - - return discovery - .start() - .doOnSuccess( - avoid -> { - ServiceDiscoveryContext discoveryContext = builder.build(); - contextMap.put(discoveryContext.id(), discoveryContext); - }); - } - - private void onDiscoveryEvent(Microservices microservices, ServiceDiscoveryEvent event) { - if (event.isEndpointAdded()) { - microservices.serviceRegistry.registerService(event.serviceEndpoint()); - } - if (event.isEndpointLeaving() || event.isEndpointRemoved()) { - microservices.serviceRegistry.unregisterService(event.serviceEndpoint().id()); - } - } - - @Override - public Mono shutdown() { - return Mono.defer( - () -> { - disposables.dispose(); - return Mono.whenDelayError( - discoveryMap.values().stream() - .map(ServiceDiscovery::shutdown) - .collect(Collectors.toList())) - .then(Mono.fromRunnable(() -> scheduler.dispose())); - }); - } - } - private static class GatewayBootstrap { private final List> factories = new ArrayList<>(); @@ -755,20 +769,20 @@ private Mono start(Microservices microservices, GatewayOptions s -> LOGGER.info( "[{}][gateway][{}][start] Starting", - microservices.id(), + microservices.id, gateway.id())) .doOnSuccess( gateway1 -> LOGGER.info( "[{}][gateway][{}][start] Started, address: {}", - microservices.id(), + microservices.id, gateway1.id(), gateway1.address())) .doOnError( ex -> LOGGER.error( "[{}][gateway][{}][start] Exception occurred: {}", - microservices.id(), + microservices.id, gateway.id(), ex.toString())); }) @@ -812,14 +826,14 @@ public ServiceTransportBootstrap(Supplier transportSupplier) { } private Mono start(Microservices microservices) { - if (transportSupplier == NULL_SUPPLIER - || (serviceTransport = transportSupplier.get()) == null) { + if (this.transportSupplier == NULL_SUPPLIER + || (this.serviceTransport = this.transportSupplier.get()) == null) { return Mono.just(NULL_INSTANCE); } - return serviceTransport + return this.serviceTransport .start() - .doOnSuccess(transport -> serviceTransport = transport) // reset self + .doOnSuccess(transport -> this.serviceTransport = transport) // reset self .flatMap( transport -> serviceTransport.serverTransport().bind(microservices.methodRegistry)) .doOnSuccess(transport -> serverTransport = transport) @@ -833,51 +847,41 @@ private Mono start(Microservices microservices) { return this; }) .doOnSubscribe( - s -> LOGGER.info("[{}][serviceTransport][start] Starting", microservices.id())) + s -> + LOGGER.info( + "[{}][serviceTransport][start] Starting", microservices.id)) .doOnSuccess( transport -> LOGGER.info( "[{}][serviceTransport][start] Started, address: {}", - microservices.id(), + microservices.id, this.transportAddress)) .doOnError( ex -> LOGGER.error( "[{}][serviceTransport][start] Exception occurred: {}", - microservices.id(), + microservices.id, ex.toString())); } public Address address() { - return transportAddress; + return this.transportAddress; } private Mono shutdown() { return Mono.defer( () -> Flux.concatDelayError( - Optional.ofNullable(serverTransport) - .map(ServerTransport::stop) - .orElse(Mono.empty()), - Optional.ofNullable(serviceTransport) - .map(ServiceTransport::stop) - .orElse(Mono.empty())) + Optional.ofNullable(this.serverTransport) + .map(ServerTransport::stop) + .orElse(Mono.empty()), + Optional.ofNullable(this.serviceTransport) + .map(ServiceTransport::stop) + .orElse(Mono.empty())) .then()); } } - @SuppressWarnings("unused") - public interface MonitorMBean { - - String getServiceEndpoint(); - - String getAllServiceEndpoints(); - - String getServiceMethodInvokers(); - - String getServiceInfos(); - } - private static class JmxMonitorMBean implements MonitorMBean { private static final String OBJECT_NAME_FORMAT = "io.scalecube.services:name=%s@%s"; @@ -888,7 +892,8 @@ private static JmxMonitorMBean start(Microservices instance) throws Exception { MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer(); JmxMonitorMBean jmxMBean = new JmxMonitorMBean(instance); ObjectName objectName = - new ObjectName(String.format(OBJECT_NAME_FORMAT, instance.id(), System.nanoTime())); + new ObjectName( + String.format(OBJECT_NAME_FORMAT, instance.context().id(), System.nanoTime())); StandardMBean standardMBean = new StandardMBean(jmxMBean, MonitorMBean.class); mbeanServer.registerMBean(standardMBean, objectName); return jmxMBean; @@ -900,7 +905,7 @@ private JmxMonitorMBean(Microservices microservices) { @Override public String getServiceEndpoint() { - return String.valueOf(microservices); + return String.valueOf(this.microservices); } @Override @@ -952,4 +957,64 @@ private static String asString(ServiceInfo serviceInfo) { .toString(); } } + + @SuppressWarnings("unused") + public interface MonitorMBean { + + String getServiceEndpoint(); + + String getAllServiceEndpoints(); + + String getServiceMethodInvokers(); + + String getServiceInfos(); + } + + private final class MicroservicesContextImpl implements MicroservicesContext { + + @Override + public ServiceEndpoint serviceEndpoint() { + return Microservices.this.serviceEndpoint; + } + + @Override + public ServiceCall serviceCall() { + return Microservices.this.call(); + } + + @Override + public Flux listenDiscovery() { + return Microservices.this.compositeDiscovery.listen(); + } + + @Override + public ServiceDiscoveryContext discovery(String id) { + Map contextMap = + Microservices.this.compositeDiscovery.contextMap; + if (contextMap.containsKey(id)) { + return contextMap.get(id); + } + throw new NoSuchElementException("[discovery] id " + id); + } + + @Override + public List gateways() { + return Microservices.this.gatewayBootstrap.gateways(); + } + + @Override + public Gateway gateway(String id) { + return Microservices.this.gatewayBootstrap.gateway(id); + } + + @Override + public Address serviceAddress() { + return Microservices.this.transportBootstrap.address(); + } + + @Override + public String id() { + return Microservices.this.id; + } + } } diff --git a/services/src/test/java/io/scalecube/services/ErrorFlowTest.java b/services/src/test/java/io/scalecube/services/ErrorFlowTest.java index bda45ad31..445f74028 100644 --- a/services/src/test/java/io/scalecube/services/ErrorFlowTest.java +++ b/services/src/test/java/io/scalecube/services/ErrorFlowTest.java @@ -40,7 +40,7 @@ public static void initNodes() { .serviceFactory(ScalecubeServiceFactory.fromInstances(new GreetingServiceImpl())) .startAwait(); - final Address seedAddress = provider.discovery("provider").address(); + final Address seedAddress = provider.context().discovery("provider").address(); consumer = Microservices.builder() @@ -64,7 +64,8 @@ public static void shutdownNodes() { public void testCorruptedRequest() { Publisher req = consumer - .call() + .context() + .serviceCall() .requestOne(TestRequests.GREETING_CORRUPTED_PAYLOAD_REQUEST, GreetingResponse.class); assertThrows(InternalServiceException.class, () -> from(req).block()); } @@ -73,7 +74,8 @@ public void testCorruptedRequest() { public void testNotAuthorized() { Publisher req = consumer - .call() + .context() + .serviceCall() .requestOne(TestRequests.GREETING_UNAUTHORIZED_REQUEST, GreetingResponse.class); assertThrows(ForbiddenException.class, () -> from(req).block()); } @@ -81,13 +83,16 @@ public void testNotAuthorized() { @Test public void testNullRequestPayload() { Publisher req = - consumer.call().requestOne(TestRequests.GREETING_NULL_PAYLOAD, GreetingResponse.class); + consumer + .context() + .serviceCall() + .requestOne(TestRequests.GREETING_NULL_PAYLOAD, GreetingResponse.class); assertThrows(BadRequestException.class, () -> from(req).block()); } @Test public void testServiceUnavailable() { - StepVerifier.create(consumer.call().requestOne(TestRequests.NOT_FOUND_REQ)) + StepVerifier.create(consumer.context().serviceCall().requestOne(TestRequests.NOT_FOUND_REQ)) .expectError(ServiceUnavailableException.class) .verify(); } diff --git a/services/src/test/java/io/scalecube/services/ServiceAuthRemoteTest.java b/services/src/test/java/io/scalecube/services/ServiceAuthRemoteTest.java index 5376c73d5..8dd93c754 100644 --- a/services/src/test/java/io/scalecube/services/ServiceAuthRemoteTest.java +++ b/services/src/test/java/io/scalecube/services/ServiceAuthRemoteTest.java @@ -67,7 +67,7 @@ static void beforeAll() { .transport(RSocketServiceTransport::new) .startAwait(); - callerAddress = caller.discovery("caller").address(); + callerAddress = caller.context().discovery("caller").address(); principalMapper = authData -> new UserProfile(authData.get("name"), authData.get("role")); @@ -98,7 +98,7 @@ static void afterAll() { @DisplayName("Successful authentication") void successfulAuthentication() { SecuredService securedService = - caller.call().credentials(CREDENTIALS).api(SecuredService.class); + caller.context().serviceCall().credentials(CREDENTIALS).api(SecuredService.class); StepVerifier.create(securedService.helloWithRequest("Bob")) .assertNext(response -> assertEquals("Hello, Bob", response)) @@ -127,7 +127,7 @@ void failedAuthenticationWhenAuthenticatorNotProvided() { .startAwait(); SecuredService securedService = - caller.call().credentials(CREDENTIALS).api(SecuredService.class); + caller.context().serviceCall().credentials(CREDENTIALS).api(SecuredService.class); Consumer verifyError = th -> { @@ -153,7 +153,7 @@ void failedAuthenticationWhenAuthenticatorNotProvided() { @Test @DisplayName("Authentication failed with invalid or empty credentials") void failedAuthenticationWithInvalidOrEmptyCredentials() { - SecuredService securedService = caller.call().api(SecuredService.class); + SecuredService securedService = caller.context().serviceCall().api(SecuredService.class); Consumer verifyError = th -> { @@ -189,7 +189,7 @@ void successfulAuthenticationOnPartiallySecuredService() { .startAwait(); PartiallySecuredService proxy = - caller.call().credentials(CREDENTIALS).api(PartiallySecuredService.class); + caller.context().serviceCall().credentials(CREDENTIALS).api(PartiallySecuredService.class); StepVerifier.create(proxy.securedMethod("Alice")) .assertNext(response -> assertEquals("Hello, Alice", response)) @@ -211,7 +211,8 @@ void successfulCallOfPublicMethodWithoutAuthentication() { .build()) .startAwait(); - PartiallySecuredService proxy = caller.call().api(PartiallySecuredService.class); + PartiallySecuredService proxy = + caller.context().serviceCall().api(PartiallySecuredService.class); StepVerifier.create(proxy.publicMethod("Alice")) .assertNext(response -> assertEquals("Hello, Alice", response)) diff --git a/services/src/test/java/io/scalecube/services/ServiceCallLocalTest.java b/services/src/test/java/io/scalecube/services/ServiceCallLocalTest.java index 3140830ed..ea857fb5a 100644 --- a/services/src/test/java/io/scalecube/services/ServiceCallLocalTest.java +++ b/services/src/test/java/io/scalecube/services/ServiceCallLocalTest.java @@ -52,7 +52,8 @@ public static void tearDown() { @Test public void test_local_async_no_params() { - ServiceCall serviceCall = provider.call().router(RoundRobinServiceRouter.class); + ServiceCall serviceCall = + provider.context().serviceCall().router(RoundRobinServiceRouter.class); // call the service. Publisher future = serviceCall.requestOne(GREETING_NO_PARAMS_REQUEST); @@ -74,20 +75,20 @@ private static Microservices serviceProvider() { @Test public void test_local_void_greeting() { // WHEN - provider.call().oneWay(GREETING_VOID_REQ).block(Duration.ofSeconds(TIMEOUT)); + provider.context().serviceCall().oneWay(GREETING_VOID_REQ).block(Duration.ofSeconds(TIMEOUT)); } @Test public void test_local_failng_void_greeting() { - StepVerifier.create(provider.call().oneWay(GREETING_FAILING_VOID_REQ)) + StepVerifier.create(provider.context().serviceCall().oneWay(GREETING_FAILING_VOID_REQ)) .expectErrorMessage(GREETING_FAILING_VOID_REQ.data().toString()) .verify(Duration.ofSeconds(TIMEOUT)); } @Test public void test_local_throwing_void_greeting() { - StepVerifier.create(provider.call().oneWay(GREETING_THROWING_VOID_REQ)) + StepVerifier.create(provider.context().serviceCall().oneWay(GREETING_THROWING_VOID_REQ)) .expectErrorMessage(GREETING_THROWING_VOID_REQ.data().toString()) .verify(Duration.ofSeconds(TIMEOUT)); } @@ -98,7 +99,9 @@ public void test_local_fail_greeting() { Throwable exception = assertThrows( ServiceException.class, - () -> Mono.from(provider.call().requestOne(GREETING_FAIL_REQ)).block(timeout)); + () -> + Mono.from(provider.context().serviceCall().requestOne(GREETING_FAIL_REQ)) + .block(timeout)); assertEquals("GreetingRequest{name='joe'}", exception.getMessage()); } @@ -109,14 +112,17 @@ public void test_local_exception_greeting() { Throwable exception = assertThrows( ServiceException.class, - () -> Mono.from(provider.call().requestOne(GREETING_ERROR_REQ)).block(timeout)); + () -> + Mono.from(provider.context().serviceCall().requestOne(GREETING_ERROR_REQ)) + .block(timeout)); } @Test public void test_local_async_greeting_return_GreetingResponse() { // When - Publisher resultFuture = provider.call().requestOne(GREETING_REQUEST_REQ); + Publisher resultFuture = + provider.context().serviceCall().requestOne(GREETING_REQUEST_REQ); // Then ServiceMessage result = Mono.from(resultFuture).block(Duration.ofSeconds(TIMEOUT)); @@ -128,7 +134,7 @@ public void test_local_async_greeting_return_GreetingResponse() { @Test public void test_local_greeting_request_timeout_expires() { - ServiceCall service = provider.call(); + ServiceCall service = provider.context().serviceCall(); // call the service. Publisher future = service.requestOne(GREETING_REQUEST_TIMEOUT_REQ); @@ -141,7 +147,8 @@ public void test_local_greeting_request_timeout_expires() { @Test public void test_local_async_greeting_return_Message() { - ServiceMessage result = provider.call().requestOne(GREETING_REQUEST_REQ).block(timeout); + ServiceMessage result = + provider.context().serviceCall().requestOne(GREETING_REQUEST_REQ).block(timeout); // print the greeting. GreetingResponse responseData = result.data(); @@ -153,8 +160,9 @@ public void test_local_async_greeting_return_Message() { @Test public void test_remote_mono_empty_request_response_greeting_messsage() { StepVerifier.create( - provider - .call() + provider + .context() + .serviceCall() .requestOne(GREETING_EMPTY_REQUEST_RESPONSE, EmptyGreetingResponse.class)) .expectNextMatches(resp -> resp.data() instanceof EmptyGreetingResponse) .expectComplete() @@ -164,7 +172,7 @@ public void test_remote_mono_empty_request_response_greeting_messsage() { @Test public void test_async_greeting_return_string_service_not_found_error_case() { - ServiceCall service = provider.call(); + ServiceCall service = provider.context().serviceCall(); try { // call the service. diff --git a/services/src/test/java/io/scalecube/services/ServiceCallRemoteTest.java b/services/src/test/java/io/scalecube/services/ServiceCallRemoteTest.java index 0ac05537e..8d8abb023 100644 --- a/services/src/test/java/io/scalecube/services/ServiceCallRemoteTest.java +++ b/services/src/test/java/io/scalecube/services/ServiceCallRemoteTest.java @@ -70,7 +70,8 @@ private static Microservices serviceProvider(Object service) { "serviceProvider", endpoint -> new ScalecubeServiceDiscovery(endpoint) - .membership(cfg -> cfg.seedMembers(gateway.discovery("gateway").address()))) + .membership( + cfg -> cfg.seedMembers(gateway.context().discovery("gateway").address()))) .transport(RSocketServiceTransport::new) .serviceFactory(ScalecubeServiceFactory.fromInstances(service)) .startAwait(); @@ -79,7 +80,7 @@ private static Microservices serviceProvider(Object service) { @Test public void test_remote_async_greeting_no_params() { - ServiceCall serviceCall = gateway.call(); + ServiceCall serviceCall = gateway.context().serviceCall(); // call the service. Publisher future = @@ -93,13 +94,18 @@ public void test_remote_async_greeting_no_params() { @Test public void test_remote_void_greeting() { // When - StepVerifier.create(gateway.call().oneWay(GREETING_VOID_REQ)).expectComplete().verify(TIMEOUT); + StepVerifier.create(gateway.context().serviceCall().oneWay(GREETING_VOID_REQ)) + .expectComplete() + .verify(TIMEOUT); } @Test public void test_remote_mono_empty_request_response_greeting_messsage() { StepVerifier.create( - gateway.call().requestOne(GREETING_EMPTY_REQUEST_RESPONSE, EmptyGreetingResponse.class)) + gateway + .context() + .serviceCall() + .requestOne(GREETING_EMPTY_REQUEST_RESPONSE, EmptyGreetingResponse.class)) .expectNextMatches(resp -> resp.data() instanceof EmptyGreetingResponse) .expectComplete() .verify(TIMEOUT); @@ -109,7 +115,8 @@ public void test_remote_mono_empty_request_response_greeting_messsage() { public void test_remote_failing_void_greeting() { // When - StepVerifier.create(gateway.call().requestOne(GREETING_FAILING_VOID_REQ, Void.class)) + StepVerifier.create( + gateway.context().serviceCall().requestOne(GREETING_FAILING_VOID_REQ, Void.class)) .expectErrorMessage(GREETING_FAILING_VOID_REQ.data().toString()) .verify(TIMEOUT); } @@ -117,7 +124,7 @@ public void test_remote_failing_void_greeting() { @Test public void test_remote_throwing_void_greeting() { // When - StepVerifier.create(gateway.call().oneWay(GREETING_THROWING_VOID_REQ)) + StepVerifier.create(gateway.context().serviceCall().oneWay(GREETING_THROWING_VOID_REQ)) .expectErrorMessage(GREETING_THROWING_VOID_REQ.data().toString()) .verify(TIMEOUT); } @@ -129,7 +136,11 @@ public void test_remote_fail_greeting() { assertThrows( ServiceException.class, () -> - Mono.from(gateway.call().requestOne(GREETING_FAIL_REQ, GreetingResponse.class)) + Mono.from( + gateway + .context() + .serviceCall() + .requestOne(GREETING_FAIL_REQ, GreetingResponse.class)) .block(TIMEOUT)); assertEquals("GreetingRequest{name='joe'}", exception.getMessage()); } @@ -142,7 +153,11 @@ public void test_remote_exception_void() { assertThrows( ServiceException.class, () -> - Mono.from(gateway.call().requestOne(GREETING_ERROR_REQ, GreetingResponse.class)) + Mono.from( + gateway + .context() + .serviceCall() + .requestOne(GREETING_ERROR_REQ, GreetingResponse.class)) .block(TIMEOUT)); assertEquals("GreetingRequest{name='joe'}", exception.getMessage()); } @@ -150,7 +165,8 @@ public void test_remote_exception_void() { @Test public void test_remote_async_greeting_return_string() { - Publisher resultFuture = gateway.call().requestOne(GREETING_REQ, String.class); + Publisher resultFuture = + gateway.context().serviceCall().requestOne(GREETING_REQ, String.class); // Then ServiceMessage result = Mono.from(resultFuture).block(TIMEOUT); @@ -164,7 +180,7 @@ public void test_remote_async_greeting_return_GreetingResponse() { // When Publisher result = - gateway.call().requestOne(GREETING_REQUEST_REQ, GreetingResponse.class); + gateway.context().serviceCall().requestOne(GREETING_REQUEST_REQ, GreetingResponse.class); // Then GreetingResponse greeting = Mono.from(result).block(TIMEOUT).data(); @@ -174,7 +190,7 @@ public void test_remote_async_greeting_return_GreetingResponse() { @Test public void test_remote_greeting_request_timeout_expires() { - ServiceCall service = gateway.call(); + ServiceCall service = gateway.context().serviceCall(); // call the service. Publisher future = service.requestOne(GREETING_REQUEST_TIMEOUT_REQ); @@ -186,7 +202,7 @@ public void test_remote_greeting_request_timeout_expires() { // Since here and below tests were not reviewed [sergeyr] @Test public void test_remote_async_greeting_return_Message() { - ServiceCall service = gateway.call(); + ServiceCall service = gateway.context().serviceCall(); // call the service. Publisher future = service.requestOne(GREETING_REQUEST_REQ); @@ -206,7 +222,7 @@ public void test_remote_async_greeting_return_Message() { public void test_remote_dispatcher_remote_greeting_request_completes_before_timeout() { Publisher result = - gateway.call().requestOne(GREETING_REQUEST_REQ, GreetingResponse.class); + gateway.context().serviceCall().requestOne(GREETING_REQUEST_REQ, GreetingResponse.class); GreetingResponse greetings = Mono.from(result).block(TIMEOUT).data(); System.out.println("greeting_request_completes_before_timeout : " + greetings.getResult()); @@ -218,7 +234,8 @@ public void test_service_address_lookup_occur_only_after_subscription() { Flux quotes = gateway - .call() + .context() + .serviceCall() .requestMany( ServiceMessage.builder() .qualifier(QuoteService.NAME, "onlyOneAndThenNever") @@ -240,7 +257,7 @@ public void test_service_address_lookup_occur_only_after_subscription() { @Disabled("https://github.com/scalecube/scalecube-services/issues/742") public void test_many_stream_block_first() { - ServiceCall call = gateway.call(); + ServiceCall call = gateway.context().serviceCall(); ServiceMessage request = TestRequests.GREETING_MANY_STREAM_30; diff --git a/services/src/test/java/io/scalecube/services/ServiceLocalTest.java b/services/src/test/java/io/scalecube/services/ServiceLocalTest.java index 5cb3c672e..476eea476 100644 --- a/services/src/test/java/io/scalecube/services/ServiceLocalTest.java +++ b/services/src/test/java/io/scalecube/services/ServiceLocalTest.java @@ -44,7 +44,7 @@ public void cleanUp() { @Test public void test_local_greeting_request_completes_before_timeout() { - GreetingService service = microservices.call().api(GreetingService.class); + GreetingService service = microservices.context().serviceCall().api(GreetingService.class); // call the service. GreetingResponse result = @@ -214,7 +214,7 @@ void test_local_greeting_message() { .verify(timeout); // using serviceCall directly - ServiceCall serviceCall = microservices.call(); + ServiceCall serviceCall = microservices.context().serviceCall(); StepVerifier.create( serviceCall.requestOne( @@ -310,6 +310,9 @@ public void test_local_bidi_greeting_expect_GreetingResponse() { } private GreetingService createProxy(Microservices gateway) { - return gateway.call().api(GreetingService.class); // create proxy for GreetingService API + return gateway + .context() + .serviceCall() + .api(GreetingService.class); // create proxy for GreetingService API } } diff --git a/services/src/test/java/io/scalecube/services/ServiceRegistryTest.java b/services/src/test/java/io/scalecube/services/ServiceRegistryTest.java index 8d7f025c5..24996ec6a 100644 --- a/services/src/test/java/io/scalecube/services/ServiceRegistryTest.java +++ b/services/src/test/java/io/scalecube/services/ServiceRegistryTest.java @@ -50,9 +50,9 @@ public void test_added_removed_registration_events(MetadataCodec metadataCodec) .transport(RSocketServiceTransport::new) .startAwait(); - seed.listenDiscovery().subscribe(events); + seed.context().listenDiscovery().subscribe(events); - Address seedAddress = seed.discovery("seed").address(); + Address seedAddress = seed.context().discovery("seed").address(); Microservices ms1 = Microservices.builder() @@ -96,9 +96,9 @@ public void test_listen_to_discovery_events(MetadataCodec metadataCodec) { .startAwait(); cluster.add(seed); - seed.listenDiscovery().subscribe(processor); + seed.context().listenDiscovery().subscribe(processor); - Address seedAddress = seed.discovery("seed").address(); + Address seedAddress = seed.context().discovery("seed").address(); StepVerifier.create(processor) .then( @@ -107,7 +107,8 @@ public void test_listen_to_discovery_events(MetadataCodec metadataCodec) { Microservices.builder() .discovery("ms1", defServiceDiscovery(seedAddress, metadataCodec)) .transport(RSocketServiceTransport::new) - .serviceFactory(ScalecubeServiceFactory.fromInstances(new GreetingServiceImpl())) + .serviceFactory( + ScalecubeServiceFactory.fromInstances(new GreetingServiceImpl())) .startAwait(); cluster.add(ms1); }) @@ -135,7 +136,8 @@ public void test_listen_to_discovery_events(MetadataCodec metadataCodec) { .thenCancel() .verify(TIMEOUT); - StepVerifier.create(seed.call().api(AnnotationService.class).serviceDiscoveryEventTypes()) + StepVerifier.create( + seed.context().serviceCall().api(AnnotationService.class).serviceDiscoveryEventTypes()) .assertNext(type -> assertEquals(ENDPOINT_ADDED, type)) .assertNext(type -> assertEquals(ENDPOINT_ADDED, type)) .assertNext(type -> assertEquals(ENDPOINT_LEAVING, type)) @@ -164,9 +166,9 @@ public void test_delayed_listen_to_discovery_events(MetadataCodec metadataCodec) .startAwait(); cluster.add(seed); - seed.listenDiscovery().subscribe(processor); + seed.context().listenDiscovery().subscribe(processor); - Address seedAddress = seed.discovery("seed").address(); + Address seedAddress = seed.context().discovery("seed").address(); StepVerifier.create(processor) .then( @@ -188,7 +190,8 @@ public void test_delayed_listen_to_discovery_events(MetadataCodec metadataCodec) Microservices.builder() .discovery("ms2", defServiceDiscovery(seedAddress, metadataCodec)) .transport(RSocketServiceTransport::new) - .serviceFactory(ScalecubeServiceFactory.fromInstances(new GreetingServiceImpl())) + .serviceFactory( + ScalecubeServiceFactory.fromInstances(new GreetingServiceImpl())) .startAwait(); cluster.add(ms2); }) @@ -196,7 +199,8 @@ public void test_delayed_listen_to_discovery_events(MetadataCodec metadataCodec) .thenCancel() .verify(TIMEOUT); - StepVerifier.create(seed.call().api(AnnotationService.class).serviceDiscoveryEventTypes()) + StepVerifier.create( + seed.context().serviceCall().api(AnnotationService.class).serviceDiscoveryEventTypes()) .assertNext(type -> assertEquals(ENDPOINT_ADDED, type)) .assertNext(type -> assertEquals(ENDPOINT_ADDED, type)) .thenCancel() diff --git a/services/src/test/java/io/scalecube/services/ServiceRemoteTest.java b/services/src/test/java/io/scalecube/services/ServiceRemoteTest.java index 027824a36..a23dc9028 100644 --- a/services/src/test/java/io/scalecube/services/ServiceRemoteTest.java +++ b/services/src/test/java/io/scalecube/services/ServiceRemoteTest.java @@ -46,7 +46,7 @@ public class ServiceRemoteTest extends BaseTest { public static void setup() { Hooks.onOperatorDebug(); gateway = gateway(); - gatewayAddress = gateway.discovery("gateway").address(); + gatewayAddress = gateway.context().discovery("gateway").address(); provider = serviceProvider(); } @@ -84,7 +84,7 @@ private static Microservices serviceProvider() { public void test_remote_greeting_request_completes_before_timeout() { Duration duration = Duration.ofSeconds(1); - GreetingService service = gateway.call().api(GreetingService.class); + GreetingService service = gateway.context().serviceCall().api(GreetingService.class); // call the service. Mono result = @@ -95,7 +95,7 @@ public void test_remote_greeting_request_completes_before_timeout() { @Test public void test_remote_void_greeting() throws Exception { - GreetingService service = gateway.call().api(GreetingService.class); + GreetingService service = gateway.context().serviceCall().api(GreetingService.class); // call the service. service.greetingVoid(new GreetingRequest("joe")).block(Duration.ofSeconds(3)); @@ -108,7 +108,7 @@ public void test_remote_void_greeting() throws Exception { @Test public void test_remote_failing_void_greeting() { - GreetingService service = gateway.call().api(GreetingService.class); + GreetingService service = gateway.context().serviceCall().api(GreetingService.class); GreetingRequest request = new GreetingRequest("joe"); // call the service. @@ -119,7 +119,7 @@ public void test_remote_failing_void_greeting() { @Test public void test_remote_throwing_void_greeting() { - GreetingService service = gateway.call().api(GreetingService.class); + GreetingService service = gateway.context().serviceCall().api(GreetingService.class); GreetingRequest request = new GreetingRequest("joe"); // call the service. @@ -228,7 +228,7 @@ void test_remote_greeting_message() { .verify(TIMEOUT); // using serviceCall directly - ServiceCall serviceCall = gateway.call(); + ServiceCall serviceCall = gateway.context().serviceCall(); StepVerifier.create( serviceCall.requestOne( @@ -272,11 +272,13 @@ public void test_remote_serviceA_calls_serviceB_using_setter() { Microservices.builder() .discovery("provider", ServiceRemoteTest::serviceDiscovery) .transport(RSocketServiceTransport::new) - .serviceFactory(ScalecubeServiceFactory.fromInstances(new CoarseGrainedServiceImpl())) // add service a and b + .serviceFactory( + ScalecubeServiceFactory.fromInstances( + new CoarseGrainedServiceImpl())) // add service a and b .startAwait(); // Get a proxy to the service api. - CoarseGrainedService service = gateway.call().api(CoarseGrainedService.class); + CoarseGrainedService service = gateway.context().serviceCall().api(CoarseGrainedService.class); Publisher future = service.callGreeting("joe"); @@ -299,7 +301,7 @@ public void test_remote_serviceA_calls_serviceB() { .startAwait(); // Get a proxy to the service api. - CoarseGrainedService service = gateway.call().api(CoarseGrainedService.class); + CoarseGrainedService service = gateway.context().serviceCall().api(CoarseGrainedService.class); Publisher future = service.callGreeting("joe"); assertEquals(" hello to: joe", Mono.from(future).block(Duration.ofSeconds(1))); provider.shutdown().then(Mono.delay(TIMEOUT2)).block(); @@ -319,7 +321,7 @@ public void test_remote_serviceA_calls_serviceB_with_timeout() { .startAwait(); // Get a proxy to the service api. - CoarseGrainedService service = gateway.call().api(CoarseGrainedService.class); + CoarseGrainedService service = gateway.context().serviceCall().api(CoarseGrainedService.class); InternalServiceException exception = assertThrows( InternalServiceException.class, @@ -344,7 +346,7 @@ public void test_remote_serviceA_calls_serviceB_with_dispatcher() { .startAwait(); // Get a proxy to the service api. - CoarseGrainedService service = gateway.call().api(CoarseGrainedService.class); + CoarseGrainedService service = gateway.context().serviceCall().api(CoarseGrainedService.class); String response = service.callGreetingWithDispatcher("joe").block(Duration.ofSeconds(5)); assertEquals(response, " hello to: joe"); @@ -428,12 +430,12 @@ public void test_services_contribute_to_cluster_metadata() { .serviceFactory(ScalecubeServiceFactory.fromInstances(new GreetingServiceImpl())) .startAwait(); - assertTrue(ms.serviceEndpoint().tags().containsKey("HOSTNAME")); + assertTrue(ms.context().serviceEndpoint().tags().containsKey("HOSTNAME")); } @Test public void test_remote_mono_empty_greeting() { - GreetingService service = gateway.call().api(GreetingService.class); + GreetingService service = gateway.context().serviceCall().api(GreetingService.class); // call the service. StepVerifier.create(service.greetingMonoEmpty(new GreetingRequest("empty"))) @@ -443,7 +445,7 @@ public void test_remote_mono_empty_greeting() { @Test public void test_remote_mono_empty_request_response_greeting() { - GreetingService service = gateway.call().api(GreetingService.class); + GreetingService service = gateway.context().serviceCall().api(GreetingService.class); // call the service. StepVerifier.create(service.emptyGreeting(new EmptyGreetingRequest())) @@ -454,7 +456,7 @@ public void test_remote_mono_empty_request_response_greeting() { @Test public void test_remote_flux_empty_greeting() { - GreetingService service = gateway.call().api(GreetingService.class); + GreetingService service = gateway.context().serviceCall().api(GreetingService.class); // call the service. StepVerifier.create(service.greetingFluxEmpty(new GreetingRequest("empty"))) @@ -464,7 +466,7 @@ public void test_remote_flux_empty_greeting() { @Disabled("https://github.com/scalecube/scalecube-services/issues/742") public void test_many_stream_block_first() { - GreetingService service = gateway.call().api(GreetingService.class); + GreetingService service = gateway.context().serviceCall().api(GreetingService.class); for (int i = 0; i < 100; i++) { //noinspection ConstantConditions @@ -474,7 +476,10 @@ public void test_many_stream_block_first() { } private GreetingService createProxy() { - return gateway.call().api(GreetingService.class); // create proxy for GreetingService API + return gateway + .context() + .serviceCall() + .api(GreetingService.class); // create proxy for GreetingService API } private static ServiceDiscovery serviceDiscovery(ServiceEndpoint endpoint) { diff --git a/services/src/test/java/io/scalecube/services/StreamingServiceTest.java b/services/src/test/java/io/scalecube/services/StreamingServiceTest.java index 1f24bbfcb..2afe316ee 100644 --- a/services/src/test/java/io/scalecube/services/StreamingServiceTest.java +++ b/services/src/test/java/io/scalecube/services/StreamingServiceTest.java @@ -34,7 +34,7 @@ public static void setup() { .defaultDataDecoder(ServiceMessageCodec::decodeData) .startAwait(); - final Address gatewayAddress = gateway.discovery("gateway").address(); + final Address gatewayAddress = gateway.context().discovery("gateway").address(); node = Microservices.builder() @@ -54,7 +54,8 @@ public void test_quotes() throws InterruptedException { CountDownLatch latch = new CountDownLatch(3); Disposable sub = - node.call() + node.context() + .serviceCall() .api(QuoteService.class) .quotes() .subscribe( @@ -70,7 +71,7 @@ public void test_quotes() throws InterruptedException { @Test public void test_local_quotes_service() { - QuoteService service = node.call().api(QuoteService.class); + QuoteService service = node.context().serviceCall().api(QuoteService.class); int expected = 3; List list = service.quotes().take(Duration.ofMillis(3500)).collectList().block(); @@ -84,7 +85,7 @@ public void test_remote_quotes_service() throws InterruptedException { CountDownLatch latch1 = new CountDownLatch(3); CountDownLatch latch2 = new CountDownLatch(3); - QuoteService service = gateway.call().api(QuoteService.class); + QuoteService service = gateway.context().serviceCall().api(QuoteService.class); service.snapshot(3).subscribe(onNext -> latch1.countDown()); service.snapshot(3).subscribe(onNext -> latch2.countDown()); @@ -100,7 +101,7 @@ public void test_remote_quotes_service() throws InterruptedException { public void test_quotes_batch() throws InterruptedException { int streamBound = 1000; - QuoteService service = gateway.call().api(QuoteService.class); + QuoteService service = gateway.context().serviceCall().api(QuoteService.class); CountDownLatch latch1 = new CountDownLatch(streamBound); final Disposable sub1 = service.snapshot(streamBound).subscribe(onNext -> latch1.countDown()); @@ -115,7 +116,7 @@ public void test_quotes_batch() throws InterruptedException { public void test_call_quotes_snapshot() { int batchSize = 1000; - ServiceCall serviceCall = gateway.call(); + ServiceCall serviceCall = gateway.context().serviceCall(); ServiceMessage message = ServiceMessage.builder().qualifier(QuoteService.NAME, "snapshot").data(batchSize).build(); @@ -128,14 +129,14 @@ public void test_call_quotes_snapshot() { @Test public void test_just_once() { - QuoteService service = gateway.call().api(QuoteService.class); + QuoteService service = gateway.context().serviceCall().api(QuoteService.class); assertEquals("1", service.justOne().block(Duration.ofSeconds(2))); } @Test public void test_just_one_message() { - ServiceCall service = gateway.call(); + ServiceCall service = gateway.context().serviceCall(); ServiceMessage justOne = ServiceMessage.builder().qualifier(QuoteService.NAME, "justOne").build(); @@ -149,7 +150,7 @@ public void test_just_one_message() { @Test public void test_scheduled_messages() { - ServiceCall serviceCall = gateway.call(); + ServiceCall serviceCall = gateway.context().serviceCall(); ServiceMessage scheduled = ServiceMessage.builder().qualifier(QuoteService.NAME, "scheduled").data(1000).build(); @@ -164,7 +165,7 @@ public void test_scheduled_messages() { @Test public void test_unknown_method() { - ServiceCall service = gateway.call(); + ServiceCall service = gateway.context().serviceCall(); ServiceMessage scheduled = ServiceMessage.builder().qualifier(QuoteService.NAME, "unknonwn").build(); @@ -180,7 +181,7 @@ public void test_unknown_method() { public void test_snapshot_completes() { int batchSize = 1000; - ServiceCall serviceCall = gateway.call(); + ServiceCall serviceCall = gateway.context().serviceCall(); ServiceMessage message = ServiceMessage.builder().qualifier(QuoteService.NAME, "snapshot").data(batchSize).build(); diff --git a/services/src/test/java/io/scalecube/services/routings/RoutersTest.java b/services/src/test/java/io/scalecube/services/routings/RoutersTest.java index 8d1420849..8b6539549 100644 --- a/services/src/test/java/io/scalecube/services/routings/RoutersTest.java +++ b/services/src/test/java/io/scalecube/services/routings/RoutersTest.java @@ -60,7 +60,7 @@ public static void setup() { .transport(RSocketServiceTransport::new) .startAwait(); - gatewayAddress = gateway.discovery("gateway").address(); + gatewayAddress = gateway.context().discovery("gateway").address(); // Create microservices instance cluster. provider1 = @@ -136,7 +136,7 @@ public void test_router_factory() { @Test public void test_round_robin() { - ServiceCall service = gateway.call(); + ServiceCall service = gateway.context().serviceCall(); // call the service. GreetingResponse result1 = @@ -158,7 +158,7 @@ public void test_remote_service_tags() throws Exception { CanaryService service = gateway - .call() + .context().serviceCall() .router(Routers.getRouter(WeightedRandomRouter.class)) .api(CanaryService.class); @@ -185,7 +185,7 @@ public void test_remote_service_tags() throws Exception { public void tesTagsFromAnnotation() { ServiceCall serviceCall = provider3 - .call() + .context().serviceCall() .router( (req, mes) -> { ServiceReference tagServiceRef = req.listServiceReferences().get(0); @@ -207,7 +207,7 @@ public void test_tag_selection_logic() { ServiceCall service = gateway - .call() + .context().serviceCall() .router( (reg, msg) -> reg.listServiceReferences().stream() @@ -230,7 +230,7 @@ public void test_tag_request_selection_logic() { ServiceCall service = gateway - .call() + .context().serviceCall() .router( (reg, msg) -> reg.listServiceReferences().stream() @@ -256,7 +256,7 @@ public void test_tag_request_selection_logic() { public void test_service_tags() throws Exception { TimeUnit.SECONDS.sleep(3); - ServiceCall service = gateway.call().router(WeightedRandomRouter.class); + ServiceCall service = gateway.context().serviceCall().router(WeightedRandomRouter.class); ServiceMessage req = ServiceMessage.builder() diff --git a/services/src/test/java/io/scalecube/services/routings/ServiceTagsExample.java b/services/src/test/java/io/scalecube/services/routings/ServiceTagsExample.java index 848e3929a..a3dc33562 100644 --- a/services/src/test/java/io/scalecube/services/routings/ServiceTagsExample.java +++ b/services/src/test/java/io/scalecube/services/routings/ServiceTagsExample.java @@ -26,7 +26,7 @@ public static void main(String[] args) { .transport(RSocketServiceTransport::new) .startAwait(); - Address seedAddress = gateway.discovery("gateway").address(); + Address seedAddress = gateway.context().discovery("gateway").address(); Microservices services1 = Microservices.builder() @@ -57,7 +57,7 @@ public static void main(String[] args) { .startAwait(); CanaryService service = - gateway.call().router(WeightedRandomRouter.class).api(CanaryService.class); + gateway.context().serviceCall().router(WeightedRandomRouter.class).api(CanaryService.class); for (int i = 0; i < 10; i++) { Mono.from(service.greeting(new GreetingRequest("joe"))) diff --git a/services/src/test/java/io/scalecube/services/sut/AnnotationServiceImpl.java b/services/src/test/java/io/scalecube/services/sut/AnnotationServiceImpl.java index 6ccb7569d..a8b84cfe3 100644 --- a/services/src/test/java/io/scalecube/services/sut/AnnotationServiceImpl.java +++ b/services/src/test/java/io/scalecube/services/sut/AnnotationServiceImpl.java @@ -13,7 +13,7 @@ public class AnnotationServiceImpl implements AnnotationService { @AfterConstruct void init(MicroservicesContext microservices) { this.serviceDiscoveryEvents = ReplayProcessor.create(); - microservices.listenDiscoveryEvents().subscribe(serviceDiscoveryEvents); + microservices.listenDiscovery().subscribe(serviceDiscoveryEvents); } @Override diff --git a/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketNettyColocatedEventLoopGroupTest.java b/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketNettyColocatedEventLoopGroupTest.java index e2117ac9a..6a23706ea 100644 --- a/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketNettyColocatedEventLoopGroupTest.java +++ b/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketNettyColocatedEventLoopGroupTest.java @@ -34,7 +34,7 @@ public void setUp() { .transport(RSocketServiceTransport::new) .startAwait(); - final Address gatewayAddress = this.gateway.discovery("gateway").address(); + final Address gatewayAddress = this.gateway.context().discovery("gateway").address(); Microservices facade = Microservices.builder() @@ -47,7 +47,7 @@ public void setUp() { .serviceFactory(ScalecubeServiceFactory.fromInstances(new Facade())) .startAwait(); - final Address facadeAddress = facade.discovery("facade").address(); + final Address facadeAddress = facade.context().discovery("facade").address(); PingService pingService = () -> Mono.just(Thread.currentThread().getName()); this.ping = @@ -76,7 +76,7 @@ public void setUp() { @Test public void testColocatedEventLoopGroup() { - ServiceCall call = gateway.call(); + ServiceCall call = gateway.context().serviceCall(); FacadeService facade = call.api(FacadeService.class); diff --git a/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketServiceTransportTest.java b/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketServiceTransportTest.java index ba9794e87..f58e7ac58 100644 --- a/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketServiceTransportTest.java +++ b/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketServiceTransportTest.java @@ -45,7 +45,7 @@ public void setUp() { .transport(RSocketServiceTransport::new) .startAwait(); - final Address gatewayAddress = this.gateway.discovery("gateway").address(); + final Address gatewayAddress = this.gateway.context().discovery("gateway").address(); serviceNode = Microservices.builder() @@ -79,10 +79,11 @@ public void test_remote_node_died_mono_never() throws Exception { AtomicReference sub1 = new AtomicReference<>(null); AtomicReference exceptionHolder = new AtomicReference<>(null); - ServiceCall serviceCall = gateway.call(); + ServiceCall serviceCall = gateway.context().serviceCall(); sub1.set(serviceCall.requestOne(JUST_NEVER).doOnError(exceptionHolder::set).subscribe()); gateway + .context() .listenDiscovery() .filter(ServiceDiscoveryEvent::isEndpointRemoved) .subscribe(onNext -> latch1.countDown(), System.err::println); @@ -107,10 +108,11 @@ public void test_remote_node_died_many_never() throws Exception { AtomicReference sub1 = new AtomicReference<>(null); AtomicReference exceptionHolder = new AtomicReference<>(null); - ServiceCall serviceCall = gateway.call(); + ServiceCall serviceCall = gateway.context().serviceCall(); sub1.set(serviceCall.requestMany(JUST_MANY_NEVER).doOnError(exceptionHolder::set).subscribe()); gateway + .context() .listenDiscovery() .filter(ServiceDiscoveryEvent::isEndpointRemoved) .subscribe(onNext -> latch1.countDown(), System.err::println); @@ -135,7 +137,7 @@ public void test_remote_node_died_many_then_never() throws Exception { AtomicReference sub1 = new AtomicReference<>(null); AtomicReference exceptionHolder = new AtomicReference<>(null); - ServiceCall serviceCall = gateway.call(); + ServiceCall serviceCall = gateway.context().serviceCall(); sub1.set( serviceCall .requestMany(ONLY_ONE_AND_THEN_NEVER) @@ -143,6 +145,7 @@ public void test_remote_node_died_many_then_never() throws Exception { .subscribe()); gateway + .context() .listenDiscovery() .filter(ServiceDiscoveryEvent::isEndpointRemoved) .subscribe(onNext -> latch1.countDown(), System.err::println); From e677a7391cd0e01a6d1e7616bb18ddd51c57f587 Mon Sep 17 00:00:00 2001 From: "e.utkin" Date: Tue, 16 Jun 2020 17:32:47 +0300 Subject: [PATCH 56/61] update docs --- README.md | 5 +++-- .../discovery/CompositeDiscoveryExample.java | 18 ++++++++++++++---- 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 8b1840f75..f2f12519e 100644 --- a/README.md +++ b/README.md @@ -63,6 +63,7 @@ The example provisions 2 cluster nodes and making a remote interaction. ```java //1. ScaleCube Node node with no members Microservices seed = Microservices.builder().startAwait(); + MicroservicesContext seedContext = seed.context(); //2. Create ServiceFactory ServiceFactory serviceFactory = ScalecubeServiceFactory.fromInstances(new GreetingServiceImpl()); @@ -73,13 +74,13 @@ The example provisions 2 cluster nodes and making a remote interaction. .discovery( self -> new ScalecubeServiceDiscovery(self) - .options(opts -> opts.seedMembers(toAddress(seed.discovery().address())))) + .options(opts -> opts.seedMembers(seedContext.discovery().address()))) .transport(ServiceTransports::rsocketServiceTransport) .serviceFactory(serviceFactory) .startAwait(); //3. Create service proxy - GreetingsService service = seed.call().api(GreetingsService.class); + GreetingsService service = seedContext.serviceCall().api(GreetingsService.class); // Execute the services and subscribe to service events service.sayHello("joe").subscribe(consumer -> { diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/discovery/CompositeDiscoveryExample.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/discovery/CompositeDiscoveryExample.java index 078b32924..644a83946 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/discovery/CompositeDiscoveryExample.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/discovery/CompositeDiscoveryExample.java @@ -29,8 +29,8 @@ public static void main(String[] args) throws InterruptedException { .transport(RSocketServiceTransport::new) .startAwait(); - final Address seed1Address = seed1.discovery("seed1").address(); - final Address seed2Address = seed2.discovery("seed2").address(); + final Address seed1Address = seed1.context().discovery("seed1").address(); + final Address seed2Address = seed2.context().discovery("seed2").address(); Microservices ms1 = Microservices.builder() @@ -72,11 +72,21 @@ public static void main(String[] args) throws InterruptedException { .startAwait(); Greeting greeting1 = - compositeMs.call().api(GreetingsService1.class).sayHello("hello one").block(); + compositeMs + .context() + .serviceCall() + .api(GreetingsService1.class) + .sayHello("hello one") + .block(); System.err.println("This is response from GreetingsService1: " + greeting1.message()); Greeting greeting2 = - compositeMs.call().api(GreetingsService2.class).sayHello("hello two").block(); + compositeMs + .context() + .serviceCall() + .api(GreetingsService2.class) + .sayHello("hello two") + .block(); System.err.println("This is response from GreetingsService2: " + greeting2.message()); Thread.currentThread().join(); From c20ede7fc0b3bce987079130f10aa138d0d0cf2e Mon Sep 17 00:00:00 2001 From: "e.utkin" Date: Tue, 16 Jun 2020 17:35:29 +0300 Subject: [PATCH 57/61] update example --- .../examples/discovery/CompositeDiscoveryExample.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/discovery/CompositeDiscoveryExample.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/discovery/CompositeDiscoveryExample.java index 644a83946..3be7e7e89 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/discovery/CompositeDiscoveryExample.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/discovery/CompositeDiscoveryExample.java @@ -2,6 +2,7 @@ import io.scalecube.net.Address; import io.scalecube.services.Microservices; +import io.scalecube.services.ScalecubeServiceFactory; import io.scalecube.services.annotations.Service; import io.scalecube.services.annotations.ServiceMethod; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; @@ -40,7 +41,7 @@ public static void main(String[] args) throws InterruptedException { new ScalecubeServiceDiscovery(endpoint) .membership(cfg -> cfg.seedMembers(seed1Address))) .transport(RSocketServiceTransport::new) - .services(new GreetingServiceImpl1()) + .serviceFactory(ScalecubeServiceFactory.fromInstances(new GreetingServiceImpl1())) .startAwait(); Microservices ms2 = @@ -51,7 +52,7 @@ public static void main(String[] args) throws InterruptedException { new ScalecubeServiceDiscovery(endpoint) .membership(cfg -> cfg.seedMembers(seed2Address))) .transport(RSocketServiceTransport::new) - .services(new GreetingServiceImpl2()) + .serviceFactory(ScalecubeServiceFactory.fromInstances(new GreetingServiceImpl2())) .startAwait(); Microservices compositeMs = From d7a37715e5cbbf073db1b6afa2247dbb39b55a5e Mon Sep 17 00:00:00 2001 From: "e.utkin" Date: Tue, 16 Jun 2020 17:52:35 +0300 Subject: [PATCH 58/61] remove redundant step --- .../src/main/java/io/scalecube/services/Microservices.java | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/services/src/main/java/io/scalecube/services/Microservices.java b/services/src/main/java/io/scalecube/services/Microservices.java index 9e9d85eda..3bd510a72 100644 --- a/services/src/main/java/io/scalecube/services/Microservices.java +++ b/services/src/main/java/io/scalecube/services/Microservices.java @@ -214,8 +214,7 @@ private Mono start() { Scheduler scheduler = Schedulers.newSingle(toString(), true); return transportBootstrap .start(this) - // because ServiceTransportBootstrap#address may return nullable value in local case - .map(transport -> (Supplier
) transport::address) + .map(ServiceTransportBootstrap::address) .flatMap(this::initializeServiceEndpoint) .flatMap( serviceEndpoint -> @@ -240,7 +239,7 @@ private Mono createDiscovery(ServiceDiscoveryOptions options) return this.compositeDiscovery.createInstance(options); } - private Mono initializeServiceEndpoint(Supplier
serviceAddress) { + private Mono initializeServiceEndpoint(Address serviceAddress) { Mono> serviceDefinitionsMono = Mono.fromCallable(this.serviceFactory::getServiceDefinitions); return serviceDefinitionsMono.map( @@ -248,7 +247,7 @@ private Mono initializeServiceEndpoint(Supplier
servic final ServiceEndpoint.Builder serviceEndpointBuilder = ServiceEndpoint.builder() .id(this.id) - .address(serviceAddress.get()) + .address(serviceAddress) .contentTypes(DataCodec.getAllContentTypes()) .tags(this.tags); serviceDefinitions.forEach( From 3b20f3331f03f564f68e80e5cb3119184d4620e1 Mon Sep 17 00:00:00 2001 From: "e.utkin" Date: Tue, 16 Jun 2020 20:07:11 +0300 Subject: [PATCH 59/61] remove context from Microservices state --- .../services/MicroservicesContext.java | 41 ----- .../io/scalecube/services/ServiceFactory.java | 3 +- .../transport/BenchmarkServiceState.java | 2 +- .../services/examples/codecs/Example1.java | 6 +- .../discovery/CompositeDiscoveryExample.java | 6 +- .../exceptions/ExceptionMapperExample.java | 2 +- .../examples/helloworld/Example1.java | 2 +- .../examples/helloworld/Example2.java | 2 +- .../examples/helloworld/Example3.java | 2 +- .../services/examples/orderbook/Example1.java | 2 +- .../services/examples/services/Example1.java | 2 +- .../services/examples/services/Example2.java | 2 +- .../factory/GuiceServiceFactoryExample.java | 4 +- ...ightweightSpringServiceFactoryExample.java | 6 +- .../factory/SpringServiceFactoryExample.java | 6 +- .../io/scalecube/services/Microservices.java | 149 ++++++------------ .../services/ScalecubeServiceFactory.java | 18 ++- .../io/scalecube/services/ErrorFlowTest.java | 7 +- .../services/ServiceAuthRemoteTest.java | 12 +- .../services/ServiceCallLocalTest.java | 29 ++-- .../services/ServiceCallRemoteTest.java | 32 ++-- .../scalecube/services/ServiceLocalTest.java | 9 +- .../services/ServiceRegistryTest.java | 16 +- .../scalecube/services/ServiceRemoteTest.java | 35 ++-- .../services/StreamingServiceTest.java | 23 ++- .../services/routings/RoutersTest.java | 14 +- .../services/routings/ServiceTagsExample.java | 4 +- ...ocketNettyColocatedEventLoopGroupTest.java | 6 +- .../rsocket/RSocketServiceTransportTest.java | 11 +- 29 files changed, 169 insertions(+), 284 deletions(-) diff --git a/services-api/src/main/java/io/scalecube/services/MicroservicesContext.java b/services-api/src/main/java/io/scalecube/services/MicroservicesContext.java index b7ea87f77..a60b8be56 100644 --- a/services-api/src/main/java/io/scalecube/services/MicroservicesContext.java +++ b/services-api/src/main/java/io/scalecube/services/MicroservicesContext.java @@ -1,10 +1,6 @@ package io.scalecube.services; -import io.scalecube.net.Address; -import io.scalecube.services.discovery.api.ServiceDiscoveryContext; import io.scalecube.services.discovery.api.ServiceDiscoveryEvent; -import io.scalecube.services.gateway.Gateway; -import java.util.List; import reactor.core.publisher.Flux; /** @@ -38,41 +34,4 @@ public interface MicroservicesContext { * @return stream of {@code ServiceDiscoveryEvent} events */ Flux listenDiscovery(); - - /** - * Returns service discovery context by id. - * - * @param id service discovery id - * @return service discovery context - */ - ServiceDiscoveryContext discovery(String id); - - /** - * All gateways registered on this Microservices node. - * - * @return list of gateway - */ - List gateways(); - - /** - * Return gateway by id. - * - * @param id gateway id - * @return gateway - */ - Gateway gateway(String id); - - /** - * Network address current Microservices node. - * - * @return network address - */ - Address serviceAddress(); - - /** - * Unique id of this Microservices node. - * - * @return id - */ - String id(); } diff --git a/services-api/src/main/java/io/scalecube/services/ServiceFactory.java b/services-api/src/main/java/io/scalecube/services/ServiceFactory.java index bb65b9532..dc4780994 100644 --- a/services-api/src/main/java/io/scalecube/services/ServiceFactory.java +++ b/services-api/src/main/java/io/scalecube/services/ServiceFactory.java @@ -26,10 +26,9 @@ public interface ServiceFactory { /** * Finalization of service instances. * - * @param microservices microservices context * @return completed Mono if finalization was successful for all services. */ - default Mono shutdownServices(MicroservicesContext microservices) { + default Mono shutdownServices() { return Mono.defer(Mono::empty); } } diff --git a/services-benchmarks/src/main/java/io/scalecube/services/benchmarks/transport/BenchmarkServiceState.java b/services-benchmarks/src/main/java/io/scalecube/services/benchmarks/transport/BenchmarkServiceState.java index 8d285d850..c3ed90f73 100644 --- a/services-benchmarks/src/main/java/io/scalecube/services/benchmarks/transport/BenchmarkServiceState.java +++ b/services-benchmarks/src/main/java/io/scalecube/services/benchmarks/transport/BenchmarkServiceState.java @@ -78,6 +78,6 @@ public T api(Class c) { } public ServiceCall call() { - return seed.call(); + return seed.serviceCall(); } } diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/codecs/Example1.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/codecs/Example1.java index b0bd5c79b..d2a691ce5 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/codecs/Example1.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/codecs/Example1.java @@ -47,18 +47,18 @@ public static void main(String[] args) { .serviceFactory(serviceFactory) .startAwait(); - seed.call() + seed.serviceCall() .api(GreetingsService.class) .sayHello("joe (on default dataFormat PROTOSTUFF)") .subscribe(consumer -> System.out.println(consumer.message())); - seed.call() + seed.serviceCall() .contentType(JSON) .api(GreetingsService.class) .sayHello("alice (on JSON dataFormat)") .subscribe(consumer -> System.out.println(consumer.message())); - seed.call() + seed.serviceCall() .contentType(OCTET_STREAM) .api(GreetingsService.class) .sayHello("bob (on java native Serializable/Externalizable dataFormat)") diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/discovery/CompositeDiscoveryExample.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/discovery/CompositeDiscoveryExample.java index 3be7e7e89..72069c058 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/discovery/CompositeDiscoveryExample.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/discovery/CompositeDiscoveryExample.java @@ -30,8 +30,8 @@ public static void main(String[] args) throws InterruptedException { .transport(RSocketServiceTransport::new) .startAwait(); - final Address seed1Address = seed1.context().discovery("seed1").address(); - final Address seed2Address = seed2.context().discovery("seed2").address(); + final Address seed1Address = seed1.discovery("seed1").address(); + final Address seed2Address = seed2.discovery("seed2").address(); Microservices ms1 = Microservices.builder() @@ -74,7 +74,6 @@ public static void main(String[] args) throws InterruptedException { Greeting greeting1 = compositeMs - .context() .serviceCall() .api(GreetingsService1.class) .sayHello("hello one") @@ -83,7 +82,6 @@ public static void main(String[] args) throws InterruptedException { Greeting greeting2 = compositeMs - .context() .serviceCall() .api(GreetingsService2.class) .sayHello("hello two") diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/exceptions/ExceptionMapperExample.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/exceptions/ExceptionMapperExample.java index c7ece9917..232daa47a 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/exceptions/ExceptionMapperExample.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/exceptions/ExceptionMapperExample.java @@ -69,7 +69,7 @@ public Mono> initializeServices( System.err.println("ms2 started: " + ms2.serviceAddress()); - ms2.call() + ms2.serviceCall() .api(ServiceB.class) .doAnotherStuff(0) .subscribe( diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example1.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example1.java index a502989b7..123e698b1 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example1.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example1.java @@ -51,7 +51,7 @@ public static void main(String[] args) { .startAwait(); // Create service proxy - GreetingsService service = seed.call().api(GreetingsService.class); + GreetingsService service = seed.serviceCall().api(GreetingsService.class); // Execute the services and subscribe to service events service.sayHello("joe").subscribe(consumer -> System.out.println(consumer.message())); diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example2.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example2.java index 7aa2a093c..c215a866a 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example2.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example2.java @@ -59,7 +59,7 @@ public static void main(String[] args) { .startAwait(); // Create a proxy to the seed service node - ServiceCall service = seed.call(); + ServiceCall service = seed.serviceCall(); // Create a ServiceMessage request with service qualifier and data ServiceMessage request = diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example3.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example3.java index 209f7b959..2508942bc 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example3.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/helloworld/Example3.java @@ -51,7 +51,7 @@ public static void main(String[] args) { .startAwait(); // Create service proxy - BidiGreetingService service = seed.call().api(BidiGreetingService.class); + BidiGreetingService service = seed.serviceCall().api(BidiGreetingService.class); // Execute the services and subscribe to service events service diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/orderbook/Example1.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/orderbook/Example1.java index b3ea1cc70..4abad4d8c 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/orderbook/Example1.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/orderbook/Example1.java @@ -56,7 +56,7 @@ public static void main(String[] args) throws InterruptedException { .serviceFactory(serviceFactory) .startAwait(); - MarketDataService marketService = ms.call().api(MarketDataService.class); + MarketDataService marketService = ms.serviceCall().api(MarketDataService.class); marketService.orderBook().subscribe(Example1::print); diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example1.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example1.java index 05020e190..70d6ac881 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example1.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example1.java @@ -52,7 +52,7 @@ public static void main(String[] args) { .startAwait(); gateway - .call() + .serviceCall() .api(Service1.class) .manyDelay(100) .publishOn(Schedulers.parallel()) diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example2.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example2.java index 6f538d2e8..8aa8f68b3 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example2.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/Example2.java @@ -52,7 +52,7 @@ public static void main(String[] args) { .startAwait(); gateway - .call() + .serviceCall() .api(Service1.class) .remoteCallThenManyDelay(100) .publishOn(Schedulers.parallel()) diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/GuiceServiceFactoryExample.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/GuiceServiceFactoryExample.java index ff1d4730d..fa63b29de 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/GuiceServiceFactoryExample.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/GuiceServiceFactoryExample.java @@ -65,13 +65,13 @@ public static void main(String[] args) { new ScalecubeServiceDiscovery(endpoint) .membership( cfg -> - cfg.seedMembers(service2Node.context().discovery("s2").address()))) + cfg.seedMembers(service2Node.discovery("s2").address()))) .serviceFactory(serviceFactory1) .transport(RSocketServiceTransport::new) .startAwait(); service1Node - .call() + .serviceCall() .api(BidiGreetingService.class) .greeting() .log("receive |") diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/LightweightSpringServiceFactoryExample.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/LightweightSpringServiceFactoryExample.java index a3ad1df95..ae1cf47a7 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/LightweightSpringServiceFactoryExample.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/LightweightSpringServiceFactoryExample.java @@ -62,13 +62,13 @@ public static void main(String[] args) { new ScalecubeServiceDiscovery(endpoint) .membership( cfg -> - cfg.seedMembers(service2Node.context().discovery("s2").address()))) + cfg.seedMembers(service2Node.discovery("s2").address()))) .serviceFactory(serviceFactory1) .transport(RSocketServiceTransport::new) .startAwait(); service1Node - .call() + .serviceCall() .api(BidiGreetingService.class) .greeting() .log("receive |") @@ -128,7 +128,7 @@ public Mono> initializeServices( } @Override - public Mono shutdownServices(MicroservicesContext microservices) { + public Mono shutdownServices() { return Mono.fromRunnable(this.context::stop); } } diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/SpringServiceFactoryExample.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/SpringServiceFactoryExample.java index a8854c780..fb9e43289 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/SpringServiceFactoryExample.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/services/factory/SpringServiceFactoryExample.java @@ -64,13 +64,13 @@ public static void main(String[] args) { new ScalecubeServiceDiscovery(endpoint) .membership( cfg -> - cfg.seedMembers(service2Node.context().discovery("s2").address()))) + cfg.seedMembers(service2Node.discovery("s2").address()))) .serviceFactory(serviceFactory1) .transport(RSocketServiceTransport::new) .startAwait(); service1Node - .call() + .serviceCall() .api(BidiGreetingService.class) .greeting() .log("receive |") @@ -187,7 +187,7 @@ public Mono> initializeServices( } @Override - public Mono shutdownServices(MicroservicesContext microservices) { + public Mono shutdownServices() { return Mono.fromRunnable(this.context::stop).then(); } } diff --git a/services/src/main/java/io/scalecube/services/Microservices.java b/services/src/main/java/io/scalecube/services/Microservices.java index 3bd510a72..ea01c8ad9 100644 --- a/services/src/main/java/io/scalecube/services/Microservices.java +++ b/services/src/main/java/io/scalecube/services/Microservices.java @@ -144,8 +144,6 @@ public final class Microservices { private final PrincipalMapper principalMapper; private final MonoProcessor shutdown = MonoProcessor.create(); private final MonoProcessor onShutdown = MonoProcessor.create(); - private MicroservicesContext microservicesContext; - private ServiceEndpoint serviceEndpoint; private Microservices(Builder builder) { this.tags = new HashMap<>(builder.tags); @@ -167,13 +165,13 @@ private Microservices(Builder builder) { : ScalecubeServiceFactory.create(builder.serviceProviders); // for initialization services by deprecated ServiceProvider if (this.serviceFactory instanceof ScalecubeServiceFactory) { - ((ScalecubeServiceFactory) this.serviceFactory).setServiceCall(this::call); + ((ScalecubeServiceFactory) this.serviceFactory).setServiceCall(this::serviceCall); } // Setup cleanup - shutdown + this.shutdown .then(doShutdown()) - .doFinally(s -> onShutdown.onComplete()) + .doFinally(s -> this.onShutdown.onComplete()) .subscribe( null, ex -> LOGGER.warn("[{}][doShutdown] Exception occurred: {}", id, ex.toString())); } @@ -186,22 +184,11 @@ public static Builder builder() { * Unique id of this Microservices node. * * @return id - * @deprecated use {@link MicroservicesContext#id()} by {@link Microservices#context()} */ - @Deprecated public String id() { return this.id; } - /** - * Return microservices context with all public information about Microservices. - * - * @return microservices context - */ - public MicroservicesContext context() { - return microservicesContext; - } - @Override public String toString() { return "Microservices@" + id; @@ -212,14 +199,12 @@ private Mono start() { // Create bootstrap scheduler Scheduler scheduler = Schedulers.newSingle(toString(), true); - return transportBootstrap + return this.transportBootstrap .start(this) .map(ServiceTransportBootstrap::address) .flatMap(this::initializeServiceEndpoint) - .flatMap( - serviceEndpoint -> - createDiscovery(new ServiceDiscoveryOptions().serviceEndpoint(serviceEndpoint))) - .map(avoid -> this.microservicesContext = new MicroservicesContextImpl()) + .flatMap(this::createDiscovery) + .map(serviceDiscovery -> new MicroservicesContextImpl(serviceDiscovery, this::serviceCall)) .flatMap(this.serviceFactory::initializeServices) .doOnNext(this::registerInMethodRegistry) .publishOn(scheduler) @@ -235,8 +220,8 @@ private Mono start() { .doOnTerminate(scheduler::dispose); } - private Mono createDiscovery(ServiceDiscoveryOptions options) { - return this.compositeDiscovery.createInstance(options); + private Mono createDiscovery(ServiceEndpoint serviceEndpoint) { + return this.compositeDiscovery.createInstance(serviceEndpoint); } private Mono initializeServiceEndpoint(Address serviceAddress) { @@ -254,9 +239,7 @@ private Mono initializeServiceEndpoint(Address serviceAddress) serviceDefinition -> serviceEndpointBuilder.appendServiceRegistrations( ServiceScanner.scanServiceDefinition(serviceDefinition))); - ServiceEndpoint serviceEndpoint = serviceEndpointBuilder.build(); - this.serviceEndpoint = serviceEndpoint; - return serviceEndpoint; + return serviceEndpointBuilder.build(); }); } @@ -274,15 +257,13 @@ private void registerInMethodRegistry(Collection services) { } private Mono startGateway() { - return this.gatewayBootstrap.start(this, new GatewayOptions().call(this.call())); + return this.gatewayBootstrap.start(this, new GatewayOptions().call(this.serviceCall())); } /** * Network address of this Microservices node. * * @return network address - * @deprecated use {@link MicroservicesContext#serviceAddress()} )} by {@link - * Microservices#context()} */ public Address serviceAddress() { return transportBootstrap.transportAddress; @@ -292,10 +273,19 @@ public Address serviceAddress() { * Creates new instance {@code ServiceCall}. * * @return new {@code ServiceCall} instance. - * @deprecated use {@link MicroservicesContext#serviceCall()} by {@link Microservices#context()} + * @deprecated use {@link this#serviceCall()} */ @Deprecated public ServiceCall call() { + return this.serviceCall(); + } + + /** + * Creates new instance {@code ServiceCall}. + * + * @return new {@code ServiceCall} instance. + */ + public ServiceCall serviceCall() { return new ServiceCall() .transport(this.transportBootstrap.clientTransport) .serviceRegistry(this.serviceRegistry) @@ -309,34 +299,27 @@ public ServiceCall call() { * List of all gateway registered in this Microservices node. * * @return gateways - * @deprecated use {@link MicroservicesContext#gateways()} by {@link Microservices#context()} */ - @Deprecated public List gateways() { - return gatewayBootstrap.gateways(); + return this.gatewayBootstrap.gateways(); } /** * Get gateway registered in this Microservices node by id. * * @return gateway - * @deprecated use {@link MicroservicesContext#gateway(String)} by {@link Microservices#context()} */ - @Deprecated public Gateway gateway(String id) { - return gatewayBootstrap.gateway(id); + return this.gatewayBootstrap.gateway(id); } /** * Service endpoint. * * @return service endpoint - * @deprecated use {@link MicroservicesContext#serviceEndpoint()} by {@link - * Microservices#context()} */ - @Deprecated public ServiceEndpoint serviceEndpoint() { - return serviceEndpoint; + return this.compositeDiscovery.serviceEndpoint; } /** @@ -344,12 +327,9 @@ public ServiceEndpoint serviceEndpoint() { * * @param id service discovery id * @return service discovery context - * @deprecated use {@link MicroservicesContext#discovery(String)} by {@link - * Microservices#context()} */ - @Deprecated public ServiceDiscoveryContext discovery(String id) { - return Optional.ofNullable(compositeDiscovery.contextMap.get(id)) + return Optional.ofNullable(this.compositeDiscovery.contextMap.get(id)) .orElseThrow(() -> new NoSuchElementException("[discovery] id: " + id)); } @@ -357,12 +337,9 @@ public ServiceDiscoveryContext discovery(String id) { * Function to subscribe and listen on {@code ServiceDiscoveryEvent} events. * * @return stream of {@code ServiceDiscoveryEvent} events - * @deprecated use {@link MicroservicesContext#listenDiscovery()} by {@link - * Microservices#context()} */ - @Deprecated public Flux listenDiscovery() { - return compositeDiscovery.listen(); + return this.compositeDiscovery.listen(); } /** @@ -397,7 +374,7 @@ private Mono doShutdown() { } private Mono processBeforeDestroy() { - return serviceFactory.shutdownServices(this.microservicesContext).then(); + return this.serviceFactory.shutdownServices().then(); } private static class CompositeServiceDiscovery implements ServiceDiscovery { @@ -412,38 +389,37 @@ private static class CompositeServiceDiscovery implements ServiceDiscovery { private final Disposable.Composite disposables = Disposables.composite(); private Scheduler scheduler; + private ServiceEndpoint serviceEndpoint; private CompositeServiceDiscovery addOperator(UnaryOperator operator) { this.operatorList.add(operator); return this; } - private Mono createInstance(ServiceDiscoveryOptions options) { + private Mono createInstance(ServiceEndpoint serviceEndpoint) { + this.serviceEndpoint = serviceEndpoint; + ServiceDiscoveryOptions options = + new ServiceDiscoveryOptions().serviceEndpoint(this.serviceEndpoint); for (UnaryOperator operator : operatorList) { final ServiceDiscoveryOptions finalOptions = operator.apply(options); - final ServiceEndpoint serviceEndpoint = finalOptions.serviceEndpoint(); final String id = finalOptions.id(); - discoveryMap.put( + this.discoveryMap.put( id, finalOptions.discoveryFactory().createServiceDiscovery(serviceEndpoint)); } - scheduler = Schedulers.newSingle("composite-discovery", true); + this.scheduler = Schedulers.newSingle("composite-discovery", true); return Mono.just(this); } private Mono startListen(Microservices microservices) { return Mono.deferWithContext(context -> start()) - .doOnSubscribe( - s -> LOGGER.info("[{}][startListen] Starting", microservices.id)) - .doOnSuccess( - discovery -> LOGGER.info("[{}][startListen] Started", microservices.id)) + .doOnSubscribe(s -> LOGGER.info("[{}][startListen] Starting", microservices.id)) + .doOnSuccess(discovery -> LOGGER.info("[{}][startListen] Started", microservices.id)) .doOnError( ex -> LOGGER.error( - "[{}][startListen] Exception occurred: {}", - microservices.id, - ex.toString())) + "[{}][startListen] Exception occurred: {}", microservices.id, ex.toString())) .subscriberContext( context -> reactor.util.context.Context.of(Microservices.class, microservices)); } @@ -846,9 +822,7 @@ private Mono start(Microservices microservices) { return this; }) .doOnSubscribe( - s -> - LOGGER.info( - "[{}][serviceTransport][start] Starting", microservices.id)) + s -> LOGGER.info("[{}][serviceTransport][start] Starting", microservices.id)) .doOnSuccess( transport -> LOGGER.info( @@ -892,7 +866,7 @@ private static JmxMonitorMBean start(Microservices instance) throws Exception { JmxMonitorMBean jmxMBean = new JmxMonitorMBean(instance); ObjectName objectName = new ObjectName( - String.format(OBJECT_NAME_FORMAT, instance.context().id(), System.nanoTime())); + String.format(OBJECT_NAME_FORMAT, instance.id(), System.nanoTime())); StandardMBean standardMBean = new StandardMBean(jmxMBean, MonitorMBean.class); mbeanServer.registerMBean(standardMBean, objectName); return jmxMBean; @@ -969,51 +943,30 @@ public interface MonitorMBean { String getServiceInfos(); } - private final class MicroservicesContextImpl implements MicroservicesContext { - - @Override - public ServiceEndpoint serviceEndpoint() { - return Microservices.this.serviceEndpoint; - } - - @Override - public ServiceCall serviceCall() { - return Microservices.this.call(); - } - - @Override - public Flux listenDiscovery() { - return Microservices.this.compositeDiscovery.listen(); - } + private static final class MicroservicesContextImpl implements MicroservicesContext { - @Override - public ServiceDiscoveryContext discovery(String id) { - Map contextMap = - Microservices.this.compositeDiscovery.contextMap; - if (contextMap.containsKey(id)) { - return contextMap.get(id); - } - throw new NoSuchElementException("[discovery] id " + id); - } + private final CompositeServiceDiscovery serviceDiscovery; + private final Supplier serviceCallSupplier; - @Override - public List gateways() { - return Microservices.this.gatewayBootstrap.gateways(); + private MicroservicesContextImpl( + CompositeServiceDiscovery serviceDiscovery, Supplier serviceCallSupplier) { + this.serviceDiscovery = serviceDiscovery; + this.serviceCallSupplier = serviceCallSupplier; } @Override - public Gateway gateway(String id) { - return Microservices.this.gatewayBootstrap.gateway(id); + public ServiceEndpoint serviceEndpoint() { + return this.serviceDiscovery.serviceEndpoint; } @Override - public Address serviceAddress() { - return Microservices.this.transportBootstrap.address(); + public ServiceCall serviceCall() { + return this.serviceCallSupplier.get(); } @Override - public String id() { - return Microservices.this.id; + public Flux listenDiscovery() { + return this.serviceDiscovery.listen(); } } } diff --git a/services/src/main/java/io/scalecube/services/ScalecubeServiceFactory.java b/services/src/main/java/io/scalecube/services/ScalecubeServiceFactory.java index eb8c7de29..4f444f835 100644 --- a/services/src/main/java/io/scalecube/services/ScalecubeServiceFactory.java +++ b/services/src/main/java/io/scalecube/services/ScalecubeServiceFactory.java @@ -17,6 +17,8 @@ public class ScalecubeServiceFactory implements ServiceFactory { // lazy init private final AtomicReference> services = new AtomicReference<>(); private Supplier serviceCallSupplier; + // lazy init + private MicroservicesContext microserviceContext; private ScalecubeServiceFactory(Collection serviceProviders) { this.serviceFactory = @@ -100,11 +102,13 @@ public Collection getServiceDefinitions() { public Mono> initializeServices( MicroservicesContext microservices) { return Mono.fromCallable( - () -> - this.services().stream() - .map(service -> Injector.inject(microservices, service)) - .map(service -> Injector.processAfterConstruct(microservices, service)) - .collect(Collectors.toList())); + () -> { + this.microserviceContext = microservices; + return this.services().stream() + .map(service -> Injector.inject(microservices, service)) + .map(service -> Injector.processAfterConstruct(microservices, service)) + .collect(Collectors.toList()); + }); } /** @@ -116,8 +120,8 @@ public Mono> initializeServices( * @return */ @Override - public Mono shutdownServices(MicroservicesContext microservices) { - return Mono.fromRunnable(() -> shutdown0(microservices)); + public Mono shutdownServices() { + return Mono.fromRunnable(() -> shutdown0(this.microserviceContext)); } private void shutdown0(MicroservicesContext microservices) { diff --git a/services/src/test/java/io/scalecube/services/ErrorFlowTest.java b/services/src/test/java/io/scalecube/services/ErrorFlowTest.java index 445f74028..eb63a578f 100644 --- a/services/src/test/java/io/scalecube/services/ErrorFlowTest.java +++ b/services/src/test/java/io/scalecube/services/ErrorFlowTest.java @@ -40,7 +40,7 @@ public static void initNodes() { .serviceFactory(ScalecubeServiceFactory.fromInstances(new GreetingServiceImpl())) .startAwait(); - final Address seedAddress = provider.context().discovery("provider").address(); + final Address seedAddress = provider.discovery("provider").address(); consumer = Microservices.builder() @@ -64,7 +64,6 @@ public static void shutdownNodes() { public void testCorruptedRequest() { Publisher req = consumer - .context() .serviceCall() .requestOne(TestRequests.GREETING_CORRUPTED_PAYLOAD_REQUEST, GreetingResponse.class); assertThrows(InternalServiceException.class, () -> from(req).block()); @@ -74,7 +73,6 @@ public void testCorruptedRequest() { public void testNotAuthorized() { Publisher req = consumer - .context() .serviceCall() .requestOne(TestRequests.GREETING_UNAUTHORIZED_REQUEST, GreetingResponse.class); assertThrows(ForbiddenException.class, () -> from(req).block()); @@ -84,7 +82,6 @@ public void testNotAuthorized() { public void testNullRequestPayload() { Publisher req = consumer - .context() .serviceCall() .requestOne(TestRequests.GREETING_NULL_PAYLOAD, GreetingResponse.class); assertThrows(BadRequestException.class, () -> from(req).block()); @@ -92,7 +89,7 @@ public void testNullRequestPayload() { @Test public void testServiceUnavailable() { - StepVerifier.create(consumer.context().serviceCall().requestOne(TestRequests.NOT_FOUND_REQ)) + StepVerifier.create(consumer.serviceCall().requestOne(TestRequests.NOT_FOUND_REQ)) .expectError(ServiceUnavailableException.class) .verify(); } diff --git a/services/src/test/java/io/scalecube/services/ServiceAuthRemoteTest.java b/services/src/test/java/io/scalecube/services/ServiceAuthRemoteTest.java index 8dd93c754..37072970a 100644 --- a/services/src/test/java/io/scalecube/services/ServiceAuthRemoteTest.java +++ b/services/src/test/java/io/scalecube/services/ServiceAuthRemoteTest.java @@ -67,7 +67,7 @@ static void beforeAll() { .transport(RSocketServiceTransport::new) .startAwait(); - callerAddress = caller.context().discovery("caller").address(); + callerAddress = caller.discovery("caller").address(); principalMapper = authData -> new UserProfile(authData.get("name"), authData.get("role")); @@ -98,7 +98,7 @@ static void afterAll() { @DisplayName("Successful authentication") void successfulAuthentication() { SecuredService securedService = - caller.context().serviceCall().credentials(CREDENTIALS).api(SecuredService.class); + caller.serviceCall().credentials(CREDENTIALS).api(SecuredService.class); StepVerifier.create(securedService.helloWithRequest("Bob")) .assertNext(response -> assertEquals("Hello, Bob", response)) @@ -127,7 +127,7 @@ void failedAuthenticationWhenAuthenticatorNotProvided() { .startAwait(); SecuredService securedService = - caller.context().serviceCall().credentials(CREDENTIALS).api(SecuredService.class); + caller.serviceCall().credentials(CREDENTIALS).api(SecuredService.class); Consumer verifyError = th -> { @@ -153,7 +153,7 @@ void failedAuthenticationWhenAuthenticatorNotProvided() { @Test @DisplayName("Authentication failed with invalid or empty credentials") void failedAuthenticationWithInvalidOrEmptyCredentials() { - SecuredService securedService = caller.context().serviceCall().api(SecuredService.class); + SecuredService securedService = caller.serviceCall().api(SecuredService.class); Consumer verifyError = th -> { @@ -189,7 +189,7 @@ void successfulAuthenticationOnPartiallySecuredService() { .startAwait(); PartiallySecuredService proxy = - caller.context().serviceCall().credentials(CREDENTIALS).api(PartiallySecuredService.class); + caller.serviceCall().credentials(CREDENTIALS).api(PartiallySecuredService.class); StepVerifier.create(proxy.securedMethod("Alice")) .assertNext(response -> assertEquals("Hello, Alice", response)) @@ -212,7 +212,7 @@ void successfulCallOfPublicMethodWithoutAuthentication() { .startAwait(); PartiallySecuredService proxy = - caller.context().serviceCall().api(PartiallySecuredService.class); + caller.serviceCall().api(PartiallySecuredService.class); StepVerifier.create(proxy.publicMethod("Alice")) .assertNext(response -> assertEquals("Hello, Alice", response)) diff --git a/services/src/test/java/io/scalecube/services/ServiceCallLocalTest.java b/services/src/test/java/io/scalecube/services/ServiceCallLocalTest.java index ea857fb5a..5c02e16ec 100644 --- a/services/src/test/java/io/scalecube/services/ServiceCallLocalTest.java +++ b/services/src/test/java/io/scalecube/services/ServiceCallLocalTest.java @@ -52,8 +52,7 @@ public static void tearDown() { @Test public void test_local_async_no_params() { - ServiceCall serviceCall = - provider.context().serviceCall().router(RoundRobinServiceRouter.class); + ServiceCall serviceCall = provider.serviceCall().router(RoundRobinServiceRouter.class); // call the service. Publisher future = serviceCall.requestOne(GREETING_NO_PARAMS_REQUEST); @@ -75,20 +74,20 @@ private static Microservices serviceProvider() { @Test public void test_local_void_greeting() { // WHEN - provider.context().serviceCall().oneWay(GREETING_VOID_REQ).block(Duration.ofSeconds(TIMEOUT)); + provider.serviceCall().oneWay(GREETING_VOID_REQ).block(Duration.ofSeconds(TIMEOUT)); } @Test public void test_local_failng_void_greeting() { - StepVerifier.create(provider.context().serviceCall().oneWay(GREETING_FAILING_VOID_REQ)) + StepVerifier.create(provider.serviceCall().oneWay(GREETING_FAILING_VOID_REQ)) .expectErrorMessage(GREETING_FAILING_VOID_REQ.data().toString()) .verify(Duration.ofSeconds(TIMEOUT)); } @Test public void test_local_throwing_void_greeting() { - StepVerifier.create(provider.context().serviceCall().oneWay(GREETING_THROWING_VOID_REQ)) + StepVerifier.create(provider.serviceCall().oneWay(GREETING_THROWING_VOID_REQ)) .expectErrorMessage(GREETING_THROWING_VOID_REQ.data().toString()) .verify(Duration.ofSeconds(TIMEOUT)); } @@ -99,9 +98,7 @@ public void test_local_fail_greeting() { Throwable exception = assertThrows( ServiceException.class, - () -> - Mono.from(provider.context().serviceCall().requestOne(GREETING_FAIL_REQ)) - .block(timeout)); + () -> Mono.from(provider.serviceCall().requestOne(GREETING_FAIL_REQ)).block(timeout)); assertEquals("GreetingRequest{name='joe'}", exception.getMessage()); } @@ -112,9 +109,7 @@ public void test_local_exception_greeting() { Throwable exception = assertThrows( ServiceException.class, - () -> - Mono.from(provider.context().serviceCall().requestOne(GREETING_ERROR_REQ)) - .block(timeout)); + () -> Mono.from(provider.serviceCall().requestOne(GREETING_ERROR_REQ)).block(timeout)); } @Test @@ -122,7 +117,7 @@ public void test_local_async_greeting_return_GreetingResponse() { // When Publisher resultFuture = - provider.context().serviceCall().requestOne(GREETING_REQUEST_REQ); + provider.serviceCall().requestOne(GREETING_REQUEST_REQ); // Then ServiceMessage result = Mono.from(resultFuture).block(Duration.ofSeconds(TIMEOUT)); @@ -134,7 +129,7 @@ public void test_local_async_greeting_return_GreetingResponse() { @Test public void test_local_greeting_request_timeout_expires() { - ServiceCall service = provider.context().serviceCall(); + ServiceCall service = provider.serviceCall(); // call the service. Publisher future = service.requestOne(GREETING_REQUEST_TIMEOUT_REQ); @@ -147,8 +142,7 @@ public void test_local_greeting_request_timeout_expires() { @Test public void test_local_async_greeting_return_Message() { - ServiceMessage result = - provider.context().serviceCall().requestOne(GREETING_REQUEST_REQ).block(timeout); + ServiceMessage result = provider.serviceCall().requestOne(GREETING_REQUEST_REQ).block(timeout); // print the greeting. GreetingResponse responseData = result.data(); @@ -161,9 +155,8 @@ public void test_local_async_greeting_return_Message() { public void test_remote_mono_empty_request_response_greeting_messsage() { StepVerifier.create( provider - .context() .serviceCall() - .requestOne(GREETING_EMPTY_REQUEST_RESPONSE, EmptyGreetingResponse.class)) + .requestOne(GREETING_EMPTY_REQUEST_RESPONSE, EmptyGreetingResponse.class)) .expectNextMatches(resp -> resp.data() instanceof EmptyGreetingResponse) .expectComplete() .verify(timeout); @@ -172,7 +165,7 @@ public void test_remote_mono_empty_request_response_greeting_messsage() { @Test public void test_async_greeting_return_string_service_not_found_error_case() { - ServiceCall service = provider.context().serviceCall(); + ServiceCall service = provider.serviceCall(); try { // call the service. diff --git a/services/src/test/java/io/scalecube/services/ServiceCallRemoteTest.java b/services/src/test/java/io/scalecube/services/ServiceCallRemoteTest.java index 8d8abb023..e2ef767bc 100644 --- a/services/src/test/java/io/scalecube/services/ServiceCallRemoteTest.java +++ b/services/src/test/java/io/scalecube/services/ServiceCallRemoteTest.java @@ -70,8 +70,7 @@ private static Microservices serviceProvider(Object service) { "serviceProvider", endpoint -> new ScalecubeServiceDiscovery(endpoint) - .membership( - cfg -> cfg.seedMembers(gateway.context().discovery("gateway").address()))) + .membership(cfg -> cfg.seedMembers(gateway.discovery("gateway").address()))) .transport(RSocketServiceTransport::new) .serviceFactory(ScalecubeServiceFactory.fromInstances(service)) .startAwait(); @@ -80,7 +79,7 @@ private static Microservices serviceProvider(Object service) { @Test public void test_remote_async_greeting_no_params() { - ServiceCall serviceCall = gateway.context().serviceCall(); + ServiceCall serviceCall = gateway.serviceCall(); // call the service. Publisher future = @@ -94,7 +93,7 @@ public void test_remote_async_greeting_no_params() { @Test public void test_remote_void_greeting() { // When - StepVerifier.create(gateway.context().serviceCall().oneWay(GREETING_VOID_REQ)) + StepVerifier.create(gateway.serviceCall().oneWay(GREETING_VOID_REQ)) .expectComplete() .verify(TIMEOUT); } @@ -103,7 +102,6 @@ public void test_remote_void_greeting() { public void test_remote_mono_empty_request_response_greeting_messsage() { StepVerifier.create( gateway - .context() .serviceCall() .requestOne(GREETING_EMPTY_REQUEST_RESPONSE, EmptyGreetingResponse.class)) .expectNextMatches(resp -> resp.data() instanceof EmptyGreetingResponse) @@ -115,8 +113,7 @@ public void test_remote_mono_empty_request_response_greeting_messsage() { public void test_remote_failing_void_greeting() { // When - StepVerifier.create( - gateway.context().serviceCall().requestOne(GREETING_FAILING_VOID_REQ, Void.class)) + StepVerifier.create(gateway.serviceCall().requestOne(GREETING_FAILING_VOID_REQ, Void.class)) .expectErrorMessage(GREETING_FAILING_VOID_REQ.data().toString()) .verify(TIMEOUT); } @@ -124,7 +121,7 @@ public void test_remote_failing_void_greeting() { @Test public void test_remote_throwing_void_greeting() { // When - StepVerifier.create(gateway.context().serviceCall().oneWay(GREETING_THROWING_VOID_REQ)) + StepVerifier.create(gateway.serviceCall().oneWay(GREETING_THROWING_VOID_REQ)) .expectErrorMessage(GREETING_THROWING_VOID_REQ.data().toString()) .verify(TIMEOUT); } @@ -137,10 +134,7 @@ public void test_remote_fail_greeting() { ServiceException.class, () -> Mono.from( - gateway - .context() - .serviceCall() - .requestOne(GREETING_FAIL_REQ, GreetingResponse.class)) + gateway.serviceCall().requestOne(GREETING_FAIL_REQ, GreetingResponse.class)) .block(TIMEOUT)); assertEquals("GreetingRequest{name='joe'}", exception.getMessage()); } @@ -155,7 +149,6 @@ public void test_remote_exception_void() { () -> Mono.from( gateway - .context() .serviceCall() .requestOne(GREETING_ERROR_REQ, GreetingResponse.class)) .block(TIMEOUT)); @@ -166,7 +159,7 @@ public void test_remote_exception_void() { public void test_remote_async_greeting_return_string() { Publisher resultFuture = - gateway.context().serviceCall().requestOne(GREETING_REQ, String.class); + gateway.serviceCall().requestOne(GREETING_REQ, String.class); // Then ServiceMessage result = Mono.from(resultFuture).block(TIMEOUT); @@ -180,7 +173,7 @@ public void test_remote_async_greeting_return_GreetingResponse() { // When Publisher result = - gateway.context().serviceCall().requestOne(GREETING_REQUEST_REQ, GreetingResponse.class); + gateway.serviceCall().requestOne(GREETING_REQUEST_REQ, GreetingResponse.class); // Then GreetingResponse greeting = Mono.from(result).block(TIMEOUT).data(); @@ -190,7 +183,7 @@ public void test_remote_async_greeting_return_GreetingResponse() { @Test public void test_remote_greeting_request_timeout_expires() { - ServiceCall service = gateway.context().serviceCall(); + ServiceCall service = gateway.serviceCall(); // call the service. Publisher future = service.requestOne(GREETING_REQUEST_TIMEOUT_REQ); @@ -202,7 +195,7 @@ public void test_remote_greeting_request_timeout_expires() { // Since here and below tests were not reviewed [sergeyr] @Test public void test_remote_async_greeting_return_Message() { - ServiceCall service = gateway.context().serviceCall(); + ServiceCall service = gateway.serviceCall(); // call the service. Publisher future = service.requestOne(GREETING_REQUEST_REQ); @@ -222,7 +215,7 @@ public void test_remote_async_greeting_return_Message() { public void test_remote_dispatcher_remote_greeting_request_completes_before_timeout() { Publisher result = - gateway.context().serviceCall().requestOne(GREETING_REQUEST_REQ, GreetingResponse.class); + gateway.serviceCall().requestOne(GREETING_REQUEST_REQ, GreetingResponse.class); GreetingResponse greetings = Mono.from(result).block(TIMEOUT).data(); System.out.println("greeting_request_completes_before_timeout : " + greetings.getResult()); @@ -234,7 +227,6 @@ public void test_service_address_lookup_occur_only_after_subscription() { Flux quotes = gateway - .context() .serviceCall() .requestMany( ServiceMessage.builder() @@ -257,7 +249,7 @@ public void test_service_address_lookup_occur_only_after_subscription() { @Disabled("https://github.com/scalecube/scalecube-services/issues/742") public void test_many_stream_block_first() { - ServiceCall call = gateway.context().serviceCall(); + ServiceCall call = gateway.serviceCall(); ServiceMessage request = TestRequests.GREETING_MANY_STREAM_30; diff --git a/services/src/test/java/io/scalecube/services/ServiceLocalTest.java b/services/src/test/java/io/scalecube/services/ServiceLocalTest.java index 476eea476..088603128 100644 --- a/services/src/test/java/io/scalecube/services/ServiceLocalTest.java +++ b/services/src/test/java/io/scalecube/services/ServiceLocalTest.java @@ -44,7 +44,7 @@ public void cleanUp() { @Test public void test_local_greeting_request_completes_before_timeout() { - GreetingService service = microservices.context().serviceCall().api(GreetingService.class); + GreetingService service = microservices.serviceCall().api(GreetingService.class); // call the service. GreetingResponse result = @@ -214,7 +214,7 @@ void test_local_greeting_message() { .verify(timeout); // using serviceCall directly - ServiceCall serviceCall = microservices.context().serviceCall(); + ServiceCall serviceCall = microservices.serviceCall(); StepVerifier.create( serviceCall.requestOne( @@ -310,9 +310,6 @@ public void test_local_bidi_greeting_expect_GreetingResponse() { } private GreetingService createProxy(Microservices gateway) { - return gateway - .context() - .serviceCall() - .api(GreetingService.class); // create proxy for GreetingService API + return gateway.serviceCall().api(GreetingService.class); // create proxy for GreetingService API } } diff --git a/services/src/test/java/io/scalecube/services/ServiceRegistryTest.java b/services/src/test/java/io/scalecube/services/ServiceRegistryTest.java index 24996ec6a..e36ad9d99 100644 --- a/services/src/test/java/io/scalecube/services/ServiceRegistryTest.java +++ b/services/src/test/java/io/scalecube/services/ServiceRegistryTest.java @@ -50,9 +50,9 @@ public void test_added_removed_registration_events(MetadataCodec metadataCodec) .transport(RSocketServiceTransport::new) .startAwait(); - seed.context().listenDiscovery().subscribe(events); + seed.listenDiscovery().subscribe(events); - Address seedAddress = seed.context().discovery("seed").address(); + Address seedAddress = seed.discovery("seed").address(); Microservices ms1 = Microservices.builder() @@ -96,9 +96,9 @@ public void test_listen_to_discovery_events(MetadataCodec metadataCodec) { .startAwait(); cluster.add(seed); - seed.context().listenDiscovery().subscribe(processor); + seed.listenDiscovery().subscribe(processor); - Address seedAddress = seed.context().discovery("seed").address(); + Address seedAddress = seed.discovery("seed").address(); StepVerifier.create(processor) .then( @@ -137,7 +137,7 @@ public void test_listen_to_discovery_events(MetadataCodec metadataCodec) { .verify(TIMEOUT); StepVerifier.create( - seed.context().serviceCall().api(AnnotationService.class).serviceDiscoveryEventTypes()) + seed.serviceCall().api(AnnotationService.class).serviceDiscoveryEventTypes()) .assertNext(type -> assertEquals(ENDPOINT_ADDED, type)) .assertNext(type -> assertEquals(ENDPOINT_ADDED, type)) .assertNext(type -> assertEquals(ENDPOINT_LEAVING, type)) @@ -166,9 +166,9 @@ public void test_delayed_listen_to_discovery_events(MetadataCodec metadataCodec) .startAwait(); cluster.add(seed); - seed.context().listenDiscovery().subscribe(processor); + seed.listenDiscovery().subscribe(processor); - Address seedAddress = seed.context().discovery("seed").address(); + Address seedAddress = seed.discovery("seed").address(); StepVerifier.create(processor) .then( @@ -200,7 +200,7 @@ public void test_delayed_listen_to_discovery_events(MetadataCodec metadataCodec) .verify(TIMEOUT); StepVerifier.create( - seed.context().serviceCall().api(AnnotationService.class).serviceDiscoveryEventTypes()) + seed.serviceCall().api(AnnotationService.class).serviceDiscoveryEventTypes()) .assertNext(type -> assertEquals(ENDPOINT_ADDED, type)) .assertNext(type -> assertEquals(ENDPOINT_ADDED, type)) .thenCancel() diff --git a/services/src/test/java/io/scalecube/services/ServiceRemoteTest.java b/services/src/test/java/io/scalecube/services/ServiceRemoteTest.java index a23dc9028..c3b4420c2 100644 --- a/services/src/test/java/io/scalecube/services/ServiceRemoteTest.java +++ b/services/src/test/java/io/scalecube/services/ServiceRemoteTest.java @@ -46,7 +46,7 @@ public class ServiceRemoteTest extends BaseTest { public static void setup() { Hooks.onOperatorDebug(); gateway = gateway(); - gatewayAddress = gateway.context().discovery("gateway").address(); + gatewayAddress = gateway.discovery("gateway").address(); provider = serviceProvider(); } @@ -84,7 +84,7 @@ private static Microservices serviceProvider() { public void test_remote_greeting_request_completes_before_timeout() { Duration duration = Duration.ofSeconds(1); - GreetingService service = gateway.context().serviceCall().api(GreetingService.class); + GreetingService service = gateway.serviceCall().api(GreetingService.class); // call the service. Mono result = @@ -95,7 +95,7 @@ public void test_remote_greeting_request_completes_before_timeout() { @Test public void test_remote_void_greeting() throws Exception { - GreetingService service = gateway.context().serviceCall().api(GreetingService.class); + GreetingService service = gateway.serviceCall().api(GreetingService.class); // call the service. service.greetingVoid(new GreetingRequest("joe")).block(Duration.ofSeconds(3)); @@ -108,7 +108,7 @@ public void test_remote_void_greeting() throws Exception { @Test public void test_remote_failing_void_greeting() { - GreetingService service = gateway.context().serviceCall().api(GreetingService.class); + GreetingService service = gateway.serviceCall().api(GreetingService.class); GreetingRequest request = new GreetingRequest("joe"); // call the service. @@ -119,7 +119,7 @@ public void test_remote_failing_void_greeting() { @Test public void test_remote_throwing_void_greeting() { - GreetingService service = gateway.context().serviceCall().api(GreetingService.class); + GreetingService service = gateway.serviceCall().api(GreetingService.class); GreetingRequest request = new GreetingRequest("joe"); // call the service. @@ -228,7 +228,7 @@ void test_remote_greeting_message() { .verify(TIMEOUT); // using serviceCall directly - ServiceCall serviceCall = gateway.context().serviceCall(); + ServiceCall serviceCall = gateway.serviceCall(); StepVerifier.create( serviceCall.requestOne( @@ -278,7 +278,7 @@ public void test_remote_serviceA_calls_serviceB_using_setter() { .startAwait(); // Get a proxy to the service api. - CoarseGrainedService service = gateway.context().serviceCall().api(CoarseGrainedService.class); + CoarseGrainedService service = gateway.serviceCall().api(CoarseGrainedService.class); Publisher future = service.callGreeting("joe"); @@ -301,7 +301,7 @@ public void test_remote_serviceA_calls_serviceB() { .startAwait(); // Get a proxy to the service api. - CoarseGrainedService service = gateway.context().serviceCall().api(CoarseGrainedService.class); + CoarseGrainedService service = gateway.serviceCall().api(CoarseGrainedService.class); Publisher future = service.callGreeting("joe"); assertEquals(" hello to: joe", Mono.from(future).block(Duration.ofSeconds(1))); provider.shutdown().then(Mono.delay(TIMEOUT2)).block(); @@ -321,7 +321,7 @@ public void test_remote_serviceA_calls_serviceB_with_timeout() { .startAwait(); // Get a proxy to the service api. - CoarseGrainedService service = gateway.context().serviceCall().api(CoarseGrainedService.class); + CoarseGrainedService service = gateway.serviceCall().api(CoarseGrainedService.class); InternalServiceException exception = assertThrows( InternalServiceException.class, @@ -346,7 +346,7 @@ public void test_remote_serviceA_calls_serviceB_with_dispatcher() { .startAwait(); // Get a proxy to the service api. - CoarseGrainedService service = gateway.context().serviceCall().api(CoarseGrainedService.class); + CoarseGrainedService service = gateway.serviceCall().api(CoarseGrainedService.class); String response = service.callGreetingWithDispatcher("joe").block(Duration.ofSeconds(5)); assertEquals(response, " hello to: joe"); @@ -430,12 +430,12 @@ public void test_services_contribute_to_cluster_metadata() { .serviceFactory(ScalecubeServiceFactory.fromInstances(new GreetingServiceImpl())) .startAwait(); - assertTrue(ms.context().serviceEndpoint().tags().containsKey("HOSTNAME")); + assertTrue(ms.serviceEndpoint().tags().containsKey("HOSTNAME")); } @Test public void test_remote_mono_empty_greeting() { - GreetingService service = gateway.context().serviceCall().api(GreetingService.class); + GreetingService service = gateway.serviceCall().api(GreetingService.class); // call the service. StepVerifier.create(service.greetingMonoEmpty(new GreetingRequest("empty"))) @@ -445,7 +445,7 @@ public void test_remote_mono_empty_greeting() { @Test public void test_remote_mono_empty_request_response_greeting() { - GreetingService service = gateway.context().serviceCall().api(GreetingService.class); + GreetingService service = gateway.serviceCall().api(GreetingService.class); // call the service. StepVerifier.create(service.emptyGreeting(new EmptyGreetingRequest())) @@ -456,7 +456,7 @@ public void test_remote_mono_empty_request_response_greeting() { @Test public void test_remote_flux_empty_greeting() { - GreetingService service = gateway.context().serviceCall().api(GreetingService.class); + GreetingService service = gateway.serviceCall().api(GreetingService.class); // call the service. StepVerifier.create(service.greetingFluxEmpty(new GreetingRequest("empty"))) @@ -466,7 +466,7 @@ public void test_remote_flux_empty_greeting() { @Disabled("https://github.com/scalecube/scalecube-services/issues/742") public void test_many_stream_block_first() { - GreetingService service = gateway.context().serviceCall().api(GreetingService.class); + GreetingService service = gateway.serviceCall().api(GreetingService.class); for (int i = 0; i < 100; i++) { //noinspection ConstantConditions @@ -476,10 +476,7 @@ public void test_many_stream_block_first() { } private GreetingService createProxy() { - return gateway - .context() - .serviceCall() - .api(GreetingService.class); // create proxy for GreetingService API + return gateway.serviceCall().api(GreetingService.class); // create proxy for GreetingService API } private static ServiceDiscovery serviceDiscovery(ServiceEndpoint endpoint) { diff --git a/services/src/test/java/io/scalecube/services/StreamingServiceTest.java b/services/src/test/java/io/scalecube/services/StreamingServiceTest.java index 2afe316ee..e937d26fa 100644 --- a/services/src/test/java/io/scalecube/services/StreamingServiceTest.java +++ b/services/src/test/java/io/scalecube/services/StreamingServiceTest.java @@ -34,7 +34,7 @@ public static void setup() { .defaultDataDecoder(ServiceMessageCodec::decodeData) .startAwait(); - final Address gatewayAddress = gateway.context().discovery("gateway").address(); + final Address gatewayAddress = gateway.discovery("gateway").address(); node = Microservices.builder() @@ -54,8 +54,7 @@ public void test_quotes() throws InterruptedException { CountDownLatch latch = new CountDownLatch(3); Disposable sub = - node.context() - .serviceCall() + node.serviceCall() .api(QuoteService.class) .quotes() .subscribe( @@ -71,7 +70,7 @@ public void test_quotes() throws InterruptedException { @Test public void test_local_quotes_service() { - QuoteService service = node.context().serviceCall().api(QuoteService.class); + QuoteService service = node.serviceCall().api(QuoteService.class); int expected = 3; List list = service.quotes().take(Duration.ofMillis(3500)).collectList().block(); @@ -85,7 +84,7 @@ public void test_remote_quotes_service() throws InterruptedException { CountDownLatch latch1 = new CountDownLatch(3); CountDownLatch latch2 = new CountDownLatch(3); - QuoteService service = gateway.context().serviceCall().api(QuoteService.class); + QuoteService service = gateway.serviceCall().api(QuoteService.class); service.snapshot(3).subscribe(onNext -> latch1.countDown()); service.snapshot(3).subscribe(onNext -> latch2.countDown()); @@ -101,7 +100,7 @@ public void test_remote_quotes_service() throws InterruptedException { public void test_quotes_batch() throws InterruptedException { int streamBound = 1000; - QuoteService service = gateway.context().serviceCall().api(QuoteService.class); + QuoteService service = gateway.serviceCall().api(QuoteService.class); CountDownLatch latch1 = new CountDownLatch(streamBound); final Disposable sub1 = service.snapshot(streamBound).subscribe(onNext -> latch1.countDown()); @@ -116,7 +115,7 @@ public void test_quotes_batch() throws InterruptedException { public void test_call_quotes_snapshot() { int batchSize = 1000; - ServiceCall serviceCall = gateway.context().serviceCall(); + ServiceCall serviceCall = gateway.serviceCall(); ServiceMessage message = ServiceMessage.builder().qualifier(QuoteService.NAME, "snapshot").data(batchSize).build(); @@ -129,14 +128,14 @@ public void test_call_quotes_snapshot() { @Test public void test_just_once() { - QuoteService service = gateway.context().serviceCall().api(QuoteService.class); + QuoteService service = gateway.serviceCall().api(QuoteService.class); assertEquals("1", service.justOne().block(Duration.ofSeconds(2))); } @Test public void test_just_one_message() { - ServiceCall service = gateway.context().serviceCall(); + ServiceCall service = gateway.serviceCall(); ServiceMessage justOne = ServiceMessage.builder().qualifier(QuoteService.NAME, "justOne").build(); @@ -150,7 +149,7 @@ public void test_just_one_message() { @Test public void test_scheduled_messages() { - ServiceCall serviceCall = gateway.context().serviceCall(); + ServiceCall serviceCall = gateway.serviceCall(); ServiceMessage scheduled = ServiceMessage.builder().qualifier(QuoteService.NAME, "scheduled").data(1000).build(); @@ -165,7 +164,7 @@ public void test_scheduled_messages() { @Test public void test_unknown_method() { - ServiceCall service = gateway.context().serviceCall(); + ServiceCall service = gateway.serviceCall(); ServiceMessage scheduled = ServiceMessage.builder().qualifier(QuoteService.NAME, "unknonwn").build(); @@ -181,7 +180,7 @@ public void test_unknown_method() { public void test_snapshot_completes() { int batchSize = 1000; - ServiceCall serviceCall = gateway.context().serviceCall(); + ServiceCall serviceCall = gateway.serviceCall(); ServiceMessage message = ServiceMessage.builder().qualifier(QuoteService.NAME, "snapshot").data(batchSize).build(); diff --git a/services/src/test/java/io/scalecube/services/routings/RoutersTest.java b/services/src/test/java/io/scalecube/services/routings/RoutersTest.java index 8b6539549..5fd5d4a42 100644 --- a/services/src/test/java/io/scalecube/services/routings/RoutersTest.java +++ b/services/src/test/java/io/scalecube/services/routings/RoutersTest.java @@ -60,7 +60,7 @@ public static void setup() { .transport(RSocketServiceTransport::new) .startAwait(); - gatewayAddress = gateway.context().discovery("gateway").address(); + gatewayAddress = gateway.discovery("gateway").address(); // Create microservices instance cluster. provider1 = @@ -136,7 +136,7 @@ public void test_router_factory() { @Test public void test_round_robin() { - ServiceCall service = gateway.context().serviceCall(); + ServiceCall service = gateway.serviceCall(); // call the service. GreetingResponse result1 = @@ -158,7 +158,7 @@ public void test_remote_service_tags() throws Exception { CanaryService service = gateway - .context().serviceCall() + .serviceCall() .router(Routers.getRouter(WeightedRandomRouter.class)) .api(CanaryService.class); @@ -185,7 +185,7 @@ public void test_remote_service_tags() throws Exception { public void tesTagsFromAnnotation() { ServiceCall serviceCall = provider3 - .context().serviceCall() + .serviceCall() .router( (req, mes) -> { ServiceReference tagServiceRef = req.listServiceReferences().get(0); @@ -207,7 +207,7 @@ public void test_tag_selection_logic() { ServiceCall service = gateway - .context().serviceCall() + .serviceCall() .router( (reg, msg) -> reg.listServiceReferences().stream() @@ -230,7 +230,7 @@ public void test_tag_request_selection_logic() { ServiceCall service = gateway - .context().serviceCall() + .serviceCall() .router( (reg, msg) -> reg.listServiceReferences().stream() @@ -256,7 +256,7 @@ public void test_tag_request_selection_logic() { public void test_service_tags() throws Exception { TimeUnit.SECONDS.sleep(3); - ServiceCall service = gateway.context().serviceCall().router(WeightedRandomRouter.class); + ServiceCall service = gateway.serviceCall().router(WeightedRandomRouter.class); ServiceMessage req = ServiceMessage.builder() diff --git a/services/src/test/java/io/scalecube/services/routings/ServiceTagsExample.java b/services/src/test/java/io/scalecube/services/routings/ServiceTagsExample.java index a3dc33562..7a8f71c11 100644 --- a/services/src/test/java/io/scalecube/services/routings/ServiceTagsExample.java +++ b/services/src/test/java/io/scalecube/services/routings/ServiceTagsExample.java @@ -26,7 +26,7 @@ public static void main(String[] args) { .transport(RSocketServiceTransport::new) .startAwait(); - Address seedAddress = gateway.context().discovery("gateway").address(); + Address seedAddress = gateway.discovery("gateway").address(); Microservices services1 = Microservices.builder() @@ -57,7 +57,7 @@ public static void main(String[] args) { .startAwait(); CanaryService service = - gateway.context().serviceCall().router(WeightedRandomRouter.class).api(CanaryService.class); + gateway.serviceCall().router(WeightedRandomRouter.class).api(CanaryService.class); for (int i = 0; i < 10; i++) { Mono.from(service.greeting(new GreetingRequest("joe"))) diff --git a/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketNettyColocatedEventLoopGroupTest.java b/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketNettyColocatedEventLoopGroupTest.java index 6a23706ea..e00238f4d 100644 --- a/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketNettyColocatedEventLoopGroupTest.java +++ b/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketNettyColocatedEventLoopGroupTest.java @@ -34,7 +34,7 @@ public void setUp() { .transport(RSocketServiceTransport::new) .startAwait(); - final Address gatewayAddress = this.gateway.context().discovery("gateway").address(); + final Address gatewayAddress = this.gateway.discovery("gateway").address(); Microservices facade = Microservices.builder() @@ -47,7 +47,7 @@ public void setUp() { .serviceFactory(ScalecubeServiceFactory.fromInstances(new Facade())) .startAwait(); - final Address facadeAddress = facade.context().discovery("facade").address(); + final Address facadeAddress = facade.discovery("facade").address(); PingService pingService = () -> Mono.just(Thread.currentThread().getName()); this.ping = @@ -76,7 +76,7 @@ public void setUp() { @Test public void testColocatedEventLoopGroup() { - ServiceCall call = gateway.context().serviceCall(); + ServiceCall call = gateway.serviceCall(); FacadeService facade = call.api(FacadeService.class); diff --git a/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketServiceTransportTest.java b/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketServiceTransportTest.java index f58e7ac58..1f67ebec1 100644 --- a/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketServiceTransportTest.java +++ b/services/src/test/java/io/scalecube/services/transport/rsocket/RSocketServiceTransportTest.java @@ -45,7 +45,7 @@ public void setUp() { .transport(RSocketServiceTransport::new) .startAwait(); - final Address gatewayAddress = this.gateway.context().discovery("gateway").address(); + final Address gatewayAddress = this.gateway.discovery("gateway").address(); serviceNode = Microservices.builder() @@ -79,11 +79,10 @@ public void test_remote_node_died_mono_never() throws Exception { AtomicReference sub1 = new AtomicReference<>(null); AtomicReference exceptionHolder = new AtomicReference<>(null); - ServiceCall serviceCall = gateway.context().serviceCall(); + ServiceCall serviceCall = gateway.serviceCall(); sub1.set(serviceCall.requestOne(JUST_NEVER).doOnError(exceptionHolder::set).subscribe()); gateway - .context() .listenDiscovery() .filter(ServiceDiscoveryEvent::isEndpointRemoved) .subscribe(onNext -> latch1.countDown(), System.err::println); @@ -108,11 +107,10 @@ public void test_remote_node_died_many_never() throws Exception { AtomicReference sub1 = new AtomicReference<>(null); AtomicReference exceptionHolder = new AtomicReference<>(null); - ServiceCall serviceCall = gateway.context().serviceCall(); + ServiceCall serviceCall = gateway.serviceCall(); sub1.set(serviceCall.requestMany(JUST_MANY_NEVER).doOnError(exceptionHolder::set).subscribe()); gateway - .context() .listenDiscovery() .filter(ServiceDiscoveryEvent::isEndpointRemoved) .subscribe(onNext -> latch1.countDown(), System.err::println); @@ -137,7 +135,7 @@ public void test_remote_node_died_many_then_never() throws Exception { AtomicReference sub1 = new AtomicReference<>(null); AtomicReference exceptionHolder = new AtomicReference<>(null); - ServiceCall serviceCall = gateway.context().serviceCall(); + ServiceCall serviceCall = gateway.serviceCall(); sub1.set( serviceCall .requestMany(ONLY_ONE_AND_THEN_NEVER) @@ -145,7 +143,6 @@ public void test_remote_node_died_many_then_never() throws Exception { .subscribe()); gateway - .context() .listenDiscovery() .filter(ServiceDiscoveryEvent::isEndpointRemoved) .subscribe(onNext -> latch1.countDown(), System.err::println); From 3d6227756fb013ae5889eb09a63734da63dd4070 Mon Sep 17 00:00:00 2001 From: "e.utkin" Date: Fri, 19 Jun 2020 17:18:30 +0300 Subject: [PATCH 60/61] merge with develop --- .../io/scalecube/services/Microservices.java | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/services/src/main/java/io/scalecube/services/Microservices.java b/services/src/main/java/io/scalecube/services/Microservices.java index ea01c8ad9..afbeae6af 100644 --- a/services/src/main/java/io/scalecube/services/Microservices.java +++ b/services/src/main/java/io/scalecube/services/Microservices.java @@ -8,6 +8,7 @@ import io.scalecube.services.discovery.api.ServiceDiscovery; import io.scalecube.services.discovery.api.ServiceDiscoveryContext; import io.scalecube.services.discovery.api.ServiceDiscoveryEvent; +import io.scalecube.services.discovery.api.ServiceDiscoveryEvent.Type; import io.scalecube.services.discovery.api.ServiceDiscoveryFactory; import io.scalecube.services.discovery.api.ServiceDiscoveryOptions; import io.scalecube.services.exceptions.DefaultErrorMapper; @@ -329,14 +330,21 @@ public ServiceEndpoint serviceEndpoint() { * @return service discovery context */ public ServiceDiscoveryContext discovery(String id) { - return Optional.ofNullable(this.compositeDiscovery.contextMap.get(id)) + return Optional.ofNullable(this.compositeDiscovery.discoveryContexts.get(id)) .orElseThrow(() -> new NoSuchElementException("[discovery] id: " + id)); } /** - * Function to subscribe and listen on {@code ServiceDiscoveryEvent} events. + * Function to subscribe and listen on the stream of {@code ServiceDiscoveryEvent}\s from + * composite service discovery instance. * - * @return stream of {@code ServiceDiscoveryEvent} events + *

Can be called before or after composite service discovery {@code .start()} method call (i.e + * before of after all service discovery instances will be started). If it's called before then + * new events will be streamed from all service discovery instances, if it's called after then + * {@link ServiceRegistry#listServiceEndpoints()} will be turned to service discovery events of + * type {@link Type#ENDPOINT_ADDED}, and concateneted with a stream of live events. + * + * @return stream of {@code ServiceDiscoveryEvent}\s */ public Flux listenDiscovery() { return this.compositeDiscovery.listen(); @@ -381,7 +389,7 @@ private static class CompositeServiceDiscovery implements ServiceDiscovery { private final List> operatorList = new ArrayList<>(); private final Map discoveryMap = new HashMap<>(); - private final Map contextMap = new ConcurrentHashMap<>(); + private final Map discoveryContexts = new ConcurrentHashMap<>(); // Subject private final DirectProcessor subject = DirectProcessor.create(); @@ -472,7 +480,7 @@ private Mono start0( .doOnSuccess( avoid -> { ServiceDiscoveryContext discoveryContext = builder.build(); - contextMap.put(discoveryContext.id(), discoveryContext); + discoveryContexts.put(discoveryContext.id(), discoveryContext); }); } From 7a0bd3a265706443de9d7e3bb0ee8a23458962de Mon Sep 17 00:00:00 2001 From: "e.utkin" Date: Fri, 19 Jun 2020 18:51:10 +0300 Subject: [PATCH 61/61] merge with develop --- .../services/MicroservicesContext.java | 9 ++ .../discovery/CompositeDiscoveryExample.java | 15 +-- .../io/scalecube/services/Microservices.java | 127 ++++++++++++------ 3 files changed, 100 insertions(+), 51 deletions(-) diff --git a/services-api/src/main/java/io/scalecube/services/MicroservicesContext.java b/services-api/src/main/java/io/scalecube/services/MicroservicesContext.java index a60b8be56..1bfbcaac0 100644 --- a/services-api/src/main/java/io/scalecube/services/MicroservicesContext.java +++ b/services-api/src/main/java/io/scalecube/services/MicroservicesContext.java @@ -34,4 +34,13 @@ public interface MicroservicesContext { * @return stream of {@code ServiceDiscoveryEvent} events */ Flux listenDiscovery(); + + /** + * Function to subscribe and listen on {@code ServiceDiscoveryEvent} events by service discovery + * id. + * + * @param id service discovery id + * @return service discovery context + */ + Flux listenDiscovery(String id); } diff --git a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/discovery/CompositeDiscoveryExample.java b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/discovery/CompositeDiscoveryExample.java index 84ecfd597..2cced46e1 100644 --- a/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/discovery/CompositeDiscoveryExample.java +++ b/services-examples-parent/services-examples/src/main/java/io/scalecube/services/examples/discovery/CompositeDiscoveryExample.java @@ -2,13 +2,12 @@ import io.scalecube.net.Address; import io.scalecube.services.Microservices; -import io.scalecube.services.annotations.AfterConstruct; -import io.scalecube.services.ScalecubeServiceFactory; import io.scalecube.services.MicroservicesContext; +import io.scalecube.services.ScalecubeServiceFactory; +import io.scalecube.services.annotations.AfterConstruct; import io.scalecube.services.annotations.Service; import io.scalecube.services.annotations.ServiceMethod; import io.scalecube.services.discovery.ScalecubeServiceDiscovery; -import io.scalecube.services.discovery.api.ServiceDiscoveryContext; import io.scalecube.services.examples.helloworld.service.api.Greeting; import io.scalecube.services.transport.rsocket.RSocketServiceTransport; import reactor.core.publisher.Mono; @@ -120,10 +119,7 @@ public static class GreetingServiceImpl1 implements GreetingsService1 { @AfterConstruct void init(MicroservicesContext ms) { - ServiceDiscoveryContext discoveryContext = ms.discovery("ms1"); - System.err.println("discovery(\"ms1\"): " + discoveryContext); - discoveryContext - .listen() + ms.listenDiscovery("ms1") .subscribe( discoveryEvent -> System.err.println("discovery(\"ms1\") event: " + discoveryEvent)); } @@ -142,10 +138,7 @@ public static class GreetingServiceImpl2 implements GreetingsService2 { @AfterConstruct void init(MicroservicesContext ms) { - ServiceDiscoveryContext discoveryContext = ms.discovery("ms2"); - System.err.println("discovery(\"ms2\"): " + discoveryContext); - discoveryContext - .listen() + ms.listenDiscovery("ms2") .subscribe( discoveryEvent -> System.err.println("discovery(\"ms2\") event: " + discoveryEvent)); } diff --git a/services/src/main/java/io/scalecube/services/Microservices.java b/services/src/main/java/io/scalecube/services/Microservices.java index a7fd24153..813579a26 100644 --- a/services/src/main/java/io/scalecube/services/Microservices.java +++ b/services/src/main/java/io/scalecube/services/Microservices.java @@ -145,6 +145,9 @@ public final class Microservices { private final MonoProcessor shutdown = MonoProcessor.create(); private final MonoProcessor onShutdown = MonoProcessor.create(); + // lazy + private ServiceEndpoint serviceEndpoint; + private Microservices(Builder builder) { this.tags = new HashMap<>(builder.tags); @@ -203,15 +206,18 @@ private Mono start() { .start(this) .map(ServiceTransportBootstrap::address) .flatMap(this::initializeServiceEndpoint) - .flatMap(this::createDiscovery) - .map(serviceDiscovery -> new MicroservicesContextImpl(serviceDiscovery, this::serviceCall)) + .flatMap(endpoint -> createDiscovery(this)) + .map( + serviceDiscovery -> + new MicroservicesContextImpl( + serviceDiscovery, this::serviceCall, this.serviceEndpoint)) .flatMap(this.serviceFactory::initializeServices) .doOnNext(this::registerInMethodRegistry) .publishOn(scheduler) .then(startGateway()) .publishOn(scheduler) .then(Mono.fromCallable(() -> JmxMonitorMBean.start(this))) - .then(this.compositeDiscovery.startListen(this)) + .then(this.compositeDiscovery.startListen()) .publishOn(scheduler) .thenReturn(this) .onErrorResume( @@ -220,28 +226,29 @@ private Mono start() { .doOnTerminate(scheduler::dispose); } - private Mono createDiscovery( - Microservices microservices, ServiceDiscoveryOptions options) { - return compositeDiscovery.createInstance(microservices, options); + private Mono createDiscovery(Microservices microservices) { + return this.compositeDiscovery.createInstance(microservices); } private Mono initializeServiceEndpoint(Address serviceAddress) { Mono> serviceDefinitionsMono = Mono.fromCallable(this.serviceFactory::getServiceDefinitions); - return serviceDefinitionsMono.map( - serviceDefinitions -> { - final ServiceEndpoint.Builder serviceEndpointBuilder = - ServiceEndpoint.builder() - .id(this.id) - .address(serviceAddress) - .contentTypes(DataCodec.getAllContentTypes()) - .tags(this.tags); - serviceDefinitions.forEach( - serviceDefinition -> - serviceEndpointBuilder.appendServiceRegistrations( - ServiceScanner.scanServiceDefinition(serviceDefinition))); - return serviceEndpointBuilder.build(); - }); + return serviceDefinitionsMono + .map( + serviceDefinitions -> { + final ServiceEndpoint.Builder serviceEndpointBuilder = + ServiceEndpoint.builder() + .id(this.id) + .address(serviceAddress) + .contentTypes(DataCodec.getAllContentTypes()) + .tags(this.tags); + serviceDefinitions.forEach( + serviceDefinition -> + serviceEndpointBuilder.appendServiceRegistrations( + ServiceScanner.scanServiceDefinition(serviceDefinition))); + return serviceEndpointBuilder.build(); + }) + .doOnSuccess(serviceEndpoint -> this.serviceEndpoint = serviceEndpoint); } private void registerInMethodRegistry(Collection services) { @@ -320,7 +327,7 @@ public Gateway gateway(String id) { * @return service endpoint */ public ServiceEndpoint serviceEndpoint() { - return this.compositeDiscovery.serviceEndpoint; + return this.serviceEndpoint; } public List serviceEndpoints() { @@ -633,30 +640,28 @@ private CompositeServiceDiscovery addOperator(UnaryOperator createInstance( - Microservices microservices, ServiceDiscoveryOptions options) { + private Mono createInstance(Microservices microservices) { this.microservices = microservices; this.scheduler = Schedulers.newSingle("composite-discovery", true); + ServiceDiscoveryOptions discoveryOptions = new ServiceDiscoveryOptions(); for (UnaryOperator operator : this.optionOperators) { - - final ServiceDiscoveryOptions finalOptions = operator.apply(options); + final ServiceDiscoveryOptions finalOptions = operator.apply(discoveryOptions); final String id = finalOptions.id(); - final ServiceEndpoint serviceEndpoint = finalOptions.serviceEndpoint(); final ServiceDiscovery serviceDiscovery = - finalOptions.discoveryFactory().createServiceDiscovery(serviceEndpoint); + finalOptions.discoveryFactory().createServiceDiscovery(microservices.serviceEndpoint()); - discoveryInstances.put(id, serviceDiscovery); + this.discoveryInstances.put(id, serviceDiscovery); - discoveryContexts.put( + this.discoveryContexts.put( id, ServiceDiscoveryContext.builder() .id(id) .address(Address.NULL_ADDRESS) .discovery(serviceDiscovery) .serviceRegistry(microservices.serviceRegistry) - .scheduler(scheduler) + .scheduler(this.scheduler) .build()); } @@ -665,28 +670,28 @@ private Mono createInstance( private Mono startListen() { return start() // start composite discovery - .doOnSubscribe(s -> LOGGER.info("[{}][startListen] Starting", microservices.id())) - .doOnSuccess(avoid -> LOGGER.info("[{}][startListen] Started", microservices.id())) + .doOnSubscribe(s -> LOGGER.info("[{}][startListen] Starting", this.microservices.id())) + .doOnSuccess(avoid -> LOGGER.info("[{}][startListen] Started", this.microservices.id())) .doOnError( ex -> LOGGER.error( "[{}][startListen] Exception occurred: {}", - microservices.id(), + this.microservices.id(), ex.toString())); } @Override public Flux listen() { - return Flux.fromStream(microservices.serviceRegistry.listServiceEndpoints().stream()) + return Flux.fromStream(this.microservices.serviceRegistry.listServiceEndpoints().stream()) .map(ServiceDiscoveryEvent::newEndpointAdded) - .concatWith(subject) - .subscribeOn(scheduler) - .publishOn(scheduler); + .concatWith(this.subject) + .subscribeOn(this.scheduler) + .publishOn(this.scheduler); } @Override public Mono start() { - return Flux.fromIterable(discoveryInstances.entrySet()) + return Flux.fromIterable(this.discoveryInstances.entrySet()) .flatMap( entry -> { final String id = entry.getKey(); @@ -902,8 +907,7 @@ private static JmxMonitorMBean start(Microservices instance) throws Exception { MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer(); JmxMonitorMBean jmxMBean = new JmxMonitorMBean(instance); ObjectName objectName = - new ObjectName( - String.format(OBJECT_NAME_FORMAT, instance.id(), System.nanoTime())); + new ObjectName(String.format(OBJECT_NAME_FORMAT, instance.id(), System.nanoTime())); StandardMBean standardMBean = new StandardMBean(jmxMBean, MonitorMBean.class); mbeanServer.registerMBean(standardMBean, objectName); return jmxMBean; @@ -967,4 +971,47 @@ private static String asString(ServiceInfo serviceInfo) { .toString(); } } + + private static final class MicroservicesContextImpl implements MicroservicesContext { + + private final CompositeServiceDiscovery serviceDiscovery; + private final Supplier serviceCallSupplier; + private final ServiceEndpoint serviceEndpoint; + + private MicroservicesContextImpl( + CompositeServiceDiscovery serviceDiscovery, + Supplier serviceCallSupplier, + ServiceEndpoint serviceEndpoint) { + this.serviceDiscovery = serviceDiscovery; + this.serviceCallSupplier = serviceCallSupplier; + this.serviceEndpoint = serviceEndpoint; + } + + @Override + public ServiceEndpoint serviceEndpoint() { + return this.serviceEndpoint; + } + + @Override + public ServiceCall serviceCall() { + return this.serviceCallSupplier.get(); + } + + @Override + public Flux listenDiscovery() { + return this.serviceDiscovery.listen(); + } + + /** + * {@inheritDoc} + * + * @see Microservices.Builder#discovery(String, ServiceDiscoveryFactory) + */ + @Override + public Flux listenDiscovery(String id) { + return Optional.ofNullable(this.serviceDiscovery.discoveryInstances.get(id)) + .map(ServiceDiscovery::listen) + .orElseThrow(() -> new NoSuchElementException("[discovery] id: " + id)); + } + } }