|
| 1 | +/* |
| 2 | + * Copyright (c) 2017, salesforce.com, inc. |
| 3 | + * All rights reserved. |
| 4 | + * Licensed under the BSD 3-Clause license. |
| 5 | + * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause |
| 6 | + */ |
| 7 | + |
| 8 | +package com.salesforce.grpc.contrib.instancemode; |
| 9 | + |
| 10 | +import com.salesforce.grpc.contrib.session.ClientSessionTransportFilter; |
| 11 | +import com.salesforce.grpc.contrib.session.SessionLifecycleEvent; |
| 12 | +import com.salesforce.grpc.contrib.session.SessionLifecycleEventListener; |
| 13 | +import com.salesforce.grpc.contrib.session.SessionLifecycleEventSource; |
| 14 | +import io.grpc.*; |
| 15 | + |
| 16 | +import java.util.Collection; |
| 17 | +import java.util.Map; |
| 18 | +import java.util.UUID; |
| 19 | +import java.util.concurrent.ConcurrentHashMap; |
| 20 | +import java.util.function.Supplier; |
| 21 | + |
| 22 | +import static com.google.common.base.Preconditions.checkNotNull; |
| 23 | + |
| 24 | +/** |
| 25 | + * {@code PerSessionService} forces gRPC to instantiate a fresh service implementation object for each unique client |
| 26 | + * session connecting to a service. |
| 27 | + * |
| 28 | + * <p>{@code PerSessionService} is useful when you want to share state between service operations on a per-session |
| 29 | + * basis. Each time a client {@code ManagedChannel} connects to a {@code PerSessionService}, a new service |
| 30 | + * implementation instance is created. This instance will be used for all calls made by the {@code ManagedChannel}, but |
| 31 | + * will be isolated from calls made from other clients. However, isolation comes at a cost to performance. Service |
| 32 | + * implementation initialization time is added to every request. If initialization is costly or time consuming, gRPC |
| 33 | + * throughput will noticeably degrade. Additionally, resource consumption will grow linearly with the number of |
| 34 | + * concurrent connections. Resource exhaustion and poor scalability will happen the service is not implemented with |
| 35 | + * care. |
| 36 | + * |
| 37 | + * <p>If the decorated service instance implements {@link AutoCloseable}, the instance's {@link AutoCloseable#close()} |
| 38 | + * method will be called when the client's connection is closed. Use this opportunity to free any shared resources. |
| 39 | + * |
| 40 | + * @param <T> a {@code BindableService} implementation to decorate |
| 41 | + */ |
| 42 | +public class PerSessionService<T extends BindableService> implements BindableService, SessionLifecycleEventListener { |
| 43 | + private ServerServiceDefinition perSessionBinding; |
| 44 | + private Map<UUID, T> sessionServices = new ConcurrentHashMap<>(); |
| 45 | + |
| 46 | + /** |
| 47 | + * Create a {@code PerSessionService} for a provided service implementation class, generated by a factory method. |
| 48 | + * |
| 49 | + * @param factory A factory that will initialize a new service implementation object for every call. |
| 50 | + * @param transportFilter A {@link SessionLifecycleEventSource} emitting {@link SessionLifecycleEvent}s. |
| 51 | + */ |
| 52 | + public PerSessionService(Supplier<T> factory, SessionLifecycleEventSource transportFilter) { |
| 53 | + checkNotNull(factory, "factory"); |
| 54 | + checkNotNull(transportFilter, "transportFilter"); |
| 55 | + |
| 56 | + perSessionBinding = bindFactory(factory); |
| 57 | + transportFilter.addSessionEventListener(this); |
| 58 | + } |
| 59 | + |
| 60 | + /** |
| 61 | + * Create a {@code PerSessionService} for a provided service implementation class. The provided class must have a |
| 62 | + * default constructor. |
| 63 | + * |
| 64 | + * @param clazz The service implementation class to decorate. |
| 65 | + */ |
| 66 | + public PerSessionService(Class<T> clazz, SessionLifecycleEventSource transportFilter) { |
| 67 | + this (() -> { |
| 68 | + try { |
| 69 | + checkNotNull(clazz, "clazz"); |
| 70 | + return clazz.newInstance(); |
| 71 | + } catch (ReflectiveOperationException e) { |
| 72 | + throw new IllegalArgumentException("Class " + clazz.getName() + " must have a public default constructor", e); |
| 73 | + } |
| 74 | + }, transportFilter); |
| 75 | + } |
| 76 | + |
| 77 | + @SuppressWarnings("unchecked") |
| 78 | + private ServerServiceDefinition bindFactory(Supplier<T> factory) { |
| 79 | + ServerServiceDefinition baseDefinition = factory.get().bindService(); |
| 80 | + ServiceDescriptor descriptor = baseDefinition.getServiceDescriptor(); |
| 81 | + Collection<ServerMethodDefinition<?, ?>> methods = baseDefinition.getMethods(); |
| 82 | + |
| 83 | + ServerServiceDefinition.Builder builder = ServerServiceDefinition.builder(descriptor); |
| 84 | + methods.forEach(method -> builder.addMethod(ServerMethodDefinition.create(method.getMethodDescriptor(), new PerSessionServerCallHandler(factory)))); |
| 85 | + return builder.build(); |
| 86 | + } |
| 87 | + |
| 88 | + @Override |
| 89 | + public ServerServiceDefinition bindService() { |
| 90 | + return perSessionBinding; |
| 91 | + } |
| 92 | + |
| 93 | + @Override |
| 94 | + public void sessionStart(SessionLifecycleEvent event) { |
| 95 | + |
| 96 | + } |
| 97 | + |
| 98 | + @Override |
| 99 | + public void sessionEnd(SessionLifecycleEvent event) { |
| 100 | + T instance = sessionServices.remove(event.getSessionId()); |
| 101 | + if (instance instanceof AutoCloseable) { |
| 102 | + try { |
| 103 | + ((AutoCloseable) instance).close(); |
| 104 | + } catch (Throwable t) { |
| 105 | + throw new RuntimeException(t); |
| 106 | + } |
| 107 | + } |
| 108 | + } |
| 109 | + |
| 110 | + /** |
| 111 | + * Internal class implementing the per-session service pattern. |
| 112 | + */ |
| 113 | + private class PerSessionServerCallHandler implements ServerCallHandler { |
| 114 | + private Supplier<T> factory; |
| 115 | + |
| 116 | + PerSessionServerCallHandler(Supplier<T> factory) { |
| 117 | + this.factory = factory; |
| 118 | + } |
| 119 | + |
| 120 | + @Override |
| 121 | + @SuppressWarnings("unchecked") |
| 122 | + public ServerCall.Listener startCall(ServerCall call, Metadata headers) { |
| 123 | + UUID sessionId = call.getAttributes().get(ClientSessionTransportFilter.TRANSPORT_ATTRIBUTES_SESSION_ID); |
| 124 | + if (sessionId != null) { |
| 125 | + if (!sessionServices.containsKey(sessionId)) { |
| 126 | + T instance = factory.get(); |
| 127 | + sessionServices.put(sessionId, instance); |
| 128 | + |
| 129 | + ServerServiceDefinition definition = instance.bindService(); |
| 130 | + ServerMethodDefinition method = definition.getMethod(call.getMethodDescriptor().getFullMethodName()); |
| 131 | + |
| 132 | + return method.getServerCallHandler().startCall(call, headers); |
| 133 | + } else { |
| 134 | + T instance = sessionServices.get(sessionId); |
| 135 | + ServerServiceDefinition definition = instance.bindService(); |
| 136 | + ServerMethodDefinition method = definition.getMethod(call.getMethodDescriptor().getFullMethodName()); |
| 137 | + |
| 138 | + return method.getServerCallHandler().startCall(call, headers); |
| 139 | + } |
| 140 | + } else { |
| 141 | + throw new IllegalStateException("ClientSessionTransportFilter was not registered with " + |
| 142 | + "ServerBuilder.addTransportFilter(new ClientSessionTransportFilter())"); |
| 143 | + } |
| 144 | + } |
| 145 | + } |
| 146 | +} |
0 commit comments