-
Notifications
You must be signed in to change notification settings - Fork 66
feat: Define strongly typed function interface #186
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
83a2107
chore: update codeql workflow to install functions-framework-api duri…
garethgeorge 2ebd873
feat: implement typed function signature
garethgeorge dd34ac8
Address codereview feedback
garethgeorge 1bbec7c
Address codereview feedback and deduplicate some shared code
garethgeorge 2396334
Change interface for configuring WireFormat
garethgeorge 2066c0e
Add test coverage for custom WireFormat
garethgeorge 5ace65f
Apply formatting fixes
garethgeorge File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
59 changes: 59 additions & 0 deletions
59
functions-framework-api/src/main/java/com/google/cloud/functions/TypedFunction.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
// Copyright 2019 Google LLC | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
|
||
package com.google.cloud.functions; | ||
|
||
import java.lang.reflect.Type; | ||
|
||
/** | ||
* Represents a Cloud Function with a strongly typed interface that is activated by an HTTP request. | ||
*/ | ||
@FunctionalInterface | ||
public interface TypedFunction<RequestT, ResponseT> { | ||
/** | ||
* Called to service an incoming HTTP request. This interface is implemented by user code to | ||
* provide the action for a given HTTP function. If this method throws any exception (including | ||
* any {@link Error}) then the HTTP response will have a 500 status code. | ||
* | ||
* @param arg the payload of the event, deserialized from the original JSON string. | ||
* @return invocation result or null to indicate the body of the response should be empty. | ||
* @throws Exception to produce a 500 status code in the HTTP response. | ||
*/ | ||
public ResponseT apply(RequestT arg) throws Exception; | ||
|
||
/** | ||
* Called to get the the format object that handles request decoding and response encoding. If | ||
* null is returned a default JSON format is used. | ||
* | ||
* @return the {@link WireFormat} to use for serialization | ||
*/ | ||
public default WireFormat getWireFormat() { | ||
return null; | ||
} | ||
|
||
/** | ||
* Describes how to deserialize request object and serialize response objects for an HTTP | ||
* invocation. | ||
*/ | ||
public interface WireFormat { | ||
/** Serialize is expected to encode the object to the provided HttpResponse. */ | ||
void serialize(Object object, HttpResponse response) throws Exception; | ||
|
||
/** | ||
* Deserialize is expected to read an object of {@code Type} from the HttpRequest. The Type is | ||
* determined through reflection on the user's function. | ||
*/ | ||
Object deserialize(HttpRequest request, Type type) throws Exception; | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
165 changes: 165 additions & 0 deletions
165
invoker/core/src/main/java/com/google/cloud/functions/invoker/TypedFunctionExecutor.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,165 @@ | ||
package com.google.cloud.functions.invoker; | ||
|
||
import com.google.cloud.functions.HttpRequest; | ||
import com.google.cloud.functions.HttpResponse; | ||
import com.google.cloud.functions.TypedFunction; | ||
import com.google.cloud.functions.TypedFunction.WireFormat; | ||
import com.google.cloud.functions.invoker.http.HttpRequestImpl; | ||
import com.google.cloud.functions.invoker.http.HttpResponseImpl; | ||
import com.google.gson.Gson; | ||
import com.google.gson.GsonBuilder; | ||
import java.io.BufferedReader; | ||
import java.io.BufferedWriter; | ||
import java.lang.reflect.Type; | ||
import java.util.Arrays; | ||
import java.util.Optional; | ||
import java.util.logging.Level; | ||
import java.util.logging.Logger; | ||
import javax.servlet.http.HttpServlet; | ||
import javax.servlet.http.HttpServletRequest; | ||
import javax.servlet.http.HttpServletResponse; | ||
|
||
public class TypedFunctionExecutor extends HttpServlet { | ||
private static final String APPLY_METHOD = "apply"; | ||
private static final Logger logger = Logger.getLogger("com.google.cloud.functions.invoker"); | ||
|
||
private final Type argType; | ||
private final TypedFunction<Object, Object> function; | ||
private final WireFormat format; | ||
|
||
private TypedFunctionExecutor( | ||
Type argType, TypedFunction<Object, Object> func, WireFormat format) { | ||
this.argType = argType; | ||
this.function = func; | ||
this.format = format; | ||
} | ||
|
||
public static TypedFunctionExecutor forClass(Class<?> functionClass) { | ||
if (!TypedFunction.class.isAssignableFrom(functionClass)) { | ||
throw new RuntimeException( | ||
"Class " | ||
+ functionClass.getName() | ||
+ " does not implement " | ||
+ TypedFunction.class.getName()); | ||
} | ||
@SuppressWarnings("unchecked") | ||
Class<? extends TypedFunction<?, ?>> typedFunctionClass = | ||
(Class<? extends TypedFunction<?, ?>>) functionClass.asSubclass(TypedFunction.class); | ||
|
||
Optional<Type> argType = handlerTypeArgument(typedFunctionClass); | ||
if (argType.isEmpty()) { | ||
throw new RuntimeException( | ||
"Class " | ||
+ typedFunctionClass.getName() | ||
+ " does not implement " | ||
+ TypedFunction.class.getName()); | ||
} | ||
|
||
TypedFunction<?, ?> typedFunction; | ||
try { | ||
typedFunction = typedFunctionClass.getDeclaredConstructor().newInstance(); | ||
} catch (Exception e) { | ||
throw new RuntimeException( | ||
"Class " | ||
+ typedFunctionClass.getName() | ||
+ " must declare a valid default constructor to be usable as a strongly typed" | ||
+ " function. Could not use constructor: " | ||
+ e.toString()); | ||
} | ||
|
||
WireFormat format = typedFunction.getWireFormat(); | ||
if (format == null) { | ||
format = LazyDefaultFormatHolder.defaultFormat; | ||
} | ||
|
||
@SuppressWarnings("unchecked") | ||
TypedFunctionExecutor executor = | ||
new TypedFunctionExecutor( | ||
argType.orElseThrow(), (TypedFunction<Object, Object>) typedFunction, format); | ||
return executor; | ||
} | ||
|
||
/** | ||
* Returns the {@code ReqT} of a concrete class that implements {@link TypedFunction | ||
* TypedFunction<ReqT, RespT>}. Returns an empty {@link Optional} if {@code ReqT} can't be | ||
* determined. | ||
*/ | ||
static Optional<Type> handlerTypeArgument(Class<? extends TypedFunction<?, ?>> functionClass) { | ||
return Arrays.stream(functionClass.getMethods()) | ||
.filter(method -> method.getName().equals(APPLY_METHOD) && method.getParameterCount() == 1) | ||
garethgeorge marked this conversation as resolved.
Show resolved
Hide resolved
|
||
.map(method -> method.getGenericParameterTypes()[0]) | ||
.filter(type -> type != Object.class) | ||
.findFirst(); | ||
} | ||
|
||
/** Executes the user's method, can handle all HTTP type methods. */ | ||
@Override | ||
public void service(HttpServletRequest req, HttpServletResponse res) { | ||
garethgeorge marked this conversation as resolved.
Show resolved
Hide resolved
|
||
HttpRequestImpl reqImpl = new HttpRequestImpl(req); | ||
HttpResponseImpl resImpl = new HttpResponseImpl(res); | ||
ClassLoader oldContextClassLoader = Thread.currentThread().getContextClassLoader(); | ||
|
||
try { | ||
Thread.currentThread().setContextClassLoader(function.getClass().getClassLoader()); | ||
handleRequest(reqImpl, resImpl); | ||
} finally { | ||
Thread.currentThread().setContextClassLoader(oldContextClassLoader); | ||
resImpl.flush(); | ||
} | ||
} | ||
|
||
private void handleRequest(HttpRequest req, HttpResponse res) { | ||
Object reqObj; | ||
try { | ||
reqObj = format.deserialize(req, argType); | ||
} catch (Throwable t) { | ||
logger.log(Level.SEVERE, "Failed to parse request for " + function.getClass().getName(), t); | ||
res.setStatusCode(HttpServletResponse.SC_BAD_REQUEST); | ||
return; | ||
} | ||
|
||
Object resObj; | ||
try { | ||
resObj = function.apply(reqObj); | ||
} catch (Throwable t) { | ||
logger.log(Level.SEVERE, "Failed to execute " + function.getClass().getName(), t); | ||
res.setStatusCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); | ||
return; | ||
} | ||
|
||
try { | ||
format.serialize(resObj, res); | ||
} catch (Throwable t) { | ||
logger.log( | ||
Level.SEVERE, "Failed to serialize response for " + function.getClass().getName(), t); | ||
res.setStatusCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); | ||
return; | ||
} | ||
} | ||
|
||
private static class LazyDefaultFormatHolder { | ||
static final WireFormat defaultFormat = new GsonWireFormat(); | ||
} | ||
|
||
private static class GsonWireFormat implements TypedFunction.WireFormat { | ||
HKWinterhalter marked this conversation as resolved.
Show resolved
Hide resolved
|
||
private final Gson gson = new GsonBuilder().create(); | ||
|
||
@Override | ||
public void serialize(Object object, HttpResponse response) throws Exception { | ||
if (object == null) { | ||
response.setStatusCode(HttpServletResponse.SC_NO_CONTENT); | ||
return; | ||
} | ||
try (BufferedWriter bodyWriter = response.getWriter()) { | ||
gson.toJson(object, bodyWriter); | ||
} | ||
} | ||
|
||
@Override | ||
public Object deserialize(HttpRequest request, Type type) throws Exception { | ||
try (BufferedReader bodyReader = request.getReader()) { | ||
return gson.fromJson(bodyReader, type); | ||
} | ||
} | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.