|
| 1 | +package com.google.cloud.functions.invoker; |
| 2 | + |
| 3 | +import com.google.cloud.functions.HttpRequest; |
| 4 | +import com.google.cloud.functions.HttpResponse; |
| 5 | +import com.google.cloud.functions.TypedFunction; |
| 6 | +import com.google.cloud.functions.TypedFunction.WireFormat; |
| 7 | +import com.google.cloud.functions.invoker.http.HttpRequestImpl; |
| 8 | +import com.google.cloud.functions.invoker.http.HttpResponseImpl; |
| 9 | +import com.google.gson.Gson; |
| 10 | +import com.google.gson.GsonBuilder; |
| 11 | +import java.io.BufferedReader; |
| 12 | +import java.io.BufferedWriter; |
| 13 | +import java.lang.reflect.Type; |
| 14 | +import java.util.Arrays; |
| 15 | +import java.util.Optional; |
| 16 | +import java.util.logging.Level; |
| 17 | +import java.util.logging.Logger; |
| 18 | +import javax.servlet.http.HttpServlet; |
| 19 | +import javax.servlet.http.HttpServletRequest; |
| 20 | +import javax.servlet.http.HttpServletResponse; |
| 21 | + |
| 22 | +public class TypedFunctionExecutor extends HttpServlet { |
| 23 | + private static final String APPLY_METHOD = "apply"; |
| 24 | + private static final Logger logger = Logger.getLogger("com.google.cloud.functions.invoker"); |
| 25 | + |
| 26 | + private final Type argType; |
| 27 | + private final TypedFunction<Object, Object> function; |
| 28 | + private final WireFormat format; |
| 29 | + |
| 30 | + private TypedFunctionExecutor( |
| 31 | + Type argType, TypedFunction<Object, Object> func, WireFormat format) { |
| 32 | + this.argType = argType; |
| 33 | + this.function = func; |
| 34 | + this.format = format; |
| 35 | + } |
| 36 | + |
| 37 | + public static TypedFunctionExecutor forClass(Class<?> functionClass) { |
| 38 | + if (!TypedFunction.class.isAssignableFrom(functionClass)) { |
| 39 | + throw new RuntimeException( |
| 40 | + "Class " |
| 41 | + + functionClass.getName() |
| 42 | + + " does not implement " |
| 43 | + + TypedFunction.class.getName()); |
| 44 | + } |
| 45 | + @SuppressWarnings("unchecked") |
| 46 | + Class<? extends TypedFunction<?, ?>> typedFunctionClass = |
| 47 | + (Class<? extends TypedFunction<?, ?>>) functionClass.asSubclass(TypedFunction.class); |
| 48 | + |
| 49 | + Optional<Type> argType = handlerTypeArgument(typedFunctionClass); |
| 50 | + if (argType.isEmpty()) { |
| 51 | + throw new RuntimeException( |
| 52 | + "Class " |
| 53 | + + typedFunctionClass.getName() |
| 54 | + + " does not implement " |
| 55 | + + TypedFunction.class.getName()); |
| 56 | + } |
| 57 | + |
| 58 | + TypedFunction<?, ?> typedFunction; |
| 59 | + try { |
| 60 | + typedFunction = typedFunctionClass.getDeclaredConstructor().newInstance(); |
| 61 | + } catch (Exception e) { |
| 62 | + throw new RuntimeException( |
| 63 | + "Class " |
| 64 | + + typedFunctionClass.getName() |
| 65 | + + " must declare a valid default constructor to be usable as a strongly typed" |
| 66 | + + " function. Could not use constructor: " |
| 67 | + + e.toString()); |
| 68 | + } |
| 69 | + |
| 70 | + WireFormat format = typedFunction.getWireFormat(); |
| 71 | + if (format == null) { |
| 72 | + format = LazyDefaultFormatHolder.defaultFormat; |
| 73 | + } |
| 74 | + |
| 75 | + @SuppressWarnings("unchecked") |
| 76 | + TypedFunctionExecutor executor = |
| 77 | + new TypedFunctionExecutor( |
| 78 | + argType.orElseThrow(), (TypedFunction<Object, Object>) typedFunction, format); |
| 79 | + return executor; |
| 80 | + } |
| 81 | + |
| 82 | + /** |
| 83 | + * Returns the {@code ReqT} of a concrete class that implements {@link TypedFunction |
| 84 | + * TypedFunction<ReqT, RespT>}. Returns an empty {@link Optional} if {@code ReqT} can't be |
| 85 | + * determined. |
| 86 | + */ |
| 87 | + static Optional<Type> handlerTypeArgument(Class<? extends TypedFunction<?, ?>> functionClass) { |
| 88 | + return Arrays.stream(functionClass.getMethods()) |
| 89 | + .filter(method -> method.getName().equals(APPLY_METHOD) && method.getParameterCount() == 1) |
| 90 | + .map(method -> method.getGenericParameterTypes()[0]) |
| 91 | + .filter(type -> type != Object.class) |
| 92 | + .findFirst(); |
| 93 | + } |
| 94 | + |
| 95 | + /** Executes the user's method, can handle all HTTP type methods. */ |
| 96 | + @Override |
| 97 | + public void service(HttpServletRequest req, HttpServletResponse res) { |
| 98 | + HttpRequestImpl reqImpl = new HttpRequestImpl(req); |
| 99 | + HttpResponseImpl resImpl = new HttpResponseImpl(res); |
| 100 | + ClassLoader oldContextClassLoader = Thread.currentThread().getContextClassLoader(); |
| 101 | + |
| 102 | + try { |
| 103 | + Thread.currentThread().setContextClassLoader(function.getClass().getClassLoader()); |
| 104 | + handleRequest(reqImpl, resImpl); |
| 105 | + } finally { |
| 106 | + Thread.currentThread().setContextClassLoader(oldContextClassLoader); |
| 107 | + resImpl.flush(); |
| 108 | + } |
| 109 | + } |
| 110 | + |
| 111 | + private void handleRequest(HttpRequest req, HttpResponse res) { |
| 112 | + Object reqObj; |
| 113 | + try { |
| 114 | + reqObj = format.deserialize(req, argType); |
| 115 | + } catch (Throwable t) { |
| 116 | + logger.log(Level.SEVERE, "Failed to parse request for " + function.getClass().getName(), t); |
| 117 | + res.setStatusCode(HttpServletResponse.SC_BAD_REQUEST); |
| 118 | + return; |
| 119 | + } |
| 120 | + |
| 121 | + Object resObj; |
| 122 | + try { |
| 123 | + resObj = function.apply(reqObj); |
| 124 | + } catch (Throwable t) { |
| 125 | + logger.log(Level.SEVERE, "Failed to execute " + function.getClass().getName(), t); |
| 126 | + res.setStatusCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); |
| 127 | + return; |
| 128 | + } |
| 129 | + |
| 130 | + try { |
| 131 | + format.serialize(resObj, res); |
| 132 | + } catch (Throwable t) { |
| 133 | + logger.log( |
| 134 | + Level.SEVERE, "Failed to serialize response for " + function.getClass().getName(), t); |
| 135 | + res.setStatusCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); |
| 136 | + return; |
| 137 | + } |
| 138 | + } |
| 139 | + |
| 140 | + private static class LazyDefaultFormatHolder { |
| 141 | + static final WireFormat defaultFormat = new GsonWireFormat(); |
| 142 | + } |
| 143 | + |
| 144 | + private static class GsonWireFormat implements TypedFunction.WireFormat { |
| 145 | + private final Gson gson = new GsonBuilder().create(); |
| 146 | + |
| 147 | + @Override |
| 148 | + public void serialize(Object object, HttpResponse response) throws Exception { |
| 149 | + if (object == null) { |
| 150 | + response.setStatusCode(HttpServletResponse.SC_NO_CONTENT); |
| 151 | + return; |
| 152 | + } |
| 153 | + try (BufferedWriter bodyWriter = response.getWriter()) { |
| 154 | + gson.toJson(object, bodyWriter); |
| 155 | + } |
| 156 | + } |
| 157 | + |
| 158 | + @Override |
| 159 | + public Object deserialize(HttpRequest request, Type type) throws Exception { |
| 160 | + try (BufferedReader bodyReader = request.getReader()) { |
| 161 | + return gson.fromJson(bodyReader, type); |
| 162 | + } |
| 163 | + } |
| 164 | + } |
| 165 | +} |
0 commit comments