You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@flink.apache.org by se...@apache.org on 2020/02/14 17:31:05 UTC
[flink-statefun] branch master updated (11f88f5 -> 4428f3e)
This is an automated email from the ASF dual-hosted git repository.
sewen pushed a change to branch master
in repository https://gitbox.apache.org/repos/asf/flink-statefun.git.
from 11f88f5 fixup! [FLINK-16061] Disable and remove state multiplexing
new 5f6a40b [FLINK-15956] Add HTTP function protocol
new 93b9626 [FLINK-15956] Move the gRPC/HTTP to their own packages
new 4663786 [FLINK-15956] Use okhttp client
new 94def77 [FLINK-15956] Add an initial HttpFunction implemention
new 85f3be9 [FLINK-15956] Add an exponential backoff
new 69abd09 [FLINK-15956] Use ExponentialBackoff during retires
new 01dfcf4 [FLINK-15956] Add "timeout" to http function spec
new 62a159b [hotfix] Include response code >= 500 as retryable
new 9505cee [FLINK-15956] Use maxRequestDuration of HttpFunctionSpec
new f3a9bd5 fixup! [FLINK-15956] Add an exponential backoff
new 4428f3e [hotfix] Remove @NonNull annotation
The 11 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
Summary of changes:
statefun-flink/statefun-flink-core/pom.xml | 13 +-
.../backpressure/BoundedExponentialBackoff.java | 66 ++++++
.../flink/core/backpressure/SystemNanoTimer.java | 33 +--
.../statefun/flink/core/backpressure/Timer.java | 9 +-
.../statefun/flink/core/common/PolyglotUtil.java | 52 +++++
.../core/{jsonmodule => grpcfn}/GrpcFunction.java | 2 +-
.../GrpcFunctionProvider.java | 2 +-
.../{jsonmodule => grpcfn}/GrpcFunctionSpec.java | 7 +-
.../statefun/flink/core/httpfn/HttpFunction.java | 231 +++++++++++++++++++++
.../HttpFunctionProvider.java | 24 ++-
.../{jsonmodule => httpfn}/HttpFunctionSpec.java | 13 +-
.../statefun/flink/core/httpfn/OkHttpUtils.java | 71 +++++++
.../flink/core/httpfn/RetryingCallback.java | 113 ++++++++++
.../statefun/flink/core/jsonmodule/JsonModule.java | 19 +-
.../statefun/flink/core/jsonmodule/Pointers.java | 2 +
.../src/main/protobuf/http-function.proto | 120 +++++++++++
.../BoundedExponentialBackoffTest.java | 65 ++++++
.../src/test/resources/bar-module/module.yaml | 2 +
18 files changed, 810 insertions(+), 34 deletions(-)
create mode 100644 statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/backpressure/BoundedExponentialBackoff.java
copy statefun-docs/src/main/java/org/apache/flink/statefun/docs/io/custom/MyEgressSpec.java => statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/backpressure/SystemNanoTimer.java (52%)
copy statefun-sdk/src/main/java/org/apache/flink/statefun/sdk/state/Accessor.java => statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/backpressure/Timer.java (86%)
create mode 100644 statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/common/PolyglotUtil.java
rename statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/{jsonmodule => grpcfn}/GrpcFunction.java (95%)
rename statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/{jsonmodule => grpcfn}/GrpcFunctionProvider.java (96%)
rename statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/{jsonmodule => grpcfn}/GrpcFunctionSpec.java (83%)
create mode 100644 statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/httpfn/HttpFunction.java
rename statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/{jsonmodule => httpfn}/HttpFunctionProvider.java (58%)
rename statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/{jsonmodule => httpfn}/HttpFunctionSpec.java (76%)
create mode 100644 statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/httpfn/OkHttpUtils.java
create mode 100644 statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/httpfn/RetryingCallback.java
create mode 100644 statefun-flink/statefun-flink-core/src/main/protobuf/http-function.proto
create mode 100644 statefun-flink/statefun-flink-core/src/test/java/org/apache/flink/statefun/flink/core/backpressure/BoundedExponentialBackoffTest.java
[flink-statefun] 02/11: [FLINK-15956] Move the gRPC/HTTP to their
own packages
Posted by se...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
sewen pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/flink-statefun.git
commit 93b9626d373d0349e740785fb1f10de630d90e48
Author: Igal Shilman <ig...@gmail.com>
AuthorDate: Mon Feb 10 12:28:45 2020 +0100
[FLINK-15956] Move the gRPC/HTTP to their own packages
---
.../statefun/flink/core/{jsonmodule => grpcfn}/GrpcFunction.java | 2 +-
.../flink/core/{jsonmodule => grpcfn}/GrpcFunctionProvider.java | 2 +-
.../flink/core/{jsonmodule => grpcfn}/GrpcFunctionSpec.java | 7 ++++---
.../flink/core/{jsonmodule => httpfn}/HttpFunctionProvider.java | 2 +-
.../flink/core/{jsonmodule => httpfn}/HttpFunctionSpec.java | 3 ++-
.../apache/flink/statefun/flink/core/jsonmodule/JsonModule.java | 4 ++++
6 files changed, 13 insertions(+), 7 deletions(-)
diff --git a/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/jsonmodule/GrpcFunction.java b/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/grpcfn/GrpcFunction.java
similarity index 95%
rename from statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/jsonmodule/GrpcFunction.java
rename to statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/grpcfn/GrpcFunction.java
index c7e7d51..9748853 100644
--- a/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/jsonmodule/GrpcFunction.java
+++ b/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/grpcfn/GrpcFunction.java
@@ -15,7 +15,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.flink.statefun.flink.core.jsonmodule;
+package org.apache.flink.statefun.flink.core.grpcfn;
import java.util.Objects;
import org.apache.flink.statefun.sdk.Context;
diff --git a/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/jsonmodule/GrpcFunctionProvider.java b/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/grpcfn/GrpcFunctionProvider.java
similarity index 96%
rename from statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/jsonmodule/GrpcFunctionProvider.java
rename to statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/grpcfn/GrpcFunctionProvider.java
index 4d5db34..828cf22 100644
--- a/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/jsonmodule/GrpcFunctionProvider.java
+++ b/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/grpcfn/GrpcFunctionProvider.java
@@ -15,7 +15,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.flink.statefun.flink.core.jsonmodule;
+package org.apache.flink.statefun.flink.core.grpcfn;
import java.util.Map;
import org.apache.flink.statefun.sdk.FunctionType;
diff --git a/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/jsonmodule/GrpcFunctionSpec.java b/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/grpcfn/GrpcFunctionSpec.java
similarity index 83%
rename from statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/jsonmodule/GrpcFunctionSpec.java
rename to statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/grpcfn/GrpcFunctionSpec.java
index 62bb4f8..711d5b7 100644
--- a/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/jsonmodule/GrpcFunctionSpec.java
+++ b/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/grpcfn/GrpcFunctionSpec.java
@@ -15,17 +15,18 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.flink.statefun.flink.core.jsonmodule;
+package org.apache.flink.statefun.flink.core.grpcfn;
import java.net.SocketAddress;
import java.util.Objects;
+import org.apache.flink.statefun.flink.core.jsonmodule.FunctionSpec;
import org.apache.flink.statefun.sdk.FunctionType;
-final class GrpcFunctionSpec implements FunctionSpec {
+public final class GrpcFunctionSpec implements FunctionSpec {
private final FunctionType functionType;
private final SocketAddress functionAddress;
- GrpcFunctionSpec(FunctionType functionType, SocketAddress functionAddress) {
+ public GrpcFunctionSpec(FunctionType functionType, SocketAddress functionAddress) {
this.functionType = Objects.requireNonNull(functionType);
this.functionAddress = Objects.requireNonNull(functionAddress);
}
diff --git a/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/jsonmodule/HttpFunctionProvider.java b/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/httpfn/HttpFunctionProvider.java
similarity index 95%
rename from statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/jsonmodule/HttpFunctionProvider.java
rename to statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/httpfn/HttpFunctionProvider.java
index 58c1c7c..c4578b0 100644
--- a/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/jsonmodule/HttpFunctionProvider.java
+++ b/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/httpfn/HttpFunctionProvider.java
@@ -16,7 +16,7 @@
* limitations under the License.
*/
-package org.apache.flink.statefun.flink.core.jsonmodule;
+package org.apache.flink.statefun.flink.core.httpfn;
import java.util.Map;
import org.apache.flink.statefun.sdk.FunctionType;
diff --git a/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/jsonmodule/HttpFunctionSpec.java b/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/httpfn/HttpFunctionSpec.java
similarity index 92%
rename from statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/jsonmodule/HttpFunctionSpec.java
rename to statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/httpfn/HttpFunctionSpec.java
index f37358f..45eef71 100644
--- a/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/jsonmodule/HttpFunctionSpec.java
+++ b/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/httpfn/HttpFunctionSpec.java
@@ -15,11 +15,12 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.flink.statefun.flink.core.jsonmodule;
+package org.apache.flink.statefun.flink.core.httpfn;
import java.net.URI;
import java.util.List;
import java.util.Objects;
+import org.apache.flink.statefun.flink.core.jsonmodule.FunctionSpec;
import org.apache.flink.statefun.sdk.FunctionType;
public final class HttpFunctionSpec implements FunctionSpec {
diff --git a/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/jsonmodule/JsonModule.java b/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/jsonmodule/JsonModule.java
index 7f2219f..7bc2d1e 100644
--- a/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/jsonmodule/JsonModule.java
+++ b/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/jsonmodule/JsonModule.java
@@ -43,6 +43,10 @@ import org.apache.flink.statefun.flink.common.ResourceLocator;
import org.apache.flink.statefun.flink.common.json.NamespaceNamePair;
import org.apache.flink.statefun.flink.common.json.Selectors;
import org.apache.flink.statefun.flink.common.protobuf.ProtobufDescriptorMap;
+import org.apache.flink.statefun.flink.core.grpcfn.GrpcFunctionProvider;
+import org.apache.flink.statefun.flink.core.grpcfn.GrpcFunctionSpec;
+import org.apache.flink.statefun.flink.core.httpfn.HttpFunctionProvider;
+import org.apache.flink.statefun.flink.core.httpfn.HttpFunctionSpec;
import org.apache.flink.statefun.flink.core.jsonmodule.FunctionSpec.Kind;
import org.apache.flink.statefun.flink.core.protorouter.ProtobufRouter;
import org.apache.flink.statefun.flink.io.spi.JsonIngressSpec;
[flink-statefun] 08/11: [hotfix] Include response code >= 500 as
retryable
Posted by se...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
sewen pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/flink-statefun.git
commit 62a159b5d6f5d2f1777602b95c2a46885a56ab01
Author: Igal Shilman <ig...@gmail.com>
AuthorDate: Thu Feb 13 15:41:31 2020 +0100
[hotfix] Include response code >= 500 as retryable
---
.../org/apache/flink/statefun/flink/core/httpfn/RetryingCallback.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/httpfn/RetryingCallback.java b/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/httpfn/RetryingCallback.java
index f8a4a8a..567f00f 100644
--- a/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/httpfn/RetryingCallback.java
+++ b/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/httpfn/RetryingCallback.java
@@ -72,7 +72,7 @@ final class RetryingCallback implements Callback {
resultFuture.complete(response);
return;
}
- if (!RETRYABLE_HTTP_CODES.contains(response.code())) {
+ if (!RETRYABLE_HTTP_CODES.contains(response.code()) && response.code() < 500) {
throw new IllegalStateException("Non successful HTTP response code " + response.code());
}
if (!retryAfterApplyingBackoff(call)) {
[flink-statefun] 07/11: [FLINK-15956] Add "timeout" to http
function spec
Posted by se...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
sewen pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/flink-statefun.git
commit 01dfcf4e00f9621b68d6e9466b5f19af2b60d077
Author: Igal Shilman <ig...@gmail.com>
AuthorDate: Thu Feb 13 15:24:40 2020 +0100
[FLINK-15956] Add "timeout" to http function spec
This commit adds a "timeout" property to a function spec module/
A timeout spans the entire HTTP request, including any retries (spaced
apart by backoffs).
---
.../statefun/flink/core/httpfn/HttpFunctionSpec.java | 10 +++++++++-
.../flink/statefun/flink/core/jsonmodule/JsonModule.java | 15 ++++++++++++++-
.../flink/statefun/flink/core/jsonmodule/Pointers.java | 2 ++
3 files changed, 25 insertions(+), 2 deletions(-)
diff --git a/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/httpfn/HttpFunctionSpec.java b/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/httpfn/HttpFunctionSpec.java
index 45eef71..1b016ac 100644
--- a/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/httpfn/HttpFunctionSpec.java
+++ b/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/httpfn/HttpFunctionSpec.java
@@ -18,6 +18,7 @@
package org.apache.flink.statefun.flink.core.httpfn;
import java.net.URI;
+import java.time.Duration;
import java.util.List;
import java.util.Objects;
import org.apache.flink.statefun.flink.core.jsonmodule.FunctionSpec;
@@ -27,11 +28,14 @@ public final class HttpFunctionSpec implements FunctionSpec {
private final FunctionType functionType;
private final URI endpoint;
private final List<String> states;
+ private final Duration maxRequestDuration;
- public HttpFunctionSpec(FunctionType functionType, URI endpoint, List<String> states) {
+ public HttpFunctionSpec(
+ FunctionType functionType, URI endpoint, List<String> states, Duration maxRequestDuration) {
this.functionType = Objects.requireNonNull(functionType);
this.endpoint = Objects.requireNonNull(endpoint);
this.states = Objects.requireNonNull(states);
+ this.maxRequestDuration = Objects.requireNonNull(maxRequestDuration);
}
@Override
@@ -51,4 +55,8 @@ public final class HttpFunctionSpec implements FunctionSpec {
public List<String> states() {
return states;
}
+
+ public Duration maxRequestDuration() {
+ return maxRequestDuration;
+ }
}
diff --git a/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/jsonmodule/JsonModule.java b/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/jsonmodule/JsonModule.java
index 7bc2d1e..dd43367 100644
--- a/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/jsonmodule/JsonModule.java
+++ b/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/jsonmodule/JsonModule.java
@@ -28,6 +28,7 @@ import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URL;
+import java.time.Duration;
import java.util.List;
import java.util.Locale;
import java.util.Map;
@@ -48,6 +49,7 @@ import org.apache.flink.statefun.flink.core.grpcfn.GrpcFunctionSpec;
import org.apache.flink.statefun.flink.core.httpfn.HttpFunctionProvider;
import org.apache.flink.statefun.flink.core.httpfn.HttpFunctionSpec;
import org.apache.flink.statefun.flink.core.jsonmodule.FunctionSpec.Kind;
+import org.apache.flink.statefun.flink.core.jsonmodule.Pointers.Functions;
import org.apache.flink.statefun.flink.core.protorouter.ProtobufRouter;
import org.apache.flink.statefun.flink.io.spi.JsonIngressSpec;
import org.apache.flink.statefun.sdk.FunctionType;
@@ -56,8 +58,10 @@ import org.apache.flink.statefun.sdk.StatefulFunctionProvider;
import org.apache.flink.statefun.sdk.io.IngressIdentifier;
import org.apache.flink.statefun.sdk.io.Router;
import org.apache.flink.statefun.sdk.spi.StatefulFunctionModule;
+import org.apache.flink.util.TimeUtils;
final class JsonModule implements StatefulFunctionModule {
+ private static final Duration DEFAULT_HTTP_TIMEOUT = Duration.ofMinutes(1);
private final JsonNode spec;
private final URL moduleUrl;
@@ -205,7 +209,10 @@ final class JsonModule implements StatefulFunctionModule {
switch (kind) {
case HTTP:
return new HttpFunctionSpec(
- functionType, functionUri(functionNode), functionStates(functionNode));
+ functionType,
+ functionUri(functionNode),
+ functionStates(functionNode),
+ maxRequestDuration(functionNode));
case GRPC:
return new GrpcFunctionSpec(functionType, functionAddress(functionNode));
default:
@@ -213,6 +220,12 @@ final class JsonModule implements StatefulFunctionModule {
}
}
+ private static Duration maxRequestDuration(JsonNode functionNode) {
+ return Selectors.optionalTextAt(functionNode, Functions.FUNCTION_TIMEOUT)
+ .map(TimeUtils::parseDuration)
+ .orElse(DEFAULT_HTTP_TIMEOUT);
+ }
+
private static List<String> functionStates(JsonNode functionNode) {
return Selectors.textListAt(functionNode, Pointers.Functions.FUNCTION_STATES);
}
diff --git a/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/jsonmodule/Pointers.java b/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/jsonmodule/Pointers.java
index fb25ac1..6d01344 100644
--- a/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/jsonmodule/Pointers.java
+++ b/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/jsonmodule/Pointers.java
@@ -46,6 +46,8 @@ public final class Pointers {
JsonPointer.compile("/function/spec/endpoint");
public static final JsonPointer FUNCTION_PORT = JsonPointer.compile("/function/spec/port");
public static final JsonPointer FUNCTION_STATES = JsonPointer.compile("/function/spec/states");
+ public static final JsonPointer FUNCTION_TIMEOUT =
+ JsonPointer.compile("/function/spec/timeout");
}
// -------------------------------------------------------------------------------------
[flink-statefun] 05/11: [FLINK-15956] Add an exponential backoff
Posted by se...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
sewen pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/flink-statefun.git
commit 85f3be9dc0848d4f0b9e5337583d40f4fed2df85
Author: Igal Shilman <ig...@gmail.com>
AuthorDate: Thu Feb 13 14:16:09 2020 +0100
[FLINK-15956] Add an exponential backoff
This commit adds an exponential backoff mechanism with
a total upper limit for the execution time.
---
.../backpressure/BoundedExponentialBackoff.java | 66 ++++++++++++++++++++++
.../flink/core/backpressure/SystemNanoTimer.java | 50 ++++++++++++++++
.../statefun/flink/core/backpressure/Timer.java | 26 +++++++++
.../BoundedExponentialBackoffTest.java | 65 +++++++++++++++++++++
4 files changed, 207 insertions(+)
diff --git a/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/backpressure/BoundedExponentialBackoff.java b/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/backpressure/BoundedExponentialBackoff.java
new file mode 100644
index 0000000..52622eb
--- /dev/null
+++ b/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/backpressure/BoundedExponentialBackoff.java
@@ -0,0 +1,66 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.statefun.flink.core.backpressure;
+
+import java.time.Duration;
+import java.util.Objects;
+import org.apache.flink.annotation.VisibleForTesting;
+
+public final class BoundedExponentialBackoff {
+ private final Timer timer;
+ private final long requestStartTimeInNanos;
+ private final long maxRequestDurationInNanos;
+
+ private long nextSleepTimeNanos;
+
+ public BoundedExponentialBackoff(Duration initialBackoffDuration, Duration maxRequestDuration) {
+ this(SystemNanoTimer.instance(), initialBackoffDuration, maxRequestDuration);
+ }
+
+ @VisibleForTesting
+ BoundedExponentialBackoff(
+ Timer timer, Duration initialBackoffDuration, Duration maxRequestDuration) {
+ this.timer = Objects.requireNonNull(timer);
+ this.requestStartTimeInNanos = timer.now();
+ this.maxRequestDurationInNanos = maxRequestDuration.toNanos();
+ this.nextSleepTimeNanos = initialBackoffDuration.toNanos();
+ }
+
+ public boolean applyNow() {
+ final long remainingNanos = remainingNanosUntilDeadLine();
+ final long nextAmountOfNanosToSleep = nextAmountOfNanosToSleep();
+ final long actualSleep = Math.min(remainingNanos, nextAmountOfNanosToSleep);
+ if (actualSleep <= 0) {
+ return false;
+ }
+ timer.sleep(actualSleep);
+ return true;
+ }
+
+ private long remainingNanosUntilDeadLine() {
+ final long totalElapsedTime = timer.now() - requestStartTimeInNanos;
+ return maxRequestDurationInNanos - totalElapsedTime;
+ }
+
+ private long nextAmountOfNanosToSleep() {
+ final long current = nextSleepTimeNanos;
+ nextSleepTimeNanos *= 2;
+ return current;
+ }
+}
diff --git a/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/backpressure/SystemNanoTimer.java b/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/backpressure/SystemNanoTimer.java
new file mode 100644
index 0000000..3eaefe3
--- /dev/null
+++ b/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/backpressure/SystemNanoTimer.java
@@ -0,0 +1,50 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.statefun.flink.core.backpressure;
+
+import static java.util.concurrent.TimeUnit.NANOSECONDS;
+
+/** A {@code Timer} backed by {@link System#nanoTime()}. */
+final class SystemNanoTimer implements Timer {
+ private static final SystemNanoTimer INSTANCE = new SystemNanoTimer();
+
+ public static SystemNanoTimer instance() {
+ return INSTANCE;
+ }
+
+ private SystemNanoTimer() {}
+
+ @Override
+ public long now() {
+ return System.nanoTime();
+ }
+
+ @Override
+ public void sleep(long sleepTimeNanos) {
+ try {
+ final long sleepTimeMs = NANOSECONDS.toMillis(sleepTimeNanos);
+ Thread.sleep(sleepTimeMs);
+ } catch (InterruptedException ex) {
+ if (Thread.interrupted()) {
+ Thread.currentThread().interrupt();
+ throw new RuntimeException("interrupted while sleeping", ex);
+ }
+ }
+ }
+}
diff --git a/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/backpressure/Timer.java b/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/backpressure/Timer.java
new file mode 100644
index 0000000..2651a52
--- /dev/null
+++ b/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/backpressure/Timer.java
@@ -0,0 +1,26 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.statefun.flink.core.backpressure;
+
+interface Timer {
+
+ long now();
+
+ void sleep(long durationNanos);
+}
diff --git a/statefun-flink/statefun-flink-core/src/test/java/org/apache/flink/statefun/flink/core/backpressure/BoundedExponentialBackoffTest.java b/statefun-flink/statefun-flink-core/src/test/java/org/apache/flink/statefun/flink/core/backpressure/BoundedExponentialBackoffTest.java
new file mode 100644
index 0000000..6b0eed5
--- /dev/null
+++ b/statefun-flink/statefun-flink-core/src/test/java/org/apache/flink/statefun/flink/core/backpressure/BoundedExponentialBackoffTest.java
@@ -0,0 +1,65 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.flink.statefun.flink.core.backpressure;
+
+import static org.hamcrest.Matchers.greaterThan;
+import static org.hamcrest.core.Is.is;
+import static org.junit.Assert.assertThat;
+
+import java.time.Duration;
+import org.junit.Test;
+
+public class BoundedExponentialBackoffTest {
+ private final FakeNanoClock fakeTime = new FakeNanoClock();
+ private final BoundedExponentialBackoff backoffUnderTest =
+ new BoundedExponentialBackoff(fakeTime, Duration.ofSeconds(1), Duration.ofMinutes(1));
+
+ @Test
+ public void simpleUsage() {
+ assertThat(backoffUnderTest.applyNow(), is(true));
+ assertThat(fakeTime.now(), greaterThan(0L));
+ }
+
+ @Test
+ public void timeoutExpired() {
+ fakeTime.now = Duration.ofMinutes(1).toNanos();
+ assertThat(backoffUnderTest.applyNow(), is(false));
+ }
+
+ @Test
+ @SuppressWarnings("StatementWithEmptyBody")
+ public void totalNumberOfBackoffsIsEqualToTimeout() {
+ while (backoffUnderTest.applyNow()) {}
+
+ assertThat(fakeTime.now(), is(Duration.ofMinutes(1).toNanos()));
+ }
+
+ private static final class FakeNanoClock implements Timer {
+ long now;
+
+ @Override
+ public long now() {
+ return now;
+ }
+
+ @Override
+ public void sleep(long durationNano) {
+ now += durationNano;
+ }
+ }
+}
[flink-statefun] 11/11: [hotfix] Remove @NonNull annotation
Posted by se...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
sewen pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/flink-statefun.git
commit 4428f3e3050eeabedac4decaa036db6ea11e7cef
Author: Igal Shilman <ig...@gmail.com>
AuthorDate: Fri Feb 14 18:26:01 2020 +0100
[hotfix] Remove @NonNull annotation
---
.../java/org/apache/flink/statefun/flink/core/common/PolyglotUtil.java | 3 +--
1 file changed, 1 insertion(+), 2 deletions(-)
diff --git a/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/common/PolyglotUtil.java b/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/common/PolyglotUtil.java
index c901e77..18cc5bb 100644
--- a/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/common/PolyglotUtil.java
+++ b/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/common/PolyglotUtil.java
@@ -22,7 +22,6 @@ import com.google.protobuf.Message;
import com.google.protobuf.Parser;
import java.io.IOException;
import java.io.InputStream;
-import javax.annotation.Nonnull;
import org.apache.flink.statefun.flink.core.polyglot.generated.Address;
import org.apache.flink.statefun.sdk.FunctionType;
@@ -38,7 +37,7 @@ public final class PolyglotUtil {
}
public static Address sdkAddressToPolyglotAddress(
- @Nonnull org.apache.flink.statefun.sdk.Address sdkAddress) {
+ org.apache.flink.statefun.sdk.Address sdkAddress) {
return Address.newBuilder()
.setNamespace(sdkAddress.type().namespace())
.setType(sdkAddress.type().name())
[flink-statefun] 04/11: [FLINK-15956] Add an initial HttpFunction
implemention
Posted by se...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
sewen pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/flink-statefun.git
commit 94def7745a6ee934150db31e19bf7e7665713ba2
Author: Igal Shilman <ig...@gmail.com>
AuthorDate: Tue Feb 11 16:07:18 2020 +0100
[FLINK-15956] Add an initial HttpFunction implemention
---
.../statefun/flink/core/common/PolyglotUtil.java | 53 ++++++
.../statefun/flink/core/httpfn/HttpFunction.java | 192 ++++++++++-----------
.../flink/core/httpfn/HttpFunctionProvider.java | 12 +-
.../statefun/flink/core/httpfn/OkHttpUtils.java | 51 +++++-
.../src/test/resources/bar-module/module.yaml | 2 +
5 files changed, 198 insertions(+), 112 deletions(-)
diff --git a/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/common/PolyglotUtil.java b/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/common/PolyglotUtil.java
new file mode 100644
index 0000000..c901e77
--- /dev/null
+++ b/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/common/PolyglotUtil.java
@@ -0,0 +1,53 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.statefun.flink.core.common;
+
+import com.google.protobuf.Message;
+import com.google.protobuf.Parser;
+import java.io.IOException;
+import java.io.InputStream;
+import javax.annotation.Nonnull;
+import org.apache.flink.statefun.flink.core.polyglot.generated.Address;
+import org.apache.flink.statefun.sdk.FunctionType;
+
+public final class PolyglotUtil {
+ private PolyglotUtil() {}
+
+ public static <M extends Message> M parseProtobufOrThrow(Parser<M> parser, InputStream input) {
+ try {
+ return parser.parseFrom(input);
+ } catch (IOException e) {
+ throw new IllegalStateException("Unable to parse a Protobuf message", e);
+ }
+ }
+
+ public static Address sdkAddressToPolyglotAddress(
+ @Nonnull org.apache.flink.statefun.sdk.Address sdkAddress) {
+ return Address.newBuilder()
+ .setNamespace(sdkAddress.type().namespace())
+ .setType(sdkAddress.type().name())
+ .setId(sdkAddress.id())
+ .build();
+ }
+
+ public static org.apache.flink.statefun.sdk.Address polyglotAddressToSdkAddress(Address address) {
+ return new org.apache.flink.statefun.sdk.Address(
+ new FunctionType(address.getNamespace(), address.getType()), address.getId());
+ }
+}
diff --git a/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/httpfn/HttpFunction.java b/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/httpfn/HttpFunction.java
index 51f0405..506081a 100644
--- a/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/httpfn/HttpFunction.java
+++ b/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/httpfn/HttpFunction.java
@@ -18,42 +18,38 @@
package org.apache.flink.statefun.flink.core.httpfn;
-import org.apache.flink.statefun.flink.core.polyglot.generated.Address;
+import static org.apache.flink.statefun.flink.core.common.PolyglotUtil.parseProtobufOrThrow;
+import static org.apache.flink.statefun.flink.core.common.PolyglotUtil.polyglotAddressToSdkAddress;
+import static org.apache.flink.statefun.flink.core.common.PolyglotUtil.sdkAddressToPolyglotAddress;
+import static org.apache.flink.statefun.flink.core.httpfn.OkHttpUtils.MEDIA_TYPE_BINARY;
+import static org.apache.flink.statefun.flink.core.httpfn.OkHttpUtils.responseBody;
+import static org.apache.flink.util.Preconditions.checkState;
+
+import com.google.protobuf.Any;
+import com.google.protobuf.ByteString;
+import java.io.InputStream;
+import java.util.Objects;
+import java.util.concurrent.CompletableFuture;
+import okhttp3.HttpUrl;
+import okhttp3.OkHttpClient;
+import okhttp3.Request;
+import okhttp3.RequestBody;
+import okhttp3.Response;
import org.apache.flink.statefun.flink.core.polyglot.generated.FromFunction;
import org.apache.flink.statefun.flink.core.polyglot.generated.FromFunction.InvocationResponse;
import org.apache.flink.statefun.flink.core.polyglot.generated.ToFunction;
import org.apache.flink.statefun.flink.core.polyglot.generated.ToFunction.Invocation;
-import org.apache.flink.statefun.flink.core.polyglot.generated.ToFunction.Invocation.Builder;
import org.apache.flink.statefun.flink.core.polyglot.generated.ToFunction.InvocationBatchRequest;
+import org.apache.flink.statefun.sdk.Address;
import org.apache.flink.statefun.sdk.AsyncOperationResult;
import org.apache.flink.statefun.sdk.Context;
-import org.apache.flink.statefun.sdk.FunctionType;
import org.apache.flink.statefun.sdk.StatefulFunction;
import org.apache.flink.statefun.sdk.annotations.Persisted;
import org.apache.flink.statefun.sdk.state.PersistedTable;
import org.apache.flink.statefun.sdk.state.PersistedValue;
-import com.google.protobuf.Any;
-import com.google.protobuf.ByteString;
-import okhttp3.HttpUrl;
-import okhttp3.MediaType;
-import okhttp3.OkHttpClient;
-import okhttp3.Request;
-import okhttp3.RequestBody;
-import okhttp3.Response;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.Objects;
-
-import javax.annotation.Nonnull;
-
-import static org.apache.flink.util.Preconditions.checkState;
-
final class HttpFunction implements StatefulFunction {
- private static final MediaType MEDIA_TYPE_BINARY = MediaType.parse("application/octet-stream");
-
private final HttpFunctionSpec functionSpec;
private final OkHttpClient client;
private final HttpUrl url;
@@ -78,17 +74,18 @@ final class HttpFunction implements StatefulFunction {
@Override
public void invoke(Context context, Object input) {
- if (input instanceof AsyncOperationResult) {
- @SuppressWarnings("unchecked")
- AsyncOperationResult<Any, Response> result = (AsyncOperationResult<Any, Response>) input;
- onAsyncResult(context, result);
- } else {
+ if (!(input instanceof AsyncOperationResult)) {
onRequest(context, (Any) input);
+ return;
}
+ @SuppressWarnings("unchecked")
+ AsyncOperationResult<ToFunction, Response> result =
+ (AsyncOperationResult<ToFunction, Response>) input;
+ onAsyncResult(context, result);
}
- private void onRequest(Context context, Any input) {
- Invocation.Builder invocationBuilder = invocationBuilder(context, input);
+ private void onRequest(Context context, Any message) {
+ Invocation.Builder invocationBuilder = singeInvocationBuilder(context, message);
if (hasInFlightRpc.getOrDefault(Boolean.FALSE)) {
addToOrCreateBatch(invocationBuilder);
return;
@@ -97,14 +94,23 @@ final class HttpFunction implements StatefulFunction {
sendToFunction(context, invocationBuilder);
}
- private void onAsyncResult(Context context, AsyncOperationResult<Any, Response> asyncResult) {
+ private void addToOrCreateBatch(Invocation.Builder invocationBuilder) {
+ InvocationBatchRequest current = batch.get();
+ InvocationBatchRequest.Builder next =
+ (current == null) ? InvocationBatchRequest.newBuilder() : current.toBuilder();
+ next.addInvocations(invocationBuilder);
+ batch.set(next.build());
+ }
+
+ private void onAsyncResult(
+ Context context, AsyncOperationResult<ToFunction, Response> asyncResult) {
if (asyncResult.unknown()) {
- Any originalMessage = asyncResult.metadata();
- Invocation.Builder invocationBuilder = invocationBuilder(context, originalMessage);
- sendToFunction(context, invocationBuilder);
+ ToFunction batch = asyncResult.metadata();
+ sendToFunction(context, batch);
return;
}
- InvocationResponse invocationResult = unpackInvocationResultOrThrow(asyncResult);
+ InvocationResponse invocationResult =
+ unpackInvocationResultOrThrow(context.self(), asyncResult);
handleInvocationResponse(context, invocationResult);
InvocationBatchRequest nextBatch = batch.get();
if (nextBatch == null) {
@@ -123,6 +129,27 @@ final class HttpFunction implements StatefulFunction {
context.send(to, message);
}
+ handleStateMutations(invocationResult);
+ }
+
+ // --------------------------------------------------------------------------------
+ // State Management
+ // --------------------------------------------------------------------------------
+
+ private void addStates(ToFunction.InvocationBatchRequest.Builder batchBuilder) {
+ for (String stateName : functionSpec.states()) {
+ ToFunction.PersistedValue.Builder valueBuilder =
+ ToFunction.PersistedValue.newBuilder().setStateName(stateName);
+
+ byte[] stateValue = managedStates.get(stateName);
+ if (stateValue != null) {
+ valueBuilder.setStateValue(ByteString.copyFrom(stateValue));
+ }
+ batchBuilder.addState(valueBuilder);
+ }
+ }
+
+ private void handleStateMutations(InvocationResponse invocationResult) {
for (FromFunction.PersistedValueMutation mutate : invocationResult.getStateMutationsList()) {
final String stateName = mutate.getStateName();
switch (mutate.getMutationType()) {
@@ -140,104 +167,65 @@ final class HttpFunction implements StatefulFunction {
}
}
- private void addToOrCreateBatch(Builder invocationBuilder) {
- batch.updateAndGet(
- existingBatch -> {
- final InvocationBatchRequest.Builder builder =
- existingBatch != null
- ? existingBatch.toBuilder()
- : InvocationBatchRequest.newBuilder();
- return builder.addInvocations(invocationBuilder).build();
- });
- }
-
// --------------------------------------------------------------------------------
- // Utilities
+ // Send Message to Remote Function
// --------------------------------------------------------------------------------
- private static Builder invocationBuilder(Context context, Any input) {
+
+ /**
+ * Returns an {@link Invocation.Builder} set with the input {@code message} and the caller
+ * information (is present).
+ */
+ private static Invocation.Builder singeInvocationBuilder(Context context, Any message) {
Invocation.Builder invocationBuilder = Invocation.newBuilder();
if (context.caller() != null) {
invocationBuilder.setCaller(sdkAddressToPolyglotAddress(context.caller()));
}
- invocationBuilder.setArgument(input);
+ invocationBuilder.setArgument(message);
return invocationBuilder;
}
- private void addStates(ToFunction.InvocationBatchRequest.Builder batchBuilder) {
- for (String stateName : functionSpec.states()) {
- ToFunction.PersistedValue.Builder valueBuilder =
- ToFunction.PersistedValue.newBuilder().setStateName(stateName);
-
- byte[] stateValue = managedStates.get(stateName);
- if (stateValue != null) {
- valueBuilder.setStateValue(ByteString.copyFrom(stateValue));
- }
- batchBuilder.addState(valueBuilder);
- }
- }
-
+ /**
+ * Sends a {@link InvocationBatchRequest} to the remote function consisting out of a single
+ * invocation represented by {@code invocationBuilder}.
+ */
private void sendToFunction(Context context, Invocation.Builder invocationBuilder) {
InvocationBatchRequest.Builder batchBuilder = InvocationBatchRequest.newBuilder();
batchBuilder.addInvocations(invocationBuilder);
sendToFunction(context, batchBuilder);
}
+ /** Sends a {@link InvocationBatchRequest} to the remote function. */
private void sendToFunction(Context context, InvocationBatchRequest.Builder batchBuilder) {
batchBuilder.setTarget(sdkAddressToPolyglotAddress(context.self()));
addStates(batchBuilder);
+ ToFunction toFunction = ToFunction.newBuilder().setInvocation(batchBuilder).build();
+ sendToFunction(context, toFunction);
+ }
+
+ private void sendToFunction(Context context, ToFunction toFunction) {
Request request =
new Request.Builder()
.url(url)
- .post(
- RequestBody.create(
- MEDIA_TYPE_BINARY,
- ToFunction.newBuilder().setInvocation(batchBuilder).build().toByteArray()))
+ .post(RequestBody.create(MEDIA_TYPE_BINARY, toFunction.toByteArray()))
.build();
- OkHttpUtils.call(client, request);
+
+ CompletableFuture<Response> responseFuture = OkHttpUtils.call(client, request);
+ context.registerAsyncOperation(toFunction, responseFuture);
}
- private static InvocationResponse unpackInvocationResultOrThrow(
- AsyncOperationResult<Any, Response> asyncResult) {
- checkState(asyncResult.failure() || asyncResult.successful());
+ private InvocationResponse unpackInvocationResultOrThrow(
+ Address self, AsyncOperationResult<?, Response> asyncResult) {
+ checkState(!asyncResult.unknown());
if (asyncResult.failure()) {
- throw new IllegalStateException("", asyncResult.throwable());
+ throw new IllegalStateException(
+ "Failure forwarding a message to a remote function " + self, asyncResult.throwable());
}
- Response httpResponse = asyncResult.value();
- checkState(httpResponse.isSuccessful(), "Unexpected HTTP status code %s", httpResponse.code());
- checkState(httpResponse.body() != null, "Unexpected empty HTTP response (no body)");
- checkState(
- Objects.equals(httpResponse.body().contentType(), MEDIA_TYPE_BINARY),
- "Wrong HTTP content-type %s",
- httpResponse.body().contentType());
- InputStream httpResponseBody = httpResponse.body().byteStream();
- FromFunction fromFunction = parseProtobufOrThrow(httpResponseBody);
+ InputStream httpResponseBody = responseBody(asyncResult.value());
+ FromFunction fromFunction = parseProtobufOrThrow(FromFunction.parser(), httpResponseBody);
checkState(
fromFunction.hasInvocationResult(),
"The received HTTP payload does not contain an InvocationResult, but rather [%s]",
fromFunction);
return fromFunction.getInvocationResult();
}
-
- private static FromFunction parseProtobufOrThrow(InputStream input) {
- try {
- return FromFunction.parseFrom(input);
- } catch (IOException e) {
- throw new IllegalStateException("Unable to parse a Protobuf message", e);
- }
- }
-
- private static Address sdkAddressToPolyglotAddress(
- @Nonnull org.apache.flink.statefun.sdk.Address sdkAddress) {
- return Address.newBuilder()
- .setNamespace(sdkAddress.type().namespace())
- .setType(sdkAddress.type().name())
- .setId(sdkAddress.id())
- .build();
- }
-
- private static org.apache.flink.statefun.sdk.Address polyglotAddressToSdkAddress(
- Address address) {
- return new org.apache.flink.statefun.sdk.Address(
- new FunctionType(address.getNamespace(), address.getType()), address.getId());
- }
}
diff --git a/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/httpfn/HttpFunctionProvider.java b/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/httpfn/HttpFunctionProvider.java
index a546865..be027e0 100644
--- a/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/httpfn/HttpFunctionProvider.java
+++ b/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/httpfn/HttpFunctionProvider.java
@@ -18,20 +18,22 @@
package org.apache.flink.statefun.flink.core.httpfn;
+import java.util.Map;
+import okhttp3.OkHttpClient;
import org.apache.flink.statefun.sdk.FunctionType;
import org.apache.flink.statefun.sdk.StatefulFunctionProvider;
-import okhttp3.OkHttpClient;
-
-import java.util.Map;
-
public class HttpFunctionProvider implements StatefulFunctionProvider {
private final Map<FunctionType, HttpFunctionSpec> supportedTypes;
private final OkHttpClient client;
public HttpFunctionProvider(Map<FunctionType, HttpFunctionSpec> supportedTypes) {
this.supportedTypes = supportedTypes;
- this.client = new OkHttpClient();
+ final long timeoutMs = 30_000;
+ // TODO: add various timeouts to HttpFunctionSpec
+ this.client =
+ OkHttpUtils.newClient(
+ timeoutMs, timeoutMs, 2 * timeoutMs, timeoutMs, Integer.MAX_VALUE, Integer.MAX_VALUE);
}
@Override
diff --git a/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/httpfn/OkHttpUtils.java b/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/httpfn/OkHttpUtils.java
index 1839c36..100c932 100644
--- a/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/httpfn/OkHttpUtils.java
+++ b/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/httpfn/OkHttpUtils.java
@@ -16,25 +16,66 @@
package org.apache.flink.statefun.flink.core.httpfn;
+import static org.apache.flink.util.Preconditions.checkState;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Objects;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
+import okhttp3.ConnectionPool;
+import okhttp3.Dispatcher;
+import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
-import java.io.IOException;
-import java.util.Objects;
-import java.util.concurrent.CompletableFuture;
-
final class OkHttpUtils {
private OkHttpUtils() {}
- public static CompletableFuture<Response> call(OkHttpClient client, Request request) {
+ static final MediaType MEDIA_TYPE_BINARY = MediaType.parse("application/octet-stream");
+
+ static CompletableFuture<Response> call(OkHttpClient client, Request request) {
CompletableFuture<Response> future = new CompletableFuture<>();
client.newCall(request).enqueue(new CompletableFutureCallback(future));
return future;
}
+ static InputStream responseBody(Response httpResponse) {
+ checkState(httpResponse.isSuccessful(), "Unexpected HTTP status code %s", httpResponse.code());
+ checkState(httpResponse.body() != null, "Unexpected empty HTTP response (no body)");
+ checkState(
+ Objects.equals(httpResponse.body().contentType(), MEDIA_TYPE_BINARY),
+ "Wrong HTTP content-type %s",
+ httpResponse.body().contentType());
+ return httpResponse.body().byteStream();
+ }
+
+ static OkHttpClient newClient(
+ long readTimeoutMillis,
+ long writeTimeoutMillis,
+ long callTimeout,
+ long connectionTimeInMillis,
+ int maxRequestsPerHost,
+ int maxRequests) {
+ Dispatcher dispatcher = new Dispatcher();
+ dispatcher.setMaxRequestsPerHost(maxRequestsPerHost);
+ dispatcher.setMaxRequests(maxRequests);
+
+ return new OkHttpClient.Builder()
+ .connectTimeout(connectionTimeInMillis, TimeUnit.MILLISECONDS)
+ .writeTimeout(writeTimeoutMillis, TimeUnit.MILLISECONDS)
+ .readTimeout(readTimeoutMillis, TimeUnit.MILLISECONDS)
+ .callTimeout(callTimeout, TimeUnit.MILLISECONDS)
+ .dispatcher(dispatcher)
+ .connectionPool(new ConnectionPool())
+ .followRedirects(true)
+ .followSslRedirects(true)
+ .build();
+ }
+
@SuppressWarnings("NullableProblems")
private static final class CompletableFutureCallback implements Callback {
private final CompletableFuture<Response> future;
diff --git a/statefun-flink/statefun-flink-core/src/test/resources/bar-module/module.yaml b/statefun-flink/statefun-flink-core/src/test/resources/bar-module/module.yaml
index c659fe9..2ef6956 100644
--- a/statefun-flink/statefun-flink-core/src/test/resources/bar-module/module.yaml
+++ b/statefun-flink/statefun-flink-core/src/test/resources/bar-module/module.yaml
@@ -31,6 +31,8 @@ module:
type: com.foo/world
spec:
endpoint: localhost:5959/statefun
+ states:
+ - seen_count
routers:
- router:
meta:
[flink-statefun] 10/11: fixup! [FLINK-15956] Add an exponential
backoff
Posted by se...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
sewen pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/flink-statefun.git
commit f3a9bd5664e56e566d9cd299f351d631d65a7766
Author: Igal Shilman <ig...@gmail.com>
AuthorDate: Fri Feb 14 18:00:32 2020 +0100
fixup! [FLINK-15956] Add an exponential backoff
---
.../flink/statefun/flink/core/backpressure/SystemNanoTimer.java | 6 ++----
1 file changed, 2 insertions(+), 4 deletions(-)
diff --git a/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/backpressure/SystemNanoTimer.java b/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/backpressure/SystemNanoTimer.java
index 3eaefe3..717c2df 100644
--- a/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/backpressure/SystemNanoTimer.java
+++ b/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/backpressure/SystemNanoTimer.java
@@ -41,10 +41,8 @@ final class SystemNanoTimer implements Timer {
final long sleepTimeMs = NANOSECONDS.toMillis(sleepTimeNanos);
Thread.sleep(sleepTimeMs);
} catch (InterruptedException ex) {
- if (Thread.interrupted()) {
- Thread.currentThread().interrupt();
- throw new RuntimeException("interrupted while sleeping", ex);
- }
+ Thread.currentThread().interrupt();
+ throw new RuntimeException("interrupted while sleeping", ex);
}
}
}
[flink-statefun] 03/11: [FLINK-15956] Use okhttp client
Posted by se...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
sewen pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/flink-statefun.git
commit 4663786a46b99c6c410bb4e1ad0b220060849327
Author: Igal Shilman <ig...@gmail.com>
AuthorDate: Mon Feb 10 16:24:36 2020 +0100
[FLINK-15956] Use okhttp client
---
statefun-flink/statefun-flink-core/pom.xml | 13 +-
.../statefun/flink/core/httpfn/HttpFunction.java | 243 +++++++++++++++++++++
.../flink/core/httpfn/HttpFunctionProvider.java | 22 +-
.../statefun/flink/core/httpfn/OkHttpUtils.java | 56 +++++
4 files changed, 327 insertions(+), 7 deletions(-)
diff --git a/statefun-flink/statefun-flink-core/pom.xml b/statefun-flink/statefun-flink-core/pom.xml
index ad0805c..c876cd1 100644
--- a/statefun-flink/statefun-flink-core/pom.xml
+++ b/statefun-flink/statefun-flink-core/pom.xml
@@ -19,7 +19,7 @@ under the License.
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
-
+
<parent>
<groupId>org.apache.flink</groupId>
<artifactId>statefun-flink</artifactId>
@@ -28,7 +28,11 @@ under the License.
</parent>
<artifactId>statefun-flink-core</artifactId>
-
+
+ <properties>
+ <okhttp.version>3.14.6</okhttp.version>
+ </properties>
+
<dependencies>
<!-- sdk -->
@@ -60,6 +64,11 @@ under the License.
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
</dependency>
+ <dependency>
+ <groupId>com.squareup.okhttp3</groupId>
+ <artifactId>okhttp</artifactId>
+ <version>${okhttp.version}</version>
+ </dependency>
<!-- tests -->
<dependency>
diff --git a/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/httpfn/HttpFunction.java b/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/httpfn/HttpFunction.java
new file mode 100644
index 0000000..51f0405
--- /dev/null
+++ b/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/httpfn/HttpFunction.java
@@ -0,0 +1,243 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.statefun.flink.core.httpfn;
+
+import org.apache.flink.statefun.flink.core.polyglot.generated.Address;
+import org.apache.flink.statefun.flink.core.polyglot.generated.FromFunction;
+import org.apache.flink.statefun.flink.core.polyglot.generated.FromFunction.InvocationResponse;
+import org.apache.flink.statefun.flink.core.polyglot.generated.ToFunction;
+import org.apache.flink.statefun.flink.core.polyglot.generated.ToFunction.Invocation;
+import org.apache.flink.statefun.flink.core.polyglot.generated.ToFunction.Invocation.Builder;
+import org.apache.flink.statefun.flink.core.polyglot.generated.ToFunction.InvocationBatchRequest;
+import org.apache.flink.statefun.sdk.AsyncOperationResult;
+import org.apache.flink.statefun.sdk.Context;
+import org.apache.flink.statefun.sdk.FunctionType;
+import org.apache.flink.statefun.sdk.StatefulFunction;
+import org.apache.flink.statefun.sdk.annotations.Persisted;
+import org.apache.flink.statefun.sdk.state.PersistedTable;
+import org.apache.flink.statefun.sdk.state.PersistedValue;
+
+import com.google.protobuf.Any;
+import com.google.protobuf.ByteString;
+import okhttp3.HttpUrl;
+import okhttp3.MediaType;
+import okhttp3.OkHttpClient;
+import okhttp3.Request;
+import okhttp3.RequestBody;
+import okhttp3.Response;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Objects;
+
+import javax.annotation.Nonnull;
+
+import static org.apache.flink.util.Preconditions.checkState;
+
+final class HttpFunction implements StatefulFunction {
+
+ private static final MediaType MEDIA_TYPE_BINARY = MediaType.parse("application/octet-stream");
+
+ private final HttpFunctionSpec functionSpec;
+ private final OkHttpClient client;
+ private final HttpUrl url;
+
+ @Persisted
+ private final PersistedValue<Boolean> hasInFlightRpc =
+ PersistedValue.of("inflight", Boolean.class);
+
+ @Persisted
+ private final PersistedValue<ToFunction.InvocationBatchRequest> batch =
+ PersistedValue.of("batch", ToFunction.InvocationBatchRequest.class);
+
+ @Persisted
+ private final PersistedTable<String, byte[]> managedStates =
+ PersistedTable.of("states", String.class, byte[].class);
+
+ public HttpFunction(HttpFunctionSpec spec, OkHttpClient client) {
+ this.functionSpec = Objects.requireNonNull(spec);
+ this.client = Objects.requireNonNull(client);
+ this.url = HttpUrl.get(functionSpec.endpoint());
+ }
+
+ @Override
+ public void invoke(Context context, Object input) {
+ if (input instanceof AsyncOperationResult) {
+ @SuppressWarnings("unchecked")
+ AsyncOperationResult<Any, Response> result = (AsyncOperationResult<Any, Response>) input;
+ onAsyncResult(context, result);
+ } else {
+ onRequest(context, (Any) input);
+ }
+ }
+
+ private void onRequest(Context context, Any input) {
+ Invocation.Builder invocationBuilder = invocationBuilder(context, input);
+ if (hasInFlightRpc.getOrDefault(Boolean.FALSE)) {
+ addToOrCreateBatch(invocationBuilder);
+ return;
+ }
+ hasInFlightRpc.set(Boolean.TRUE);
+ sendToFunction(context, invocationBuilder);
+ }
+
+ private void onAsyncResult(Context context, AsyncOperationResult<Any, Response> asyncResult) {
+ if (asyncResult.unknown()) {
+ Any originalMessage = asyncResult.metadata();
+ Invocation.Builder invocationBuilder = invocationBuilder(context, originalMessage);
+ sendToFunction(context, invocationBuilder);
+ return;
+ }
+ InvocationResponse invocationResult = unpackInvocationResultOrThrow(asyncResult);
+ handleInvocationResponse(context, invocationResult);
+ InvocationBatchRequest nextBatch = batch.get();
+ if (nextBatch == null) {
+ hasInFlightRpc.clear();
+ return;
+ }
+ batch.clear();
+ sendToFunction(context, nextBatch.toBuilder());
+ }
+
+ private void handleInvocationResponse(Context context, InvocationResponse invocationResult) {
+ for (FromFunction.Invocation invokeCommand : invocationResult.getOutgoingMessagesList()) {
+ final org.apache.flink.statefun.sdk.Address to =
+ polyglotAddressToSdkAddress(invokeCommand.getTarget());
+ final Any message = invokeCommand.getArgument();
+
+ context.send(to, message);
+ }
+ for (FromFunction.PersistedValueMutation mutate : invocationResult.getStateMutationsList()) {
+ final String stateName = mutate.getStateName();
+ switch (mutate.getMutationType()) {
+ case DELETE:
+ managedStates.remove(stateName);
+ break;
+ case MODIFY:
+ managedStates.set(stateName, mutate.getStateValue().toByteArray());
+ break;
+ case UNRECOGNIZED:
+ break;
+ default:
+ throw new IllegalStateException("Unexpected value: " + mutate.getMutationType());
+ }
+ }
+ }
+
+ private void addToOrCreateBatch(Builder invocationBuilder) {
+ batch.updateAndGet(
+ existingBatch -> {
+ final InvocationBatchRequest.Builder builder =
+ existingBatch != null
+ ? existingBatch.toBuilder()
+ : InvocationBatchRequest.newBuilder();
+ return builder.addInvocations(invocationBuilder).build();
+ });
+ }
+
+ // --------------------------------------------------------------------------------
+ // Utilities
+ // --------------------------------------------------------------------------------
+ private static Builder invocationBuilder(Context context, Any input) {
+ Invocation.Builder invocationBuilder = Invocation.newBuilder();
+ if (context.caller() != null) {
+ invocationBuilder.setCaller(sdkAddressToPolyglotAddress(context.caller()));
+ }
+ invocationBuilder.setArgument(input);
+ return invocationBuilder;
+ }
+
+ private void addStates(ToFunction.InvocationBatchRequest.Builder batchBuilder) {
+ for (String stateName : functionSpec.states()) {
+ ToFunction.PersistedValue.Builder valueBuilder =
+ ToFunction.PersistedValue.newBuilder().setStateName(stateName);
+
+ byte[] stateValue = managedStates.get(stateName);
+ if (stateValue != null) {
+ valueBuilder.setStateValue(ByteString.copyFrom(stateValue));
+ }
+ batchBuilder.addState(valueBuilder);
+ }
+ }
+
+ private void sendToFunction(Context context, Invocation.Builder invocationBuilder) {
+ InvocationBatchRequest.Builder batchBuilder = InvocationBatchRequest.newBuilder();
+ batchBuilder.addInvocations(invocationBuilder);
+ sendToFunction(context, batchBuilder);
+ }
+
+ private void sendToFunction(Context context, InvocationBatchRequest.Builder batchBuilder) {
+ batchBuilder.setTarget(sdkAddressToPolyglotAddress(context.self()));
+ addStates(batchBuilder);
+ Request request =
+ new Request.Builder()
+ .url(url)
+ .post(
+ RequestBody.create(
+ MEDIA_TYPE_BINARY,
+ ToFunction.newBuilder().setInvocation(batchBuilder).build().toByteArray()))
+ .build();
+ OkHttpUtils.call(client, request);
+ }
+
+ private static InvocationResponse unpackInvocationResultOrThrow(
+ AsyncOperationResult<Any, Response> asyncResult) {
+ checkState(asyncResult.failure() || asyncResult.successful());
+ if (asyncResult.failure()) {
+ throw new IllegalStateException("", asyncResult.throwable());
+ }
+ Response httpResponse = asyncResult.value();
+ checkState(httpResponse.isSuccessful(), "Unexpected HTTP status code %s", httpResponse.code());
+ checkState(httpResponse.body() != null, "Unexpected empty HTTP response (no body)");
+ checkState(
+ Objects.equals(httpResponse.body().contentType(), MEDIA_TYPE_BINARY),
+ "Wrong HTTP content-type %s",
+ httpResponse.body().contentType());
+ InputStream httpResponseBody = httpResponse.body().byteStream();
+ FromFunction fromFunction = parseProtobufOrThrow(httpResponseBody);
+ checkState(
+ fromFunction.hasInvocationResult(),
+ "The received HTTP payload does not contain an InvocationResult, but rather [%s]",
+ fromFunction);
+ return fromFunction.getInvocationResult();
+ }
+
+ private static FromFunction parseProtobufOrThrow(InputStream input) {
+ try {
+ return FromFunction.parseFrom(input);
+ } catch (IOException e) {
+ throw new IllegalStateException("Unable to parse a Protobuf message", e);
+ }
+ }
+
+ private static Address sdkAddressToPolyglotAddress(
+ @Nonnull org.apache.flink.statefun.sdk.Address sdkAddress) {
+ return Address.newBuilder()
+ .setNamespace(sdkAddress.type().namespace())
+ .setType(sdkAddress.type().name())
+ .setId(sdkAddress.id())
+ .build();
+ }
+
+ private static org.apache.flink.statefun.sdk.Address polyglotAddressToSdkAddress(
+ Address address) {
+ return new org.apache.flink.statefun.sdk.Address(
+ new FunctionType(address.getNamespace(), address.getType()), address.getId());
+ }
+}
diff --git a/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/httpfn/HttpFunctionProvider.java b/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/httpfn/HttpFunctionProvider.java
index c4578b0..a546865 100644
--- a/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/httpfn/HttpFunctionProvider.java
+++ b/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/httpfn/HttpFunctionProvider.java
@@ -18,16 +18,28 @@
package org.apache.flink.statefun.flink.core.httpfn;
-import java.util.Map;
import org.apache.flink.statefun.sdk.FunctionType;
-import org.apache.flink.statefun.sdk.StatefulFunction;
import org.apache.flink.statefun.sdk.StatefulFunctionProvider;
+import okhttp3.OkHttpClient;
+
+import java.util.Map;
+
public class HttpFunctionProvider implements StatefulFunctionProvider {
- public HttpFunctionProvider(Map<FunctionType, HttpFunctionSpec> specs) {}
+ private final Map<FunctionType, HttpFunctionSpec> supportedTypes;
+ private final OkHttpClient client;
+
+ public HttpFunctionProvider(Map<FunctionType, HttpFunctionSpec> supportedTypes) {
+ this.supportedTypes = supportedTypes;
+ this.client = new OkHttpClient();
+ }
@Override
- public StatefulFunction functionOfType(FunctionType type) {
- throw new UnsupportedOperationException("Not implemented yet");
+ public HttpFunction functionOfType(FunctionType type) {
+ HttpFunctionSpec spec = supportedTypes.get(type);
+ if (spec == null) {
+ throw new IllegalArgumentException("Unsupported type " + type);
+ }
+ return new HttpFunction(spec, client);
}
}
diff --git a/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/httpfn/OkHttpUtils.java b/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/httpfn/OkHttpUtils.java
new file mode 100644
index 0000000..1839c36
--- /dev/null
+++ b/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/httpfn/OkHttpUtils.java
@@ -0,0 +1,56 @@
+/*
+ * Copyright 2019 Ververica GmbH.
+ *
+ * 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 org.apache.flink.statefun.flink.core.httpfn;
+
+import okhttp3.Call;
+import okhttp3.Callback;
+import okhttp3.OkHttpClient;
+import okhttp3.Request;
+import okhttp3.Response;
+
+import java.io.IOException;
+import java.util.Objects;
+import java.util.concurrent.CompletableFuture;
+
+final class OkHttpUtils {
+ private OkHttpUtils() {}
+
+ public static CompletableFuture<Response> call(OkHttpClient client, Request request) {
+ CompletableFuture<Response> future = new CompletableFuture<>();
+ client.newCall(request).enqueue(new CompletableFutureCallback(future));
+ return future;
+ }
+
+ @SuppressWarnings("NullableProblems")
+ private static final class CompletableFutureCallback implements Callback {
+ private final CompletableFuture<Response> future;
+
+ public CompletableFutureCallback(CompletableFuture<Response> future) {
+ this.future = Objects.requireNonNull(future);
+ }
+
+ @Override
+ public void onFailure(Call call, IOException e) {
+ future.completeExceptionally(e);
+ }
+
+ @Override
+ public void onResponse(Call call, Response response) {
+ future.complete(response);
+ }
+ }
+}
[flink-statefun] 09/11: [FLINK-15956] Use maxRequestDuration of
HttpFunctionSpec
Posted by se...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
sewen pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/flink-statefun.git
commit 9505ceed6d9b0a1b3b06f3ee4a012a83ff663808
Author: Igal Shilman <ig...@gmail.com>
AuthorDate: Thu Feb 13 15:42:40 2020 +0100
[FLINK-15956] Use maxRequestDuration of HttpFunctionSpec
---
.../flink/statefun/flink/core/httpfn/HttpFunctionProvider.java | 10 +++++++---
1 file changed, 7 insertions(+), 3 deletions(-)
diff --git a/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/httpfn/HttpFunctionProvider.java b/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/httpfn/HttpFunctionProvider.java
index 3d94109..43da918 100644
--- a/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/httpfn/HttpFunctionProvider.java
+++ b/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/httpfn/HttpFunctionProvider.java
@@ -25,11 +25,11 @@ import org.apache.flink.statefun.sdk.StatefulFunctionProvider;
public class HttpFunctionProvider implements StatefulFunctionProvider {
private final Map<FunctionType, HttpFunctionSpec> supportedTypes;
- private final OkHttpClient client;
+ private final OkHttpClient sharedClient;
public HttpFunctionProvider(Map<FunctionType, HttpFunctionSpec> supportedTypes) {
this.supportedTypes = supportedTypes;
- this.client = OkHttpUtils.newClient();
+ this.sharedClient = OkHttpUtils.newClient();
}
@Override
@@ -38,6 +38,10 @@ public class HttpFunctionProvider implements StatefulFunctionProvider {
if (spec == null) {
throw new IllegalArgumentException("Unsupported type " + type);
}
- return new HttpFunction(spec, client);
+ // specific client reuses the same the connection pool and thread pool
+ // as the sharedClient.
+ OkHttpClient specificClient =
+ sharedClient.newBuilder().callTimeout(spec.maxRequestDuration()).build();
+ return new HttpFunction(spec, specificClient);
}
}
[flink-statefun] 06/11: [FLINK-15956] Use ExponentialBackoff during
retires
Posted by se...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
sewen pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/flink-statefun.git
commit 69abd0984f8b3acb11306a38676c346e3a189c60
Author: Igal Shilman <ig...@gmail.com>
AuthorDate: Thu Feb 13 14:56:17 2020 +0100
[FLINK-15956] Use ExponentialBackoff during retires
---
.../flink/core/httpfn/HttpFunctionProvider.java | 6 +-
.../statefun/flink/core/httpfn/OkHttpUtils.java | 70 ++++---------
.../flink/core/httpfn/RetryingCallback.java | 113 +++++++++++++++++++++
3 files changed, 136 insertions(+), 53 deletions(-)
diff --git a/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/httpfn/HttpFunctionProvider.java b/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/httpfn/HttpFunctionProvider.java
index be027e0..3d94109 100644
--- a/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/httpfn/HttpFunctionProvider.java
+++ b/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/httpfn/HttpFunctionProvider.java
@@ -29,11 +29,7 @@ public class HttpFunctionProvider implements StatefulFunctionProvider {
public HttpFunctionProvider(Map<FunctionType, HttpFunctionSpec> supportedTypes) {
this.supportedTypes = supportedTypes;
- final long timeoutMs = 30_000;
- // TODO: add various timeouts to HttpFunctionSpec
- this.client =
- OkHttpUtils.newClient(
- timeoutMs, timeoutMs, 2 * timeoutMs, timeoutMs, Integer.MAX_VALUE, Integer.MAX_VALUE);
+ this.client = OkHttpUtils.newClient();
}
@Override
diff --git a/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/httpfn/OkHttpUtils.java b/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/httpfn/OkHttpUtils.java
index 100c932..c5fb4be 100644
--- a/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/httpfn/OkHttpUtils.java
+++ b/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/httpfn/OkHttpUtils.java
@@ -18,13 +18,11 @@ package org.apache.flink.statefun.flink.core.httpfn;
import static org.apache.flink.util.Preconditions.checkState;
-import java.io.IOException;
import java.io.InputStream;
+import java.time.Duration;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
-import java.util.concurrent.TimeUnit;
import okhttp3.Call;
-import okhttp3.Callback;
import okhttp3.ConnectionPool;
import okhttp3.Dispatcher;
import okhttp3.MediaType;
@@ -35,63 +33,39 @@ import okhttp3.Response;
final class OkHttpUtils {
private OkHttpUtils() {}
- static final MediaType MEDIA_TYPE_BINARY = MediaType.parse("application/octet-stream");
-
- static CompletableFuture<Response> call(OkHttpClient client, Request request) {
- CompletableFuture<Response> future = new CompletableFuture<>();
- client.newCall(request).enqueue(new CompletableFutureCallback(future));
- return future;
- }
+ private static final Duration DEFAULT_CALL_TIMEOUT = Duration.ofMinutes(2);
- static InputStream responseBody(Response httpResponse) {
- checkState(httpResponse.isSuccessful(), "Unexpected HTTP status code %s", httpResponse.code());
- checkState(httpResponse.body() != null, "Unexpected empty HTTP response (no body)");
- checkState(
- Objects.equals(httpResponse.body().contentType(), MEDIA_TYPE_BINARY),
- "Wrong HTTP content-type %s",
- httpResponse.body().contentType());
- return httpResponse.body().byteStream();
- }
+ static final MediaType MEDIA_TYPE_BINARY = MediaType.parse("application/octet-stream");
- static OkHttpClient newClient(
- long readTimeoutMillis,
- long writeTimeoutMillis,
- long callTimeout,
- long connectionTimeInMillis,
- int maxRequestsPerHost,
- int maxRequests) {
+ static OkHttpClient newClient() {
Dispatcher dispatcher = new Dispatcher();
- dispatcher.setMaxRequestsPerHost(maxRequestsPerHost);
- dispatcher.setMaxRequests(maxRequests);
+ dispatcher.setMaxRequestsPerHost(Integer.MAX_VALUE);
+ dispatcher.setMaxRequests(Integer.MAX_VALUE);
return new OkHttpClient.Builder()
- .connectTimeout(connectionTimeInMillis, TimeUnit.MILLISECONDS)
- .writeTimeout(writeTimeoutMillis, TimeUnit.MILLISECONDS)
- .readTimeout(readTimeoutMillis, TimeUnit.MILLISECONDS)
- .callTimeout(callTimeout, TimeUnit.MILLISECONDS)
+ .callTimeout(DEFAULT_CALL_TIMEOUT)
.dispatcher(dispatcher)
.connectionPool(new ConnectionPool())
.followRedirects(true)
.followSslRedirects(true)
+ .retryOnConnectionFailure(true)
.build();
}
- @SuppressWarnings("NullableProblems")
- private static final class CompletableFutureCallback implements Callback {
- private final CompletableFuture<Response> future;
-
- public CompletableFutureCallback(CompletableFuture<Response> future) {
- this.future = Objects.requireNonNull(future);
- }
-
- @Override
- public void onFailure(Call call, IOException e) {
- future.completeExceptionally(e);
- }
+ static CompletableFuture<Response> call(OkHttpClient client, Request request) {
+ Call newCall = client.newCall(request);
+ RetryingCallback callback = new RetryingCallback(newCall.timeout());
+ newCall.enqueue(callback);
+ return callback.future();
+ }
- @Override
- public void onResponse(Call call, Response response) {
- future.complete(response);
- }
+ static InputStream responseBody(Response httpResponse) {
+ checkState(httpResponse.isSuccessful(), "Unexpected HTTP status code %s", httpResponse.code());
+ checkState(httpResponse.body() != null, "Unexpected empty HTTP response (no body)");
+ checkState(
+ Objects.equals(httpResponse.body().contentType(), MEDIA_TYPE_BINARY),
+ "Wrong HTTP content-type %s",
+ httpResponse.body().contentType());
+ return httpResponse.body().byteStream();
}
}
diff --git a/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/httpfn/RetryingCallback.java b/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/httpfn/RetryingCallback.java
new file mode 100644
index 0000000..f8a4a8a
--- /dev/null
+++ b/statefun-flink/statefun-flink-core/src/main/java/org/apache/flink/statefun/flink/core/httpfn/RetryingCallback.java
@@ -0,0 +1,113 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.statefun.flink.core.httpfn;
+
+import java.io.IOException;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import okhttp3.Call;
+import okhttp3.Callback;
+import okhttp3.Response;
+import okio.Timeout;
+import org.apache.flink.statefun.flink.core.backpressure.BoundedExponentialBackoff;
+import org.apache.flink.util.function.RunnableWithException;
+
+@SuppressWarnings("NullableProblems")
+final class RetryingCallback implements Callback {
+ private static final Duration INITIAL_BACKOFF_DURATION = Duration.ofMillis(10);
+
+ private static final Set<Integer> RETRYABLE_HTTP_CODES =
+ new HashSet<>(Arrays.asList(409, 420, 408, 429, 499, 500));
+
+ private final CompletableFuture<Response> resultFuture;
+ private final BoundedExponentialBackoff backoff;
+
+ RetryingCallback(Timeout timeout) {
+ this.resultFuture = new CompletableFuture<>();
+ this.backoff = new BoundedExponentialBackoff(INITIAL_BACKOFF_DURATION, duration(timeout));
+ }
+
+ CompletableFuture<Response> future() {
+ return resultFuture;
+ }
+
+ @Override
+ public void onFailure(Call call, IOException cause) {
+ tryWithFuture(() -> onFailureUnsafe(call, cause));
+ }
+
+ @Override
+ public void onResponse(Call call, Response response) {
+ tryWithFuture(() -> onResponseUnsafe(call, response));
+ }
+
+ private void onFailureUnsafe(Call call, IOException cause) {
+ if (!retryAfterApplyingBackoff(call)) {
+ throw new IllegalStateException(
+ "Maximal request time has elapsed. Last cause is attached", cause);
+ }
+ }
+
+ private void onResponseUnsafe(Call call, Response response) {
+ if (response.isSuccessful()) {
+ resultFuture.complete(response);
+ return;
+ }
+ if (!RETRYABLE_HTTP_CODES.contains(response.code())) {
+ throw new IllegalStateException("Non successful HTTP response code " + response.code());
+ }
+ if (!retryAfterApplyingBackoff(call)) {
+ throw new IllegalStateException(
+ "Maximal request time has elapsed. Last known error is: invalid HTTP response code "
+ + response.code());
+ }
+ }
+
+ /**
+ * Retires the original call, after applying backoff.
+ *
+ * @return if the request was retried successfully, false otherwise.
+ */
+ private boolean retryAfterApplyingBackoff(Call call) {
+ if (backoff.applyNow()) {
+ call.clone().enqueue(this);
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Executes the runnable, and completes {@link #resultFuture} with any exceptions thrown, during
+ * its execution.
+ */
+ private void tryWithFuture(RunnableWithException runnable) {
+ try {
+ runnable.run();
+ } catch (Throwable t) {
+ resultFuture.completeExceptionally(t);
+ }
+ }
+
+ private static Duration duration(Timeout timeout) {
+ return Duration.ofNanos(timeout.timeoutNanos());
+ }
+}
[flink-statefun] 01/11: [FLINK-15956] Add HTTP function protocol
Posted by se...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
sewen pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/flink-statefun.git
commit 5f6a40b7388703f8e9d66d7f5ac5d108aa937637
Author: Igal Shilman <ig...@gmail.com>
AuthorDate: Mon Feb 10 12:01:20 2020 +0100
[FLINK-15956] Add HTTP function protocol
This commit provides the initial version of the HTTP based remote
function invocation protocol for stateful functions.
---
.../src/main/protobuf/http-function.proto | 120 +++++++++++++++++++++
1 file changed, 120 insertions(+)
diff --git a/statefun-flink/statefun-flink-core/src/main/protobuf/http-function.proto b/statefun-flink/statefun-flink-core/src/main/protobuf/http-function.proto
new file mode 100644
index 0000000..2a1557d
--- /dev/null
+++ b/statefun-flink/statefun-flink-core/src/main/protobuf/http-function.proto
@@ -0,0 +1,120 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+syntax = "proto3";
+
+package org.apache.flink.statefun.flink.core.polyglot;
+option java_package = "org.apache.flink.statefun.flink.core.polyglot.generated";
+option java_multiple_files = true;
+
+import "google/protobuf/any.proto";
+
+// -------------------------------------------------------------------------------------------------------------------
+// Common message definitions
+// -------------------------------------------------------------------------------------------------------------------
+
+// An Address is the unique identity of an individual StatefulFunction, containing
+// a function's type and an unique identifier within the type. The function's
+// type denotes the "class" of function to invoke, while the unique identifier addresses the
+// invocation to a specific function instance.
+message Address {
+ string namespace = 1;
+ string type = 2;
+ string id = 3;
+}
+
+// -------------------------------------------------------------------------------------------------------------------
+// Messages sent to a Remote Function
+// -------------------------------------------------------------------------------------------------------------------
+
+// The following section contains all the message types that are sent
+// from Flink to a remote function.
+message ToFunction {
+ // PersistedValue represents a PersistedValue's value that is managed by Flink on behalf of a remote function.
+ message PersistedValue {
+ // The unique name of the persisted state.
+ string state_name = 1;
+ // The serialized state value
+ bytes state_value = 2;
+ }
+
+ // Invocation represents a remote function call, it associated with an (optional) return address,
+ // and an argument.
+ message Invocation {
+ // The address of the function that requested the invocation (possibly absent)
+ Address caller = 1;
+ // The invocation argument (aka the message sent to the target function)
+ google.protobuf.Any argument = 2;
+ }
+
+ // InvocationBatchRequest represents a request to invoke a remote function. It is always associated with a target
+ // address (the function to invoke), a list of eager state values.
+ message InvocationBatchRequest {
+ // The address of the function to invoke
+ Address target = 1;
+ // A list of PersistedValues that were registered as an eager state.
+ repeated PersistedValue state = 2;
+ // A non empty (at least one) list of invocations
+ repeated Invocation invocations = 3;
+ }
+
+ oneof request {
+ InvocationBatchRequest invocation = 100;
+ }
+}
+
+// -------------------------------------------------------------------------------------------------------------------
+// Messages sent from a Remote Function
+// -------------------------------------------------------------------------------------------------------------------
+
+// The following section contains messages sent from a remote function back to Flink.
+message FromFunction {
+ // MutatePersistedValueCommand represents a command sent from a remote function to Flink,
+ // requesting a change to a persisted value.
+ message PersistedValueMutation {
+ enum MutationType {
+ DELETE = 0;
+ MODIFY = 1;
+ }
+ MutationType mutation_type = 1;
+ string state_name = 2;
+ bytes state_value = 3;
+ }
+
+ // Invocation represents a remote function call, it associated with a (mandatory) target address,
+ // and an argument.
+ message Invocation {
+ // The target function to invoke
+ Address target = 1;
+ // The invocation argument (aka the message sent to the target function)
+ google.protobuf.Any argument = 2;
+ }
+
+ // InvocationResponse represents a result of an org.apache.flink.statefun.flink.core.polyglot.ToFunction.InvocationBatchRequest
+ // it contains a list of state mutation to preform as a result of computing this batch, and a list of outgoing messages.
+ message InvocationResponse {
+ repeated PersistedValueMutation state_mutations = 1;
+ repeated Invocation outgoing_messages = 2;
+ }
+
+ oneof response {
+ InvocationResponse invocation_result = 100;
+ }
+}
+
+