index int64 0 0 | repo_id stringlengths 9 205 | file_path stringlengths 31 246 | content stringlengths 1 12.2M | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/flink-statefun/statefun-kafka-io/src/main/java/org/apache/flink/statefun/sdk | Create_ds/flink-statefun/statefun-kafka-io/src/main/java/org/apache/flink/statefun/sdk/kafka/KafkaIngressAutoResetPosition.java | /*
* 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.sdk.kafka;
import java.util.Locale;
/** The auto offset reset position to use in case consumed offsets are invalid. */
public enum KafkaIngressAutoResetPosition {
EARLIEST,
LATEST;
@Override
public String toString() {
return name().toLowerCase(Locale.ENGLISH);
}
}
| 5,800 |
0 | Create_ds/flink-statefun/statefun-kafka-io/src/main/java/org/apache/flink/statefun/sdk | Create_ds/flink-statefun/statefun-kafka-io/src/main/java/org/apache/flink/statefun/sdk/kafka/KafkaIngressStartupPosition.java | /*
* 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.sdk.kafka;
import java.time.ZonedDateTime;
import java.util.Map;
/** Position for the ingress to start consuming Kafka partitions. */
@SuppressWarnings("WeakerAccess, unused")
public class KafkaIngressStartupPosition {
/** Private constructor to prevent instantiation. */
private KafkaIngressStartupPosition() {}
/**
* Start consuming from committed consumer group offsets in Kafka.
*
* <p>Note that a consumer group id must be provided for this startup mode. Please see {@link
* KafkaIngressBuilder#withConsumerGroupId(String)}.
*/
public static KafkaIngressStartupPosition fromGroupOffsets() {
return GroupOffsetsPosition.INSTANCE;
}
/** Start consuming from the earliest offset possible. */
public static KafkaIngressStartupPosition fromEarliest() {
return EarliestPosition.INSTANCE;
}
/** Start consuming from the latest offset, i.e. head of the topic partitions. */
public static KafkaIngressStartupPosition fromLatest() {
return LatestPosition.INSTANCE;
}
/**
* Start consuming from a specified set of offsets.
*
* <p>If a specified offset does not exist for a partition, the position for that partition will
* fallback to the reset position configured via {@link
* KafkaIngressBuilder#withAutoResetPosition(KafkaIngressAutoResetPosition)}.
*
* @param specificOffsets map of specific set of offsets.
*/
public static KafkaIngressStartupPosition fromSpecificOffsets(
Map<KafkaTopicPartition, Long> specificOffsets) {
if (specificOffsets == null || specificOffsets.isEmpty()) {
throw new IllegalArgumentException("Provided specific offsets must not be empty.");
}
return new SpecificOffsetsPosition(specificOffsets);
}
/**
* Start consuming from offsets with ingestion timestamps after or equal to a specified {@link
* ZonedDateTime}.
*
* <p>If a Kafka partition does not have any records with ingestion timestamps after or equal to
* the specified date, the position for that partition will fallback to the reset position
* configured via {@link
* KafkaIngressBuilder#withAutoResetPosition(KafkaIngressAutoResetPosition)}.
*/
public static KafkaIngressStartupPosition fromDate(ZonedDateTime date) {
return new DatePosition(date);
}
/** Checks whether this position is configured using committed consumer group offsets in Kafka. */
public boolean isGroupOffsets() {
return getClass() == GroupOffsetsPosition.class;
}
/** Checks whether this position is configured using the earliest offset. */
public boolean isEarliest() {
return getClass() == EarliestPosition.class;
}
/** Checks whether this position is configured using the latest offset. */
public boolean isLatest() {
return getClass() == LatestPosition.class;
}
/** Checks whether this position is configured using specific offsets. */
public boolean isSpecificOffsets() {
return getClass() == SpecificOffsetsPosition.class;
}
/** Checks whether this position is configured using a date. */
public boolean isDate() {
return getClass() == DatePosition.class;
}
/** Returns this position as a {@link SpecificOffsetsPosition}. */
public SpecificOffsetsPosition asSpecificOffsets() {
if (!isSpecificOffsets()) {
throw new IllegalStateException(
"This is not a startup position configured using specific offsets.");
}
return (SpecificOffsetsPosition) this;
}
/** Returns this position as a {@link DatePosition}. */
public DatePosition asDate() {
if (!isDate()) {
throw new IllegalStateException("This is not a startup position configured using a Date.");
}
return (DatePosition) this;
}
public static final class GroupOffsetsPosition extends KafkaIngressStartupPosition {
private static final GroupOffsetsPosition INSTANCE = new GroupOffsetsPosition();
private GroupOffsetsPosition() {}
@Override
public boolean equals(Object obj) {
return obj != null && obj instanceof GroupOffsetsPosition;
}
@Override
public int hashCode() {
return getClass().hashCode();
}
}
public static final class EarliestPosition extends KafkaIngressStartupPosition {
private static final EarliestPosition INSTANCE = new EarliestPosition();
private EarliestPosition() {}
@Override
public boolean equals(Object obj) {
return obj != null && obj instanceof EarliestPosition;
}
@Override
public int hashCode() {
return getClass().hashCode();
}
}
public static final class LatestPosition extends KafkaIngressStartupPosition {
private static final LatestPosition INSTANCE = new LatestPosition();
private LatestPosition() {}
@Override
public boolean equals(Object obj) {
return obj != null && obj instanceof LatestPosition;
}
@Override
public int hashCode() {
return getClass().hashCode();
}
}
public static final class SpecificOffsetsPosition extends KafkaIngressStartupPosition {
private final Map<KafkaTopicPartition, Long> specificOffsets;
private SpecificOffsetsPosition(Map<KafkaTopicPartition, Long> specificOffsets) {
this.specificOffsets = specificOffsets;
}
public Map<KafkaTopicPartition, Long> specificOffsets() {
return specificOffsets;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (obj == this) {
return true;
}
if (!(obj instanceof SpecificOffsetsPosition)) {
return false;
}
SpecificOffsetsPosition that = (SpecificOffsetsPosition) obj;
return that.specificOffsets.equals(specificOffsets);
}
@Override
public int hashCode() {
return specificOffsets.hashCode();
}
}
public static final class DatePosition extends KafkaIngressStartupPosition {
private final ZonedDateTime date;
private DatePosition(ZonedDateTime date) {
this.date = date;
}
public long epochMilli() {
return date.toInstant().toEpochMilli();
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (obj == this) {
return true;
}
if (!(obj instanceof DatePosition)) {
return false;
}
DatePosition that = (DatePosition) obj;
return that.date.equals(date);
}
@Override
public int hashCode() {
return date.hashCode();
}
}
}
| 5,801 |
0 | Create_ds/flink-statefun/statefun-kafka-io/src/main/java/org/apache/flink/statefun/sdk | Create_ds/flink-statefun/statefun-kafka-io/src/main/java/org/apache/flink/statefun/sdk/kafka/KafkaIngressSpec.java | /*
* 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.sdk.kafka;
import java.util.List;
import java.util.Objects;
import java.util.Properties;
import org.apache.flink.statefun.sdk.IngressType;
import org.apache.flink.statefun.sdk.io.IngressIdentifier;
import org.apache.flink.statefun.sdk.io.IngressSpec;
import org.apache.kafka.clients.consumer.ConsumerConfig;
public class KafkaIngressSpec<T> implements IngressSpec<T> {
private final Properties properties;
private final List<String> topics;
private final KafkaIngressDeserializer<T> deserializer;
private final KafkaIngressStartupPosition startupPosition;
private final IngressIdentifier<T> ingressIdentifier;
KafkaIngressSpec(
IngressIdentifier<T> id,
Properties properties,
List<String> topics,
KafkaIngressDeserializer<T> deserializer,
KafkaIngressStartupPosition startupPosition) {
this.properties = requireValidProperties(properties);
this.topics = requireValidTopics(topics);
this.startupPosition = requireValidStartupPosition(startupPosition, properties);
this.deserializer = Objects.requireNonNull(deserializer);
this.ingressIdentifier = Objects.requireNonNull(id);
}
@Override
public IngressIdentifier<T> id() {
return ingressIdentifier;
}
@Override
public IngressType type() {
return Constants.KAFKA_INGRESS_TYPE;
}
public Properties properties() {
return properties;
}
public List<String> topics() {
return topics;
}
public KafkaIngressDeserializer<T> deserializer() {
return deserializer;
}
public KafkaIngressStartupPosition startupPosition() {
return startupPosition;
}
private static Properties requireValidProperties(Properties properties) {
Objects.requireNonNull(properties);
if (!properties.containsKey(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG)) {
throw new IllegalArgumentException("Missing setting for Kafka address.");
}
// TODO: we eventually want to make the ingress work out-of-the-box without the need to set the
// consumer group id
if (!properties.containsKey(ConsumerConfig.GROUP_ID_CONFIG)) {
throw new IllegalArgumentException("Missing setting for consumer group id.");
}
return properties;
}
private static List<String> requireValidTopics(List<String> topics) {
Objects.requireNonNull(topics);
if (topics.isEmpty()) {
throw new IllegalArgumentException("Must define at least one Kafka topic to consume from.");
}
return topics;
}
private static KafkaIngressStartupPosition requireValidStartupPosition(
KafkaIngressStartupPosition startupPosition, Properties properties) {
if (startupPosition.isGroupOffsets()
&& !properties.containsKey(ConsumerConfig.GROUP_ID_CONFIG)) {
throw new IllegalStateException(
"The ingress is configured to start from committed consumer group offsets in Kafka, but no consumer group id was set.\n"
+ "Please set the group id with the withConsumerGroupId(String) method.");
}
return startupPosition;
}
}
| 5,802 |
0 | Create_ds/flink-statefun/statefun-kafka-io/src/main/java/org/apache/flink/statefun/sdk | Create_ds/flink-statefun/statefun-kafka-io/src/main/java/org/apache/flink/statefun/sdk/kafka/Constants.java | /*
* 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.sdk.kafka;
import org.apache.flink.statefun.sdk.EgressType;
import org.apache.flink.statefun.sdk.IngressType;
public final class Constants {
public static final IngressType KAFKA_INGRESS_TYPE =
new IngressType("statefun.kafka.io", "universal-ingress");
public static final EgressType KAFKA_EGRESS_TYPE =
new EgressType("statefun.kafka.io", "universal-egress");
private Constants() {}
}
| 5,803 |
0 | Create_ds/flink-statefun/statefun-testutil/src/test/java/org/apache/flink/statefun/testutils | Create_ds/flink-statefun/statefun-testutil/src/test/java/org/apache/flink/statefun/testutils/function/FunctionTestHarnessTest.java | /*
* 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.testutils.function;
import static org.apache.flink.statefun.testutils.matchers.StatefulFunctionMatchers.*;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.equalTo;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;
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.io.EgressIdentifier;
import org.junit.Assert;
import org.junit.Test;
/** Simple validation tests of the test harness. */
public class FunctionTestHarnessTest {
private static final FunctionType UNDER_TEST = new FunctionType("flink", "undertest");
private static final FunctionType OTHER_FUNCTION = new FunctionType("flink", "function");
private static final Address CALLER = new Address(OTHER_FUNCTION, "id");
private static final Address SOME_ADDRESS = new Address(OTHER_FUNCTION, "id2");
private static final Address SELF_ADDRESS = new Address(UNDER_TEST, "id");
private static final EgressIdentifier<String> EGRESS =
new EgressIdentifier<>("flink", "egress", String.class);
@Test
public void basicMessageTest() {
FunctionTestHarness harness =
FunctionTestHarness.test(ignore -> new BasicFunction(), UNDER_TEST, "id");
Assert.assertThat(harness.invoke(CALLER, "ping"), sent(messagesTo(CALLER, equalTo("pong"))));
}
@Test
public void multiReturnTest() {
FunctionTestHarness harness =
FunctionTestHarness.test(ignore -> new MultiResponseFunction(), UNDER_TEST, "id");
Assert.assertThat(
harness.invoke("hello"),
sent(
messagesTo(CALLER, equalTo("a"), equalTo("b")),
messagesTo(SOME_ADDRESS, equalTo("c"))));
}
@Test
public void selfSentTest() {
FunctionTestHarness harness =
FunctionTestHarness.test(ignore -> new SelfResponseFunction(), UNDER_TEST, "id");
Assert.assertThat(harness.invoke("hello"), sent(messagesTo(SELF_ADDRESS, equalTo("world"))));
}
@Test
public void egressTest() {
FunctionTestHarness harness =
FunctionTestHarness.test(ignore -> new EgressFunction(), UNDER_TEST, "id");
Assert.assertThat(harness.invoke(CALLER, "ping"), sentNothing());
Assert.assertThat(harness.getEgress(EGRESS), contains(equalTo("pong")));
}
@Test
public void delayedMessageTest() {
FunctionTestHarness harness =
FunctionTestHarness.test(ignore -> new DelayedResponse(), UNDER_TEST, "id");
Assert.assertThat(harness.invoke(CALLER, "ping"), sentNothing());
Assert.assertThat(
harness.tick(Duration.ofMinutes(1)), sent(messagesTo(CALLER, equalTo("pong"))));
}
@Test
public void asyncMessageTest() {
FunctionTestHarness harness =
FunctionTestHarness.test(ignore -> new AsyncOperation(), UNDER_TEST, "id");
Assert.assertThat(harness.invoke(CALLER, "ping"), sent(messagesTo(CALLER, equalTo("pong"))));
}
private static class BasicFunction implements StatefulFunction {
@Override
public void invoke(Context context, Object input) {
context.reply("pong");
}
}
private static class MultiResponseFunction implements StatefulFunction {
@Override
public void invoke(Context context, Object input) {
context.send(CALLER, "a");
context.send(CALLER, "b");
context.send(SOME_ADDRESS, "c");
}
}
private static class SelfResponseFunction implements StatefulFunction {
@Override
public void invoke(Context context, Object input) {
if ("hello".equals(input)) {
context.send(context.self(), "world");
}
}
}
private static class EgressFunction implements StatefulFunction {
@Override
public void invoke(Context context, Object input) {
context.send(EGRESS, "pong");
}
}
private static class DelayedResponse implements StatefulFunction {
@Override
public void invoke(Context context, Object input) {
context.sendAfter(Duration.ofMinutes(1), context.caller(), "pong");
}
}
private static class AsyncOperation implements StatefulFunction {
@Override
public void invoke(Context context, Object input) {
if (input instanceof String) {
CompletableFuture<String> future = CompletableFuture.completedFuture("pong");
context.registerAsyncOperation(context.caller(), future);
}
if (input instanceof AsyncOperationResult) {
AsyncOperationResult<Address, String> result =
(AsyncOperationResult<Address, String>) input;
context.send(result.metadata(), result.value());
}
}
}
}
| 5,804 |
0 | Create_ds/flink-statefun/statefun-testutil/src/main/java/org/apache/flink/statefun/testutils | Create_ds/flink-statefun/statefun-testutil/src/main/java/org/apache/flink/statefun/testutils/function/TestContext.java | /*
* 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.testutils.function;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
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.StatefulFunction;
import org.apache.flink.statefun.sdk.io.EgressIdentifier;
import org.apache.flink.statefun.sdk.metrics.Counter;
import org.apache.flink.statefun.sdk.metrics.Metrics;
/** A simple context that is strictly synchronous and captures all responses. */
class TestContext implements Context {
private final Address selfAddress;
private final StatefulFunction function;
private final Map<EgressIdentifier<?>, List<Object>> outputs;
private final Queue<Envelope> messages;
private final PriorityQueue<PendingMessage> pendingMessage;
private Map<Address, List<Object>> responses;
private Address from;
private long watermark;
TestContext(Address selfAddress, StatefulFunction function, Instant startTime) {
this.selfAddress = Objects.requireNonNull(selfAddress);
this.function = Objects.requireNonNull(function);
this.watermark = startTime.toEpochMilli();
this.messages = new ArrayDeque<>();
this.pendingMessage = new PriorityQueue<>(Comparator.comparingLong(a -> a.timer));
this.outputs = new HashMap<>();
}
@Override
public Address self() {
return selfAddress;
}
@Override
public Address caller() {
return from;
}
@Override
public void reply(Object message) {
Address to = caller();
if (to == null) {
throw new IllegalStateException("The caller address is null");
}
send(to, message);
}
@Override
public void send(Address to, Object message) {
if (to.equals(selfAddress)) {
messages.add(new Envelope(self(), to, message));
}
responses.computeIfAbsent(to, ignore -> new ArrayList<>()).add(message);
}
@Override
public <T> void send(EgressIdentifier<T> egress, T message) {
outputs.computeIfAbsent(egress, ignore -> new ArrayList<>()).add(message);
}
@Override
public void sendAfter(Duration delay, Address to, Object message) {
pendingMessage.add(
new PendingMessage(new Envelope(self(), to, message), watermark + delay.toMillis(), null));
}
@Override
public void sendAfter(Duration delay, Address to, Object message, String cancellationToken) {
Objects.requireNonNull(cancellationToken);
pendingMessage.add(
new PendingMessage(
new Envelope(self(), to, message), watermark + delay.toMillis(), cancellationToken));
}
@Override
public void cancelDelayedMessage(String cancellationToken) {
pendingMessage.removeIf(
pendingMessage -> Objects.equals(pendingMessage.cancellationToken, cancellationToken));
}
@Override
public <M, T> void registerAsyncOperation(M metadata, CompletableFuture<T> future) {
T value = null;
Throwable error = null;
try {
value = future.get();
} catch (InterruptedException e) {
throw new RuntimeException("Failed to get results from async action", e);
} catch (ExecutionException e) {
error = e.getCause();
}
AsyncOperationResult.Status status;
if (error == null) {
status = AsyncOperationResult.Status.SUCCESS;
} else {
status = AsyncOperationResult.Status.FAILURE;
}
AsyncOperationResult<M, T> result = new AsyncOperationResult<>(metadata, status, value, error);
messages.add(new Envelope(self(), self(), result));
}
@Override
public Metrics metrics() {
// return a NOOP metrics
return name ->
new Counter() {
@Override
public void inc(long amount) {}
@Override
public void dec(long amount) {}
};
}
@SuppressWarnings("unchecked")
<T> List<T> getEgress(EgressIdentifier<T> identifier) {
List<?> values = outputs.getOrDefault(identifier, Collections.emptyList());
// Because the type is part of the identifier key
// this cast is always safe.
return (List<T>) values;
}
Map<Address, List<Object>> invoke(Address from, Object message) {
messages.add(new Envelope(from, null, message));
return processAllMessages();
}
Map<Address, List<Object>> tick(Duration duration) {
watermark += duration.toMillis();
while (!pendingMessage.isEmpty() && pendingMessage.peek().timer <= watermark) {
messages.add(pendingMessage.poll().envelope);
}
return processAllMessages();
}
private Map<Address, List<Object>> processAllMessages() {
responses = new HashMap<>();
while (!messages.isEmpty()) {
Envelope envelope = messages.poll();
if (envelope.to != null && !envelope.to.equals(self())) {
send(envelope.to, envelope.message);
} else {
from = envelope.from;
function.invoke(this, envelope.message);
}
}
return responses;
}
private static class Envelope {
Address from;
Address to;
Object message;
Envelope(Address from, Address to, Object message) {
this.from = from;
this.to = to;
this.message = message;
}
}
private static class PendingMessage {
Envelope envelope;
String cancellationToken;
long timer;
PendingMessage(Envelope envelope, long timer, String cancellationToken) {
this.envelope = envelope;
this.timer = timer;
this.cancellationToken = cancellationToken;
}
}
}
| 5,805 |
0 | Create_ds/flink-statefun/statefun-testutil/src/main/java/org/apache/flink/statefun/testutils | Create_ds/flink-statefun/statefun-testutil/src/main/java/org/apache/flink/statefun/testutils/function/FunctionTestHarness.java | /*
* 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.testutils.function;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import org.apache.flink.statefun.sdk.Address;
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.StatefulFunctionProvider;
import org.apache.flink.statefun.sdk.io.EgressIdentifier;
/**
* The {@link FunctionTestHarness} provides a thin convenience wrapper around a {@link
* StatefulFunction} to capture its results under test.
*
* <p>The harness captures all messages sent using the {@link org.apache.flink.statefun.sdk.Context}
* from within the functions {@link StatefulFunction#invoke(Context, Object)} method and returns
* them. Values sent to an egress are also captured and can be queried via the {@link
* #getEgress(EgressIdentifier)} method.
*
* <p><b>Important</b>This test harness is intended strictly for basic unit tests of functions. As
* such, {@link Context#registerAsyncOperation(Object, CompletableFuture)} awaits all futures. If
* you want to test in an asyncronous environment please consider using the the {@code
* statefun-flink-harness}.
*
* <pre>{@code
* {@code @Test}
* public void test() {
* FunctionType type = new FunctionType("flink", "testfunc");
* FunctionTestHarness harness = TestHarness.test(new TestFunctionProvider(), type, "my-id");
*
* Assert.assertThat(
* harness.invoke("ping"),
* sent(
* messagesTo(
* new Address(new FunctionType("flink", "func"), "id"), equalTo("pong"));
* }
* }</pre>
*/
@SuppressWarnings("WeakerAccess")
public class FunctionTestHarness {
private final TestContext context;
/**
* Creates a test harness, pinning the function to a particular address.
*
* @param provider A provider for the function under test.
* @param type The type of the function.
* @param id The static id of the function for the duration of the test.
* @param startTime The initial timestamp of the internal clock.
* @return A fully configured test harness.
*/
public static FunctionTestHarness test(
StatefulFunctionProvider provider, FunctionType type, String id, Instant startTime) {
Objects.requireNonNull(provider, "Function provider can not be null");
return new FunctionTestHarness(provider.functionOfType(type), type, id, startTime);
}
/**
* Creates a test harness, pinning the function to a particular address.
*
* @param provider A provider for the function under test.
* @param type The type of the function.
* @param id The static id of the function for the duration of the test.
* @return A fully configured test harness.
*/
public static FunctionTestHarness test(
StatefulFunctionProvider provider, FunctionType type, String id) {
Objects.requireNonNull(provider, "Function provider can not be null");
return new FunctionTestHarness(provider.functionOfType(type), type, id, Instant.EPOCH);
}
private FunctionTestHarness(
StatefulFunction function, FunctionType type, String id, Instant startTime) {
this.context = new TestContext(new Address(type, id), function, startTime);
}
/**
* @param message A message that will be sent to the function.
* @return A responses sent from the function after invocation using {@link Context#send(Address,
* Object)}.
*/
public Map<Address, List<Object>> invoke(Object message) {
return context.invoke(null, message);
}
/**
* @param message A message that will be sent to the function.
* @param from The address of the function that sent the message.
* @return A responses sent from the function after invocation using {@link Context#send(Address,
* Object)}.
*/
public Map<Address, List<Object>> invoke(Address from, Object message) {
Objects.requireNonNull(from);
return context.invoke(from, message);
}
/**
* Advances the internal clock the harness and fires and pending timers.
*
* @param duration the amount of time to advance for this tick.
* @return A responses sent from the function after invocation.
*/
public Map<Address, List<Object>> tick(Duration duration) {
Objects.requireNonNull(duration);
return context.tick(duration);
}
/**
* @param identifier An egress identifier
* @param <T> the data type consumed by the egress.
* @return All the messages sent to that egress.
*/
public <T> List<T> getEgress(EgressIdentifier<T> identifier) {
return context.getEgress(identifier);
}
}
| 5,806 |
0 | Create_ds/flink-statefun/statefun-testutil/src/main/java/org/apache/flink/statefun/testutils | Create_ds/flink-statefun/statefun-testutil/src/main/java/org/apache/flink/statefun/testutils/matchers/MessagesSentToAddress.java | /*
* 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.testutils.matchers;
import java.util.List;
import java.util.Map;
import org.apache.flink.statefun.sdk.Address;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
/** A matcher for checking all the responses sent to a particular function type. */
public class MessagesSentToAddress extends TypeSafeMatcher<Map<Address, List<Object>>> {
private final Map<Address, List<Matcher<?>>> matcherByAddress;
MessagesSentToAddress(Map<Address, List<Matcher<?>>> matcherByAddress) {
this.matcherByAddress = matcherByAddress;
}
@Override
protected boolean matchesSafely(Map<Address, List<Object>> item) {
for (Map.Entry<Address, List<Matcher<?>>> entry : matcherByAddress.entrySet()) {
List<Object> messages = item.get(entry.getKey());
if (messages == null) {
return false;
}
if (messages.size() != entry.getValue().size()) {
return false;
}
for (int i = 0; i < messages.size(); i++) {
Matcher<?> matcher = entry.getValue().get(i);
if (!matcher.matches(messages.get(i))) {
return false;
}
}
}
return true;
}
@Override
public void describeTo(Description description) {
description.appendText("<{");
for (Map.Entry<Address, List<Matcher<?>>> entry : matcherByAddress.entrySet()) {
description
.appendText(entry.getKey().toString())
.appendText("=")
.appendList("[", ",", "]", entry.getValue());
}
description.appendText("}>");
}
}
| 5,807 |
0 | Create_ds/flink-statefun/statefun-testutil/src/main/java/org/apache/flink/statefun/testutils | Create_ds/flink-statefun/statefun-testutil/src/main/java/org/apache/flink/statefun/testutils/matchers/SentNothingMatcher.java | /*
* 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.testutils.matchers;
import java.util.List;
import java.util.Map;
import org.apache.flink.statefun.sdk.Address;
import org.hamcrest.Description;
import org.hamcrest.TypeSafeMatcher;
/** A matcher for that the function did not message any other functions. */
public class SentNothingMatcher extends TypeSafeMatcher<Map<Address, List<Object>>> {
SentNothingMatcher() {}
@Override
protected boolean matchesSafely(Map<Address, List<Object>> item) {
return item.isEmpty();
}
@Override
public void describeTo(Description description) {
description.appendText("Nothing Sent");
}
}
| 5,808 |
0 | Create_ds/flink-statefun/statefun-testutil/src/main/java/org/apache/flink/statefun/testutils | Create_ds/flink-statefun/statefun-testutil/src/main/java/org/apache/flink/statefun/testutils/matchers/MatchersByAddress.java | /*
* 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.testutils.matchers;
import java.util.List;
import java.util.Objects;
import org.apache.flink.statefun.sdk.Address;
import org.hamcrest.Matcher;
@SuppressWarnings("WeakerAccess")
public class MatchersByAddress {
final Address address;
final List<Matcher<?>> matchers;
MatchersByAddress(Address address, List<Matcher<?>> messages) {
this.address = Objects.requireNonNull(address);
this.matchers = Objects.requireNonNull(messages);
}
}
| 5,809 |
0 | Create_ds/flink-statefun/statefun-testutil/src/main/java/org/apache/flink/statefun/testutils | Create_ds/flink-statefun/statefun-testutil/src/main/java/org/apache/flink/statefun/testutils/matchers/StatefulFunctionMatchers.java | /*
* 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.testutils.matchers;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.flink.statefun.sdk.Address;
import org.apache.flink.statefun.sdk.FunctionType;
import org.apache.flink.statefun.testutils.function.FunctionTestHarness;
import org.hamcrest.Matcher;
/**
* A set of Hamcrest matchers to help check the responses from a {@link FunctionTestHarness}
*
* @see FunctionTestHarness for usage details.
*/
public final class StatefulFunctionMatchers {
private StatefulFunctionMatchers() {
throw new AssertionError();
}
public static MatchersByAddress messagesTo(
Address to, Matcher<?> matcher, Matcher<?>... matchers) {
List<Matcher<?>> allMatchers = new ArrayList<>(1 + matchers.length);
allMatchers.add(matcher);
allMatchers.addAll(Arrays.asList(matchers));
return new MatchersByAddress(to, allMatchers);
}
/**
* A matcher that checks all the responses sent to a given {@link FunctionType}.
*
* <p><b>Important:</b> This matcher expects an exact match on the number of responses sent to
* this function.
*
* @param matcher matcher for address.
* @param matchers matchers for addresses.
* @return a matcher that checks all the responses sent to a given {@link FunctionType}.
*/
public static MessagesSentToAddress sent(
MatchersByAddress matcher, MatchersByAddress... matchers) {
Map<Address, List<Matcher<?>>> messagesByAddress = new HashMap<>();
messagesByAddress.put(matcher.address, matcher.matchers);
for (MatchersByAddress match : matchers) {
messagesByAddress.put(match.address, match.matchers);
}
return new MessagesSentToAddress(messagesByAddress);
}
/**
* A matcher that checks the function did not send any messages.
*
* @return a matcher that checks the function did not send any messages.
*/
public static SentNothingMatcher sentNothing() {
return new SentNothingMatcher();
}
}
| 5,810 |
0 | Create_ds/flink-statefun/statefun-sdk-java/src/test | Create_ds/flink-statefun/statefun-sdk-java/src/test/java/ValueSpecTest.java | /*
* 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.
*/
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import org.apache.flink.statefun.sdk.java.ValueSpec;
import org.apache.flink.statefun.sdk.java.types.Types;
import org.junit.Test;
public class ValueSpecTest {
@Test
public void exampleUsage() {
final ValueSpec<Integer> spec = ValueSpec.named("state_name").withIntType();
assertThat(spec.name(), is("state_name"));
assertThat(spec.type(), is(Types.integerType()));
}
@Test(expected = IllegalArgumentException.class)
public void stateNameWithSpaces() {
ValueSpec.named("bad state name").withIntType();
}
@Test(expected = IllegalArgumentException.class)
public void stateNameWithInvalidStartChar() {
ValueSpec.named("123bad_state_name").withIntType();
}
@Test(expected = IllegalArgumentException.class)
public void stateNameWithInvalidPartChar() {
ValueSpec.named("bad!_state_name").withIntType();
}
}
| 5,811 |
0 | Create_ds/flink-statefun/statefun-sdk-java/src/test/java/org/apache/flink/statefun/sdk | Create_ds/flink-statefun/statefun-sdk-java/src/test/java/org/apache/flink/statefun/sdk/java/StatefulFunctionSpecTest.java | /*
* 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.sdk.java;
import static org.hamcrest.Matchers.hasKey;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import java.util.concurrent.CompletableFuture;
import org.apache.flink.statefun.sdk.java.message.Message;
import org.junit.Test;
public class StatefulFunctionSpecTest {
private static final ValueSpec<Integer> STATE_A = ValueSpec.named("state_a").withIntType();
private static final ValueSpec<Boolean> STATE_B = ValueSpec.named("state_b").withBooleanType();
@Test
public void exampleUsage() {
final StatefulFunctionSpec spec =
StatefulFunctionSpec.builder(TypeName.typeNameOf("test.namespace", "test.name"))
.withValueSpecs(STATE_A, STATE_B)
.withSupplier(TestFunction::new)
.build();
assertThat(spec.supplier().get(), instanceOf(TestFunction.class));
assertThat(spec.typeName(), is(TypeName.typeNameOf("test.namespace", "test.name")));
assertThat(spec.knownValues(), hasKey("state_a"));
assertThat(spec.knownValues(), hasKey("state_b"));
}
@Test(expected = IllegalArgumentException.class)
public void duplicateRegistration() {
StatefulFunctionSpec.builder(TypeName.typeNameOf("test.namespace", "test.name"))
.withValueSpecs(
ValueSpec.named("foobar").withIntType(), ValueSpec.named("foobar").withBooleanType());
}
private static class TestFunction implements StatefulFunction {
@Override
public CompletableFuture<Void> apply(Context context, Message argument) {
// no-op
return context.done();
}
}
}
| 5,812 |
0 | Create_ds/flink-statefun/statefun-sdk-java/src/test/java/org/apache/flink/statefun/sdk/java | Create_ds/flink-statefun/statefun-sdk-java/src/test/java/org/apache/flink/statefun/sdk/java/handler/ConcurrentRequestReplyHandlerTest.java | /*
* 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.sdk.java.handler;
import static java.util.Collections.singletonMap;
import static org.apache.flink.statefun.sdk.java.handler.TestUtils.modifiedValue;
import static org.apache.flink.statefun.sdk.java.handler.TestUtils.protoFromValueSpec;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;
import org.apache.flink.statefun.sdk.java.Context;
import org.apache.flink.statefun.sdk.java.StatefulFunction;
import org.apache.flink.statefun.sdk.java.StatefulFunctionSpec;
import org.apache.flink.statefun.sdk.java.TypeName;
import org.apache.flink.statefun.sdk.java.ValueSpec;
import org.apache.flink.statefun.sdk.java.handler.TestUtils.RequestBuilder;
import org.apache.flink.statefun.sdk.java.message.Message;
import org.apache.flink.statefun.sdk.java.types.Types;
import org.apache.flink.statefun.sdk.reqreply.generated.FromFunction;
import org.apache.flink.statefun.sdk.reqreply.generated.ToFunction;
import org.junit.Test;
public class ConcurrentRequestReplyHandlerTest {
private static final TypeName GREETER_TYPE = TypeName.typeNameFromString("example/greeter");
private static final ValueSpec<Integer> SEEN_INT_SPEC =
ValueSpec.named("seen").thatExpiresAfterCall(Duration.ofDays(1)).withIntType();
private static final StatefulFunctionSpec GREET_FN_SPEC =
StatefulFunctionSpec.builder(GREETER_TYPE)
.withValueSpec(SEEN_INT_SPEC)
.withSupplier(SimpleGreeter::new)
.build();
private final ConcurrentRequestReplyHandler handlerUnderTest =
new ConcurrentRequestReplyHandler(singletonMap(GREETER_TYPE, GREET_FN_SPEC));
@Test
public void simpleInvocationExample() {
ToFunction request =
new RequestBuilder()
.withTarget(GREETER_TYPE, "0")
.withState(SEEN_INT_SPEC, 1023)
.withInvocation(Types.stringType(), "Hello world")
.build();
FromFunction response = handlerUnderTest.handleInternally(request).join();
assertThat(response, notNullValue());
}
@Test
public void invocationWithoutStateDefinition() {
ToFunction request =
new RequestBuilder()
.withTarget(GREETER_TYPE, "0")
.withInvocation(Types.stringType(), "Hello world")
.build();
FromFunction response = handlerUnderTest.handleInternally(request).join();
assertThat(
response.getIncompleteInvocationContext().getMissingValuesList(),
hasItem(protoFromValueSpec(SEEN_INT_SPEC)));
}
@Test
public void multipleInvocations() {
ToFunction request =
new RequestBuilder()
.withTarget(GREETER_TYPE, "0")
.withState(SEEN_INT_SPEC, 0)
.withInvocation(Types.stringType(), "a")
.withInvocation(Types.stringType(), "b")
.withInvocation(Types.stringType(), "c")
.build();
FromFunction response = handlerUnderTest.handleInternally(request).join();
assertThat(
response.getInvocationResult().getStateMutationsList(),
hasItem(modifiedValue(SEEN_INT_SPEC, 3)));
}
private static final class SimpleGreeter implements StatefulFunction {
@Override
public CompletableFuture<Void> apply(Context context, Message argument) {
int seen = context.storage().get(SEEN_INT_SPEC).orElse(0);
context.storage().set(SEEN_INT_SPEC, seen + 1);
return CompletableFuture.completedFuture(null);
}
}
}
| 5,813 |
0 | Create_ds/flink-statefun/statefun-sdk-java/src/test/java/org/apache/flink/statefun/sdk/java | Create_ds/flink-statefun/statefun-sdk-java/src/test/java/org/apache/flink/statefun/sdk/java/handler/TestUtils.java | /*
* 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.sdk.java.handler;
import org.apache.flink.statefun.sdk.java.TypeName;
import org.apache.flink.statefun.sdk.java.ValueSpec;
import org.apache.flink.statefun.sdk.java.slice.Slice;
import org.apache.flink.statefun.sdk.java.slice.SliceProtobufUtil;
import org.apache.flink.statefun.sdk.java.types.Type;
import org.apache.flink.statefun.sdk.reqreply.generated.Address;
import org.apache.flink.statefun.sdk.reqreply.generated.FromFunction;
import org.apache.flink.statefun.sdk.reqreply.generated.ToFunction;
import org.apache.flink.statefun.sdk.reqreply.generated.TypedValue;
import org.hamcrest.Matcher;
import org.hamcrest.Matchers;
public class TestUtils {
private TestUtils() {}
public static <T> Matcher<FromFunction.PersistedValueMutation> modifiedValue(
ValueSpec<T> spec, T newValue) {
FromFunction.PersistedValueMutation mutation =
FromFunction.PersistedValueMutation.newBuilder()
.setStateName(spec.name())
.setMutationType(FromFunction.PersistedValueMutation.MutationType.MODIFY)
.setStateValue(typedValue(spec.type(), newValue))
.build();
return Matchers.is(mutation);
}
public static FromFunction.PersistedValueSpec protoFromValueSpec(ValueSpec<?> spec) {
return ProtoUtils.protoFromValueSpec(spec).build();
}
public static <T> TypedValue.Builder typedValue(Type<T> type, T value) {
Slice serializedValue = type.typeSerializer().serialize(value);
return TypedValue.newBuilder()
.setTypename(type.typeName().asTypeNameString())
.setHasValue(value != null)
.setValue(SliceProtobufUtil.asByteString(serializedValue));
}
/** A test utility to build ToFunction messages using SDK concepts. */
public static final class RequestBuilder {
private final ToFunction.InvocationBatchRequest.Builder builder =
ToFunction.InvocationBatchRequest.newBuilder();
public RequestBuilder withTarget(TypeName target, String id) {
builder.setTarget(
Address.newBuilder().setNamespace(target.namespace()).setType(target.name()).setId(id));
return this;
}
public <T> RequestBuilder withState(ValueSpec<T> spec) {
builder.addState(ToFunction.PersistedValue.newBuilder().setStateName(spec.name()));
return this;
}
public <T> RequestBuilder withState(ValueSpec<T> spec, T value) {
builder.addState(
ToFunction.PersistedValue.newBuilder()
.setStateName(spec.name())
.setStateValue(typedValue(spec.type(), value)));
return this;
}
public <T> RequestBuilder withInvocation(Type<T> type, T value) {
builder.addInvocations(
ToFunction.Invocation.newBuilder().setArgument(typedValue(type, value)));
return this;
}
public ToFunction build() {
return ToFunction.newBuilder().setInvocation(builder).build();
}
}
}
| 5,814 |
0 | Create_ds/flink-statefun/statefun-sdk-java/src/test/java/org/apache/flink/statefun/sdk/java | Create_ds/flink-statefun/statefun-sdk-java/src/test/java/org/apache/flink/statefun/sdk/java/handler/MoreFuturesTest.java | /*
* 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.sdk.java.handler;
import static org.apache.flink.statefun.sdk.java.handler.MoreFutures.applySequentially;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.is;
import java.util.Arrays;
import java.util.Iterator;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.stream.IntStream;
import org.junit.Test;
public class MoreFuturesTest {
@Test
public void usageExample() {
final ConcurrentLinkedDeque<String> results = new ConcurrentLinkedDeque<>();
CompletableFuture<?> allDone =
applySequentially(
Arrays.asList("a", "b", "c"),
letter -> CompletableFuture.runAsync(() -> results.addLast(letter)));
allDone.join();
assertThat(results, contains("a", "b", "c"));
}
@Test
public void firstThrows() {
CompletableFuture<Void> allDone =
applySequentially(Arrays.asList("a", "b", "c"), throwing("a"));
assertThat(allDone.isCompletedExceptionally(), is(true));
}
@Test
public void lastThrows() {
CompletableFuture<Void> allDone =
applySequentially(Arrays.asList("a", "b", "c"), throwing("c"));
assertThat(allDone.isCompletedExceptionally(), is(true));
}
@Test
public void bigList() {
Iterator<String> lotsOfInts =
IntStream.range(0, 1_000_000).mapToObj(String::valueOf).iterator();
Iterable<String> input = () -> lotsOfInts;
CompletableFuture<Void> allDone = applySequentially(input, throwing(null));
allDone.join();
}
private static MoreFutures.Fn<String, CompletableFuture<Void>> throwing(String when) {
return letter -> {
if (letter.equals(when)) {
throw new IllegalStateException("I'm a throwing function");
} else {
return CompletableFuture.completedFuture(null);
// return CompletableFuture.runAsync(
// () -> {
//// try {
//// Thread.sleep(1_00);
//// } catch (InterruptedException e) {
//// e.printStackTrace();
//// }
// /* complete successfully */
// });
}
};
}
}
| 5,815 |
0 | Create_ds/flink-statefun/statefun-sdk-java/src/test/java/org/apache/flink/statefun/sdk/java | Create_ds/flink-statefun/statefun-sdk-java/src/test/java/org/apache/flink/statefun/sdk/java/types/SimpleTypeTest.java | /*
* 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.sdk.java.types;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import java.nio.charset.StandardCharsets;
import org.apache.flink.statefun.sdk.java.TypeName;
import org.apache.flink.statefun.sdk.java.slice.Slice;
import org.junit.Test;
public class SimpleTypeTest {
@Test
public void mutableType() {
final Type<String> type =
SimpleType.simpleTypeFrom(
TypeName.typeNameFromString("test/simple-mutable-type"),
val -> val.getBytes(StandardCharsets.UTF_8),
bytes -> new String(bytes, StandardCharsets.UTF_8));
assertThat(type.typeName(), is(TypeName.typeNameFromString("test/simple-mutable-type")));
assertRoundTrip(type, "hello world!");
}
@Test
public void immutableType() {
final Type<String> type =
SimpleType.simpleImmutableTypeFrom(
TypeName.typeNameFromString("test/simple-immutable-type"),
val -> val.getBytes(StandardCharsets.UTF_8),
bytes -> new String(bytes, StandardCharsets.UTF_8));
assertThat(type.typeName(), is(TypeName.typeNameFromString("test/simple-immutable-type")));
assertRoundTrip(type, "hello world!");
}
public <T> void assertRoundTrip(Type<T> type, T element) {
final Slice slice;
{
TypeSerializer<T> serializer = type.typeSerializer();
slice = serializer.serialize(element);
}
TypeSerializer<T> serializer = type.typeSerializer();
T deserialized = serializer.deserialize(slice);
assertEquals(element, deserialized);
}
}
| 5,816 |
0 | Create_ds/flink-statefun/statefun-sdk-java/src/test/java/org/apache/flink/statefun/sdk/java | Create_ds/flink-statefun/statefun-sdk-java/src/test/java/org/apache/flink/statefun/sdk/java/types/SanityPrimitiveTypeTest.java | /*
* 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.sdk.java.types;
import static org.junit.Assert.assertEquals;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ThreadLocalRandom;
import org.apache.flink.statefun.sdk.java.TypeName;
import org.apache.flink.statefun.sdk.java.slice.Slice;
import org.apache.flink.statefun.sdk.java.slice.Slices;
import org.apache.flink.statefun.sdk.shaded.com.google.protobuf.InvalidProtocolBufferException;
import org.apache.flink.statefun.sdk.types.generated.BooleanWrapper;
import org.apache.flink.statefun.sdk.types.generated.IntWrapper;
import org.apache.flink.statefun.sdk.types.generated.LongWrapper;
import org.apache.flink.statefun.sdk.types.generated.StringWrapper;
import org.junit.Ignore;
import org.junit.Test;
public class SanityPrimitiveTypeTest {
@Test
public void testBoolean() {
assertRoundTrip(Types.booleanType(), Boolean.TRUE);
assertRoundTrip(Types.booleanType(), Boolean.FALSE);
}
@Test
public void testInt() {
assertRoundTrip(Types.integerType(), 1);
assertRoundTrip(Types.integerType(), 1048576);
assertRoundTrip(Types.integerType(), Integer.MIN_VALUE);
assertRoundTrip(Types.integerType(), Integer.MAX_VALUE);
assertRoundTrip(Types.integerType(), -1);
}
@Test
public void testLong() {
assertRoundTrip(Types.longType(), -1L);
assertRoundTrip(Types.longType(), 0L);
assertRoundTrip(Types.longType(), Long.MIN_VALUE);
assertRoundTrip(Types.longType(), Long.MAX_VALUE);
}
@Test
public void testFloat() {
assertRoundTrip(Types.floatType(), Float.MIN_VALUE);
assertRoundTrip(Types.floatType(), Float.MAX_VALUE);
assertRoundTrip(Types.floatType(), 2.1459f);
assertRoundTrip(Types.floatType(), -1e-4f);
}
@Test
public void testDouble() {
assertRoundTrip(Types.doubleType(), Double.MIN_VALUE);
assertRoundTrip(Types.doubleType(), Double.MAX_VALUE);
assertRoundTrip(Types.doubleType(), 2.1459d);
assertRoundTrip(Types.doubleType(), -1e-4d);
}
@Test
public void testString() {
assertRoundTrip(Types.stringType(), "");
assertRoundTrip(Types.stringType(), "This is a string");
}
@Test
public void testSlice() {
final TypeName typename = TypeName.typeNameOf("test.namespace", "test.name");
assertRoundTrip(
new SliceType(typename), Slices.wrap("payload-foobar".getBytes(StandardCharsets.UTF_8)));
assertRoundTrip(new SliceType(typename), Slices.wrap(new byte[] {}));
}
@Test
public void testRandomCompatibilityWithAnIntegerWrapper() throws InvalidProtocolBufferException {
TypeSerializer<Integer> serializer = Types.integerType().typeSerializer();
for (int i = 0; i < 1_000_000; i++) {
testCompatibilityWithWrapper(
serializer, IntWrapper::parseFrom, IntWrapper::getValue, IntWrapper::toByteArray, i);
}
}
@Test
public void testCompatibilityWithABooleanWrapper() throws InvalidProtocolBufferException {
TypeSerializer<Boolean> serializer = Types.booleanType().typeSerializer();
testCompatibilityWithWrapper(
serializer,
BooleanWrapper::parseFrom,
BooleanWrapper::getValue,
BooleanWrapper::toByteArray,
true);
testCompatibilityWithWrapper(
serializer,
BooleanWrapper::parseFrom,
BooleanWrapper::getValue,
BooleanWrapper::toByteArray,
false);
}
@Test
public void testRandomCompatibilityWithALongWrapper() throws InvalidProtocolBufferException {
TypeSerializer<Long> serializer = Types.longType().typeSerializer();
for (long i = 0; i < 1_000_000; i++) {
testCompatibilityWithWrapper(
serializer, LongWrapper::parseFrom, LongWrapper::getValue, LongWrapper::toByteArray, i);
}
}
@Ignore
@Test
public void testCompatibilityWithAnIntegerWrapper() throws InvalidProtocolBufferException {
TypeSerializer<Integer> serializer = Types.integerType().typeSerializer();
for (int expected = Integer.MIN_VALUE; expected != Integer.MAX_VALUE; expected++) {
testCompatibilityWithWrapper(
serializer,
IntWrapper::parseFrom,
IntWrapper::getValue,
IntWrapper::toByteArray,
expected);
}
}
@Test
public void testRandomCompatibilityWithStringWrapper() throws InvalidProtocolBufferException {
TypeSerializer<String> serializer = Types.stringType().typeSerializer();
ThreadLocalRandom random = ThreadLocalRandom.current();
for (int i = 0; i < 1_000; i++) {
int n = random.nextInt(4096);
byte[] buf = new byte[n];
random.nextBytes(buf);
String expected = new String(buf, StandardCharsets.UTF_8);
testCompatibilityWithWrapper(
serializer,
StringWrapper::parseFrom,
StringWrapper::getValue,
StringWrapper::toByteArray,
expected);
}
}
@FunctionalInterface
interface Fn<I, O> {
O apply(I input) throws InvalidProtocolBufferException;
}
private static <T, W> void testCompatibilityWithWrapper(
TypeSerializer<T> serializer,
Fn<ByteBuffer, W> parseFrom,
Fn<W, T> getValue,
Fn<W, byte[]> toByteArray,
T expected)
throws InvalidProtocolBufferException {
//
// test round trip with ourself.
//
final Slice serialized = serializer.serialize(expected);
final T got = serializer.deserialize(serialized);
assertEquals(expected, got);
//
// test that protobuf can parse what we wrote:
//
final W wrapper = parseFrom.apply(serialized.asReadOnlyByteBuffer());
assertEquals(expected, getValue.apply(wrapper));
//
// test that we can parse what protobuf wrote:
//
final Slice serializedByPb = Slices.wrap(toByteArray.apply(wrapper));
final T gotPb = serializer.deserialize(serializedByPb);
assertEquals(gotPb, expected);
// test that pb byte representation is equal to ours:
assertEquals(serializedByPb.asReadOnlyByteBuffer(), serialized.asReadOnlyByteBuffer());
}
public <T> void assertRoundTrip(Type<T> type, T element) {
final Slice slice;
{
TypeSerializer<T> serializer = type.typeSerializer();
slice = serializer.serialize(element);
}
TypeSerializer<T> serializer = type.typeSerializer();
T got = serializer.deserialize(slice);
assertEquals(element, got);
}
}
| 5,817 |
0 | Create_ds/flink-statefun/statefun-sdk-java/src/test/java/org/apache/flink/statefun/sdk/java | Create_ds/flink-statefun/statefun-sdk-java/src/test/java/org/apache/flink/statefun/sdk/java/slice/SliceProtobufUtilTest.java | /*
* 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.sdk.java.slice;
import static org.junit.Assert.assertSame;
import org.apache.flink.statefun.sdk.shaded.com.google.protobuf.ByteString;
import org.junit.Test;
public class SliceProtobufUtilTest {
@Test
public void usageExample() {
ByteString expected = ByteString.copyFromUtf8("Hello world");
Slice slice = SliceProtobufUtil.asSlice(expected);
ByteString got = SliceProtobufUtil.asByteString(slice);
assertSame("Expecting the same reference.", expected, got);
}
}
| 5,818 |
0 | Create_ds/flink-statefun/statefun-sdk-java/src/test/java/org/apache/flink/statefun/sdk/java | Create_ds/flink-statefun/statefun-sdk-java/src/test/java/org/apache/flink/statefun/sdk/java/slice/SliceOutputTest.java | /*
* 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.sdk.java.slice;
import static org.junit.Assert.assertArrayEquals;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import org.junit.Test;
public class SliceOutputTest {
private static final byte[] TEST_BYTES = new byte[] {1, 2, 3, 4, 5};
@Test
public void usageExample() {
SliceOutput output = SliceOutput.sliceOutput(32);
output.write(TEST_BYTES);
Slice slice = output.copyOf();
assertArrayEquals(TEST_BYTES, slice.toByteArray());
}
@Test
public void sliceShouldAutoGrow() {
SliceOutput sliceOutput = SliceOutput.sliceOutput(0);
sliceOutput.write(TEST_BYTES);
Slice slice = sliceOutput.copyOf();
byte[] got = new byte[slice.readableBytes()];
slice.copyTo(got);
assertArrayEquals(got, TEST_BYTES);
}
@Test
public void writeStartingAtOffset() {
SliceOutput output = SliceOutput.sliceOutput(32);
output.write(TEST_BYTES);
Slice slice = output.copyOf();
byte[] slightlyBiggerBuf = new byte[1 + slice.readableBytes()];
slice.copyTo(slightlyBiggerBuf, 1);
byte[] got = deleteFirstByte(slightlyBiggerBuf);
assertArrayEquals(TEST_BYTES, got);
}
@Test
public void randomizedTest() {
ThreadLocalRandom random = ThreadLocalRandom.current();
for (int i = 0; i < 1_000_000; i++) {
// create a random buffer of a random size.
final int size = random.nextInt(0, 32);
byte[] buf = randomBuffer(random, size);
// write the buffer in random chunks
SliceOutput sliceOutput = SliceOutput.sliceOutput(0);
for (OffsetLenPair chunk : randomChunks(random, size)) {
sliceOutput.write(buf, chunk.offset, chunk.len);
}
// verify
Slice slice = sliceOutput.copyOf();
assertArrayEquals(buf, slice.toByteArray());
}
}
@Test
public void copyFromInputStreamRandomizedTest() {
byte[] expected = randomBuffer(ThreadLocalRandom.current(), 256);
ByteArrayInputStream input = new ByteArrayInputStream(expected);
Slice slice = Slices.copyOf(input, 0);
byte[] actual = slice.toByteArray();
assertArrayEquals(expected, actual);
}
@Test
public void toOutputStreamTest() {
byte[] expected = randomBuffer(ThreadLocalRandom.current(), 256);
Slice slice = Slices.wrap(expected);
ByteArrayOutputStream output = new ByteArrayOutputStream(expected.length);
slice.copyTo(output);
assertArrayEquals(expected, output.toByteArray());
}
private static byte[] deleteFirstByte(byte[] slightlyBiggerBuf) {
return Arrays.copyOfRange(slightlyBiggerBuf, 1, slightlyBiggerBuf.length);
}
private static byte[] randomBuffer(ThreadLocalRandom random, int size) {
byte[] buf = new byte[size];
random.nextBytes(buf);
return buf;
}
/** Compute a random partition of @size to pairs of (offset, len). */
private static List<OffsetLenPair> randomChunks(ThreadLocalRandom random, int size) {
ArrayList<OffsetLenPair> chunks = new ArrayList<>();
int offset = 0;
while (offset != size) {
int remaining = size - offset;
int toWrite = random.nextInt(remaining + 1);
chunks.add(new OffsetLenPair(offset, toWrite));
offset += toWrite;
}
return chunks;
}
private static final class OffsetLenPair {
final int offset;
final int len;
public OffsetLenPair(int offset, int len) {
this.offset = offset;
this.len = len;
}
}
}
| 5,819 |
0 | Create_ds/flink-statefun/statefun-sdk-java/src/test/java/org/apache/flink/statefun/sdk/java | Create_ds/flink-statefun/statefun-sdk-java/src/test/java/org/apache/flink/statefun/sdk/java/storage/TestMutableType.java | /*
* 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.sdk.java.storage;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
import org.apache.flink.statefun.sdk.java.TypeName;
import org.apache.flink.statefun.sdk.java.slice.Slice;
import org.apache.flink.statefun.sdk.java.slice.Slices;
import org.apache.flink.statefun.sdk.java.types.Type;
import org.apache.flink.statefun.sdk.java.types.TypeSerializer;
public class TestMutableType implements Type<TestMutableType.Type> {
@Override
public TypeName typeName() {
return TypeName.typeNameOf("test", "my-mutable-type");
}
@Override
public TypeSerializer<TestMutableType.Type> typeSerializer() {
return new Serializer();
}
public static class Type {
private String value;
public Type(String value) {
this.value = value;
}
public void mutate(String newValue) {
this.value = newValue;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Type type = (Type) o;
return Objects.equals(value, type.value);
}
@Override
public int hashCode() {
return Objects.hash(value);
}
}
private static class Serializer implements TypeSerializer<TestMutableType.Type> {
@Override
public Slice serialize(Type value) {
return Slices.wrap(value.value.getBytes(StandardCharsets.UTF_8));
}
@Override
public Type deserialize(Slice bytes) {
return new Type(new String(bytes.toByteArray(), StandardCharsets.UTF_8));
}
}
}
| 5,820 |
0 | Create_ds/flink-statefun/statefun-sdk-java/src/test/java/org/apache/flink/statefun/sdk/java | Create_ds/flink-statefun/statefun-sdk-java/src/test/java/org/apache/flink/statefun/sdk/java/storage/ConcurrentAddressScopedStorageTest.java | /*
* 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.sdk.java.storage;
import static org.apache.flink.statefun.sdk.java.storage.StateValueContexts.StateValueContext;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import org.apache.flink.statefun.sdk.java.AddressScopedStorage;
import org.apache.flink.statefun.sdk.java.ValueSpec;
import org.apache.flink.statefun.sdk.java.types.Type;
import org.apache.flink.statefun.sdk.reqreply.generated.ToFunction;
import org.apache.flink.statefun.sdk.reqreply.generated.TypedValue;
import org.apache.flink.statefun.sdk.shaded.com.google.protobuf.ByteString;
import org.junit.Test;
public class ConcurrentAddressScopedStorageTest {
@Test
public void exampleUsage() {
final ValueSpec<Integer> stateSpec1 = ValueSpec.named("state_1").withIntType();
final ValueSpec<Boolean> stateSpec2 = ValueSpec.named("state_2").withBooleanType();
final List<StateValueContext<?>> testStateValues =
testStateValues(stateValue(stateSpec1, 91), stateValue(stateSpec2, true));
final AddressScopedStorage storage = new ConcurrentAddressScopedStorage(testStateValues);
assertThat(storage.get(stateSpec1), is(Optional.of(91)));
assertThat(storage.get(stateSpec2), is(Optional.of(true)));
}
@Test
public void getNullValueCell() {
final ValueSpec<Integer> stateSpec = ValueSpec.named("state").withIntType();
final List<StateValueContext<?>> testStateValues = testStateValues(stateValue(stateSpec, null));
final AddressScopedStorage storage = new ConcurrentAddressScopedStorage(testStateValues);
assertThat(storage.get(stateSpec), is(Optional.empty()));
}
@Test
public void setCell() {
final ValueSpec<Integer> stateSpec = ValueSpec.named("state").withIntType();
final List<StateValueContext<?>> testStateValues = testStateValues(stateValue(stateSpec, 91));
final AddressScopedStorage storage = new ConcurrentAddressScopedStorage(testStateValues);
storage.set(stateSpec, 1111);
assertThat(storage.get(stateSpec), is(Optional.of(1111)));
}
@Test
public void setMutableTypeCell() {
final ValueSpec<TestMutableType.Type> stateSpec =
ValueSpec.named("state").withCustomType(new TestMutableType());
final List<StateValueContext<?>> testStateValues =
testStateValues(stateValue(stateSpec, new TestMutableType.Type("hello")));
final AddressScopedStorage storage = new ConcurrentAddressScopedStorage(testStateValues);
final TestMutableType.Type newValue = new TestMutableType.Type("hello again!");
storage.set(stateSpec, newValue);
// mutations after a set should not have any effect
newValue.mutate("this value should not be written to storage!");
assertThat(storage.get(stateSpec), is(Optional.of(new TestMutableType.Type("hello again!"))));
}
@Test
public void clearCell() {
final ValueSpec<Integer> stateSpec = ValueSpec.named("state").withIntType();
List<StateValueContext<?>> testStateValues = testStateValues(stateValue(stateSpec, 91));
final AddressScopedStorage storage = new ConcurrentAddressScopedStorage(testStateValues);
storage.remove(stateSpec);
assertThat(storage.get(stateSpec), is(Optional.empty()));
}
@Test
public void clearMutableTypeCell() {
final ValueSpec<TestMutableType.Type> stateSpec =
ValueSpec.named("state").withCustomType(new TestMutableType());
List<StateValueContext<?>> testStateValues =
testStateValues(stateValue(stateSpec, new TestMutableType.Type("hello")));
final AddressScopedStorage storage = new ConcurrentAddressScopedStorage(testStateValues);
storage.remove(stateSpec);
assertThat(storage.get(stateSpec), is(Optional.empty()));
}
@Test(expected = IllegalStorageAccessException.class)
public void getNonExistingCell() {
final AddressScopedStorage storage =
new ConcurrentAddressScopedStorage(Collections.emptyList());
storage.get(ValueSpec.named("does_not_exist").withIntType());
}
@Test(expected = IllegalStorageAccessException.class)
public void setNonExistingCell() {
final AddressScopedStorage storage =
new ConcurrentAddressScopedStorage(Collections.emptyList());
storage.set(ValueSpec.named("does_not_exist").withIntType(), 999);
}
@Test(expected = IllegalStorageAccessException.class)
public void clearNonExistingCell() {
final AddressScopedStorage storage =
new ConcurrentAddressScopedStorage(Collections.emptyList());
storage.remove(ValueSpec.named("does_not_exist").withIntType());
}
@Test(expected = IllegalStorageAccessException.class)
public void setToNull() {
final ValueSpec<Integer> stateSpec = ValueSpec.named("state").withIntType();
List<StateValueContext<?>> testStateValues = testStateValues(stateValue(stateSpec, 91));
final AddressScopedStorage storage = new ConcurrentAddressScopedStorage(testStateValues);
storage.set(stateSpec, null);
}
@Test(expected = IllegalStorageAccessException.class)
public void getWithWrongType() {
final ValueSpec<Integer> stateSpec = ValueSpec.named("state").withIntType();
final List<StateValueContext<?>> testStateValues = testStateValues(stateValue(stateSpec, 91));
final AddressScopedStorage storage = new ConcurrentAddressScopedStorage(testStateValues);
storage.get(ValueSpec.named("state").withBooleanType());
}
@Test(expected = IllegalStorageAccessException.class)
public void setWithWrongType() {
final ValueSpec<Integer> stateSpec = ValueSpec.named("state").withIntType();
final List<StateValueContext<?>> testStateValues = testStateValues(stateValue(stateSpec, 91));
final AddressScopedStorage storage = new ConcurrentAddressScopedStorage(testStateValues);
storage.set(ValueSpec.named("state").withBooleanType(), true);
}
@Test(expected = IllegalStorageAccessException.class)
public void clearWithWrongType() {
final ValueSpec<Integer> stateSpec = ValueSpec.named("state").withIntType();
final List<StateValueContext<?>> testStateValues = testStateValues(stateValue(stateSpec, 91));
final AddressScopedStorage storage = new ConcurrentAddressScopedStorage(testStateValues);
storage.remove(ValueSpec.named("state").withBooleanType());
}
private static List<StateValueContext<?>> testStateValues(StateValueContext<?>... testValues) {
return Arrays.asList(testValues);
}
private static <T> StateValueContext<T> stateValue(ValueSpec<T> spec, T value) {
final ToFunction.PersistedValue protocolValue =
ToFunction.PersistedValue.newBuilder()
.setStateName(spec.name())
.setStateValue(
TypedValue.newBuilder()
.setTypename(value == null ? "" : spec.type().typeName().asTypeNameString())
.setHasValue(value != null)
.setValue(toByteString(spec.type(), value)))
.build();
return new StateValueContext<>(spec, protocolValue);
}
private static <T> ByteString toByteString(Type<T> type, T value) {
if (value == null) {
return ByteString.EMPTY;
}
return ByteString.copyFrom(type.typeSerializer().serialize(value).toByteArray());
}
}
| 5,821 |
0 | Create_ds/flink-statefun/statefun-sdk-java/src/test/java/org/apache/flink/statefun/sdk/java | Create_ds/flink-statefun/statefun-sdk-java/src/test/java/org/apache/flink/statefun/sdk/java/storage/StateValueContextsTest.java | /*
* 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.sdk.java.storage;
import static org.apache.flink.statefun.sdk.java.storage.StateValueContexts.StateValueContext;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsCollectionContaining.hasItem;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import org.apache.flink.statefun.sdk.java.ValueSpec;
import org.apache.flink.statefun.sdk.java.types.Type;
import org.apache.flink.statefun.sdk.java.types.Types;
import org.apache.flink.statefun.sdk.reqreply.generated.ToFunction;
import org.apache.flink.statefun.sdk.reqreply.generated.TypedValue;
import org.apache.flink.statefun.sdk.shaded.com.google.protobuf.ByteString;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.Matchers;
import org.hamcrest.TypeSafeDiagnosingMatcher;
import org.hamcrest.TypeSafeMatcher;
import org.junit.Test;
public final class StateValueContextsTest {
@Test
public void exampleUsage() {
final Map<String, ValueSpec<?>> registeredSpecs = new HashMap<>(2);
registeredSpecs.put("state_1", ValueSpec.named("state_1").withIntType());
registeredSpecs.put("state_2", ValueSpec.named("state_2").withBooleanType());
final List<ToFunction.PersistedValue> providedProtocolValues = new ArrayList<>(2);
providedProtocolValues.add(protocolValue("state_1", Types.integerType(), 66));
providedProtocolValues.add(protocolValue("state_2", Types.booleanType(), true));
final List<StateValueContext<?>> resolvedStateValues =
StateValueContexts.resolve(registeredSpecs, providedProtocolValues).resolved();
assertThat(resolvedStateValues.size(), is(2));
assertThat(resolvedStateValues, hasItem(stateValueContextNamed("state_1")));
assertThat(resolvedStateValues, hasItem(stateValueContextNamed("state_2")));
}
@Test
public void missingProtocolValues() {
final Map<String, ValueSpec<?>> registeredSpecs = new HashMap<>(3);
registeredSpecs.put("state_1", ValueSpec.named("state_1").withIntType());
registeredSpecs.put("state_2", ValueSpec.named("state_2").withBooleanType());
registeredSpecs.put("state_3", ValueSpec.named("state_3").withUtf8StringType());
// only value for state-2 was provided
final List<ToFunction.PersistedValue> providedProtocolValues = new ArrayList<>(1);
providedProtocolValues.add(protocolValue("state_2", Types.booleanType(), true));
final List<ValueSpec<?>> statesWithMissingValue =
StateValueContexts.resolve(registeredSpecs, providedProtocolValues).missingValues();
assertThat(statesWithMissingValue.size(), is(2));
assertThat(statesWithMissingValue, hasItem(valueSpec("state_1", Types.integerType())));
assertThat(statesWithMissingValue, hasItem(valueSpec("state_3", Types.stringType())));
}
@Test
public void extraProtocolValues() {
final Map<String, ValueSpec<?>> registeredSpecs = new HashMap<>(1);
registeredSpecs.put("state_1", ValueSpec.named("state_1").withIntType());
// a few extra states were provided, and should be ignored
final List<ToFunction.PersistedValue> providedProtocolValues = new ArrayList<>(3);
providedProtocolValues.add(protocolValue("state_1", Types.integerType(), 66));
providedProtocolValues.add(protocolValue("state_2", Types.booleanType(), true));
providedProtocolValues.add(protocolValue("state_3", Types.stringType(), "ignore me!"));
final List<StateValueContext<?>> resolvedStateValues =
StateValueContexts.resolve(registeredSpecs, providedProtocolValues).resolved();
assertThat(resolvedStateValues.size(), is(1));
ValueSpec<?> spec = resolvedStateValues.get(0).spec();
assertThat(spec.name(), Matchers.is("state_1"));
}
private static <T> ToFunction.PersistedValue protocolValue(
String stateName, Type<T> type, T value) {
return ToFunction.PersistedValue.newBuilder()
.setStateName(stateName)
.setStateValue(
TypedValue.newBuilder()
.setTypename(type.typeName().asTypeNameString())
.setHasValue(value != null)
.setValue(toByteString(type, value)))
.build();
}
private static <T> ByteString toByteString(Type<T> type, T value) {
if (value == null) {
return ByteString.EMPTY;
}
return ByteString.copyFrom(type.typeSerializer().serialize(value).toByteArray());
}
private static <T> Matcher<ValueSpec<T>> valueSpec(String stateName, Type<T> type) {
return new TypeSafeMatcher<ValueSpec<T>>() {
@Override
protected boolean matchesSafely(ValueSpec<T> testSpec) {
return testSpec.type().getClass() == type.getClass() && testSpec.name().equals(stateName);
}
@Override
public void describeTo(Description description) {}
};
}
private static <T> Matcher<StateValueContext<T>> stateValueContextNamed(String name) {
return new TypeSafeDiagnosingMatcher<StateValueContext<T>>() {
@Override
protected boolean matchesSafely(StateValueContext<T> ctx, Description description) {
if (!Objects.equals(ctx.spec().name(), name)) {
description.appendText(ctx.spec().name());
return false;
}
return true;
}
@Override
public void describeTo(Description description) {
description.appendText("A StateValueContext named ").appendText(name);
}
};
}
}
| 5,822 |
0 | Create_ds/flink-statefun/statefun-sdk-java/src/test/java/org/apache/flink/statefun/sdk/java | Create_ds/flink-statefun/statefun-sdk-java/src/test/java/org/apache/flink/statefun/sdk/java/testing/TestContextTest.java | /*
* 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.sdk.java.testing;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.empty;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Optional;
import org.apache.flink.statefun.sdk.java.Address;
import org.apache.flink.statefun.sdk.java.TypeName;
import org.apache.flink.statefun.sdk.java.ValueSpec;
import org.apache.flink.statefun.sdk.java.message.Message;
import org.apache.flink.statefun.sdk.java.message.MessageBuilder;
import org.apache.flink.statefun.sdk.java.types.SimpleType;
import org.apache.flink.statefun.sdk.java.types.Type;
import org.junit.Before;
import org.junit.Test;
public class TestContextTest {
private TestContext context;
private Address someone;
private Address me;
@Before
public void resetContext() {
me = new Address(TypeName.typeNameOf("com.example", "function"), "me");
someone = new Address(TypeName.typeNameOf("com.example", "function"), "someone");
context = TestContext.forTargetWithCaller(me, someone);
}
@Test
public void testSelfAndCaller() {
assertThat(context.self(), equalTo(me));
assertThat(context.caller(), equalTo(Optional.of(someone)));
}
@Test
public void testRoundTripToAddressedScopeStorageWithBuiltInType() {
ValueSpec<Boolean> builtInTypeSpec = ValueSpec.named("type").withBooleanType();
context.storage().set(builtInTypeSpec, true);
assertThat(context.storage().get(builtInTypeSpec), equalTo(Optional.of(true)));
}
@Test
public void testRoundTripToAddressedScopeStorageWithCustomType() {
Type<User> type =
SimpleType.simpleImmutableTypeFrom(
TypeName.typeNameFromString("com.example/User"), User::toBytes, User::new);
User user = new User("someone".getBytes(StandardCharsets.UTF_8));
ValueSpec<User> customTypeSpec = ValueSpec.named("type").withCustomType(type);
context.storage().set(customTypeSpec, user);
assertThat(context.storage().get(customTypeSpec), equalTo(Optional.of(user)));
}
@Test
public void testMessageCancellation() {
Message aMessage = MessageBuilder.forAddress(someone).withValue(1).build();
context.sendAfter(Duration.ZERO, "abcd", aMessage);
context.cancelDelayedMessage("abcd");
assertThat(context.getSentDelayedMessages(), empty());
}
private static class User {
public String name;
public User(byte[] bytes) {
name = new String(bytes);
}
public byte[] toBytes() {
return name.getBytes(StandardCharsets.UTF_8);
}
}
}
| 5,823 |
0 | Create_ds/flink-statefun/statefun-sdk-java/src/test/java/org/apache/flink/statefun/sdk/java | Create_ds/flink-statefun/statefun-sdk-java/src/test/java/org/apache/flink/statefun/sdk/java/testing/TestContextIntegrationTest.java | /*
* 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.sdk.java.testing;
import static org.apache.flink.statefun.sdk.java.testing.SideEffects.sentAfter;
import static org.apache.flink.statefun.sdk.java.testing.SideEffects.sentEgress;
import static org.apache.flink.statefun.sdk.java.testing.SideEffects.sentMessage;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.equalTo;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;
import org.apache.flink.statefun.sdk.java.Address;
import org.apache.flink.statefun.sdk.java.AddressScopedStorage;
import org.apache.flink.statefun.sdk.java.Context;
import org.apache.flink.statefun.sdk.java.StatefulFunction;
import org.apache.flink.statefun.sdk.java.TypeName;
import org.apache.flink.statefun.sdk.java.ValueSpec;
import org.apache.flink.statefun.sdk.java.message.EgressMessage;
import org.apache.flink.statefun.sdk.java.message.EgressMessageBuilder;
import org.apache.flink.statefun.sdk.java.message.Message;
import org.apache.flink.statefun.sdk.java.message.MessageBuilder;
import org.junit.Test;
public class TestContextIntegrationTest {
private static class SimpleFunctionUnderTest implements StatefulFunction {
static final TypeName TYPE = TypeName.typeNameFromString("com.example.fns/simple-fn");
static final TypeName ANOTHER_TYPE = TypeName.typeNameFromString("com.example.fns/another-fn");
static final TypeName SOME_EGRESS = TypeName.typeNameFromString("com.example.fns/another-fn");
static final ValueSpec<Integer> NUM_INVOCATIONS = ValueSpec.named("seen").withIntType();
@Override
public CompletableFuture<Void> apply(Context context, Message message) {
AddressScopedStorage storage = context.storage();
int numInvocations = storage.get(NUM_INVOCATIONS).orElse(0);
storage.set(NUM_INVOCATIONS, numInvocations + 1);
Message messageToSomeone =
MessageBuilder.forAddress(ANOTHER_TYPE, "someone")
.withValue("I have an important message!")
.build();
context.send(messageToSomeone);
context.send(
EgressMessageBuilder.forEgress(SOME_EGRESS)
.withValue("I have an important egress message!")
.build());
context.sendAfter(Duration.ofMillis(1000), messageToSomeone);
return context.done();
}
}
@SuppressWarnings("OptionalGetWithoutIsPresent")
@Test
public void testSimpleFunction() {
// Arrange
Address someone = new Address(SimpleFunctionUnderTest.ANOTHER_TYPE, "someone");
Address me = new Address(SimpleFunctionUnderTest.TYPE, "me");
TestContext context = TestContext.forTargetWithCaller(me, someone);
context.storage().set(SimpleFunctionUnderTest.NUM_INVOCATIONS, 2);
// Action
SimpleFunctionUnderTest function = new SimpleFunctionUnderTest();
Message testMessage = MessageBuilder.forAddress(me).withValue("This is a message").build();
function.apply(context, testMessage);
// Assert
// Assert Send
Message expectedMessageToSomeone =
MessageBuilder.forAddress(someone).withValue("I have an important message!").build();
assertThat(context.getSentMessages(), contains(sentMessage(expectedMessageToSomeone)));
assertThat(
context.getSentDelayedMessages(),
contains(sentAfter(Duration.ofMillis(1_000), expectedMessageToSomeone)));
EgressMessage expectedMessageToEgress =
EgressMessageBuilder.forEgress(SimpleFunctionUnderTest.SOME_EGRESS)
.withValue("I have an important egress message!")
.build();
assertThat(context.getSentEgressMessages(), contains(sentEgress(expectedMessageToEgress)));
// Assert State
assertThat(context.storage().get(SimpleFunctionUnderTest.NUM_INVOCATIONS).get(), equalTo(3));
}
}
| 5,824 |
0 | Create_ds/flink-statefun/statefun-sdk-java/src/main/resources/META-INF | Create_ds/flink-statefun/statefun-sdk-java/src/main/resources/META-INF/licenses/LICENSE.protobuf-java | Copyright 2008 Google Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google Inc. nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Code generated by the Protocol Buffer compiler is owned by the owner
of the input file used when generating it. This code is not
standalone and requires a support library to be linked with it. This
support library is itself covered by the above license. | 5,825 |
0 | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java/Expiration.java | /*
* 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.sdk.java;
import java.io.Serializable;
import java.time.Duration;
import java.util.Objects;
/**
* State Expiration Configuration
*
* <p>This class defines the way state can be auto expired by the runtime. State expiration (also
* known as state TTL) can be used to keep state from growing arbitrarily by assigning an expiration
* date to a value.
*
* <p>State can be expired after a duration had passed since either from the last write to the
* state, or the last call to the function.
*/
public final class Expiration implements Serializable {
private static final long serialVersionUID = 1L;
public enum Mode {
NONE,
AFTER_WRITE,
AFTER_CALL;
}
/**
* Returns an {@link Expiration} configuration that would expire a @duration after the last write.
*
* @param duration a duration to wait before considering the state expired.
*/
public static Expiration expireAfterWriting(Duration duration) {
return new Expiration(Mode.AFTER_WRITE, duration);
}
/**
* Returns an {@link Expiration} configuration that would expire a @duration after the last
* invocation of the function.
*
* @param duration a duration to wait before considering the state expired.
*/
public static Expiration expireAfterCall(Duration duration) {
return new Expiration(Mode.AFTER_CALL, duration);
}
/**
* Returns an {@link Expiration} configuration that has an expiration characteristic based on the
* provided expire {@link Mode}.
*
* @param duration a duration to wait before considering the state expired.
* @param mode the expire mode.
*/
public static Expiration expireAfter(Duration duration, Mode mode) {
return new Expiration(mode, duration);
}
/** @return Returns a disabled expiration */
public static Expiration none() {
return new Expiration(Mode.NONE, Duration.ZERO);
}
private final Mode mode;
private final Duration duration;
private Expiration(Mode mode, Duration duration) {
this.mode = Objects.requireNonNull(mode);
this.duration = Objects.requireNonNull(duration);
}
/** @return The expire mode of this {@link Expiration} configuration. */
public Mode mode() {
return mode;
}
/** @return The duration of this {@link Expiration} configuration. */
public Duration duration() {
return duration;
}
@Override
public String toString() {
return String.format("Expiration{mode=%s, duration=%s}", mode, duration);
}
}
| 5,826 |
0 | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java/TypeName.java | /*
* 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.sdk.java;
import java.io.Serializable;
import java.util.Objects;
import org.apache.flink.statefun.sdk.java.types.Type;
import org.apache.flink.statefun.sdk.shaded.com.google.protobuf.ByteString;
/**
* A {@link TypeName} is used to uniquely identify objects within a Stateful Functions application,
* including functions, egresses, and types. Typenames serves as an integral part of identifying
* these objects for message delivery as well as message data serialization and deserialization.
*
* @see Address
* @see Type
* @see StatefulFunctionSpec
*/
public final class TypeName implements Serializable {
private static final long serialVersionUID = 1;
private final String namespace;
private final String type;
private final String typenameString;
private final ByteString typenameByteString;
public static TypeName typeNameOf(String namespace, String name) {
Objects.requireNonNull(namespace);
Objects.requireNonNull(name);
if (namespace.endsWith("/")) {
namespace = namespace.substring(0, namespace.length() - 1);
}
if (namespace.isEmpty()) {
throw new IllegalArgumentException("namespace can not be empty.");
}
if (name.isEmpty()) {
throw new IllegalArgumentException("name can not be empty.");
}
return new TypeName(namespace, name);
}
public static TypeName typeNameFromString(String typeNameString) {
Objects.requireNonNull(typeNameString);
final int pos = typeNameString.lastIndexOf("/");
if (pos <= 0 || pos == typeNameString.length() - 1) {
throw new IllegalArgumentException(
typeNameString + " does not conform to the <namespace>/<name> format");
}
String namespace = typeNameString.substring(0, pos);
String name = typeNameString.substring(pos + 1);
return typeNameOf(namespace, name);
}
/**
* Creates a {@link TypeName}.
*
* @param namespace the function type's namepsace.
* @param type the function type's name.
*/
private TypeName(String namespace, String type) {
this.namespace = Objects.requireNonNull(namespace);
this.type = Objects.requireNonNull(type);
String typenameString = canonicalTypeNameString(namespace, type);
this.typenameString = typenameString;
this.typenameByteString = ByteString.copyFromUtf8(typenameString);
}
/**
* Returns the namespace of the function type.
*
* @return the namespace of the function type.
*/
public String namespace() {
return namespace;
}
/**
* Returns the name of the function type.
*
* @return the name of the function type.
*/
public String name() {
return type;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
TypeName functionType = (TypeName) o;
return namespace.equals(functionType.namespace) && type.equals(functionType.type);
}
@Override
public int hashCode() {
int hash = 0;
hash = 37 * hash + namespace.hashCode();
hash = 37 * hash + type.hashCode();
return hash;
}
@Override
public String toString() {
return "TypeName(" + namespace + ", " + type + ")";
}
public String asTypeNameString() {
return typenameString;
}
ByteString typeNameByteString() {
return typenameByteString;
}
private static String canonicalTypeNameString(String namespace, String type) {
return namespace + '/' + type;
}
}
| 5,827 |
0 | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java/ApiExtension.java | /*
* 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.sdk.java;
import org.apache.flink.statefun.sdk.java.annotations.Internal;
import org.apache.flink.statefun.sdk.shaded.com.google.protobuf.ByteString;
@Internal
public final class ApiExtension {
public static ByteString typeNameByteString(TypeName typeName) {
return typeName.typeNameByteString();
}
public static ByteString stateNameByteString(ValueSpec<?> spec) {
return spec.nameByteString();
}
}
| 5,828 |
0 | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java/StatefulFunctions.java | /*
* 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.sdk.java;
import java.util.HashMap;
import java.util.Map;
import org.apache.flink.statefun.sdk.java.handler.ConcurrentRequestReplyHandler;
import org.apache.flink.statefun.sdk.java.handler.RequestReplyHandler;
/**
* A registry for multiple {@link StatefulFunction}s. A {@link RequestReplyHandler} can be created
* from the registry that understands how to dispatch invocation requests to the registered
* functions as well as encode side-effects (e.g., sending messages to other functions or updating
* values in storage) as the response.
*/
public class StatefulFunctions {
private final Map<TypeName, StatefulFunctionSpec> specs = new HashMap<>();
/**
* Registers a {@link StatefulFunctionSpec} builder, which will be used to build the function
* spec.
*
* @param builder a builder for the function spec to register.
* @throws IllegalArgumentException if multiple {@link StatefulFunctionSpec} under the same {@link
* TypeName} have been registered.
*/
public StatefulFunctions withStatefulFunction(StatefulFunctionSpec.Builder builder) {
return withStatefulFunction(builder.build());
}
/**
* Registers a {@link StatefulFunctionSpec}.
*
* @param spec the function spec to register.
* @throws IllegalArgumentException if multiple {@link StatefulFunctionSpec} under the same {@link
* TypeName} have been registered.
*/
public StatefulFunctions withStatefulFunction(StatefulFunctionSpec spec) {
if (specs.put(spec.typeName(), spec) != null) {
throw new IllegalArgumentException(
"Attempted to register more than one StatefulFunctionSpec for the function typename: "
+ spec.typeName());
}
return this;
}
/** @return The registered {@link StatefulFunctionSpec}s. */
public Map<TypeName, StatefulFunctionSpec> functionSpecs() {
return specs;
}
/**
* Creates a {@link RequestReplyHandler} that understands how to dispatch invocation requests to
* the registered functions as well as encode side-effects (e.g., sending messages to other
* functions or updating values in storage) as the response.
*
* @return a {@link RequestReplyHandler} for the registered functions.
*/
public RequestReplyHandler requestReplyHandler() {
return new ConcurrentRequestReplyHandler(specs);
}
}
| 5,829 |
0 | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java/AddressScopedStorage.java | /*
* 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.sdk.java;
import java.util.Optional;
import org.apache.flink.statefun.sdk.java.storage.IllegalStorageAccessException;
/**
* An {@link AddressScopedStorage} is used for reading and writing persistent values that is managed
* by Stateful Functions for fault-tolerance and consistency.
*
* <p>All access to the storage is scoped to the current invoked function instance, identified by
* the instance's {@link Address}. This means that within an invocation, function instances may only
* access it's own persisted values through this storage.
*/
public interface AddressScopedStorage {
/**
* Gets the value of the provided {@link ValueSpec}, scoped to the current invoked {@link
* Address}.
*
* @param spec the {@link ValueSpec} to read the value for.
* @param <T> the type of the value.
* @return the value, or {@link Optional#empty()} if there was not prior value set.
* @throws IllegalStorageAccessException if the provided {@link ValueSpec} is not recognized by
* the storage (e.g., if it wasn't registered for the accessing function).
*/
<T> Optional<T> get(ValueSpec<T> spec);
/**
* Sets the value for the provided {@link ValueSpec}, scoped to the current invoked {@link
* Address}.
*
* @param spec the {@link ValueSpec} to write the new value for.
* @param value the new value to set.
* @param <T> the type of the value.
* @throws IllegalStorageAccessException if the provided {@link ValueSpec} is not recognized by
* the storage (e.g., if it wasn't registered for the accessing function).
*/
<T> void set(ValueSpec<T> spec, T value);
/**
* Removes the prior value set for the provided {@link ValueSpec}, scoped to the current invoked
* {@link Address}.
*
* <p>After removing the value, calling {@link #get(ValueSpec)} for the same spec will return an
* {@link Optional#empty()}.
*
* @param spec the {@link ValueSpec} to remove the prior value for.
* @param <T> the type of the value.
* @throws IllegalStorageAccessException if the provided {@link ValueSpec} is not recognized by
* the storage (e.g., if it wasn't registered for the accessing function).
*/
<T> void remove(ValueSpec<T> spec);
}
| 5,830 |
0 | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java/StatefulFunction.java | /*
* 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.sdk.java;
import java.util.concurrent.CompletableFuture;
import org.apache.flink.statefun.sdk.java.message.Message;
/**
* A {@link StatefulFunction} is a user-defined function that can be invoked with a given input.
* This is the primitive building block for a Stateful Functions application.
*
* <h2>Concept</h2>
*
* <p>Each individual {@code StatefulFunction} is an uniquely invokable "instance" of a registered
* {@link StatefulFunctionSpec}. Each instance is identified by an {@link Address}, representing the
* function's unique id (a string) within its type. From a user's perspective, it would seem as if
* for each unique function id, there exists a stateful instance of the function that is always
* available to be invoked within a Stateful Functions application.
*
* <h2>Invoking a {@code StatefulFunction}</h2>
*
* <p>An individual {@code StatefulFunction} can be invoked with arbitrary input from any another
* {@code StatefulFunction} (including itself), or routed from ingresses. To invoke a {@code
* StatefulFunction}, the caller simply needs to know the {@code Address} of the target function.
*
* <p>As a result of invoking a {@code StatefulFunction}, the function may continue to invoke other
* functions, access persisted values, or send messages to egresses.
*
* <h2>Persistent State</h2>
*
* <p>Each individual {@code StatefulFunction} may have persistent values written to storage that is
* maintained by the system, providing consistent exactly-once and fault-tolerant guarantees. Please
* see Javadocs in {@link ValueSpec} and {@link AddressScopedStorage} for an overview of how to
* register persistent values and access the storage.
*
* @see Address
* @see StatefulFunctionSpec
* @see ValueSpec
* @see AddressScopedStorage
*/
public interface StatefulFunction {
/**
* Applies an input message to this function.
*
* @param context the {@link Context} of the current invocation.
* @param argument the input message.
*/
CompletableFuture<Void> apply(Context context, Message argument) throws Throwable;
}
| 5,831 |
0 | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java/Context.java | /*
* 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.sdk.java;
import java.time.Duration;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import org.apache.flink.statefun.sdk.java.message.EgressMessage;
import org.apache.flink.statefun.sdk.java.message.Message;
/**
* A {@link Context} contains information about the current function invocation, such as the invoked
* function instance's and caller's {@link Address}. It is also used for side-effects as a result of
* the invocation such as send messages to other functions or egresses, and provides access to
* {@link AddressScopedStorage} scoped to the current {@link Address}.
*/
public interface Context {
/** @return The current invoked function instance's {@link Address}. */
Address self();
/**
* @return The caller function instance's {@link Address}, if applicable. This is {@link
* Optional#empty()} if the message was sent to this function via an ingress.
*/
Optional<Address> caller();
/**
* Sends out a {@link Message} to another function.
*
* @param message the message to send.
*/
void send(Message message);
/**
* Sends out a {@link Message} to another function, after a specified {@link Duration} delay.
*
* @param duration the amount of time to delay the message delivery.
* @param message the message to send.
*/
void sendAfter(Duration duration, Message message);
/**
* Sends out a {@link Message} to another function, after a specified {@link Duration} delay.
*
* @param duration the amount of time to delay the message delivery. * @param cancellationToken
* @param cancellationToken the non-empty, non-null, unique token to attach to this message, to be
* used for message cancellation. (see {@link #cancelDelayedMessage(String)}.)
* @param message the message to send.
*/
void sendAfter(Duration duration, String cancellationToken, Message message);
/**
* Cancel a delayed message (a message that was send via {@link #sendAfter(Duration, Message)}).
*
* <p>NOTE: this is a best-effort operation, since the message might have been already delivered.
* If the message was delivered, this is a no-op operation.
*
* @param cancellationToken the id of the message to un-send.
*/
void cancelDelayedMessage(String cancellationToken);
/**
* Sends out a {@link EgressMessage} to an egress.
*
* @param message the message to send.
*/
void send(EgressMessage message);
/**
* @return The {@link AddressScopedStorage}, providing access to stored values scoped to the
* current invoked function instance's {@link Address} (which is obtainable using {@link
* #self()}).
*/
AddressScopedStorage storage();
default CompletableFuture<Void> done() {
return CompletableFuture.completedFuture(null);
}
}
| 5,832 |
0 | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java/ValueSpec.java | /*
* 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.sdk.java;
import java.time.Duration;
import java.util.Objects;
import org.apache.flink.statefun.sdk.java.types.Type;
import org.apache.flink.statefun.sdk.java.types.Types;
import org.apache.flink.statefun.sdk.shaded.com.google.protobuf.ByteString;
/**
* A {@link ValueSpec} identifies a registered persistent value of a function, which will be managed
* by the Stateful Functions runtime for consistency and fault-tolerance. A {@link ValueSpec} is
* registered for a function by configuring it on the function's assoicated {@link
* StatefulFunctionSpec}.
*
* @see StatefulFunctionSpec.Builder#withValueSpec(ValueSpec)
* @see AddressScopedStorage
* @param <T> the type of the value.
*/
public final class ValueSpec<T> {
/**
* Creates an {@link Untyped} spec with the given name. To complete the creation of a {@link
* ValueSpec}, please specify the {@link Type} of the value. For example:
*
* <pre>{@code
* final ValueSpec<Integer> intValue = ValueSpec.named("my_int_state").withIntType();
* }</pre>
*
* <p>The specified name string must be a valid identifier conforming to the following rules:
*
* <ul>
* <li>First character must be an alphabet letter [a-z] / [A-Z], or an underscore '_'.
* <li>Remaining characters can be an alphabet letter [a-z] / [A-Z], a digit [0-9], or an
* underscore '_'.
* <li>Must not contain any spaces.
* </ul>
*
* @param name name for the value. Please see the method Javadocs for format rules.
* @return an {@link Untyped} spec. Specify the {@link Type} of the value to instantiate a {@link
* ValueSpec}.
*/
public static Untyped named(String name) {
validateStateName(name);
return new Untyped(name);
}
private final String name;
private final Expiration expiration;
private final Type<T> type;
private final ByteString nameByteString;
private ValueSpec(Untyped untyped, Type<T> type) {
Objects.requireNonNull(untyped);
Objects.requireNonNull(type);
this.name = untyped.stateName;
this.expiration = untyped.expiration;
this.type = Objects.requireNonNull(type);
this.nameByteString = ByteString.copyFromUtf8(untyped.stateName);
}
/** @return The name of the value. */
public String name() {
return name;
}
/** @return The expiration configuration of the value. */
public Expiration expiration() {
return expiration;
}
/** @return The {@link TypeName} of the value's type. */
public TypeName typeName() {
return type.typeName();
}
/** @return The {@link Type} of the value. */
public Type<T> type() {
return type;
}
ByteString nameByteString() {
return nameByteString;
}
public static final class Untyped {
private final String stateName;
private Expiration expiration = Expiration.none();
public Untyped(String name) {
this.stateName = Objects.requireNonNull(name);
}
public Untyped thatExpireAfterWrite(Duration duration) {
this.expiration = Expiration.expireAfterWriting(duration);
return this;
}
public Untyped thatExpiresAfterCall(Duration duration) {
this.expiration = Expiration.expireAfterCall(duration);
return this;
}
public ValueSpec<Integer> withIntType() {
return withCustomType(Types.integerType());
}
public ValueSpec<Long> withLongType() {
return withCustomType(Types.longType());
}
public ValueSpec<Float> withFloatType() {
return withCustomType(Types.floatType());
}
public ValueSpec<Double> withDoubleType() {
return withCustomType(Types.doubleType());
}
public ValueSpec<String> withUtf8StringType() {
return withCustomType(Types.stringType());
}
public ValueSpec<Boolean> withBooleanType() {
return new ValueSpec<>(this, Types.booleanType());
}
public <T> ValueSpec<T> withCustomType(Type<T> type) {
Objects.requireNonNull(type);
return new ValueSpec<>(this, type);
}
}
private static void validateStateName(String stateName) {
Objects.requireNonNull(stateName);
final char[] chars = stateName.toCharArray();
if (!isValidStateNameStart(chars[0])) {
throw new IllegalArgumentException(
"Invalid state name: "
+ stateName
+ ". State names can only start with alphabet letters [a-z] / [A-Z], or an underscore ('_').");
}
for (int i = 1; i < chars.length; i++) {
if (!isValidStateNamePart(chars[i])) {
throw new IllegalArgumentException(
"Invalid state name: "
+ stateName
+ ". State names can only contain alphabet letters [a-z] / [A-Z], digits [0-9], or underscores ('_').");
}
}
}
private static boolean isValidStateNameStart(char character) {
return Character.isLetter(character) || character == '_';
}
private static boolean isValidStateNamePart(char character) {
return Character.isLetter(character) || Character.isDigit(character) || character == '_';
}
}
| 5,833 |
0 | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java/StatefulFunctionSpec.java | /*
* 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.sdk.java;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.function.Supplier;
/** Specification for a {@link StatefulFunction}, identifiable by a unique {@link TypeName}. */
public final class StatefulFunctionSpec {
private final TypeName typeName;
private final Map<String, ValueSpec<?>> knownValues;
private final Supplier<? extends StatefulFunction> supplier;
/**
* Creates a {@link Builder} for the spec.
*
* @param typeName the associated {@link TypeName} for the spec.
*/
public static Builder builder(TypeName typeName) {
return new Builder(typeName);
}
private StatefulFunctionSpec(
TypeName typeName,
Map<String, ValueSpec<?>> knownValues,
Supplier<? extends StatefulFunction> supplier) {
this.typeName = Objects.requireNonNull(typeName);
this.supplier = Objects.requireNonNull(supplier);
this.knownValues = Objects.requireNonNull(knownValues);
}
/** @return The {@link TypeName} of the function. */
public TypeName typeName() {
return typeName;
}
/** @return The registered {@link ValueSpec}s for the function. */
public Map<String, ValueSpec<?>> knownValues() {
return knownValues;
}
/** @return The supplier for instances of the function. */
public Supplier<? extends StatefulFunction> supplier() {
return supplier;
}
/** Builder for a {@link StatefulFunctionSpec}. */
public static final class Builder {
private final TypeName typeName;
private final Map<String, ValueSpec<?>> knownValues = new HashMap<>();
private Supplier<? extends StatefulFunction> supplier;
/**
* Creates a {@link Builder} for a {@link StatefulFunctionSpec} which is identifiable via the
* specified {@link TypeName}.
*
* @param typeName the associated {@link TypeName} of the {@link StatefulFunctionSpec} being
* built.
*/
private Builder(TypeName typeName) {
this.typeName = Objects.requireNonNull(typeName);
}
/**
* Registers a {@link ValueSpec} that will be used by this function. A function may only access
* values which have a registered {@link ValueSpec}.
*
* @param valueSpec the value spec to register.
* @throws IllegalArgumentException if multiple {@link ValueSpec}s with the same name was
* registered.
*/
public Builder withValueSpec(ValueSpec<?> valueSpec) {
Objects.requireNonNull(valueSpec);
if (knownValues.put(valueSpec.name(), valueSpec) != null) {
throw new IllegalArgumentException(
"Attempted to register more than one ValueSpec for the state name: "
+ valueSpec.name());
}
return this;
}
/**
* Registers multiple {@link ValueSpec}s that will be used by this function. A function may only
* access values which have a registered {@link ValueSpec}.
*
* @param valueSpecs the value specs to register.
* @throws IllegalArgumentException if multiple {@link ValueSpec}s with the same name was
* registered.
*/
public Builder withValueSpecs(ValueSpec<?>... valueSpecs) {
for (ValueSpec<?> spec : valueSpecs) {
withValueSpec(spec);
}
return this;
}
/**
* A {@link Supplier} used to create instances of a {@link StatefulFunction} for this {@link
* StatefulFunctionSpec}.
*
* @param supplier the supplier.
*/
public Builder withSupplier(Supplier<? extends StatefulFunction> supplier) {
this.supplier = Objects.requireNonNull(supplier);
return this;
}
/** Builds the {@link StatefulFunctionSpec}. */
public StatefulFunctionSpec build() {
return new StatefulFunctionSpec(typeName, knownValues, supplier);
}
}
}
| 5,834 |
0 | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java/Address.java | /*
* 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.sdk.java;
import java.util.Objects;
/**
* An {@link Address} is the unique identity of an individual {@link StatefulFunction}, containing
* of the function's {@link TypeName} 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.
*/
public final class Address {
private final TypeName type;
private final String id;
/**
* Creates an {@link Address}.
*
* @param type type of the function.
* @param id unique id within the function type.
*/
public Address(TypeName type, String id) {
this.type = Objects.requireNonNull(type);
this.id = Objects.requireNonNull(id);
}
/**
* Returns the {@link TypeName} that this address identifies.
*
* @return type of the function
*/
public TypeName type() {
return type;
}
/**
* Returns the unique function id, within its type, that this address identifies.
*
* @return unique id within the function type.
*/
public String id() {
return id;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Address address = (Address) o;
return type.equals(address.type) && id.equals(address.id);
}
@Override
public int hashCode() {
int hash = 0;
hash = 37 * hash + type.hashCode();
hash = 37 * hash + id.hashCode();
return hash;
}
@Override
public String toString() {
return String.format("Address(%s, %s, %s)", type.namespace(), type.name(), id);
}
}
| 5,835 |
0 | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java/handler/ConcurrentContext.java | /*
* 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.sdk.java.handler;
import static org.apache.flink.statefun.sdk.java.handler.ProtoUtils.getTypedValue;
import static org.apache.flink.statefun.sdk.java.handler.ProtoUtils.protoAddressFromSdk;
import java.time.Duration;
import java.util.Objects;
import java.util.Optional;
import org.apache.flink.statefun.sdk.java.Address;
import org.apache.flink.statefun.sdk.java.AddressScopedStorage;
import org.apache.flink.statefun.sdk.java.Context;
import org.apache.flink.statefun.sdk.java.TypeName;
import org.apache.flink.statefun.sdk.java.message.EgressMessage;
import org.apache.flink.statefun.sdk.java.message.Message;
import org.apache.flink.statefun.sdk.java.storage.ConcurrentAddressScopedStorage;
import org.apache.flink.statefun.sdk.reqreply.generated.FromFunction;
/**
* A thread safe implementation of a {@linkplain Context}.
*
* <p>This context's life cycle is tied to a single batch request. It is constructed when a
* {@linkplain org.apache.flink.statefun.sdk.reqreply.generated.ToFunction} message arrives, and it
* carries enough context to compute an {@linkplain
* org.apache.flink.statefun.sdk.reqreply.generated.FromFunction.InvocationResponse}. Access to the
* send/sendAfter/sendEgress methods are synchronized with a @responseBuilder's lock, to prevent
* concurrent modification. When the last invocation of the batch completes successfully, a {@link
* #finalBuilder()} will be called. After that point no further operations are allowed.
*/
final class ConcurrentContext implements Context {
private final org.apache.flink.statefun.sdk.java.Address self;
private final FromFunction.InvocationResponse.Builder responseBuilder;
private final ConcurrentAddressScopedStorage storage;
private boolean noFurtherModificationsAllowed;
private Address caller;
public ConcurrentContext(
org.apache.flink.statefun.sdk.java.Address self,
FromFunction.InvocationResponse.Builder responseBuilder,
ConcurrentAddressScopedStorage storage) {
this.self = Objects.requireNonNull(self);
this.responseBuilder = Objects.requireNonNull(responseBuilder);
this.storage = Objects.requireNonNull(storage);
}
@Override
public org.apache.flink.statefun.sdk.java.Address self() {
return self;
}
void setCaller(Address address) {
this.caller = address;
}
FromFunction.InvocationResponse.Builder finalBuilder() {
synchronized (responseBuilder) {
noFurtherModificationsAllowed = true;
return responseBuilder;
}
}
@Override
public Optional<Address> caller() {
return Optional.ofNullable(caller);
}
@Override
public void send(Message message) {
Objects.requireNonNull(message);
FromFunction.Invocation outInvocation =
FromFunction.Invocation.newBuilder()
.setArgument(getTypedValue(message))
.setTarget(protoAddressFromSdk(message.targetAddress()))
.build();
synchronized (responseBuilder) {
checkNotDone();
responseBuilder.addOutgoingMessages(outInvocation);
}
}
@Override
public void sendAfter(Duration duration, Message message) {
Objects.requireNonNull(duration);
Objects.requireNonNull(message);
FromFunction.DelayedInvocation outInvocation =
FromFunction.DelayedInvocation.newBuilder()
.setArgument(getTypedValue(message))
.setTarget(protoAddressFromSdk(message.targetAddress()))
.setDelayInMs(duration.toMillis())
.build();
synchronized (responseBuilder) {
checkNotDone();
responseBuilder.addDelayedInvocations(outInvocation);
}
}
@Override
public void sendAfter(Duration duration, String cancellationToken, Message message) {
Objects.requireNonNull(duration);
if (cancellationToken == null || cancellationToken.isEmpty()) {
throw new IllegalArgumentException("message cancellation token can not be empty or null.");
}
Objects.requireNonNull(message);
FromFunction.DelayedInvocation outInvocation =
FromFunction.DelayedInvocation.newBuilder()
.setArgument(getTypedValue(message))
.setTarget(protoAddressFromSdk(message.targetAddress()))
.setDelayInMs(duration.toMillis())
.setCancellationToken(cancellationToken)
.build();
synchronized (responseBuilder) {
checkNotDone();
responseBuilder.addDelayedInvocations(outInvocation);
}
}
@Override
public void cancelDelayedMessage(String cancellationToken) {
if (cancellationToken == null || cancellationToken.isEmpty()) {
throw new IllegalArgumentException("message cancellation token can not be empty or null.");
}
FromFunction.DelayedInvocation cancellation =
FromFunction.DelayedInvocation.newBuilder()
.setIsCancellationRequest(true)
.setCancellationToken(cancellationToken)
.build();
synchronized (responseBuilder) {
checkNotDone();
responseBuilder.addDelayedInvocations(cancellation);
}
}
@Override
public void send(EgressMessage message) {
Objects.requireNonNull(message);
TypeName target = message.targetEgressId();
FromFunction.EgressMessage outInvocation =
FromFunction.EgressMessage.newBuilder()
.setArgument(getTypedValue(message))
.setEgressNamespace(target.namespace())
.setEgressType(target.name())
.build();
synchronized (responseBuilder) {
checkNotDone();
responseBuilder.addOutgoingEgresses(outInvocation);
}
}
@Override
public AddressScopedStorage storage() {
return storage;
}
private void checkNotDone() {
if (noFurtherModificationsAllowed) {
throw new IllegalStateException("Function has already completed its execution.");
}
}
}
| 5,836 |
0 | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java/handler/RequestReplyHandler.java | /*
* 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.sdk.java.handler;
import java.util.concurrent.CompletableFuture;
import org.apache.flink.statefun.sdk.java.slice.Slice;
public interface RequestReplyHandler {
/**
* Handles a {@code Stateful Functions} invocation.
*
* @param input a {@linkplain Slice} as received from the {@code StateFun} server.
* @return a serialized representation of the side-effects to preform by the {@code StateFun}
* server, as the result of this invocation.
*/
CompletableFuture<Slice> handle(Slice input);
}
| 5,837 |
0 | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java/handler/ConcurrentRequestReplyHandler.java | /*
* 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.sdk.java.handler;
import static org.apache.flink.statefun.sdk.java.handler.MoreFutures.applySequentially;
import static org.apache.flink.statefun.sdk.java.handler.ProtoUtils.sdkAddressFromProto;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier;
import org.apache.flink.statefun.sdk.java.Address;
import org.apache.flink.statefun.sdk.java.StatefulFunction;
import org.apache.flink.statefun.sdk.java.StatefulFunctionSpec;
import org.apache.flink.statefun.sdk.java.TypeName;
import org.apache.flink.statefun.sdk.java.ValueSpec;
import org.apache.flink.statefun.sdk.java.annotations.Internal;
import org.apache.flink.statefun.sdk.java.message.MessageWrapper;
import org.apache.flink.statefun.sdk.java.slice.Slice;
import org.apache.flink.statefun.sdk.java.slice.SliceProtobufUtil;
import org.apache.flink.statefun.sdk.java.storage.ConcurrentAddressScopedStorage;
import org.apache.flink.statefun.sdk.java.storage.StateValueContexts;
import org.apache.flink.statefun.sdk.reqreply.generated.FromFunction;
import org.apache.flink.statefun.sdk.reqreply.generated.ToFunction;
import org.apache.flink.statefun.sdk.reqreply.generated.TypedValue;
import org.apache.flink.statefun.sdk.shaded.com.google.protobuf.ByteString;
/**
* A threadsafe {@linkplain RequestReplyHandler}. This handler lifecycle is bound to the entire
* program, and can be safely and concurrently used to handle {@linkplain ToFunction} requests.
*/
@Internal
public final class ConcurrentRequestReplyHandler implements RequestReplyHandler {
private final Map<TypeName, StatefulFunctionSpec> functionSpecs;
public ConcurrentRequestReplyHandler(Map<TypeName, StatefulFunctionSpec> functionSpecs) {
this.functionSpecs = Objects.requireNonNull(functionSpecs);
}
@Override
public CompletableFuture<Slice> handle(Slice requestBytes) {
try {
ByteString in = SliceProtobufUtil.asByteString(requestBytes);
ToFunction request = ToFunction.parseFrom(in);
CompletableFuture<FromFunction> response = handleInternally(request);
return response.thenApply(
res -> {
ByteString out = res.toByteString();
return SliceProtobufUtil.asSlice(out);
});
} catch (Throwable throwable) {
return MoreFutures.exceptional(throwable);
}
}
CompletableFuture<FromFunction> handleInternally(ToFunction request) {
if (!request.hasInvocation()) {
return CompletableFuture.completedFuture(FromFunction.getDefaultInstance());
}
ToFunction.InvocationBatchRequest batchRequest = request.getInvocation();
Address self = sdkAddressFromProto(batchRequest.getTarget());
StatefulFunctionSpec targetSpec = functionSpecs.get(self.type());
if (targetSpec == null) {
throw new IllegalStateException("Unknown target type " + self);
}
Supplier<? extends StatefulFunction> supplier = targetSpec.supplier();
if (supplier == null) {
throw new NullPointerException("missing function supplier for " + self);
}
StatefulFunction function = supplier.get();
if (function == null) {
throw new NullPointerException("supplier for " + self + " supplied NULL function.");
}
StateValueContexts.ResolutionResult stateResolution =
StateValueContexts.resolve(targetSpec.knownValues(), batchRequest.getStateList());
if (stateResolution.hasMissingValues()) {
// not enough information to compute this batch.
FromFunction res = buildIncompleteInvocationResponse(stateResolution.missingValues());
return CompletableFuture.completedFuture(res);
}
final ConcurrentAddressScopedStorage storage =
new ConcurrentAddressScopedStorage(stateResolution.resolved());
return executeBatch(batchRequest, self, storage, function);
}
private CompletableFuture<FromFunction> executeBatch(
ToFunction.InvocationBatchRequest inputBatch,
Address self,
ConcurrentAddressScopedStorage storage,
StatefulFunction function) {
FromFunction.InvocationResponse.Builder responseBuilder =
FromFunction.InvocationResponse.newBuilder();
ConcurrentContext context = new ConcurrentContext(self, responseBuilder, storage);
CompletableFuture<Void> allDone =
applySequentially(
inputBatch.getInvocationsList(), invocation -> apply(function, context, invocation));
return allDone.thenApply(unused -> finalizeResponse(storage, context.finalBuilder()));
}
private static FromFunction buildIncompleteInvocationResponse(List<ValueSpec<?>> missing) {
FromFunction.IncompleteInvocationContext.Builder result =
FromFunction.IncompleteInvocationContext.newBuilder();
for (ValueSpec<?> v : missing) {
result.addMissingValues(ProtoUtils.protoFromValueSpec(v));
}
return FromFunction.newBuilder().setIncompleteInvocationContext(result).build();
}
private static CompletableFuture<Void> apply(
StatefulFunction function, ConcurrentContext context, ToFunction.Invocation invocation)
throws Throwable {
TypedValue argument = invocation.getArgument();
MessageWrapper wrapper = new MessageWrapper(context.self(), argument);
context.setCaller(sdkAddressFromProto(invocation.getCaller()));
CompletableFuture<Void> future = function.apply(context, wrapper);
if (future == null) {
throw new IllegalStateException(
"User function " + context.self() + " has returned a NULL future.");
}
return future;
}
private static FromFunction finalizeResponse(
ConcurrentAddressScopedStorage storage, FromFunction.InvocationResponse.Builder builder) {
storage.addMutations(builder::addStateMutations);
return FromFunction.newBuilder().setInvocationResult(builder).build();
}
}
| 5,838 |
0 | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java/handler/ProtoUtils.java | /*
* 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.sdk.java.handler;
import static org.apache.flink.statefun.sdk.reqreply.generated.FromFunction.ExpirationSpec.ExpireMode;
import static org.apache.flink.statefun.sdk.reqreply.generated.FromFunction.ExpirationSpec.newBuilder;
import org.apache.flink.statefun.sdk.java.ApiExtension;
import org.apache.flink.statefun.sdk.java.Expiration;
import org.apache.flink.statefun.sdk.java.TypeName;
import org.apache.flink.statefun.sdk.java.ValueSpec;
import org.apache.flink.statefun.sdk.java.message.EgressMessage;
import org.apache.flink.statefun.sdk.java.message.EgressMessageWrapper;
import org.apache.flink.statefun.sdk.java.message.Message;
import org.apache.flink.statefun.sdk.java.message.MessageWrapper;
import org.apache.flink.statefun.sdk.java.slice.SliceProtobufUtil;
import org.apache.flink.statefun.sdk.reqreply.generated.Address;
import org.apache.flink.statefun.sdk.reqreply.generated.FromFunction.PersistedValueSpec;
import org.apache.flink.statefun.sdk.reqreply.generated.TypedValue;
final class ProtoUtils {
private ProtoUtils() {}
static Address protoAddressFromSdk(org.apache.flink.statefun.sdk.java.Address address) {
return Address.newBuilder()
.setNamespace(address.type().namespace())
.setType(address.type().name())
.setId(address.id())
.build();
}
static org.apache.flink.statefun.sdk.java.Address sdkAddressFromProto(Address address) {
if (address == null
|| (address.getNamespace().isEmpty()
&& address.getType().isEmpty()
&& address.getId().isEmpty())) {
return null;
}
return new org.apache.flink.statefun.sdk.java.Address(
TypeName.typeNameOf(address.getNamespace(), address.getType()), address.getId());
}
static PersistedValueSpec.Builder protoFromValueSpec(ValueSpec<?> valueSpec) {
PersistedValueSpec.Builder specBuilder =
PersistedValueSpec.newBuilder()
.setStateNameBytes(ApiExtension.stateNameByteString(valueSpec))
.setTypeTypenameBytes(ApiExtension.typeNameByteString(valueSpec.typeName()));
if (valueSpec.expiration().mode() == Expiration.Mode.NONE) {
return specBuilder;
}
ExpireMode mode =
valueSpec.expiration().mode() == Expiration.Mode.AFTER_CALL
? ExpireMode.AFTER_INVOKE
: ExpireMode.AFTER_WRITE;
long value = valueSpec.expiration().duration().toMillis();
specBuilder.setExpirationSpec(newBuilder().setExpireAfterMillis(value).setMode(mode));
return specBuilder;
}
static TypedValue getTypedValue(Message message) {
if (message instanceof MessageWrapper) {
return ((MessageWrapper) message).typedValue();
}
return TypedValue.newBuilder()
.setTypenameBytes(ApiExtension.typeNameByteString(message.valueTypeName()))
.setValue(SliceProtobufUtil.asByteString(message.rawValue()))
.setHasValue(true)
.build();
}
static TypedValue getTypedValue(EgressMessage message) {
if (message instanceof EgressMessageWrapper) {
return ((EgressMessageWrapper) message).typedValue();
}
return TypedValue.newBuilder()
.setTypenameBytes(ApiExtension.typeNameByteString(message.egressMessageValueType()))
.setValue(SliceProtobufUtil.asByteString(message.egressMessageValueBytes()))
.setHasValue(true)
.build();
}
}
| 5,839 |
0 | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java/handler/MoreFutures.java | /*
* 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.sdk.java.handler;
import java.util.Iterator;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
final class MoreFutures {
@FunctionalInterface
public interface Fn<I, O> {
O apply(I input) throws Throwable;
}
/**
* Apply @fn for each element of @elements sequentially. Subsequent element is handed to fn only
* after the previous future has completed.
*/
public static <T> CompletableFuture<Void> applySequentially(
Iterable<T> elements, Fn<T, CompletableFuture<Void>> fn) {
Objects.requireNonNull(elements);
Objects.requireNonNull(fn);
return applySequentially(elements.iterator(), fn);
}
private static <T> CompletableFuture<Void> applySequentially(
Iterator<T> iterator, Fn<T, CompletableFuture<Void>> fn) {
try {
while (iterator.hasNext()) {
T next = iterator.next();
CompletableFuture<Void> future = fn.apply(next);
if (!future.isDone()) {
return future.thenCompose(ignored -> applySequentially(iterator, fn));
}
if (future.isCompletedExceptionally()) {
return future;
}
}
return CompletableFuture.completedFuture(null);
} catch (Throwable t) {
return exceptional(t);
}
}
static <T> CompletableFuture<T> exceptional(Throwable cause) {
CompletableFuture<T> e = new CompletableFuture<>();
e.completeExceptionally(cause);
return e;
}
}
| 5,840 |
0 | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java/types/SliceType.java | /*
* 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.sdk.java.types;
import java.util.Collections;
import java.util.EnumSet;
import java.util.Objects;
import java.util.Set;
import org.apache.flink.statefun.sdk.java.TypeName;
import org.apache.flink.statefun.sdk.java.slice.Slice;
public final class SliceType implements Type<Slice> {
private static final Set<TypeCharacteristics> IMMUTABLE_TYPE_CHARS =
Collections.unmodifiableSet(EnumSet.of(TypeCharacteristics.IMMUTABLE_VALUES));
private final TypeName typename;
private final Serializer serializer = new Serializer();
public SliceType(TypeName typename) {
this.typename = Objects.requireNonNull(typename);
}
@Override
public TypeName typeName() {
return typename;
}
@Override
public TypeSerializer<Slice> typeSerializer() {
return serializer;
}
@Override
public Set<TypeCharacteristics> typeCharacteristics() {
return IMMUTABLE_TYPE_CHARS;
}
private static final class Serializer implements TypeSerializer<Slice> {
@Override
public Slice serialize(Slice slice) {
return slice;
}
@Override
public Slice deserialize(Slice slice) {
return slice;
}
}
}
| 5,841 |
0 | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java/types/Type.java | /*
* 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.sdk.java.types;
import java.util.Collections;
import java.util.Set;
import org.apache.flink.statefun.sdk.java.TypeName;
import org.apache.flink.statefun.sdk.java.ValueSpec;
import org.apache.flink.statefun.sdk.shaded.com.google.protobuf.Message;
/**
* This class is the core abstraction used by Stateful Functions's type system, and consists of a
* few things that StateFun uses to handle {@link Message}s and {@link ValueSpec}s:
*
* <ul>
* <li>A {@link TypeName} to identify the type.
* <li>A {@link TypeSerializer} for serializing and deserializing instances of the type.
* </ul>
*
* <h2>Cross-language primitive types</h2>
*
* <p>StateFun's type system has cross-language support for common primitive types, such as boolean,
* integer, long, etc. These primitive types have built-in {@link Type}s implemented for them
* already, with predefined {@link TypeName}s.
*
* <p>This is of course all transparent for the user, so you don't need to worry about it. Functions
* implemented in various languages (e.g. Java or Python) can message each other by directly sending
* supported primitive values as message arguments. Moreover, the type system is used for state
* values as well; so, you can expect that a function can safely read previous state after
* reimplementing it in a different language.
*
* <h2>Common custom types (e.g. JSON or Protobuf)</h2>
*
* <p>The type system is also very easily extensible to support custom message types, such as JSON
* or Protobuf messages. This is just a matter of implementing your own {@link Type} with a custom
* typename and serializer. Alternatively, you can also use the {@link SimpleType} class to do this
* easily.
*
* @param <T> the Java type of serialized / deserialized instances.
*/
public interface Type<T> {
/** @return The unique {@link TypeName} of this type. */
TypeName typeName();
/** @return A {@link TypeSerializer} that can serialize and deserialize this type. */
TypeSerializer<T> typeSerializer();
default Set<TypeCharacteristics> typeCharacteristics() {
return Collections.emptySet();
}
}
| 5,842 |
0 | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java/types/TypeSerializer.java | /*
* 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.sdk.java.types;
import org.apache.flink.statefun.sdk.java.slice.Slice;
public interface TypeSerializer<T> {
Slice serialize(T value);
T deserialize(Slice bytes);
}
| 5,843 |
0 | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java/types/TypeCharacteristics.java | /*
* 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.sdk.java.types;
public enum TypeCharacteristics {
IMMUTABLE_VALUES
}
| 5,844 |
0 | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java/types/Types.java | /*
* 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.sdk.java.types;
import static org.apache.flink.statefun.sdk.java.slice.SliceProtobufUtil.parseFrom;
import static org.apache.flink.statefun.sdk.java.slice.SliceProtobufUtil.toSlice;
import java.util.Collections;
import java.util.EnumSet;
import java.util.Set;
import org.apache.flink.statefun.sdk.java.TypeName;
import org.apache.flink.statefun.sdk.java.slice.Slice;
import org.apache.flink.statefun.sdk.java.slice.SliceProtobufUtil;
import org.apache.flink.statefun.sdk.java.slice.Slices;
import org.apache.flink.statefun.sdk.shaded.com.google.protobuf.ByteString;
import org.apache.flink.statefun.sdk.shaded.com.google.protobuf.InvalidProtocolBufferException;
import org.apache.flink.statefun.sdk.shaded.com.google.protobuf.MoreByteStrings;
import org.apache.flink.statefun.sdk.shaded.com.google.protobuf.WireFormat;
import org.apache.flink.statefun.sdk.types.generated.BooleanWrapper;
import org.apache.flink.statefun.sdk.types.generated.DoubleWrapper;
import org.apache.flink.statefun.sdk.types.generated.FloatWrapper;
import org.apache.flink.statefun.sdk.types.generated.IntWrapper;
import org.apache.flink.statefun.sdk.types.generated.LongWrapper;
import org.apache.flink.statefun.sdk.types.generated.StringWrapper;
public final class Types {
private Types() {}
// primitives
public static final TypeName BOOLEAN_TYPENAME =
TypeName.typeNameFromString("io.statefun.types/bool");
public static final TypeName INTEGER_TYPENAME =
TypeName.typeNameFromString("io.statefun.types/int");
public static final TypeName FLOAT_TYPENAME =
TypeName.typeNameFromString("io.statefun.types/float");
public static final TypeName LONG_TYPENAME =
TypeName.typeNameFromString("io.statefun.types/long");
public static final TypeName DOUBLE_TYPENAME =
TypeName.typeNameFromString("io.statefun.types/double");
public static final TypeName STRING_TYPENAME =
TypeName.typeNameFromString("io.statefun.types/string");
// common characteristics
private static final Set<TypeCharacteristics> IMMUTABLE_TYPE_CHARS =
Collections.unmodifiableSet(EnumSet.of(TypeCharacteristics.IMMUTABLE_VALUES));
public static Type<Long> longType() {
return LongType.INSTANCE;
}
public static Type<String> stringType() {
return StringType.INSTANCE;
}
public static Type<Integer> integerType() {
return IntegerType.INSTANCE;
}
public static Type<Boolean> booleanType() {
return BooleanType.INSTANCE;
}
public static Type<Float> floatType() {
return FloatType.INSTANCE;
}
public static Type<Double> doubleType() {
return DoubleType.INSTANCE;
}
/**
* Compute the Protobuf field tag, as specified by the Protobuf wire format. See {@code
* WireFormat#makeTag(int, int)}}. NOTE: that, currently, for all StateFun provided wire types the
* tags should be 1 byte.
*
* @param fieldNumber the field number as specified in the message definition.
* @param wireType the field type as specified in the message definition.
* @return the field tag as a single byte.
*/
private static byte protobufTagAsSingleByte(int fieldNumber, int wireType) {
int fieldTag = fieldNumber << 3 | wireType;
if (fieldTag < -127 || fieldTag > 127) {
throw new IllegalStateException(
"Protobuf Wrapper type compatibility is bigger than one byte.");
}
return (byte) fieldTag;
}
private static final Slice EMPTY_SLICE = Slices.wrap(new byte[] {});
private static final class LongType implements Type<Long> {
static final Type<Long> INSTANCE = new LongType();
private final TypeSerializer<Long> serializer = new LongTypeSerializer();
@Override
public TypeName typeName() {
return LONG_TYPENAME;
}
@Override
public TypeSerializer<Long> typeSerializer() {
return serializer;
}
public Set<TypeCharacteristics> typeCharacteristics() {
return IMMUTABLE_TYPE_CHARS;
}
}
private static final class LongTypeSerializer implements TypeSerializer<Long> {
@Override
public Slice serialize(Long element) {
return serializeLongWrapperCompatibleLong(element);
}
@Override
public Long deserialize(Slice input) {
return deserializeLongWrapperCompatibleLong(input);
}
private static final byte WRAPPER_TYPE_FIELD_TAG =
protobufTagAsSingleByte(LongWrapper.VALUE_FIELD_NUMBER, WireFormat.WIRETYPE_FIXED64);
private static Slice serializeLongWrapperCompatibleLong(long n) {
if (n == 0) {
return EMPTY_SLICE;
}
byte[] out = new byte[9];
out[0] = WRAPPER_TYPE_FIELD_TAG;
out[1] = (byte) (n & 0xFF);
out[2] = (byte) ((n >> 8) & 0xFF);
out[3] = (byte) ((n >> 16) & 0xFF);
out[4] = (byte) ((n >> 24) & 0xFF);
out[5] = (byte) ((n >> 32) & 0xFF);
out[6] = (byte) ((n >> 40) & 0xFF);
out[7] = (byte) ((n >> 48) & 0xFF);
out[8] = (byte) ((n >> 56) & 0xFF);
return Slices.wrap(out);
}
private static long deserializeLongWrapperCompatibleLong(Slice slice) {
if (slice.readableBytes() == 0) {
return 0;
}
if (slice.byteAt(0) != WRAPPER_TYPE_FIELD_TAG) {
throw new IllegalStateException("Not a LongWrapper");
}
return slice.byteAt(1) & 0xFFL
| (slice.byteAt(2) & 0xFFL) << 8
| (slice.byteAt(3) & 0xFFL) << 16
| (slice.byteAt(4) & 0xFFL) << 24
| (slice.byteAt(5) & 0xFFL) << 32
| (slice.byteAt(6) & 0xFFL) << 40
| (slice.byteAt(7) & 0xFFL) << 48
| (slice.byteAt(8) & 0xFFL) << 56;
}
}
private static final class StringType implements Type<String> {
static final Type<String> INSTANCE = new StringType();
private final TypeSerializer<String> serializer = new StringTypeSerializer();
@Override
public TypeName typeName() {
return STRING_TYPENAME;
}
@Override
public TypeSerializer<String> typeSerializer() {
return serializer;
}
public Set<TypeCharacteristics> typeCharacteristics() {
return IMMUTABLE_TYPE_CHARS;
}
}
private static final class StringTypeSerializer implements TypeSerializer<String> {
private static final byte STRING_WRAPPER_FIELD_TYPE =
protobufTagAsSingleByte(
StringWrapper.VALUE_FIELD_NUMBER, WireFormat.WIRETYPE_LENGTH_DELIMITED);
@Override
public Slice serialize(String element) {
return serializeStringWrapperCompatibleString(element);
}
@Override
public String deserialize(Slice input) {
return deserializeStringWrapperCompatibleString(input);
}
private static Slice serializeStringWrapperCompatibleString(String element) {
if (element.isEmpty()) {
return EMPTY_SLICE;
}
ByteString utf8 = ByteString.copyFromUtf8(element);
byte[] header = new byte[1 + 5 + utf8.size()];
int position = 0;
// write the field tag
header[position++] = STRING_WRAPPER_FIELD_TYPE;
// write utf8 bytes.length as a VarInt.
int varIntLen = utf8.size();
while ((varIntLen & -128) != 0) {
header[position++] = ((byte) (varIntLen & 127 | 128));
varIntLen >>>= 7;
}
header[position++] = ((byte) varIntLen);
// concat header and the utf8 string bytes
ByteString headerBuf = MoreByteStrings.wrap(header, 0, position);
ByteString result = MoreByteStrings.concat(headerBuf, utf8);
return SliceProtobufUtil.asSlice(result);
}
private static String deserializeStringWrapperCompatibleString(Slice input) {
if (input.readableBytes() == 0) {
return "";
}
ByteString buf = SliceProtobufUtil.asByteString(input);
int position = 0;
// read field tag
if (buf.byteAt(position++) != STRING_WRAPPER_FIELD_TYPE) {
throw new IllegalStateException("Not a StringWrapper");
}
// read VarInt32 length
int shift = 0;
long varIntSize = 0;
while (shift < 32) {
final byte b = buf.byteAt(position++);
varIntSize |= (long) (b & 0x7F) << shift;
if ((b & 0x80) == 0) {
break;
}
shift += 7;
}
// sanity checks
if (varIntSize < 0 || varIntSize > Integer.MAX_VALUE) {
throw new IllegalStateException("Malformed VarInt");
}
final int endIndex = position + (int) varIntSize;
ByteString utf8Bytes = buf.substring(position, endIndex);
return utf8Bytes.toStringUtf8();
}
}
private static final class IntegerType implements Type<Integer> {
static final Type<Integer> INSTANCE = new IntegerType();
private final TypeSerializer<Integer> serializer = new IntegerTypeSerializer();
@Override
public TypeName typeName() {
return INTEGER_TYPENAME;
}
@Override
public TypeSerializer<Integer> typeSerializer() {
return serializer;
}
public Set<TypeCharacteristics> typeCharacteristics() {
return IMMUTABLE_TYPE_CHARS;
}
}
private static final class IntegerTypeSerializer implements TypeSerializer<Integer> {
private static final byte WRAPPER_TYPE_FIELD_TYPE =
protobufTagAsSingleByte(IntWrapper.VALUE_FIELD_NUMBER, WireFormat.WIRETYPE_FIXED32);
@Override
public Slice serialize(Integer element) {
return serializeIntegerWrapperCompatibleInt(element);
}
@Override
public Integer deserialize(Slice input) {
return deserializeIntegerWrapperCompatibleInt(input);
}
private static Slice serializeIntegerWrapperCompatibleInt(int n) {
if (n == 0) {
return EMPTY_SLICE;
}
byte[] out = new byte[5];
out[0] = WRAPPER_TYPE_FIELD_TYPE;
out[1] = (byte) (n & 0xFF);
out[2] = (byte) ((n >> 8) & 0xFF);
out[3] = (byte) ((n >> 16) & 0xFF);
out[4] = (byte) ((n >> 24) & 0xFF);
return Slices.wrap(out);
}
private static int deserializeIntegerWrapperCompatibleInt(Slice slice) {
if (slice.readableBytes() == 0) {
return 0;
}
if (slice.byteAt(0) != WRAPPER_TYPE_FIELD_TYPE) {
throw new IllegalStateException("Not an IntWrapper");
}
return slice.byteAt(1) & 0xFF
| (slice.byteAt(2) & 0xFF) << 8
| (slice.byteAt(3) & 0xFF) << 16
| (slice.byteAt(4) & 0xFF) << 24;
}
}
private static final class BooleanType implements Type<Boolean> {
static final Type<Boolean> INSTANCE = new BooleanType();
private final TypeSerializer<Boolean> serializer = new BooleanTypeSerializer();
@Override
public TypeName typeName() {
return BOOLEAN_TYPENAME;
}
@Override
public TypeSerializer<Boolean> typeSerializer() {
return serializer;
}
public Set<TypeCharacteristics> typeCharacteristics() {
return IMMUTABLE_TYPE_CHARS;
}
}
private static final class BooleanTypeSerializer implements TypeSerializer<Boolean> {
private static final Slice TRUE_SLICE =
toSlice(BooleanWrapper.newBuilder().setValue(true).build());
private static final Slice FALSE_SLICE =
toSlice(BooleanWrapper.newBuilder().setValue(false).build());
private static final byte WRAPPER_TYPE_TAG =
protobufTagAsSingleByte(BooleanWrapper.VALUE_FIELD_NUMBER, WireFormat.WIRETYPE_VARINT);
@Override
public Slice serialize(Boolean element) {
return element ? TRUE_SLICE : FALSE_SLICE;
}
@Override
public Boolean deserialize(Slice input) {
if (input.readableBytes() == 0) {
return false;
}
final byte tag = input.byteAt(0);
final byte value = input.byteAt(1);
if (tag != WRAPPER_TYPE_TAG || value != (byte) 1) {
throw new IllegalStateException("Not a BooleanWrapper value.");
}
return true;
}
}
private static final class FloatType implements Type<Float> {
static final Type<Float> INSTANCE = new FloatType();
private final TypeSerializer<Float> serializer = new FloatTypeSerializer();
@Override
public TypeName typeName() {
return FLOAT_TYPENAME;
}
@Override
public TypeSerializer<Float> typeSerializer() {
return serializer;
}
public Set<TypeCharacteristics> typeCharacteristics() {
return IMMUTABLE_TYPE_CHARS;
}
}
private static final class FloatTypeSerializer implements TypeSerializer<Float> {
@Override
public Slice serialize(Float element) {
FloatWrapper wrapper = FloatWrapper.newBuilder().setValue(element).build();
return toSlice(wrapper);
}
@Override
public Float deserialize(Slice input) {
try {
FloatWrapper wrapper = parseFrom(FloatWrapper.parser(), input);
return wrapper.getValue();
} catch (InvalidProtocolBufferException e) {
throw new IllegalArgumentException(e);
}
}
}
private static final class DoubleType implements Type<Double> {
static final Type<Double> INSTANCE = new DoubleType();
private final TypeSerializer<Double> serializer = new DoubleTypeSerializer();
@Override
public TypeName typeName() {
return DOUBLE_TYPENAME;
}
@Override
public TypeSerializer<Double> typeSerializer() {
return serializer;
}
public Set<TypeCharacteristics> typeCharacteristics() {
return IMMUTABLE_TYPE_CHARS;
}
}
private static final class DoubleTypeSerializer implements TypeSerializer<Double> {
@Override
public Slice serialize(Double element) {
DoubleWrapper wrapper = DoubleWrapper.newBuilder().setValue(element).build();
return toSlice(wrapper);
}
@Override
public Double deserialize(Slice input) {
try {
DoubleWrapper wrapper = parseFrom(DoubleWrapper.parser(), input);
return wrapper.getValue();
} catch (InvalidProtocolBufferException e) {
throw new IllegalArgumentException(e);
}
}
}
}
| 5,845 |
0 | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java/types/SimpleType.java | /*
* 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.sdk.java.types;
import java.util.Collections;
import java.util.EnumSet;
import java.util.Objects;
import java.util.Set;
import org.apache.flink.statefun.sdk.java.TypeName;
import org.apache.flink.statefun.sdk.java.slice.Slice;
import org.apache.flink.statefun.sdk.java.slice.Slices;
/**
* A utility to create simple {@link Type} implementations.
*
* @param <T> the Java type handled by this {@link Type}.
*/
public final class SimpleType<T> implements Type<T> {
@FunctionalInterface
public interface Fn<I, O> {
O apply(I input) throws Throwable;
}
public static <T> Type<T> simpleTypeFrom(
TypeName typeName, Fn<T, byte[]> serialize, Fn<byte[], T> deserialize) {
return new SimpleType<>(typeName, serialize, deserialize, Collections.emptySet());
}
public static <T> Type<T> simpleImmutableTypeFrom(
TypeName typeName, Fn<T, byte[]> serialize, Fn<byte[], T> deserialize) {
return new SimpleType<>(
typeName, serialize, deserialize, EnumSet.of(TypeCharacteristics.IMMUTABLE_VALUES));
}
private final TypeName typeName;
private final TypeSerializer<T> serializer;
private final Set<TypeCharacteristics> typeCharacteristics;
private SimpleType(
TypeName typeName,
Fn<T, byte[]> serialize,
Fn<byte[], T> deserialize,
Set<TypeCharacteristics> typeCharacteristics) {
this.typeName = Objects.requireNonNull(typeName);
this.serializer = new Serializer<>(serialize, deserialize);
this.typeCharacteristics = Collections.unmodifiableSet(typeCharacteristics);
}
@Override
public TypeName typeName() {
return typeName;
}
@Override
public TypeSerializer<T> typeSerializer() {
return serializer;
}
@Override
public Set<TypeCharacteristics> typeCharacteristics() {
return typeCharacteristics;
}
private static final class Serializer<T> implements TypeSerializer<T> {
private final Fn<T, byte[]> serialize;
private final Fn<byte[], T> deserialize;
private Serializer(Fn<T, byte[]> serialize, Fn<byte[], T> deserialize) {
this.serialize = Objects.requireNonNull(serialize);
this.deserialize = Objects.requireNonNull(deserialize);
}
@Override
public Slice serialize(T value) {
try {
byte[] bytes = serialize.apply(value);
return Slices.wrap(bytes);
} catch (Throwable throwable) {
throw new IllegalStateException(throwable);
}
}
@Override
public T deserialize(Slice input) {
try {
byte[] bytes = input.toByteArray();
return deserialize.apply(bytes);
} catch (Throwable throwable) {
throw new IllegalStateException(throwable);
}
}
}
}
| 5,846 |
0 | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java/slice/SliceOutput.java | /*
* 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.sdk.java.slice;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Objects;
public final class SliceOutput {
private byte[] buf;
private int position;
public static SliceOutput sliceOutput(int initialSize) {
return new SliceOutput(initialSize);
}
private SliceOutput(int initialSize) {
if (initialSize < 0) {
throw new IllegalArgumentException("initial size has to be non negative");
}
this.buf = new byte[initialSize];
this.position = 0;
}
public void write(byte b) {
ensureCapacity(1);
buf[position] = b;
position++;
}
public void write(byte[] buffer) {
write(buffer, 0, buffer.length);
}
public void write(byte[] buffer, int offset, int len) {
Objects.requireNonNull(buffer);
if (offset < 0 || offset > buffer.length) {
throw new IllegalArgumentException("Offset out of range " + offset);
}
if (len < 0) {
throw new IllegalArgumentException("Negative length " + len);
}
ensureCapacity(len);
System.arraycopy(buffer, offset, buf, position, len);
position += len;
}
public void write(ByteBuffer buffer) {
int n = buffer.remaining();
ensureCapacity(n);
buffer.get(buf, position, n);
position += n;
}
public void write(Slice slice) {
write(slice.asReadOnlyByteBuffer());
}
public void writeFully(InputStream input) {
try {
int bytesRead;
do {
ensureCapacity(256);
bytesRead = input.read(buf, position, remaining());
position += bytesRead;
} while (bytesRead != -1);
position++; // compensate for the latest -1 addition.
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
public Slice copyOf() {
return Slices.copyOf(buf, 0, position);
}
public Slice view() {
return Slices.wrap(buf, 0, position);
}
private int remaining() {
return buf.length - position;
}
private void ensureCapacity(final int bytesNeeded) {
final int requiredNewLength = position + bytesNeeded;
if (requiredNewLength >= buf.length) {
this.buf = Arrays.copyOf(buf, 2 * requiredNewLength);
}
}
}
| 5,847 |
0 | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java/slice/Slices.java | /*
* 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.sdk.java.slice;
import java.io.InputStream;
import java.nio.ByteBuffer;
import org.apache.flink.statefun.sdk.shaded.com.google.protobuf.ByteString;
import org.apache.flink.statefun.sdk.shaded.com.google.protobuf.MoreByteStrings;
public final class Slices {
private Slices() {}
public static Slice wrap(ByteBuffer buffer) {
return wrap(MoreByteStrings.wrap(buffer));
}
public static Slice wrap(byte[] bytes) {
return wrap(MoreByteStrings.wrap(bytes));
}
private static Slice wrap(ByteString bytes) {
return new ByteStringSlice(bytes);
}
public static Slice wrap(byte[] bytes, int offset, int len) {
return wrap(MoreByteStrings.wrap(bytes, offset, len));
}
public static Slice copyOf(byte[] bytes) {
return wrap(ByteString.copyFrom(bytes));
}
public static Slice copyOf(byte[] bytes, int offset, int len) {
return wrap(ByteString.copyFrom(bytes, offset, len));
}
public static Slice copyOf(InputStream inputStream, int expectedStreamSize) {
SliceOutput out = SliceOutput.sliceOutput(expectedStreamSize);
out.writeFully(inputStream);
return out.view();
}
public static Slice copyFromUtf8(String input) {
return wrap(ByteString.copyFromUtf8(input));
}
}
| 5,848 |
0 | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java/slice/ByteStringSlice.java | /*
* 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.sdk.java.slice;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.Objects;
import org.apache.flink.statefun.sdk.shaded.com.google.protobuf.ByteString;
final class ByteStringSlice implements Slice {
private final ByteString byteString;
public ByteStringSlice(ByteString bytes) {
this.byteString = Objects.requireNonNull(bytes);
}
public ByteString byteString() {
return byteString;
}
@Override
public ByteBuffer asReadOnlyByteBuffer() {
return byteString.asReadOnlyByteBuffer();
}
@Override
public int readableBytes() {
return byteString.size();
}
@Override
public void copyTo(byte[] target) {
copyTo(target, 0);
}
@Override
public void copyTo(byte[] target, int targetOffset) {
byteString.copyTo(target, targetOffset);
}
@Override
public void copyTo(OutputStream outputStream) {
try {
byteString.writeTo(outputStream);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override
public byte byteAt(int position) {
return byteString.byteAt(position);
}
@Override
public void copyTo(ByteBuffer buffer) {
byteString.copyTo(buffer);
}
@Override
public byte[] toByteArray() {
return byteString.toByteArray();
}
}
| 5,849 |
0 | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java/slice/Slice.java | /*
* 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.sdk.java.slice;
import java.io.OutputStream;
import java.nio.ByteBuffer;
public interface Slice {
int readableBytes();
void copyTo(ByteBuffer target);
void copyTo(byte[] target);
void copyTo(byte[] target, int targetOffset);
void copyTo(OutputStream outputStream);
byte byteAt(int position);
ByteBuffer asReadOnlyByteBuffer();
byte[] toByteArray();
}
| 5,850 |
0 | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java/slice/SliceProtobufUtil.java | /*
* 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.sdk.java.slice;
import org.apache.flink.statefun.sdk.java.annotations.Internal;
import org.apache.flink.statefun.sdk.shaded.com.google.protobuf.ByteString;
import org.apache.flink.statefun.sdk.shaded.com.google.protobuf.InvalidProtocolBufferException;
import org.apache.flink.statefun.sdk.shaded.com.google.protobuf.Message;
import org.apache.flink.statefun.sdk.shaded.com.google.protobuf.MoreByteStrings;
import org.apache.flink.statefun.sdk.shaded.com.google.protobuf.Parser;
@Internal
public final class SliceProtobufUtil {
private SliceProtobufUtil() {}
public static <T> T parseFrom(Parser<T> parser, Slice slice)
throws InvalidProtocolBufferException {
if (slice instanceof ByteStringSlice) {
ByteString byteString = ((ByteStringSlice) slice).byteString();
return parser.parseFrom(byteString);
}
return parser.parseFrom(slice.asReadOnlyByteBuffer());
}
public static Slice toSlice(Message message) {
return Slices.wrap(message.toByteArray());
}
public static ByteString asByteString(Slice slice) {
if (slice instanceof ByteStringSlice) {
ByteStringSlice byteStringSlice = (ByteStringSlice) slice;
return byteStringSlice.byteString();
}
return MoreByteStrings.wrap(slice.asReadOnlyByteBuffer());
}
public static Slice asSlice(ByteString byteString) {
return new ByteStringSlice(byteString);
}
}
| 5,851 |
0 | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java/io/KafkaEgressMessage.java | /*
* 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.sdk.java.io;
import java.util.Objects;
import org.apache.flink.statefun.sdk.egress.generated.KafkaProducerRecord;
import org.apache.flink.statefun.sdk.java.ApiExtension;
import org.apache.flink.statefun.sdk.java.TypeName;
import org.apache.flink.statefun.sdk.java.message.EgressMessage;
import org.apache.flink.statefun.sdk.java.message.EgressMessageWrapper;
import org.apache.flink.statefun.sdk.java.slice.Slice;
import org.apache.flink.statefun.sdk.java.slice.SliceProtobufUtil;
import org.apache.flink.statefun.sdk.java.types.Type;
import org.apache.flink.statefun.sdk.java.types.TypeSerializer;
import org.apache.flink.statefun.sdk.reqreply.generated.TypedValue;
import org.apache.flink.statefun.sdk.shaded.com.google.protobuf.ByteString;
public final class KafkaEgressMessage {
public static Builder forEgress(TypeName targetEgressId) {
Objects.requireNonNull(targetEgressId);
return new Builder(targetEgressId);
}
public static final class Builder {
private static final TypeName KAFKA_PRODUCER_RECORD_TYPENAME =
TypeName.typeNameOf(
"type.googleapis.com", KafkaProducerRecord.getDescriptor().getFullName());
private final TypeName targetEgressId;
private ByteString targetTopic;
private ByteString keyBytes;
private ByteString value;
private Builder(TypeName targetEgressId) {
this.targetEgressId = targetEgressId;
}
public Builder withTopic(String topic) {
this.targetTopic = ByteString.copyFromUtf8(topic);
return this;
}
public Builder withTopic(Slice topic) {
this.targetTopic = SliceProtobufUtil.asByteString(topic);
return this;
}
public Builder withUtf8Key(String key) {
Objects.requireNonNull(key);
this.keyBytes = ByteString.copyFromUtf8(key);
return this;
}
public Builder withKey(byte[] key) {
Objects.requireNonNull(key);
this.keyBytes = ByteString.copyFrom(key);
return this;
}
public Builder withKey(Slice slice) {
Objects.requireNonNull(slice);
this.keyBytes = SliceProtobufUtil.asByteString(slice);
return this;
}
public <T> Builder withKey(Type<T> type, T value) {
TypeSerializer<T> serializer = type.typeSerializer();
return withKey(serializer.serialize(value));
}
public Builder withUtf8Value(String value) {
Objects.requireNonNull(value);
this.value = ByteString.copyFromUtf8(value);
return this;
}
public Builder withValue(Slice slice) {
Objects.requireNonNull(slice);
this.value = SliceProtobufUtil.asByteString(slice);
return this;
}
public <T> Builder withValue(Type<T> type, T value) {
TypeSerializer<T> serializer = type.typeSerializer();
return withValue(serializer.serialize(value));
}
public Builder withValue(byte[] value) {
Objects.requireNonNull(value);
this.value = ByteString.copyFrom(value);
return this;
}
public EgressMessage build() {
if (targetTopic == null) {
throw new IllegalStateException("A Kafka record requires a target topic.");
}
if (value == null) {
throw new IllegalStateException("A Kafka record requires value bytes");
}
KafkaProducerRecord.Builder builder =
KafkaProducerRecord.newBuilder().setTopicBytes(targetTopic).setValueBytes(value);
if (keyBytes != null) {
builder.setKeyBytes(keyBytes);
}
KafkaProducerRecord record = builder.build();
TypedValue typedValue =
TypedValue.newBuilder()
.setTypenameBytes(ApiExtension.typeNameByteString(KAFKA_PRODUCER_RECORD_TYPENAME))
.setValue(record.toByteString())
.setHasValue(true)
.build();
return new EgressMessageWrapper(targetEgressId, typedValue);
}
}
}
| 5,852 |
0 | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java/io/KinesisEgressMessage.java | /*
* 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.sdk.java.io;
import java.util.Objects;
import org.apache.flink.statefun.sdk.egress.generated.KinesisEgressRecord;
import org.apache.flink.statefun.sdk.java.ApiExtension;
import org.apache.flink.statefun.sdk.java.TypeName;
import org.apache.flink.statefun.sdk.java.message.EgressMessage;
import org.apache.flink.statefun.sdk.java.message.EgressMessageWrapper;
import org.apache.flink.statefun.sdk.java.slice.Slice;
import org.apache.flink.statefun.sdk.java.slice.SliceProtobufUtil;
import org.apache.flink.statefun.sdk.java.types.Type;
import org.apache.flink.statefun.sdk.java.types.TypeSerializer;
import org.apache.flink.statefun.sdk.reqreply.generated.TypedValue;
import org.apache.flink.statefun.sdk.shaded.com.google.protobuf.ByteString;
public final class KinesisEgressMessage {
public static Builder forEgress(TypeName targetEgressId) {
Objects.requireNonNull(targetEgressId);
return new Builder(targetEgressId);
}
public static final class Builder {
private static final TypeName KINESIS_PRODUCER_RECORD_TYPENAME =
TypeName.typeNameOf(
"type.googleapis.com", KinesisEgressRecord.getDescriptor().getFullName());
private final TypeName targetEgressId;
private ByteString targetStreamBytes;
private ByteString partitionKeyBytes;
private ByteString valueBytes;
private ByteString explicitHashKey;
private Builder(TypeName targetEgressId) {
this.targetEgressId = targetEgressId;
}
public Builder withStream(String stream) {
Objects.requireNonNull(stream);
this.targetStreamBytes = ByteString.copyFromUtf8(stream);
return this;
}
public Builder withStream(Slice stream) {
this.targetStreamBytes = SliceProtobufUtil.asByteString(stream);
return this;
}
public Builder withUtf8PartitionKey(String key) {
Objects.requireNonNull(key);
this.partitionKeyBytes = ByteString.copyFromUtf8(key);
return this;
}
public Builder withPartitionKey(byte[] key) {
Objects.requireNonNull(key);
this.partitionKeyBytes = ByteString.copyFrom(key);
return this;
}
public Builder withPartitionKey(Slice key) {
Objects.requireNonNull(key);
this.partitionKeyBytes = SliceProtobufUtil.asByteString(key);
return this;
}
public Builder withUtf8Value(String value) {
Objects.requireNonNull(value);
this.valueBytes = ByteString.copyFromUtf8(value);
return this;
}
public Builder withValue(byte[] value) {
Objects.requireNonNull(value);
this.valueBytes = ByteString.copyFrom(value);
return this;
}
public Builder withValue(Slice value) {
Objects.requireNonNull(value);
this.valueBytes = SliceProtobufUtil.asByteString(value);
return this;
}
public <T> Builder withValue(Type<T> type, T value) {
TypeSerializer<T> serializer = type.typeSerializer();
return withValue(serializer.serialize(value));
}
public Builder withUtf8ExplicitHashKey(String value) {
Objects.requireNonNull(value);
this.explicitHashKey = ByteString.copyFromUtf8(value);
return this;
}
public Builder withUtf8ExplicitHashKey(Slice utf8Slice) {
Objects.requireNonNull(utf8Slice);
this.explicitHashKey = SliceProtobufUtil.asByteString(utf8Slice);
return this;
}
public EgressMessage build() {
KinesisEgressRecord.Builder builder = KinesisEgressRecord.newBuilder();
if (targetStreamBytes == null) {
throw new IllegalStateException("Missing destination Kinesis stream");
}
builder.setStreamBytes(targetStreamBytes);
if (partitionKeyBytes == null) {
throw new IllegalStateException("Missing partition key");
}
builder.setPartitionKeyBytes(partitionKeyBytes);
if (valueBytes == null) {
throw new IllegalStateException("Missing value");
}
builder.setValueBytes(valueBytes);
if (explicitHashKey != null) {
builder.setExplicitHashKeyBytes(explicitHashKey);
}
TypedValue typedValue =
TypedValue.newBuilder()
.setTypenameBytes(ApiExtension.typeNameByteString(KINESIS_PRODUCER_RECORD_TYPENAME))
.setValue(builder.build().toByteString())
.setHasValue(true)
.build();
return new EgressMessageWrapper(targetEgressId, typedValue);
}
}
}
| 5,853 |
0 | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java/message/Message.java | /*
* 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.sdk.java.message;
import org.apache.flink.statefun.sdk.java.Address;
import org.apache.flink.statefun.sdk.java.TypeName;
import org.apache.flink.statefun.sdk.java.slice.Slice;
import org.apache.flink.statefun.sdk.java.types.Type;
public interface Message {
Address targetAddress();
boolean isLong();
long asLong();
boolean isUtf8String();
String asUtf8String();
boolean isInt();
int asInt();
boolean isBoolean();
boolean asBoolean();
boolean isFloat();
float asFloat();
boolean isDouble();
double asDouble();
<T> boolean is(Type<T> type);
<T> T as(Type<T> type);
TypeName valueTypeName();
Slice rawValue();
}
| 5,854 |
0 | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java/message/MessageWrapper.java | /*
* 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.sdk.java.message;
import java.util.Objects;
import org.apache.flink.statefun.sdk.java.Address;
import org.apache.flink.statefun.sdk.java.TypeName;
import org.apache.flink.statefun.sdk.java.annotations.Internal;
import org.apache.flink.statefun.sdk.java.slice.Slice;
import org.apache.flink.statefun.sdk.java.slice.SliceProtobufUtil;
import org.apache.flink.statefun.sdk.java.types.Type;
import org.apache.flink.statefun.sdk.java.types.TypeSerializer;
import org.apache.flink.statefun.sdk.java.types.Types;
import org.apache.flink.statefun.sdk.reqreply.generated.TypedValue;
@Internal
public final class MessageWrapper implements Message {
private final TypedValue typedValue;
private final Address targetAddress;
public MessageWrapper(Address targetAddress, TypedValue typedValue) {
this.targetAddress = Objects.requireNonNull(targetAddress);
if (!typedValue.getHasValue()) {
throw new IllegalStateException("Unset empty Messages are prohibited.");
}
this.typedValue = Objects.requireNonNull(typedValue);
}
@Override
public Address targetAddress() {
return targetAddress;
}
@Override
public boolean isLong() {
return is(Types.longType());
}
@Override
public long asLong() {
return as(Types.longType());
}
@Override
public boolean isUtf8String() {
return is(Types.stringType());
}
@Override
public String asUtf8String() {
return as(Types.stringType());
}
@Override
public boolean isInt() {
return is(Types.integerType());
}
@Override
public int asInt() {
return as(Types.integerType());
}
@Override
public boolean isBoolean() {
return is(Types.booleanType());
}
@Override
public boolean asBoolean() {
return as(Types.booleanType());
}
@Override
public boolean isFloat() {
return is(Types.floatType());
}
@Override
public float asFloat() {
return as(Types.floatType());
}
@Override
public boolean isDouble() {
return is(Types.doubleType());
}
@Override
public double asDouble() {
return as(Types.doubleType());
}
@Override
public <T> boolean is(Type<T> type) {
String thisTypeNameString = typedValue.getTypename();
String thatTypeNameString = type.typeName().asTypeNameString();
return thisTypeNameString.equals(thatTypeNameString);
}
@Override
public <T> T as(Type<T> type) {
TypeSerializer<T> typeSerializer = type.typeSerializer();
Slice input = SliceProtobufUtil.asSlice(typedValue.getValue());
return typeSerializer.deserialize(input);
}
@Override
public TypeName valueTypeName() {
return TypeName.typeNameFromString(typedValue.getTypename());
}
@Override
public Slice rawValue() {
return SliceProtobufUtil.asSlice(typedValue.getValue());
}
public TypedValue typedValue() {
return typedValue;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MessageWrapper that = (MessageWrapper) o;
return Objects.equals(typedValue, that.typedValue)
&& Objects.equals(targetAddress, that.targetAddress);
}
@Override
public int hashCode() {
return Objects.hash(typedValue, targetAddress);
}
@Override
public String toString() {
return "MessageWrapper{"
+ "typedValue="
+ typedValue
+ ", targetAddress="
+ targetAddress
+ '}';
}
}
| 5,855 |
0 | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java/message/MessageBuilder.java | /*
* 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.sdk.java.message;
import java.util.Objects;
import org.apache.flink.statefun.sdk.java.Address;
import org.apache.flink.statefun.sdk.java.ApiExtension;
import org.apache.flink.statefun.sdk.java.TypeName;
import org.apache.flink.statefun.sdk.java.slice.Slice;
import org.apache.flink.statefun.sdk.java.slice.SliceProtobufUtil;
import org.apache.flink.statefun.sdk.java.types.Type;
import org.apache.flink.statefun.sdk.java.types.TypeSerializer;
import org.apache.flink.statefun.sdk.java.types.Types;
import org.apache.flink.statefun.sdk.reqreply.generated.TypedValue;
import org.apache.flink.statefun.sdk.shaded.com.google.protobuf.ByteString;
public final class MessageBuilder {
private final TypedValue.Builder builder;
private Address targetAddress;
private MessageBuilder(TypeName functionType, String id) {
this(functionType, id, TypedValue.newBuilder());
}
private MessageBuilder(TypeName functionType, String id, TypedValue.Builder builder) {
this.targetAddress = new Address(functionType, id);
this.builder = Objects.requireNonNull(builder);
}
public static MessageBuilder forAddress(TypeName functionType, String id) {
return new MessageBuilder(functionType, id);
}
public static MessageBuilder forAddress(Address address) {
Objects.requireNonNull(address);
return new MessageBuilder(address.type(), address.id());
}
public static MessageBuilder fromMessage(Message message) {
Address targetAddress = message.targetAddress();
TypedValue.Builder builder = typedValueBuilder(message);
return new MessageBuilder(targetAddress.type(), targetAddress.id(), builder);
}
public MessageBuilder withValue(long value) {
return withCustomType(Types.longType(), value);
}
public MessageBuilder withValue(int value) {
return withCustomType(Types.integerType(), value);
}
public MessageBuilder withValue(boolean value) {
return withCustomType(Types.booleanType(), value);
}
public MessageBuilder withValue(String value) {
return withCustomType(Types.stringType(), value);
}
public MessageBuilder withValue(float value) {
return withCustomType(Types.floatType(), value);
}
public MessageBuilder withValue(double value) {
return withCustomType(Types.doubleType(), value);
}
public MessageBuilder withTargetAddress(Address targetAddress) {
this.targetAddress = Objects.requireNonNull(targetAddress);
return this;
}
public MessageBuilder withTargetAddress(TypeName typeName, String id) {
return withTargetAddress(new Address(typeName, id));
}
public <T> MessageBuilder withCustomType(Type<T> customType, T element) {
Objects.requireNonNull(customType);
Objects.requireNonNull(element);
TypeSerializer<T> typeSerializer = customType.typeSerializer();
builder.setTypenameBytes(ApiExtension.typeNameByteString(customType.typeName()));
Slice serialized = typeSerializer.serialize(element);
ByteString serializedByteString = SliceProtobufUtil.asByteString(serialized);
builder.setValue(serializedByteString);
builder.setHasValue(true);
return this;
}
public Message build() {
return new MessageWrapper(targetAddress, builder.build());
}
private static TypedValue.Builder typedValueBuilder(Message message) {
ByteString typenameBytes = ApiExtension.typeNameByteString(message.valueTypeName());
ByteString valueBytes = SliceProtobufUtil.asByteString(message.rawValue());
return TypedValue.newBuilder()
.setTypenameBytes(typenameBytes)
.setHasValue(true)
.setValue(valueBytes);
}
}
| 5,856 |
0 | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java/message/EgressMessage.java | /*
* 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.sdk.java.message;
import org.apache.flink.statefun.sdk.java.TypeName;
import org.apache.flink.statefun.sdk.java.slice.Slice;
public interface EgressMessage {
TypeName targetEgressId();
TypeName egressMessageValueType();
Slice egressMessageValueBytes();
}
| 5,857 |
0 | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java/message/EgressMessageWrapper.java | /*
* 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.sdk.java.message;
import java.util.Objects;
import org.apache.flink.statefun.sdk.java.TypeName;
import org.apache.flink.statefun.sdk.java.annotations.Internal;
import org.apache.flink.statefun.sdk.java.slice.Slice;
import org.apache.flink.statefun.sdk.java.slice.SliceProtobufUtil;
import org.apache.flink.statefun.sdk.reqreply.generated.TypedValue;
@Internal
public final class EgressMessageWrapper implements EgressMessage {
private final TypedValue typedValue;
private final TypeName targetEgressId;
public EgressMessageWrapper(TypeName targetEgressId, TypedValue actualMessage) {
this.targetEgressId = Objects.requireNonNull(targetEgressId);
this.typedValue = Objects.requireNonNull(actualMessage);
}
@Override
public TypeName targetEgressId() {
return targetEgressId;
}
@Override
public TypeName egressMessageValueType() {
return TypeName.typeNameFromString(typedValue.getTypename());
}
@Override
public Slice egressMessageValueBytes() {
return SliceProtobufUtil.asSlice(typedValue.getValue());
}
public TypedValue typedValue() {
return typedValue;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
EgressMessageWrapper that = (EgressMessageWrapper) o;
return Objects.equals(typedValue, that.typedValue)
&& Objects.equals(targetEgressId, that.targetEgressId);
}
@Override
public int hashCode() {
return Objects.hash(typedValue, targetEgressId);
}
@Override
public String toString() {
return "EgressMessageWrapper{"
+ "typedValue="
+ typedValue
+ ", targetEgressId="
+ targetEgressId
+ '}';
}
}
| 5,858 |
0 | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java/message/EgressMessageBuilder.java | /*
* 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.sdk.java.message;
import java.util.Objects;
import org.apache.flink.statefun.sdk.java.ApiExtension;
import org.apache.flink.statefun.sdk.java.TypeName;
import org.apache.flink.statefun.sdk.java.slice.Slice;
import org.apache.flink.statefun.sdk.java.slice.SliceProtobufUtil;
import org.apache.flink.statefun.sdk.java.types.Type;
import org.apache.flink.statefun.sdk.java.types.TypeSerializer;
import org.apache.flink.statefun.sdk.java.types.Types;
import org.apache.flink.statefun.sdk.reqreply.generated.TypedValue;
import org.apache.flink.statefun.sdk.shaded.com.google.protobuf.ByteString;
/**
* A Custom {@link EgressMessage} builder.
*
* <p>To use {code Kafka} specific builder please use {@link
* org.apache.flink.statefun.sdk.java.io.KafkaEgressMessage}. To use {code Kinesis} specific egress
* please use {@link org.apache.flink.statefun.sdk.egress.generated.KinesisEgress}.
*
* <p>Use this builder if you need to send message to a custom egress defined via the embedded SDK.
*/
public final class EgressMessageBuilder {
private final TypeName target;
private final TypedValue.Builder builder;
public static EgressMessageBuilder forEgress(TypeName targetEgress) {
return new EgressMessageBuilder(targetEgress);
}
private EgressMessageBuilder(TypeName target) {
this.target = Objects.requireNonNull(target);
this.builder = TypedValue.newBuilder();
}
public EgressMessageBuilder withValue(long value) {
return withCustomType(Types.longType(), value);
}
public EgressMessageBuilder withValue(int value) {
return withCustomType(Types.integerType(), value);
}
public EgressMessageBuilder withValue(boolean value) {
return withCustomType(Types.booleanType(), value);
}
public EgressMessageBuilder withValue(String value) {
return withCustomType(Types.stringType(), value);
}
public EgressMessageBuilder withValue(float value) {
return withCustomType(Types.floatType(), value);
}
public EgressMessageBuilder withValue(double value) {
return withCustomType(Types.doubleType(), value);
}
public <T> EgressMessageBuilder withCustomType(Type<T> customType, T element) {
Objects.requireNonNull(customType);
Objects.requireNonNull(element);
TypeSerializer<T> typeSerializer = customType.typeSerializer();
builder.setTypenameBytes(ApiExtension.typeNameByteString(customType.typeName()));
Slice serialized = typeSerializer.serialize(element);
ByteString serializedByteString = SliceProtobufUtil.asByteString(serialized);
builder.setValue(serializedByteString);
builder.setHasValue(true);
return this;
}
public EgressMessage build() {
return new EgressMessageWrapper(target, builder.build());
}
}
| 5,859 |
0 | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java/storage/StateValueContexts.java | /*
* 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.sdk.java.storage;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import org.apache.flink.statefun.sdk.java.ValueSpec;
import org.apache.flink.statefun.sdk.java.annotations.Internal;
import org.apache.flink.statefun.sdk.reqreply.generated.ToFunction;
/**
* Utility for pairing registered {@link ValueSpec}s with values provided by the protocol's {@link
* ToFunction} message.
*/
@Internal
public final class StateValueContexts {
public static final class StateValueContext<T> {
private final ValueSpec<T> spec;
private final ToFunction.PersistedValue protocolValue;
StateValueContext(ValueSpec<T> spec, ToFunction.PersistedValue protocolValue) {
this.spec = Objects.requireNonNull(spec);
this.protocolValue = Objects.requireNonNull(protocolValue);
}
public ValueSpec<T> spec() {
return spec;
}
public ToFunction.PersistedValue protocolValue() {
return protocolValue;
}
}
public static final class ResolutionResult {
private final List<StateValueContext<?>> resolved;
private final List<ValueSpec<?>> missingValues;
private ResolutionResult(
List<StateValueContext<?>> resolved, List<ValueSpec<?>> missingValues) {
this.resolved = resolved;
this.missingValues = missingValues;
}
public boolean hasMissingValues() {
return missingValues != null;
}
public List<StateValueContext<?>> resolved() {
return resolved;
}
public List<ValueSpec<?>> missingValues() {
return missingValues;
}
}
/**
* Tries to resolve any registered states that are known to us by the {@link ValueSpec} with the
* states provided to us by the runtime.
*/
public static ResolutionResult resolve(
Map<String, ValueSpec<?>> registeredSpecs,
List<ToFunction.PersistedValue> protocolProvidedValues) {
// holds a set of missing ValueSpec's. a missing ValueSpec is a value spec that was
// registered by the user but wasn't sent to the SDK by the runtime.
// this can happen upon an initial request.
List<ValueSpec<?>> statesWithMissingValue =
null; // optimize for normal execution, where states aren't missing.
// holds the StateValueContext that will be used to serialize and deserialize user state.
final List<StateValueContext<?>> resolvedStateValues = new ArrayList<>(registeredSpecs.size());
for (ValueSpec<?> spec : registeredSpecs.values()) {
ToFunction.PersistedValue persistedValue =
findPersistedValueByName(protocolProvidedValues, spec.name());
if (persistedValue != null) {
resolvedStateValues.add(new StateValueContext<>(spec, persistedValue));
} else {
// oh no. the runtime doesn't know (yet) about a state that was registered by the user.
// we need to collect these.
statesWithMissingValue =
(statesWithMissingValue != null)
? statesWithMissingValue
: new ArrayList<>(registeredSpecs.size());
statesWithMissingValue.add(spec);
}
}
if (statesWithMissingValue == null) {
return new ResolutionResult(resolvedStateValues, null);
}
return new ResolutionResult(null, statesWithMissingValue);
}
/**
* finds a {@linkplain org.apache.flink.statefun.sdk.reqreply.generated.ToFunction.PersistedValue}
* with a given name. The size of the list, in practice is expected to be very small (0-10) items.
* just use a plain linear search.
*/
private static ToFunction.PersistedValue findPersistedValueByName(
List<ToFunction.PersistedValue> protocolProvidedValues, String name) {
for (ToFunction.PersistedValue value : protocolProvidedValues) {
if (Objects.equals(value.getStateName(), name)) {
return value;
}
}
return null;
}
}
| 5,860 |
0 | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java/storage/ConcurrentAddressScopedStorage.java | /*
* 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.sdk.java.storage;
import static org.apache.flink.statefun.sdk.java.storage.StateValueContexts.StateValueContext;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;
import org.apache.flink.statefun.sdk.java.AddressScopedStorage;
import org.apache.flink.statefun.sdk.java.ApiExtension;
import org.apache.flink.statefun.sdk.java.ValueSpec;
import org.apache.flink.statefun.sdk.java.annotations.Internal;
import org.apache.flink.statefun.sdk.java.slice.Slice;
import org.apache.flink.statefun.sdk.java.slice.SliceProtobufUtil;
import org.apache.flink.statefun.sdk.java.types.TypeCharacteristics;
import org.apache.flink.statefun.sdk.java.types.TypeSerializer;
import org.apache.flink.statefun.sdk.reqreply.generated.FromFunction;
import org.apache.flink.statefun.sdk.reqreply.generated.FromFunction.PersistedValueMutation;
import org.apache.flink.statefun.sdk.reqreply.generated.TypedValue;
import org.apache.flink.statefun.sdk.shaded.com.google.protobuf.ByteString;
@Internal
public final class ConcurrentAddressScopedStorage implements AddressScopedStorage {
private final List<Cell<?>> cells;
public ConcurrentAddressScopedStorage(List<StateValueContext<?>> stateValues) {
this.cells = createCells(stateValues);
}
@Override
public <T> Optional<T> get(ValueSpec<T> valueSpec) {
final Cell<T> cell = getCellOrThrow(valueSpec);
return cell.get();
}
@Override
public <T> void set(ValueSpec<T> valueSpec, T value) {
final Cell<T> cell = getCellOrThrow(valueSpec);
cell.set(value);
}
@Override
public <T> void remove(ValueSpec<T> valueSpec) {
final Cell<T> cell = getCellOrThrow(valueSpec);
cell.remove();
}
@SuppressWarnings("unchecked")
private <T> Cell<T> getCellOrThrow(ValueSpec<T> runtimeSpec) {
// fast path: the user used the same ValueSpec reference to declare the function
// and to index into the state.
for (Cell<?> cell : cells) {
ValueSpec<?> registeredSpec = cell.spec();
if (runtimeSpec == registeredSpec) {
return (Cell<T>) cell;
}
}
return slowGetCellOrThrow(runtimeSpec);
}
@SuppressWarnings("unchecked")
private <T> Cell<T> slowGetCellOrThrow(ValueSpec<T> valueSpec) {
// unlikely slow path: when the users used a different ValueSpec instance in registration
// and at runtime.
for (Cell<?> cell : cells) {
ValueSpec<?> thisSpec = cell.spec();
String thisName = thisSpec.name();
if (!thisName.equals(valueSpec.name())) {
continue;
}
if (thisSpec.typeName().equals(valueSpec.typeName())) {
return (Cell<T>) cell;
}
throw new IllegalStorageAccessException(
valueSpec.name(),
"Accessed state with incorrect type; state type was registered as "
+ thisSpec.typeName()
+ ", but was accessed as type "
+ valueSpec.typeName());
}
throw new IllegalStorageAccessException(
valueSpec.name(), "State does not exist; make sure that this state was registered.");
}
public void addMutations(Consumer<PersistedValueMutation> consumer) {
for (Cell<?> cell : cells) {
cell.toProtocolValueMutation().ifPresent(consumer);
}
}
// ===============================================================================
// Thread-safe state value cells
// ===============================================================================
private interface Cell<T> {
Optional<T> get();
void set(T value);
void remove();
Optional<FromFunction.PersistedValueMutation> toProtocolValueMutation();
ValueSpec<T> spec();
}
private static <T> Optional<T> tryDeserialize(
TypeSerializer<T> serializer, TypedValue typedValue) {
if (!typedValue.getHasValue()) {
return Optional.empty();
}
Slice slice = SliceProtobufUtil.asSlice(typedValue.getValue());
T value = serializer.deserialize(slice);
return Optional.ofNullable(value);
}
private static <T> ByteString serialize(TypeSerializer<T> serializer, T value) {
Slice slice = serializer.serialize(value);
return SliceProtobufUtil.asByteString(slice);
}
private static final class ImmutableTypeCell<T> implements Cell<T> {
private final ReentrantLock lock = new ReentrantLock();
private final ValueSpec<T> spec;
private final TypedValue typedValue;
private final TypeSerializer<T> serializer;
private CellStatus status = CellStatus.UNMODIFIED;
private T cachedObject;
public ImmutableTypeCell(ValueSpec<T> spec, TypedValue typedValue) {
this.spec = spec;
this.typedValue = typedValue;
this.serializer = Objects.requireNonNull(spec.type().typeSerializer());
}
@Override
public Optional<T> get() {
lock.lock();
try {
if (status == CellStatus.DELETED) {
return Optional.empty();
}
if (cachedObject != null) {
return Optional.of(cachedObject);
}
Optional<T> result = tryDeserialize(serializer, typedValue);
result.ifPresent(object -> this.cachedObject = object);
return result;
} finally {
lock.unlock();
}
}
@Override
public void set(T value) {
if (value == null) {
throw new IllegalStorageAccessException(
spec.name(), "Can not set state to NULL. Please use remove() instead.");
}
lock.lock();
try {
cachedObject = value;
status = CellStatus.MODIFIED;
} finally {
lock.unlock();
}
}
@Override
public void remove() {
lock.lock();
try {
cachedObject = null;
status = CellStatus.DELETED;
} finally {
lock.unlock();
}
}
@Override
public Optional<PersistedValueMutation> toProtocolValueMutation() {
final String typeNameString = spec.typeName().asTypeNameString();
switch (status) {
case MODIFIED:
final TypedValue.Builder newValue =
TypedValue.newBuilder()
.setTypename(typeNameString)
.setHasValue(true)
.setValue(serialize(serializer, cachedObject));
return Optional.of(
PersistedValueMutation.newBuilder()
.setStateName(spec.name())
.setMutationType(PersistedValueMutation.MutationType.MODIFY)
.setStateValue(newValue)
.build());
case DELETED:
return Optional.of(
PersistedValueMutation.newBuilder()
.setStateName(spec.name())
.setMutationType(PersistedValueMutation.MutationType.DELETE)
.build());
case UNMODIFIED:
return Optional.empty();
default:
throw new IllegalStateException("Unknown cell status: " + status);
}
}
@Override
public ValueSpec<T> spec() {
return spec;
}
}
private static final class MutableTypeCell<T> implements Cell<T> {
private final ReentrantLock lock = new ReentrantLock();
private final TypeSerializer<T> serializer;
private final ValueSpec<T> spec;
private TypedValue typedValue;
private CellStatus status = CellStatus.UNMODIFIED;
private MutableTypeCell(ValueSpec<T> spec, TypedValue typedValue) {
this.spec = spec;
this.typedValue = typedValue;
this.serializer = Objects.requireNonNull(spec.type().typeSerializer());
}
@Override
public Optional<T> get() {
lock.lock();
try {
if (status == CellStatus.DELETED) {
return Optional.empty();
}
return tryDeserialize(serializer, typedValue);
} finally {
lock.unlock();
}
}
@Override
public void set(T value) {
if (value == null) {
throw new IllegalStorageAccessException(
spec.name(), "Can not set state to NULL. Please use remove() instead.");
}
lock.lock();
try {
ByteString typenameBytes = ApiExtension.typeNameByteString(spec.typeName());
this.typedValue =
TypedValue.newBuilder()
.setTypenameBytes(typenameBytes)
.setHasValue(true)
.setValue(serialize(serializer, value))
.build();
this.status = CellStatus.MODIFIED;
} finally {
lock.unlock();
}
}
@Override
public void remove() {
lock.lock();
try {
status = CellStatus.DELETED;
} finally {
lock.unlock();
}
}
@Override
public Optional<PersistedValueMutation> toProtocolValueMutation() {
switch (status) {
case MODIFIED:
return Optional.of(
PersistedValueMutation.newBuilder()
.setStateName(spec.name())
.setMutationType(PersistedValueMutation.MutationType.MODIFY)
.setStateValue(typedValue)
.build());
case DELETED:
return Optional.of(
PersistedValueMutation.newBuilder()
.setStateName(spec.name())
.setMutationType(PersistedValueMutation.MutationType.DELETE)
.build());
case UNMODIFIED:
return Optional.empty();
default:
throw new IllegalStateException("Unknown cell status: " + status);
}
}
@Override
public ValueSpec<T> spec() {
return spec;
}
}
private enum CellStatus {
UNMODIFIED,
MODIFIED,
DELETED
}
private static List<Cell<?>> createCells(List<StateValueContext<?>> stateValues) {
final List<Cell<?>> cells = new ArrayList<>(stateValues.size());
for (StateValueContext<?> stateValueContext : stateValues) {
final TypedValue typedValue = stateValueContext.protocolValue().getStateValue();
final ValueSpec<?> spec = stateValueContext.spec();
@SuppressWarnings({"unchecked", "rawtypes"})
final Cell<?> cell =
spec.type().typeCharacteristics().contains(TypeCharacteristics.IMMUTABLE_VALUES)
? new ImmutableTypeCell(spec, typedValue)
: new MutableTypeCell(spec, typedValue);
cells.add(cell);
}
return cells;
}
}
| 5,861 |
0 | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java/storage/IllegalStorageAccessException.java | /*
* 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.sdk.java.storage;
public final class IllegalStorageAccessException extends RuntimeException {
private static final long serialVersionUID = 1;
protected IllegalStorageAccessException(String stateName, String message) {
super("Error accessing state " + stateName + "; " + message);
}
}
| 5,862 |
0 | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java/annotations/Internal.java | /*
* 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.sdk.java.annotations;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
/**
* Methods, constructors or classes annotated with this annotation, are used for by the SDK
* internally.
*/
@Documented
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.TYPE})
public @interface Internal {}
| 5,863 |
0 | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java/testing/TestContext.java | /*
* 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.sdk.java.testing;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import org.apache.flink.statefun.sdk.java.Address;
import org.apache.flink.statefun.sdk.java.AddressScopedStorage;
import org.apache.flink.statefun.sdk.java.Context;
import org.apache.flink.statefun.sdk.java.message.EgressMessage;
import org.apache.flink.statefun.sdk.java.message.Message;
/**
* An implementation of {@link Context} to to make it easier to test {@link
* org.apache.flink.statefun.sdk.java.StatefulFunction}s in isolation. It can be instantiated with
* the address of the function under test and optionally the address of the caller.
*/
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
public final class TestContext implements Context {
public static TestContext forTarget(Address self) {
return new TestContext(self);
}
public static TestContext forTargetWithCaller(Address self, Address caller) {
return new TestContext(self, caller);
}
private final AddressScopedStorage storage;
private final Address self;
private final Optional<Address> caller;
private final List<SideEffects.SendSideEffect> sentMessages = new ArrayList<>();
private final List<SideEffects.SendAfterSideEffect> sentDelayedMessages = new ArrayList<>();
private final List<SideEffects.EgressSideEffect> sentEgressMessages = new ArrayList<>();
private TestContext(Address self, Optional<Address> caller) {
this.self = self;
this.caller = caller;
this.storage = new TestAddressScopedStorage();
}
private TestContext(Address self) {
this(Objects.requireNonNull(self), Optional.empty());
}
private TestContext(Address self, Address caller) {
this(Objects.requireNonNull(self), Optional.of(Objects.requireNonNull(caller)));
}
@Override
public Address self() {
return self;
}
@Override
public Optional<Address> caller() {
return caller;
}
@Override
public void send(Message message) {
Message m = Objects.requireNonNull(message);
sentMessages.add(new SideEffects.SendSideEffect(m));
}
@Override
public void sendAfter(Duration duration, Message message) {
Duration d = Objects.requireNonNull(duration);
Message m = Objects.requireNonNull(message);
sentDelayedMessages.add(new SideEffects.SendAfterSideEffect(d, m));
}
@Override
public void sendAfter(Duration duration, String cancellationToken, Message message) {
Duration d = Objects.requireNonNull(duration);
Message m = Objects.requireNonNull(message);
sentDelayedMessages.add(new SideEffects.SendAfterSideEffect(d, m, cancellationToken));
}
@Override
public void cancelDelayedMessage(String cancellationToken) {
sentDelayedMessages.removeIf(
effect ->
effect.cancellationToken().isPresent()
&& effect.cancellationToken().get().equals(cancellationToken));
}
@Override
public void send(EgressMessage message) {
EgressMessage m = Objects.requireNonNull(message);
sentEgressMessages.add(new SideEffects.EgressSideEffect(m));
}
@Override
public AddressScopedStorage storage() {
return storage;
}
/**
* This method returns a list of all messages sent by this function via {@link
* Context#send(Message)} or {@link Context#sendAfter(Duration, Message)}.
*
* <p>Messages are wrapped in an {@link SideEffects.SendSideEffect} that contains the message
* itself and the duration after which the message was sent. The Duration is {@link Duration#ZERO}
* for messages sent via {@link Context#send(Message)}.
*
* @return the list of sent messages wrapped in {@link SideEffects.SendSideEffect}s
*/
public List<SideEffects.SendSideEffect> getSentMessages() {
return new ArrayList<>(sentMessages);
}
public List<SideEffects.SendAfterSideEffect> getSentDelayedMessages() {
return new ArrayList<>(sentDelayedMessages);
}
/**
* This method returns a list of all egress messages sent by this function via {@link
* Context#send(EgressMessage)}.
*
* @return the list of sent {@link EgressMessage}s
*/
public List<SideEffects.EgressSideEffect> getSentEgressMessages() {
return new ArrayList<>(sentEgressMessages);
}
}
| 5,864 |
0 | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java/testing/SideEffects.java | /*
* 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.sdk.java.testing;
import java.time.Duration;
import java.util.Objects;
import java.util.Optional;
import org.apache.flink.statefun.sdk.java.message.EgressMessage;
import org.apache.flink.statefun.sdk.java.message.Message;
public final class SideEffects {
private SideEffects() {}
public static SendSideEffect sentMessage(Message message) {
return new SendSideEffect(message);
}
public static SendAfterSideEffect sentAfter(Duration duration, Message message) {
return new SendAfterSideEffect(duration, message);
}
public static EgressSideEffect sentEgress(EgressMessage message) {
return new EgressSideEffect(message);
}
/**
* A utility class that wraps a {@link EgressMessage} thats was sent by a {@link
* org.apache.flink.statefun.sdk.java.StatefulFunction}. It is used by the {@link TestContext}.
*/
public static final class EgressSideEffect {
private final EgressMessage message;
public EgressSideEffect(EgressMessage message) {
this.message = Objects.requireNonNull(message);
}
public EgressMessage message() {
return message;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
EgressSideEffect envelope = (EgressSideEffect) o;
return Objects.equals(message, envelope.message);
}
@Override
public int hashCode() {
return message.hashCode();
}
@Override
public String toString() {
return "EgressEnvelope{" + "message=" + message + '}';
}
}
/**
* A utility class that wraps a {@link Message} and the {@link Duration} after which it was sent
* by a {@link org.apache.flink.statefun.sdk.java.StatefulFunction}. It is used by the {@link
* TestContext}.
*/
public static final class SendAfterSideEffect {
private final Duration duration;
private final Message message;
private final String cancellationToken;
public SendAfterSideEffect(Duration duration, Message message) {
this.duration = Objects.requireNonNull(duration);
this.message = Objects.requireNonNull(message);
this.cancellationToken = null;
}
public SendAfterSideEffect(Duration duration, Message message, String cancellationToken) {
this.duration = Objects.requireNonNull(duration);
this.message = Objects.requireNonNull(message);
this.cancellationToken = Objects.requireNonNull(cancellationToken);
}
public Duration duration() {
return duration;
}
public Message message() {
return message;
}
public Optional<String> cancellationToken() {
return Optional.ofNullable(cancellationToken);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SendAfterSideEffect that = (SendAfterSideEffect) o;
return Objects.equals(duration, that.duration)
&& Objects.equals(message, that.message)
&& Objects.equals(cancellationToken, that.cancellationToken);
}
@Override
public int hashCode() {
return Objects.hash(duration, message, cancellationToken);
}
@Override
public String toString() {
return "DelayedEnvelope{" + "duration=" + duration + ", message=" + message + '}';
}
}
/**
* A utility class that wraps a {@link Message} that was sent by a {@link
* org.apache.flink.statefun.sdk.java.StatefulFunction}. It is used by the {@link TestContext}.
*/
public static final class SendSideEffect {
private final Message message;
public SendSideEffect(Message message) {
this.message = Objects.requireNonNull(message);
}
public Message message() {
return message;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SendSideEffect sendSideEffect = (SendSideEffect) o;
return Objects.equals(message, sendSideEffect.message);
}
@Override
public int hashCode() {
return message.hashCode();
}
@Override
public String toString() {
return "Envelope{" + "message=" + message + '}';
}
}
}
| 5,865 |
0 | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java | Create_ds/flink-statefun/statefun-sdk-java/src/main/java/org/apache/flink/statefun/sdk/java/testing/TestAddressScopedStorage.java | /*
* 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.sdk.java.testing;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.flink.statefun.sdk.java.AddressScopedStorage;
import org.apache.flink.statefun.sdk.java.ValueSpec;
final class TestAddressScopedStorage implements AddressScopedStorage {
private final ConcurrentHashMap<String, Object> storage = new ConcurrentHashMap<>();
@Override
public <T> Optional<T> get(ValueSpec<T> spec) {
Objects.requireNonNull(spec);
Object value = storage.get(spec.name());
@SuppressWarnings("unchecked")
Optional<T> maybeValue = (Optional<T>) Optional.ofNullable(value);
return maybeValue;
}
@Override
public <T> void set(ValueSpec<T> spec, T value) {
Objects.requireNonNull(spec);
Objects.requireNonNull(value);
storage.put(spec.name(), value);
}
@Override
public <T> void remove(ValueSpec<T> spec) {
Objects.requireNonNull(spec);
storage.remove(spec.name());
}
}
| 5,866 |
0 | Create_ds/flink-statefun/statefun-sdk-embedded/src/test/java/org/apache/flink/statefun/sdk | Create_ds/flink-statefun/statefun-sdk-embedded/src/test/java/org/apache/flink/statefun/sdk/state/PersistedAppendingBufferTest.java | /*
* 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.sdk.state;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import org.junit.Test;
public class PersistedAppendingBufferTest {
@Test
public void viewOnInit() {
PersistedAppendingBuffer<String> buffer = PersistedAppendingBuffer.of("test", String.class);
assertFalse(buffer.view().iterator().hasNext());
}
@Test
public void append() {
PersistedAppendingBuffer<String> buffer = PersistedAppendingBuffer.of("test", String.class);
buffer.append("element");
assertThat(buffer.view().iterator().next(), is("element"));
}
@Test
public void appendAll() {
PersistedAppendingBuffer<String> buffer = PersistedAppendingBuffer.of("test", String.class);
buffer.appendAll(Arrays.asList("element-1", "element-2"));
assertThat(buffer.view(), contains("element-1", "element-2"));
}
@Test
public void appendAllEmptyList() {
PersistedAppendingBuffer<String> buffer = PersistedAppendingBuffer.of("test", String.class);
buffer.append("element");
buffer.appendAll(new ArrayList<>());
assertThat(buffer.view().iterator().next(), is("element"));
}
@Test
public void replaceWith() {
PersistedAppendingBuffer<String> buffer = PersistedAppendingBuffer.of("test", String.class);
buffer.append("element");
buffer.replaceWith(Collections.singletonList("element-new"));
assertThat(buffer.view().iterator().next(), is("element-new"));
}
@Test
public void replaceWithEmptyList() {
PersistedAppendingBuffer<String> buffer = PersistedAppendingBuffer.of("test", String.class);
buffer.append("element");
buffer.replaceWith(new ArrayList<>());
assertFalse(buffer.view().iterator().hasNext());
}
@Test
public void viewAfterClear() {
PersistedAppendingBuffer<String> buffer = PersistedAppendingBuffer.of("test", String.class);
buffer.append("element");
buffer.clear();
assertFalse(buffer.view().iterator().hasNext());
}
@Test(expected = UnsupportedOperationException.class)
public void viewUnmodifiable() {
PersistedAppendingBuffer<String> buffer = PersistedAppendingBuffer.of("test", String.class);
buffer.append("element");
Iterator<String> view = buffer.view().iterator();
view.remove();
}
}
| 5,867 |
0 | Create_ds/flink-statefun/statefun-sdk-embedded/src/test/java/org/apache/flink/statefun/sdk | Create_ds/flink-statefun/statefun-sdk-embedded/src/test/java/org/apache/flink/statefun/sdk/state/PersistedStateRegistryTest.java | /*
* 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.sdk.state;
import org.apache.flink.statefun.sdk.TypeName;
import org.junit.Test;
public class PersistedStateRegistryTest {
@Test
public void exampleUsage() {
final PersistedStateRegistry registry = new PersistedStateRegistry();
registry.registerValue(PersistedValue.of("value", String.class));
registry.registerTable(PersistedTable.of("table", String.class, Integer.class));
registry.registerAppendingBuffer(PersistedAppendingBuffer.of("buffer", String.class));
registry.registerRemoteValue(
RemotePersistedValue.of("remote", TypeName.parseFrom("io.statefun.types/raw")));
}
@Test(expected = IllegalStateException.class)
public void duplicateRegistration() {
final PersistedStateRegistry registry = new PersistedStateRegistry();
registry.registerValue(PersistedValue.of("my-state", String.class));
registry.registerTable(PersistedTable.of("my-state", String.class, Integer.class));
}
}
| 5,868 |
0 | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun/sdk/AsyncOperationResult.java | /*
* 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.sdk;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import org.apache.flink.statefun.sdk.annotations.ForRuntime;
/**
* AsyncOperationResult - An asynchronous operation result.
*
* <p>{@code AsyncOperationResult} represents a completion of an asynchronous operation, registered
* by a stateful function instance via a {@link Context#registerAsyncOperation(Object,
* CompletableFuture)}.
*
* <p>The status of the asynchronous operation can be obtain via {@link #status()}, and it can be
* one of:
*
* <ul>
* <li>{@code success} - The asynchronous operation has succeeded, and the produced result can be
* obtained via {@link #value()}.
* <li>{@code failure} - The asynchronous operation has failed, and the cause can be obtained via
* ({@link #throwable()}.
* <li>{@code unknown} - the stateful function was restarted, possibly on a different machine,
* before the {@link CompletableFuture} was completed, therefore it is unknown what is the
* status of the asynchronous operation.
* </ul>
*
* @param <M> metadata type
* @param <T> result type.
*/
public final class AsyncOperationResult<M, T> {
public enum Status {
SUCCESS,
FAILURE,
UNKNOWN
}
private final M metadata;
private final Status status;
private final T value;
private final Throwable throwable;
@ForRuntime
public AsyncOperationResult(M metadata, Status status, T value, Throwable throwable) {
this.metadata = Objects.requireNonNull(metadata);
this.status = Objects.requireNonNull(status);
this.value = value;
this.throwable = throwable;
}
/**
* @return the metadata assosicted with this async operation, as supplied at {@link
* Context#registerAsyncOperation(Object, CompletableFuture)}.
*/
public M metadata() {
return metadata;
}
/** @return the status of this async operation. */
public Status status() {
return status;
}
/** @return the successfully completed value. */
public T value() {
if (status != Status.SUCCESS) {
throw new IllegalStateException("Not a successful result, but rather " + status);
}
return value;
}
/** @return the exception thrown during an attempt to complete the asynchronous operation. */
public Throwable throwable() {
if (status != Status.FAILURE) {
throw new IllegalStateException("Not a failure, but rather " + status);
}
return throwable;
}
public boolean successful() {
return status == Status.SUCCESS;
}
public boolean unknown() {
return status == Status.UNKNOWN;
}
public boolean failure() {
return status == Status.FAILURE;
}
}
| 5,869 |
0 | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun/sdk/TypeName.java | /*
* 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.sdk;
import java.io.Serializable;
import java.util.Objects;
public final class TypeName implements Serializable {
private static final long serialVersionUID = 1L;
private static final String DELIMITER = "/";
private final String namespace;
private final String name;
private final String canonicalTypenameString;
public static TypeName parseFrom(String typeNameString) {
final String[] split = typeNameString.split(DELIMITER);
if (split.length != 2) {
throw new IllegalArgumentException(
"Invalid type name string: "
+ typeNameString
+ ". Must be of format <namespace>"
+ DELIMITER
+ "<name>.");
}
return new TypeName(split[0], split[1]);
}
public TypeName(String namespace, String name) {
this.namespace = Objects.requireNonNull(namespace);
this.name = Objects.requireNonNull(name);
this.canonicalTypenameString = canonicalTypeNameString(namespace, name);
}
public String namespace() {
return namespace;
}
public String name() {
return name;
}
public String canonicalTypenameString() {
return canonicalTypenameString;
}
@Override
public String toString() {
return "TypeName(" + namespace + ", " + name + ")";
}
private static String canonicalTypeNameString(String namespace, String name) {
return namespace + DELIMITER + name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TypeName typeName = (TypeName) o;
return Objects.equals(namespace, typeName.namespace)
&& Objects.equals(name, typeName.name)
&& Objects.equals(canonicalTypenameString, typeName.canonicalTypenameString);
}
@Override
public int hashCode() {
return Objects.hash(namespace, name, canonicalTypenameString);
}
}
| 5,870 |
0 | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun/sdk/StatefulFunction.java | /*
* 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.sdk;
import org.apache.flink.statefun.sdk.annotations.Persisted;
import org.apache.flink.statefun.sdk.io.EgressIdentifier;
import org.apache.flink.statefun.sdk.io.Router;
import org.apache.flink.statefun.sdk.state.PersistedValue;
/**
* A {@link StatefulFunction} is a user-defined function that can be invoked with a given input.
* This is the primitive building block for a Stateful Functions application.
*
* <h2>Concept</h2>
*
* <p>Each individual {@code StatefulFunction} is an uniquely invokable "instance" of a {@link
* FunctionType}. Each function is identified by an {@link Address}, representing the function's
* unique id (a string) within its type. From a user's perspective, it would seem as if for each
* unique function id, there exists a stateful instance of the function that is always available to
* be invoked within a Stateful Functions application.
*
* <h2>Invoking a {@code StatefulFunction}</h2>
*
* <p>An individual {@code StatefulFunction} can be invoked with arbitrary input from any another
* {@code StatefulFunction} (including itself), or routed from ingresses via a {@link Router}. To
* invoke a {@code StatefulFunction}, the caller simply needs to know the {@code Address} of the
* target function.
*
* <p>As a result of invoking a {@code StatefulFunction}, the function may continue to invoke other
* functions, modify its state, or send messages to egresses addressed by an {@link
* EgressIdentifier}.
*
* <h2>State</h2>
*
* <p>Each individual {@code StatefulFunction} may have state that is maintained by the system,
* providing exactly-once guarantees. Below is a code example of how to register and access state in
* functions:
*
* <pre>{@code
* public class MyFunction implements StatefulFunction {
*
* {@code @Persisted}
* PersistedValue<Integer> intState = PersistedValue.of("state-name", Integer.class);
*
* {@code @Override}
* public void invoke(Context context, Object input) {
* Integer stateValue = intState.get();
* //...
* intState.set(1108);
* // send messages using context
* }
* }
* }</pre>
*
* @see Address
* @see FunctionType
* @see Persisted
* @see PersistedValue
*/
public interface StatefulFunction {
/**
* Invokes this function with a given input.
*
* @param context context for the current invocation. The provided context instance should not be
* used outside the scope of the current invocation.
* @param input input for the current invocation.
*/
void invoke(Context context, Object input);
}
| 5,871 |
0 | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun/sdk/Context.java | /*
* 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.sdk;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;
import org.apache.flink.statefun.sdk.io.EgressIdentifier;
import org.apache.flink.statefun.sdk.metrics.Metrics;
/**
* Provides context for a single {@link StatefulFunction} invocation.
*
* <p>The invocation's context may be used to obtain the {@link Address} of itself or the calling
* function (if the function was invoked by another function), or used to invoke other functions
* (including itself) and to send messages to egresses.
*/
public interface Context {
/**
* Returns the {@link Address} of the invoked function.
*
* @return the invoked function's own address.
*/
Address self();
/**
* Returns the {@link Address} of the invoking function. This is {@code null} if the function
* under context was not invoked by another function.
*
* @return the address of the invoking function; {@code null} if the function under context was
* not invoked by another function.
*/
Address caller();
/**
* Invokes another function with an input, identified by the target function's {@link Address}.
*
* @param to the target function's address.
* @param message the input to provide for the invocation.
*/
void send(Address to, Object message);
/**
* Sends an output to an egress, identified by the egress' {@link EgressIdentifier}.
*
* @param egress the target egress' identifier
* @param message the output to send
* @param <T> type of the inputs that the target egress consumes
*/
<T> void send(EgressIdentifier<T> egress, T message);
/**
* Invokes another function with an input, identified by the target function's {@link Address},
* after a given delay.
*
* @param delay the amount of delay before invoking the target function. Value needs to be >=
* 0.
* @param to the target function's address.
* @param message the input to provide for the delayed invocation.
*/
void sendAfter(Duration delay, Address to, Object message);
/**
* Invokes another function with an input (associated with a {@code cancellationToken}),
* identified by the target function's {@link Address}, after a given delay.
*
* <p>Providing an id to a message, allows "unsending" this message later. ({@link
* #cancelDelayedMessage(String)}).
*
* @param delay the amount of delay before invoking the target function. Value needs to be >=
* 0.
* @param to the target function's address.
* @param message the input to provide for the delayed invocation.
* @param cancellationToken the non-empty, non-null, unique token to attach to this message, to be
* used for message cancellation. (see {@link #cancelDelayedMessage(String)}.)
*/
void sendAfter(Duration delay, Address to, Object message, String cancellationToken);
/**
* Cancel a delayed message (a message that was send via {@link #sendAfter(Duration, Address,
* Object, String)}).
*
* <p>NOTE: this is a best-effort operation, since the message might have been already delivered.
* If the message was delivered, this is a no-op operation.
*
* @param cancellationToken the id of the message to un-send.
*/
void cancelDelayedMessage(String cancellationToken);
/**
* Invokes another function with an input, identified by the target function's {@link
* FunctionType} and unique id.
*
* @param functionType the target function's type.
* @param id the target function's id within its type.
* @param message the input to provide for the invocation.
*/
default void send(FunctionType functionType, String id, Object message) {
send(new Address(functionType, id), message);
}
/**
* Invokes another function with an input, identified by the target function's {@link
* FunctionType} and unique id.
*
* @param delay the amount of delay before invoking the target function. Value needs to be >=
* 0.
* @param functionType the target function's type.
* @param id the target function's id within its type.
* @param message the input to provide for the delayed invocation.
*/
default void sendAfter(Duration delay, FunctionType functionType, String id, Object message) {
sendAfter(delay, new Address(functionType, id), message);
}
/**
* Invokes the calling function of the current invocation under context. This has the same effect
* as calling {@link #send(Address, Object)} with the address obtained from {@link #caller()}, and
* will not work if the current function was not invoked by another function.
*
* @param message the input to provide to the replying invocation.
*/
default void reply(Object message) {
send(caller(), message);
}
/**
* Registers an asynchronous operation.
*
* <p>Register an asynchronous operation represented by a {@code future}, and associated with
* {@code metadata}.
*
* <p>The runtime would invoke (at some time in the future) the currently executing stateful
* function with a {@link AsyncOperationResult} argument, that represents the completion of that
* asynchronous operation.
*
* <p>If the supplied future was completed successfully, then the result can be obtained via
* {@link AsyncOperationResult#value()}. If it is completed exceptionally, then the failure cause
* can be obtain via {@link AsyncOperationResult#throwable()}.
*
* <p>Please note that if, for some reason, the processes executing the stateful had fail, the
* status of the asynchronous operation is unknown (it might have succeeded or failed before the
* stateful function was notified). In that case the status of the {@code AsyncOperationResult}
* would be {@code UNKNOWN}.
*
* <p>{@code metadata} - Each asynchronous operation is also associated with a metadata object
* that can be used to correlate multiple in flight asynchronous operations. This object can be
* obtained via {@link AsyncOperationResult#metadata()}. This object would be serialized with the
* same serializer used to serializer the messages.
*
* @param metadata a meta data object to associated with this in flight async operation.
* @param future the {@link CompletableFuture} that represents the async operation.
* @param <M> metadata type.
* @param <T> value type.
*/
<M, T> void registerAsyncOperation(M metadata, CompletableFuture<T> future);
/** @return a function type scoped metrics. */
Metrics metrics();
}
| 5,872 |
0 | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun/sdk/FunctionTypeNamespaceMatcher.java | /*
* 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.sdk;
import java.io.Serializable;
import java.util.Objects;
public final class FunctionTypeNamespaceMatcher implements Serializable {
private static final long serialVersionUID = 1;
private final String targetNamespace;
public static FunctionTypeNamespaceMatcher targetNamespace(String namespace) {
return new FunctionTypeNamespaceMatcher(namespace);
}
private FunctionTypeNamespaceMatcher(String targetNamespace) {
this.targetNamespace = Objects.requireNonNull(targetNamespace);
}
public String targetNamespace() {
return targetNamespace;
}
public boolean matches(FunctionType functionType) {
return targetNamespace.equals(functionType.namespace());
}
@Override
public int hashCode() {
return targetNamespace.hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
FunctionTypeNamespaceMatcher other = (FunctionTypeNamespaceMatcher) obj;
return targetNamespace.equals(other.targetNamespace);
}
@Override
public String toString() {
return String.format("FunctionTypeNamespaceMatcher(%s)", targetNamespace);
}
}
| 5,873 |
0 | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun/sdk/EgressType.java | /*
* 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.sdk;
import java.util.Objects;
import org.apache.flink.statefun.sdk.io.EgressSpec;
/**
* Defines the type of an egress, represented by a namespace and the type's name.
*
* <p>This is used by the system to translate an {@link EgressSpec} to a physical runtime-specific
* representation.
*/
public final class EgressType {
private final String namespace;
private final String type;
/**
* Creates an {@link EgressType}.
*
* @param namespace the type's namespace.
* @param type the type's name.
*/
public EgressType(String namespace, String type) {
this.namespace = Objects.requireNonNull(namespace);
this.type = Objects.requireNonNull(type);
}
/**
* Returns the namespace of this egress type.
*
* @return the namespace of this egress type.
*/
public String namespace() {
return namespace;
}
/**
* Returns the name of this egress type.
*
* @return the name of this egress type.
*/
public String type() {
return type;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
EgressType that = (EgressType) o;
return namespace.equals(that.namespace) && type.equals(that.type);
}
@Override
public int hashCode() {
int hash = 0;
hash = 37 * hash + namespace.hashCode();
hash = 37 * hash + type.hashCode();
return hash;
}
@Override
public String toString() {
return String.format("IngressType(%s, %s)", namespace, type);
}
}
| 5,874 |
0 | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun/sdk/FunctionType.java | /*
* 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.sdk;
import java.io.Serializable;
import java.util.Objects;
/**
* This class represents the type of a {@link StatefulFunction}, consisting of a namespace of the
* function type as well as the type's name.
*
* <p>A function's type is part of a function's {@link Address} and serves as integral part of an
* individual function's identity.
*
* @see Address
*/
public final class FunctionType implements Serializable {
private static final long serialVersionUID = 1;
private final String namespace;
private final String type;
/**
* Creates a {@link FunctionType}.
*
* @param namespace the function type's namepsace.
* @param type the function type's name.
*/
public FunctionType(String namespace, String type) {
this.namespace = Objects.requireNonNull(namespace);
this.type = Objects.requireNonNull(type);
}
/**
* Returns the namespace of the function type.
*
* @return the namespace of the function type.
*/
public String namespace() {
return namespace;
}
/**
* Returns the name of the function type.
*
* @return the name of the function type.
*/
public String name() {
return type;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
FunctionType functionType = (FunctionType) o;
return namespace.equals(functionType.namespace) && type.equals(functionType.type);
}
@Override
public int hashCode() {
int hash = 0;
hash = 37 * hash + namespace.hashCode();
hash = 37 * hash + type.hashCode();
return hash;
}
@Override
public String toString() {
return String.format("FunctionType(%s, %s)", namespace, type);
}
}
| 5,875 |
0 | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun/sdk/Address.java | /*
* 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.sdk;
import java.util.Objects;
/**
* An {@link Address} is the unique identity of an individual {@link StatefulFunction}, containing
* of the function's {@link FunctionType} 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.
*/
public final class Address {
private final FunctionType type;
private final String id;
/**
* Creates an {@link Address}.
*
* @param type type of the function.
* @param id unique id within the function type.
*/
public Address(FunctionType type, String id) {
this.type = Objects.requireNonNull(type);
this.id = Objects.requireNonNull(id);
}
/**
* Returns the {@link FunctionType} that this address identifies.
*
* @return type of the function
*/
public FunctionType type() {
return type;
}
/**
* Returns the unique function id, within its type, that this address identifies.
*
* @return unique id within the function type.
*/
public String id() {
return id;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Address address = (Address) o;
return type.equals(address.type) && id.equals(address.id);
}
@Override
public int hashCode() {
int hash = 0;
hash = 37 * hash + type.hashCode();
hash = 37 * hash + id.hashCode();
return hash;
}
@Override
public String toString() {
return String.format("Address(%s, %s, %s)", type.namespace(), type.name(), id);
}
}
| 5,876 |
0 | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun/sdk/StatefulFunctionProvider.java | /*
* 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.sdk;
/** Provides instances of {@link StatefulFunction}s for a given {@link FunctionType}. */
public interface StatefulFunctionProvider {
/**
* Creates a {@link StatefulFunction} instance for the given {@link FunctionType},
*
* @param type the type of function to create an instance for.
* @return an instance of a function for the given type.
*/
StatefulFunction functionOfType(FunctionType type);
}
| 5,877 |
0 | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun/sdk/IngressType.java | /*
* 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.sdk;
import java.util.Objects;
import org.apache.flink.statefun.sdk.io.IngressSpec;
/**
* Defines the type of an ingress, represented by a namespace and the type's name.
*
* <p>This is used by the system to translate an {@link IngressSpec} to a physical runtime-specific
* representation.
*/
public final class IngressType {
private final String namespace;
private final String type;
/**
* Creates an {@link IngressType}.
*
* @param namespace the type's namespace.
* @param type the type's name.
*/
public IngressType(String namespace, String type) {
this.namespace = Objects.requireNonNull(namespace);
this.type = Objects.requireNonNull(type);
}
/**
* Returns the namespace of this ingress type.
*
* @return the namespace of this ingress type.
*/
public String namespace() {
return namespace;
}
/**
* Returns the name of this ingress type.
*
* @return the name of this ingress type.
*/
public String type() {
return type;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
IngressType that = (IngressType) o;
return namespace.equals(that.namespace) && type.equals(that.type);
}
@Override
public int hashCode() {
int hash = 0;
hash = 37 * hash + namespace.hashCode();
hash = 37 * hash + type.hashCode();
return hash;
}
@Override
public String toString() {
return String.format("IngressType(%s, %s)", namespace, type);
}
}
| 5,878 |
0 | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun/sdk | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun/sdk/metrics/Counter.java | /*
* 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.sdk.metrics;
/** A Counter. */
public interface Counter {
/**
* Increment the amount of this counter by @amount;
*
* @param amount the amount to increment by;
*/
void inc(long amount);
/**
* Decrement the amount of this counter by @amount;
*
* @param amount the amount to increment by;
*/
void dec(long amount);
/** Increment the value of this counter by 1. */
default void inc() {
inc(1);
}
/** Decrement the value of this counter by 1. */
default void dec() {
dec(1);
}
}
| 5,879 |
0 | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun/sdk | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun/sdk/metrics/Metrics.java | /*
* 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.sdk.metrics;
public interface Metrics {
/**
* Retrieves (or creates) a counter metric with this name.
*
* @param name a metric name
* @return a counter.
*/
Counter counter(String name);
}
| 5,880 |
0 | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun/sdk | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun/sdk/core/OptionalProperty.java | /*
* 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.sdk.core;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Properties;
import java.util.function.BiConsumer;
import javax.annotation.Nullable;
import org.apache.flink.statefun.sdk.annotations.ForRuntime;
/**
* Utility class to represent an optional config, which may have a predefined default value.
*
* @param <T> type of the configuration value.
*/
@ForRuntime
public final class OptionalProperty<T> {
private final T defaultValue;
private T value;
public static <T> OptionalProperty<T> withDefault(T defaultValue) {
Objects.requireNonNull(defaultValue);
return new OptionalProperty<>(defaultValue);
}
public static <T> OptionalProperty<T> withoutDefault() {
return new OptionalProperty<>(null);
}
private OptionalProperty(@Nullable T defaultValue) {
this.defaultValue = defaultValue;
}
public void set(T value) {
this.value = Objects.requireNonNull(value);
}
public T get() {
if (!isSet() && !hasDefault()) {
throw new NoSuchElementException(
"A value has not been set, and no default value was defined.");
}
return isSet() ? value : defaultValue;
}
public void overwritePropertiesIfPresent(Properties properties, String key) {
if (isSet() || (!properties.containsKey(key) && hasDefault())) {
properties.setProperty(key, get().toString());
}
}
public void transformPropertiesIfPresent(
Properties properties, String key, BiConsumer<Properties, T> transformer) {
if (isSet() || (!properties.containsKey(key) && hasDefault())) {
transformer.accept(properties, get());
}
}
private boolean hasDefault() {
return defaultValue != null;
}
private boolean isSet() {
return value != null;
}
}
| 5,881 |
0 | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun/sdk | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun/sdk/match/StatefulMatchFunction.java | /*
* 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.sdk.match;
import org.apache.flink.statefun.sdk.Context;
import org.apache.flink.statefun.sdk.StatefulFunction;
/**
* A {@link StatefulMatchFunction} is an utility {@link StatefulFunction} that supports pattern
* matching on function inputs to decide how the inputs should be processed.
*
* <p>Please see {@link MatchBinder} for the supported types of pattern matching.
*
* @see MatchBinder
*/
public abstract class StatefulMatchFunction implements StatefulFunction {
private boolean setup = false;
private MatchBinder matcher = new MatchBinder();
/**
* Configures the patterns to match for the function's inputs.
*
* @param binder a {@link MatchBinder} to bind patterns on.
*/
public abstract void configure(MatchBinder binder);
@Override
public final void invoke(Context context, Object input) {
ensureInitialized();
matcher.invoke(context, input);
}
private void ensureInitialized() {
if (!setup) {
setup = true;
configure(matcher);
}
}
}
| 5,882 |
0 | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun/sdk | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun/sdk/match/MatchBinder.java | /*
* 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.sdk.match;
import java.util.ArrayList;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Objects;
import java.util.function.BiConsumer;
import java.util.function.Predicate;
import org.apache.flink.statefun.sdk.Context;
/**
* Binds patterns to be matched on inputs and their corresponding actions to the processing logic of
* a {@link StatefulMatchFunction}.
*
* <p>The following methods are supported for binding patterns, in order of precedence that they are
* checked for matches:
*
* <ul>
* <li>{@link #predicate(Class, Predicate, BiConsumer)}: matches on the input's type and a
* conditional predicate on the input object state.
* <li>{@link #predicate(Class, BiConsumer)}: simple type match on the input's type.
* <li>{@link #otherwise(BiConsumer)}: default action to take if no match can be found for the
* input.
* </ul>
*/
public final class MatchBinder {
private final IdentityHashMap<Class<?>, List<Method<Object>>> multiMethods =
new IdentityHashMap<>();
private final IdentityHashMap<Class<?>, BiConsumer<Context, Object>> noPredicateMethods =
new IdentityHashMap<>();
private boolean customDefaultAction = false;
private BiConsumer<Context, Object> defaultAction = MatchBinder::unhandledDefaultAction;
MatchBinder() {}
/**
* Binds a simple type pattern which matches on the input's type.
*
* <p>This has a lower precedence than matches found on patterns registered via {@link
* #predicate(Class, Predicate, BiConsumer)}. If no conditional predicates matches for a given
* input of type {@code type}, then the action registered here will be used.
*
* @param type the expected input type.
* @param action the action to take if this pattern matches.
* @param <T> the expected input type.
* @return the binder, with predicate bound
*/
@SuppressWarnings("unchecked")
public <T> MatchBinder predicate(Class<T> type, BiConsumer<Context, T> action) {
Objects.requireNonNull(type);
Objects.requireNonNull(action);
if (noPredicateMethods.containsKey(type)) {
throw new IllegalStateException("There is already a catch all case for class " + type);
}
noPredicateMethods.put(type, (BiConsumer<Context, Object>) action);
return this;
}
/**
* Binds a pattern which matches on a function's input type, as well as a conditional predicate on
* the input object's state.
*
* <p>Precedence of conditional predicate matches is determined by the order in which they were
* bind; predicates that were bind first have higher precedence. Patterns bind via this method
* have the highest precedence over other methods.
*
* @param type the expected input type.
* @param predicate a predicate on the input object state to match on.
* @param action the action to take if this patten matches.
* @param <T> the expected input type.
* @return the binder, with predicate bound
*/
@SuppressWarnings("unchecked")
public <T> MatchBinder predicate(
Class<T> type, Predicate<T> predicate, BiConsumer<Context, T> action) {
List<Method<Object>> methods = multiMethods.computeIfAbsent(type, ignored -> new ArrayList<>());
BiConsumer<Context, Object> a = (BiConsumer<Context, Object>) action;
Predicate<Object> p = (Predicate<Object>) predicate;
methods.add(new Method<>(p, a));
return this;
}
/**
* Binds a default action for inputs that fail to match any of the patterns bind via the {@link
* #predicate(Class, Predicate, BiConsumer)} and {@link #predicate(Class, BiConsumer)} methods. If
* no default action was bind using this method, then a {@link IllegalStateException} would be
* thrown for inputs that fail to match.
*
* @param action the default action
* @return the binder, with default action bound
*/
public MatchBinder otherwise(BiConsumer<Context, Object> action) {
if (customDefaultAction) {
throw new IllegalStateException("There can only be one default action");
}
customDefaultAction = true;
defaultAction = Objects.requireNonNull(action);
return this;
}
void invoke(Context context, Object input) {
final Class<?> type = input.getClass();
List<Method<Object>> methods = multiMethods.getOrDefault(type, Collections.emptyList());
for (Method<Object> m : methods) {
if (m.canApply(input)) {
m.apply(context, input);
return;
}
}
noPredicateMethods.getOrDefault(type, defaultAction).accept(context, input);
}
private static final class Method<T> {
private final Predicate<T> predicate;
private final BiConsumer<Context, T> apply;
Method(Predicate<T> predicate, BiConsumer<Context, T> method) {
this.predicate = Objects.requireNonNull(predicate);
this.apply = Objects.requireNonNull(method);
}
boolean canApply(T input) {
return predicate.test(input);
}
void apply(Context context, T input) {
apply.accept(context, input);
}
}
private static void unhandledDefaultAction(Context context, Object input) {
throw new IllegalStateException("Don't know how to handle " + input);
}
}
| 5,883 |
0 | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun/sdk | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun/sdk/io/Router.java | /*
* 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.sdk.io;
import org.apache.flink.statefun.sdk.Address;
import org.apache.flink.statefun.sdk.FunctionType;
import org.apache.flink.statefun.sdk.StatefulFunction;
import org.apache.flink.statefun.sdk.metrics.Metrics;
/**
* A {@link Router} routes messages from ingresses to individual {@link StatefulFunction}s.
*
* <p>Implementations should be stateless, as any state in routers are not persisted by the system.
*
* @param <InT> the type of messages being routed.
*/
public interface Router<InT> {
/**
* Routes a given message to downstream {@link StatefulFunction}s. A single message may result in
* multiple functions being invoked.
*
* @param message the message to route.
* @param downstream used to invoke downstream functions.
*/
void route(InT message, Downstream<InT> downstream);
/**
* Interface for invoking downstream functions.
*
* @param <T> the type of messages being routed to downstream functions.
*/
interface Downstream<T> {
/**
* Forwards the message as an input to a downstream function, addressed by a specified {@link
* Address}.
*
* @param to the target function's address.
* @param message the message being forwarded.
*/
void forward(Address to, T message);
/**
* Forwards the message as an input to a downstream function, addressed by a specified {@link
* FunctionType} and the functions unique id within its type.
*
* @param functionType the target function's type.
* @param id the target function's unique id.
* @param message the message being forwarded.
*/
default void forward(FunctionType functionType, String id, T message) {
forward(new Address(functionType, id), message);
}
/**
* Returns the metrics that are scoped to this ingress.
*
* <p>Every metric defined here will be associated to the ingress, that this router is attached
* to. For example, if this router is attached to an ingress with an {@code
* IngressIdentifier("foo", "bar")}, then every metric name {@code M} will appear as
* "routers.foo.bar.M".
*/
Metrics metrics();
}
}
| 5,884 |
0 | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun/sdk | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun/sdk/io/IngressIdentifier.java | /*
* 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.sdk.io;
import java.io.Serializable;
import java.util.Objects;
/**
* This class identifies an ingress within a Stateful Functions application, and is part of an
* {@link IngressSpec}.
*/
public final class IngressIdentifier<T> implements Serializable {
private static final long serialVersionUID = 1L;
private final String namespace;
private final String name;
private final Class<T> producedType;
/**
* Creates an {@link IngressIdentifier}.
*
* @param producedType the type of messages produced by the ingress.
* @param namespace the namespace of the ingress.
* @param name the name of the ingress.
*/
public IngressIdentifier(Class<T> producedType, String namespace, String name) {
this.namespace = Objects.requireNonNull(namespace);
this.name = Objects.requireNonNull(name);
this.producedType = Objects.requireNonNull(producedType);
}
/**
* Returns the namespace of the ingress.
*
* @return the namespace of the ingress.
*/
public String namespace() {
return namespace;
}
/**
* Returns the name of the ingress.
*
* @return the name of the ingress.
*/
public String name() {
return name;
}
/**
* Returns the type of messages produced by the ingress.
*
* @return the type of messages produced by the ingress.
*/
public Class<T> producedType() {
return producedType;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
IngressIdentifier<?> that = (IngressIdentifier<?>) o;
return namespace.equals(that.namespace)
&& name.equals(that.name)
&& producedType.equals(that.producedType);
}
@Override
public int hashCode() {
int hash = 0;
hash = 37 * hash + namespace.hashCode();
hash = 37 * hash + name.hashCode();
hash = 37 * hash + producedType.hashCode();
return hash;
}
@Override
public String toString() {
return String.format("IngressIdentifier(%s, %s, %s)", namespace, name, producedType);
}
}
| 5,885 |
0 | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun/sdk | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun/sdk/io/IngressSpec.java | /*
* 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.sdk.io;
import org.apache.flink.statefun.sdk.IngressType;
/**
* Complete specification for an ingress, containing of the ingress' {@link IngressIdentifier} and
* the {@link IngressType}. This fully defines an ingress within a Stateful Functions application.
*
* <p>This serves as a "logical" representation of an input source for invoking stateful functions
* within an application. Under the scenes, the system translates this to a physical
* runtime-specific representation corresponding to the specified {@link IngressType}.
*
* @param <T> the type of messages produced by this ingress.
*/
public interface IngressSpec<T> {
/**
* Returns the unique identifier of the ingress.
*
* @return the unique identifier of the ingress.
*/
IngressIdentifier<T> id();
/**
* Returns the type of the ingress.
*
* @return the type of the ingress.
*/
IngressType type();
}
| 5,886 |
0 | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun/sdk | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun/sdk/io/EgressSpec.java | /*
* 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.sdk.io;
import org.apache.flink.statefun.sdk.EgressType;
/**
* Complete specification for an egress, containing of the egress' {@link EgressIdentifier} and the
* {@link EgressType}. This fully defines an egress within a Stateful Functions application.
*
* <p>This serves as a "logical" representation of an output sink that stateful functions within an
* application can send messages to. Under the scenes, the system translates this to a physical
* runtime-specific representation corresponding to the specified {@link EgressType}.
*
* @param <T> the type of messages consumed by this egress.
*/
public interface EgressSpec<T> {
/**
* Returns the unique identifier of the egress.
*
* @return the unique identifier of the egress.
*/
EgressIdentifier<T> id();
/**
* Returns the type of the egress.
*
* @return the type of the egress.
*/
EgressType type();
}
| 5,887 |
0 | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun/sdk | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun/sdk/io/EgressIdentifier.java | /*
* 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.sdk.io;
import java.io.Serializable;
import java.util.Objects;
/**
* This class identifies an egress within a Stateful Functions application, and is part of an {@link
* EgressSpec}.
*/
public final class EgressIdentifier<T> implements Serializable {
private static final long serialVersionUID = 1L;
private final String namespace;
private final String name;
private final Class<T> consumedType;
/**
* Creates an {@link EgressIdentifier}.
*
* @param namespace the namespace of the egress.
* @param name the name of the egress.
* @param consumedType the type of messages consumed by the egress.
*/
public EgressIdentifier(String namespace, String name, Class<T> consumedType) {
this.namespace = Objects.requireNonNull(namespace);
this.name = Objects.requireNonNull(name);
this.consumedType = Objects.requireNonNull(consumedType);
}
/**
* Returns the namespace of the egress.
*
* @return the namespace of the egress.
*/
public String namespace() {
return namespace;
}
/**
* Returns the name of the egress.
*
* @return the name of the egress.
*/
public String name() {
return name;
}
/**
* Returns the type of messages consumed by the egress.
*
* @return the type of messages consumed by the egress.
*/
public Class<T> consumedType() {
return consumedType;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
EgressIdentifier<?> egressIdentifier = (EgressIdentifier<?>) o;
return namespace.equals(egressIdentifier.namespace)
&& name.equals(egressIdentifier.name)
&& consumedType.equals(egressIdentifier.consumedType);
}
@Override
public int hashCode() {
int hash = 0;
hash = 37 * hash + namespace.hashCode();
hash = 37 * hash + name.hashCode();
hash = 37 * hash + consumedType.hashCode();
return hash;
}
@Override
public String toString() {
return String.format("EgressKey(%s, %s, %s)", namespace, name, consumedType);
}
}
| 5,888 |
0 | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun/sdk | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun/sdk/state/Expiration.java | /*
* 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.sdk.state;
import java.io.Serializable;
import java.time.Duration;
import java.util.Objects;
import org.apache.flink.statefun.sdk.annotations.ForRuntime;
/**
* State Expiration Configuration
*
* <p>This class defines the way state can be auto expired by the runtime. State expiration (also
* known as state TTL) can be used to keep state from growing arbitrarily by assigning an expiration
* date to a {@link PersistedAppendingBuffer}, {@link PersistedValue} or a {@link PersistedTable}.
*
* <p>State can be expired after a duration had passed since either from the last write to the
* state, or the last read.
*/
public final class Expiration implements Serializable {
private static final long serialVersionUID = 1L;
public enum Mode {
NONE,
AFTER_WRITE,
AFTER_READ_OR_WRITE;
}
/**
* Returns an Expiration configuration that would expire a @duration after the last write.
*
* @param duration a duration to wait before considering the state expired.
*/
public static Expiration expireAfterWriting(Duration duration) {
return new Expiration(Mode.AFTER_WRITE, duration);
}
/**
* Returns an Expiration configuration that would expire a @duration after the last write or read.
*
* @param duration a duration to wait before considering the state expired.
*/
public static Expiration expireAfterReadingOrWriting(Duration duration) {
return new Expiration(Mode.AFTER_READ_OR_WRITE, duration);
}
public static Expiration expireAfter(Duration duration, Mode mode) {
return new Expiration(mode, duration);
}
/** @return Returns a disabled expiration */
public static Expiration none() {
return new Expiration(Mode.NONE, Duration.ZERO);
}
private final Mode mode;
private final Duration duration;
@ForRuntime
public Expiration(Mode mode, Duration duration) {
this.mode = Objects.requireNonNull(mode);
this.duration = Objects.requireNonNull(duration);
}
public Mode mode() {
return mode;
}
public Duration duration() {
return duration;
}
@Override
public String toString() {
return String.format("Expiration{mode=%s, duration=%s}", mode, duration);
}
}
| 5,889 |
0 | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun/sdk | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun/sdk/state/AppendingBufferAccessor.java | /*
* 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.sdk.state;
import java.util.List;
import javax.annotation.Nonnull;
public interface AppendingBufferAccessor<E> {
void append(@Nonnull E element);
void appendAll(@Nonnull List<E> elements);
void replaceWith(@Nonnull List<E> elements);
@Nonnull
Iterable<E> view();
void clear();
}
| 5,890 |
0 | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun/sdk | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun/sdk/state/PersistedValue.java | /*
* 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.sdk.state;
import java.util.Objects;
import java.util.function.Function;
import java.util.function.Supplier;
import org.apache.flink.statefun.sdk.StatefulFunction;
import org.apache.flink.statefun.sdk.annotations.ForRuntime;
import org.apache.flink.statefun.sdk.annotations.Persisted;
/**
* A {@link PersistedValue} is a value registered within {@link StatefulFunction}s and is persisted
* and maintained by the system for fault-tolerance.
*
* <p>Created persisted values must be registered by using the {@link Persisted} annotation. Please
* see the class-level Javadoc of {@link StatefulFunction} for an example on how to do that.
*
* @see StatefulFunction
* @param <T> type of the state.
*/
public final class PersistedValue<T> {
private final String name;
private final Class<T> type;
private final Expiration expiration;
private Accessor<T> accessor;
private PersistedValue(String name, Class<T> type, Expiration expiration, Accessor<T> accessor) {
this.name = Objects.requireNonNull(name);
this.type = Objects.requireNonNull(type);
this.expiration = Objects.requireNonNull(expiration);
this.accessor = Objects.requireNonNull(accessor);
}
/**
* Creates a {@link PersistedValue} instance that may be used to access persisted state managed by
* the system. Access to the persisted value is identified by an unique name and type of the
* value. These may not change across multiple executions of the application.
*
* @param name the unique name of the persisted state.
* @param type the type of the state values of this {@code PersistedValue}.
* @param <T> the type of the state values.
* @return a {@code PersistedValue} instance.
*/
public static <T> PersistedValue<T> of(String name, Class<T> type) {
return of(name, type, Expiration.none());
}
/**
* Creates a {@link PersistedValue} instance that may be used to access persisted state managed by
* the system. Access to the persisted value is identified by an unique name and type of the
* value. These may not change across multiple executions of the application.
*
* @param name the unique name of the persisted state.
* @param type the type of the state values of this {@code PersistedValue}.
* @param expiration state expiration configuration.
* @param <T> the type of the state values.
* @return a {@code PersistedValue} instance.
*/
public static <T> PersistedValue<T> of(String name, Class<T> type, Expiration expiration) {
return new PersistedValue<>(name, type, expiration, new NonFaultTolerantAccessor<>());
}
/**
* Returns the unique name of the persisted value.
*
* @return unique name of the persisted value.
*/
public String name() {
return name;
}
/**
* Returns the type of the persisted values.
*
* @return the type of the persisted values.
*/
public Class<T> type() {
return type;
}
public Expiration expiration() {
return expiration;
}
/**
* Returns the persisted value.
*
* @return the persisted value.
*/
public T get() {
return accessor.get();
}
/**
* Updates the persisted value.
*
* @param value the new value.
*/
public void set(T value) {
accessor.set(value);
}
/** Clears the persisted value. After being cleared, the value would be {@code null}. */
public void clear() {
accessor.clear();
}
/**
* Updates the persisted value and returns it, in a single operation.
*
* @param update function to process the previous value to obtain the new value.
* @return the new updated value.
*/
public T updateAndGet(Function<T, T> update) {
T current = accessor.get();
T updated = update.apply(current);
accessor.set(updated);
return updated;
}
/**
* Attempts to get the persisted value. If the current value is {@code null}, then a specified
* default is returned instead.
*
* @param orElse the default value to return if the current value is not present.
* @return the persisted value, or the provided default if it isn't present.
*/
public T getOrDefault(T orElse) {
T value = accessor.get();
return value != null ? value : orElse;
}
/**
* Attempts to get the persisted value. If the current value is {@code null}, then a default value
* obtained from a specified supplier is returned instead.
*
* @param defaultSupplier supplier for a default value to be used if the current value is not
* present.
* @return the persisted value, or a default value if it isn't present.
*/
public T getOrDefault(Supplier<T> defaultSupplier) {
T value = accessor.get();
return value != null ? value : defaultSupplier.get();
}
@ForRuntime
void setAccessor(Accessor<T> newAccessor) {
Objects.requireNonNull(newAccessor);
this.accessor = newAccessor;
}
@Override
public String toString() {
return String.format(
"PersistedValue{name=%s, type=%s, expiration=%s}", name, type.getName(), expiration);
}
private static final class NonFaultTolerantAccessor<E> implements Accessor<E> {
private E element;
@Override
public void set(E element) {
this.element = element;
}
@Override
public E get() {
return element;
}
@Override
public void clear() {
element = null;
}
}
}
| 5,891 |
0 | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun/sdk | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun/sdk/state/Accessor.java | /*
* 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.sdk.state;
public interface Accessor<T> {
void set(T value);
T get();
void clear();
}
| 5,892 |
0 | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun/sdk | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun/sdk/state/PersistedStateRegistry.java | /*
* 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.sdk.state;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import org.apache.flink.statefun.sdk.StatefulFunction;
import org.apache.flink.statefun.sdk.annotations.ForRuntime;
import org.apache.flink.statefun.sdk.annotations.Persisted;
/**
* A {@link PersistedStateRegistry} can be used to register persisted state, such as a {@link
* PersistedValue} or {@link PersistedTable}, etc. All state that is registered via this registry is
* persisted and maintained by the system for fault-tolerance.
*
* <p>Created state registries must be bound to the system by using the {@link Persisted}
* annotation. Please see the class-level Javadoc of {@link StatefulFunction} for an example on how
* to do that.
*
* @see StatefulFunction
*/
public final class PersistedStateRegistry {
private final Map<String, Object> registeredStates = new HashMap<>();
private StateBinder stateBinder;
public PersistedStateRegistry() {
this.stateBinder = new NonFaultTolerantStateBinder();
}
/**
* Registers a {@link PersistedValue}. If a registered state already exists for the specified name
* of the value, the registration fails.
*
* @param valueState the value state to register.
* @param <T> the type of the value.
* @throws IllegalStateException if a previous registration exists for the given state name.
*/
public <T> void registerValue(PersistedValue<T> valueState) {
acceptRegistrationOrThrowIfPresent(valueState.name(), valueState);
}
/**
* Registers a {@link PersistedTable}. If a registered state already exists for the specified name
* of the table, the registration fails.
*
* @param tableState the table state to register.
* @param <K> the type of the keys.
* @param <V> the type of the values.
* @throws IllegalStateException if a previous registration exists for the given state name.
*/
public <K, V> void registerTable(PersistedTable<K, V> tableState) {
acceptRegistrationOrThrowIfPresent(tableState.name(), tableState);
}
/**
* Registers a {@link PersistedAppendingBuffer}. If a registered state already exists for the
* specified name of the table, the registration fails.
*
* @param bufferState the appending buffer to register.
* @param <E> the type of the buffer elements.
* @throws IllegalStateException if a previous registration exists for the given state name.
*/
public <E> void registerAppendingBuffer(PersistedAppendingBuffer<E> bufferState) {
acceptRegistrationOrThrowIfPresent(bufferState.name(), bufferState);
}
/**
* Registers a {@link RemotePersistedValue}. If a registered state already exists for the
* specified name of the table, the registration fails.
*
* <p>This method is intended only for internal use by the runtime.
*
* @param remoteValueState the remote value to register.
* @throws IllegalStateException if a previous registration exists for the given state name.
*/
@ForRuntime
public void registerRemoteValue(RemotePersistedValue remoteValueState) {
acceptRegistrationOrThrowIfPresent(remoteValueState.name(), remoteValueState);
}
/**
* Binds this state registry to a given function. All existing registered state in this registry
* will also be bound to the system.
*
* @param stateBinder the new fault-tolerant state binder to use.
* @throws IllegalStateException if the registry was attempted to be bound more than once.
*/
@ForRuntime
void bind(StateBinder stateBinder) {
if (isBound()) {
throw new IllegalStateException(
"This registry was already bound to state binder: "
+ this.stateBinder.getClass().getName()
+ ", attempting to rebind to state binder: "
+ stateBinder.getClass().getName());
}
this.stateBinder = Objects.requireNonNull(stateBinder);
registeredStates.values().forEach(stateBinder::bind);
}
private boolean isBound() {
return stateBinder != null && !(stateBinder instanceof NonFaultTolerantStateBinder);
}
private void acceptRegistrationOrThrowIfPresent(String stateName, Object newStateObject) {
final Object previousRegistration = registeredStates.get(stateName);
if (previousRegistration != null) {
throw new IllegalStateException(
String.format(
"State name '%s' was registered twice; previous registered state object with the same name was a %s, attempting to register a new %s under the same name.",
stateName, previousRegistration, newStateObject));
}
registeredStates.put(stateName, newStateObject);
stateBinder.bind(newStateObject);
}
private static final class NonFaultTolerantStateBinder extends StateBinder {
@Override
public void bind(Object stateObject) {}
}
}
| 5,893 |
0 | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun/sdk | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun/sdk/state/TableAccessor.java | /*
* 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.sdk.state;
import java.util.Map;
public interface TableAccessor<K, V> {
void set(K key, V value);
V get(K key);
void remove(K key);
Iterable<Map.Entry<K, V>> entries();
Iterable<K> keys();
Iterable<V> values();
void clear();
}
| 5,894 |
0 | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun/sdk | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun/sdk/state/StateBinder.java | /*
* 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.sdk.state;
import org.apache.flink.statefun.sdk.annotations.ForRuntime;
@ForRuntime
public abstract class StateBinder {
public abstract void bind(Object stateObject);
}
| 5,895 |
0 | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun/sdk | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun/sdk/state/PersistedAppendingBuffer.java | /*
* 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.sdk.state;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import javax.annotation.Nonnull;
import org.apache.flink.statefun.sdk.StatefulFunction;
import org.apache.flink.statefun.sdk.annotations.ForRuntime;
import org.apache.flink.statefun.sdk.annotations.Persisted;
/**
* A {@link PersistedAppendingBuffer} is an append-only buffer registered within {@link
* StatefulFunction}s and is persisted and maintained by the system for fault-tolerance. Persisted
* elements in the buffer may only be updated with bulk replacements.
*
* <p>Created persisted buffers must be registered by using the {@link Persisted} annotation. Please
* see the class-level Javadoc of {@link StatefulFunction} for an example on how to do that.
*
* @see StatefulFunction
* @param <E> type of the buffer elements.
*/
public final class PersistedAppendingBuffer<E> {
private final String name;
private final Class<E> elementType;
private final Expiration expiration;
private AppendingBufferAccessor<E> accessor;
private PersistedAppendingBuffer(
String name,
Class<E> elementType,
Expiration expiration,
AppendingBufferAccessor<E> accessor) {
this.name = Objects.requireNonNull(name);
this.elementType = Objects.requireNonNull(elementType);
this.expiration = Objects.requireNonNull(expiration);
this.accessor = Objects.requireNonNull(accessor);
}
/**
* Creates a {@link PersistedAppendingBuffer} instance that may be used to access persisted state
* managed by the system. Access to the persisted buffer is identified by an unique name and type
* of the elements. These may not change across multiple executions of the application.
*
* @param name the unique name of the persisted buffer state
* @param elementType the type of the elements of this {@code PersistedAppendingBuffer}.
* @param <E> the type of the elements.
* @return a {@code PersistedAppendingBuffer} instance.
*/
public static <E> PersistedAppendingBuffer<E> of(String name, Class<E> elementType) {
return of(name, elementType, Expiration.none());
}
/**
* Creates a {@link PersistedAppendingBuffer} instance that may be used to access persisted state
* managed by the system. Access to the persisted buffer is identified by an unique name and type
* of the elements. These may not change across multiple executions of the application.
*
* @param name the unique name of the persisted buffer state
* @param elementType the type of the elements of this {@code PersistedAppendingBuffer}.
* @param expiration state expiration configuration.
* @param <E> the type of the elements.
* @return a {@code PersistedAppendingBuffer} instance.
*/
public static <E> PersistedAppendingBuffer<E> of(
String name, Class<E> elementType, Expiration expiration) {
return new PersistedAppendingBuffer<>(
name, elementType, expiration, new NonFaultTolerantAccessor<>());
}
/**
* Returns the unique name of the persisted buffer.
*
* @return unique name of the persisted buffer.
*/
public String name() {
return name;
}
/**
* Returns the type of the persisted buffer elements.
*
* @return the type of the persisted buffer elements.
*/
public Class<E> elementType() {
return elementType;
}
public Expiration expiration() {
return expiration;
}
/**
* Appends an element to the persisted buffer.
*
* @param element the element to add to the persisted buffer.
*/
public void append(@Nonnull E element) {
accessor.append(element);
}
/**
* Adds all elements of a list to the persisted buffer.
*
* <p>If an empty list is passed in, then this method has no effect and the persisted buffer
* remains the same.
*
* @param elements a list of elements to add to the persisted buffer.
*/
public void appendAll(@Nonnull List<E> elements) {
if (!elements.isEmpty()) {
accessor.appendAll(elements);
}
}
/**
* Replace the elements in the persisted buffer with the provided list of elements.
*
* <p>If an empty list is passed in, this method will have the same effect as {@link #clear()}.
*
* @param elements list of elements to replace the elements in the persisted buffer with.
*/
public void replaceWith(@Nonnull List<E> elements) {
if (!elements.isEmpty()) {
accessor.replaceWith(elements);
} else {
accessor.clear();
}
}
/**
* Gets an unmodifiable view of the elements of the persisted buffer, as an {@link Iterable}.
*
* @return an unmodifiable view, as an {@link Iterable}, of the elements of the persisted buffer.
*/
@Nonnull
public Iterable<E> view() {
return new UnmodifiableViewIterable<>(accessor.view());
}
/** Clears all elements in the persisted buffer. */
public void clear() {
accessor.clear();
}
@Override
public String toString() {
return String.format(
"PersistedAppendingBuffer{name=%s, elementType=%s, expiration=%s}",
name, elementType.getName(), expiration);
}
@ForRuntime
void setAccessor(AppendingBufferAccessor<E> newAccessor) {
this.accessor = Objects.requireNonNull(newAccessor);
}
private static final class NonFaultTolerantAccessor<E> implements AppendingBufferAccessor<E> {
private List<E> list = new ArrayList<>();
@Override
public void append(@Nonnull E element) {
list.add(element);
}
@Override
public void appendAll(@Nonnull List<E> elements) {
list.addAll(elements);
}
@Override
public void replaceWith(@Nonnull List<E> elements) {
list.clear();
list.addAll(elements);
}
@Nonnull
@Override
public Iterable<E> view() {
return list;
}
@Override
public void clear() {
list.clear();
}
}
private static final class UnmodifiableViewIterable<E> implements Iterable<E> {
private final Iterable<E> delegate;
private UnmodifiableViewIterable(Iterable<E> delegate) {
this.delegate = Objects.requireNonNull(delegate);
}
@Override
public Iterator<E> iterator() {
return new UnmodifiableViewIterator<>(delegate.iterator());
}
}
private static final class UnmodifiableViewIterator<E> implements Iterator<E> {
private final Iterator<E> delegate;
UnmodifiableViewIterator(Iterator<E> delegate) {
this.delegate = Objects.requireNonNull(delegate);
}
@Override
public boolean hasNext() {
return delegate.hasNext();
}
@Override
public E next() {
return delegate.next();
}
public final void remove() {
throw new UnsupportedOperationException("This is an unmodifiable view.");
}
}
}
| 5,896 |
0 | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun/sdk | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun/sdk/state/RemotePersistedValue.java | /*
* 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.sdk.state;
import java.util.Objects;
import org.apache.flink.statefun.sdk.TypeName;
import org.apache.flink.statefun.sdk.annotations.ForRuntime;
@ForRuntime
public final class RemotePersistedValue {
private final String name;
private final TypeName type;
private final Expiration expiration;
private Accessor<byte[]> accessor;
private RemotePersistedValue(
String name, TypeName type, Expiration expiration, Accessor<byte[]> accessor) {
this.name = Objects.requireNonNull(name);
this.type = Objects.requireNonNull(type);
this.expiration = Objects.requireNonNull(expiration);
this.accessor = Objects.requireNonNull(accessor);
}
public static RemotePersistedValue of(String stateName, TypeName typeName) {
return new RemotePersistedValue(
stateName, typeName, Expiration.none(), new NonFaultTolerantAccessor<>());
}
public static RemotePersistedValue of(
String stateName, TypeName typeName, Expiration expiration) {
return new RemotePersistedValue(
stateName, typeName, expiration, new NonFaultTolerantAccessor<>());
}
public byte[] get() {
return accessor.get();
}
public void set(byte[] value) {
accessor.set(value);
}
public void clear() {
accessor.clear();
}
public String name() {
return name;
}
public TypeName type() {
return type;
}
public Expiration expiration() {
return expiration;
}
@ForRuntime
void setAccessor(Accessor<byte[]> newAccessor) {
this.accessor = Objects.requireNonNull(newAccessor);
}
private static final class NonFaultTolerantAccessor<E> implements Accessor<E> {
private E element;
@Override
public void set(E element) {
this.element = element;
}
@Override
public E get() {
return element;
}
@Override
public void clear() {
element = null;
}
}
}
| 5,897 |
0 | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun/sdk | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun/sdk/state/PersistedTable.java | /*
* 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.sdk.state;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import org.apache.flink.statefun.sdk.StatefulFunction;
import org.apache.flink.statefun.sdk.annotations.ForRuntime;
import org.apache.flink.statefun.sdk.annotations.Persisted;
/**
* A {@link PersistedTable} is a table (collection of keys and values) registered within {@link
* StatefulFunction}s and is persisted and maintained by the system for fault-tolerance.
*
* <p>Created persisted tables must be registered by using the {@link Persisted} annotation. Please
* see the class-level Javadoc of {@link StatefulFunction} for an example on how to do that.
*
* @see StatefulFunction
* @param <K> type of the key - Please note that the key have a meaningful {@link #hashCode()} and
* {@link #equals(Object)} implemented.
* @param <V> type of the value.
*/
public final class PersistedTable<K, V> {
private final String name;
private final Class<K> keyType;
private final Class<V> valueType;
private final Expiration expiration;
private TableAccessor<K, V> accessor;
private PersistedTable(
String name,
Class<K> keyType,
Class<V> valueType,
Expiration expiration,
TableAccessor<K, V> accessor) {
this.name = Objects.requireNonNull(name);
this.keyType = Objects.requireNonNull(keyType);
this.valueType = Objects.requireNonNull(valueType);
this.expiration = Objects.requireNonNull(expiration);
this.accessor = Objects.requireNonNull(accessor);
}
/**
* Creates a {@link PersistedTable} instance that may be used to access persisted state managed by
* the system. Access to the persisted table is identified by an unique name, type of the key, and
* type of the value. These may not change across multiple executions of the application.
*
* @param name the unique name of the persisted state.
* @param keyType the type of the state keys of this {@code PersistedTable}.
* @param valueType the type of the state values of this {@code PersistedTale}.
* @param <K> the type of the state keys.
* @param <V> the type of the state values.
* @return a {@code PersistedTable} instance.
*/
public static <K, V> PersistedTable<K, V> of(String name, Class<K> keyType, Class<V> valueType) {
return of(name, keyType, valueType, Expiration.none());
}
/**
* Creates a {@link PersistedTable} instance that may be used to access persisted state managed by
* the system. Access to the persisted table is identified by an unique name, type of the key, and
* type of the value. These may not change across multiple executions of the application.
*
* @param name the unique name of the persisted state.
* @param keyType the type of the state keys of this {@code PersistedTable}.
* @param valueType the type of the state values of this {@code PersistedTale}.
* @param expiration state expiration configuration.
* @param <K> the type of the state keys.
* @param <V> the type of the state values.
* @return a {@code PersistedTable} instance.
*/
public static <K, V> PersistedTable<K, V> of(
String name, Class<K> keyType, Class<V> valueType, Expiration expiration) {
return new PersistedTable<>(
name, keyType, valueType, expiration, new NonFaultTolerantAccessor<>());
}
/**
* Returns the unique name of the persisted table.
*
* @return unique name of the persisted table.
*/
public String name() {
return name;
}
/**
* Returns the type of the persisted tables keys.
*
* @return the type of the persisted tables keys.
*/
public Class<K> keyType() {
return keyType;
}
/**
* Returns the type of the persisted tables values.
*
* @return the type of the persisted tables values.
*/
public Class<V> valueType() {
return valueType;
}
public Expiration expiration() {
return expiration;
}
/**
* Returns a persisted table's value.
*
* @return the persisted table value associated with {@code key}.
*/
public V get(K key) {
return accessor.get(key);
}
/**
* Updates the persisted table.
*
* @param key the to associate the value with.
* @param value the new value.
*/
public void set(K key, V value) {
accessor.set(key, value);
}
/**
* Removes the value associated with {@code key}.
*
* @param key the key to remove.
*/
public void remove(K key) {
accessor.remove(key);
}
/**
* Gets an {@link Iterable} over all the entries of the persisted table.
*
* @return An {@link Iterable} of the elements of the persisted table.
*/
public Iterable<Map.Entry<K, V>> entries() {
return accessor.entries();
}
/**
* Gets an {@link Iterable} over all keys of the persisted table.
*
* @return An {@link Iterable} of keys in the persisted table.
*/
public Iterable<K> keys() {
return accessor.keys();
}
/**
* Gets an {@link Iterable} over all values of the persisted table.
*
* @return An {@link Iterable} of values in the persisted table.
*/
public Iterable<V> values() {
return accessor.values();
}
/** Clears all elements in the persisted buffer. */
public void clear() {
accessor.clear();
}
@Override
public String toString() {
return String.format(
"PersistedTable{name=%s, keyType=%s, valueType=%s, expiration=%s}",
name, keyType.getName(), valueType.getName(), expiration);
}
@ForRuntime
void setAccessor(TableAccessor<K, V> newAccessor) {
Objects.requireNonNull(newAccessor);
this.accessor = newAccessor;
}
private static final class NonFaultTolerantAccessor<K, V> implements TableAccessor<K, V> {
private final Map<K, V> map = new HashMap<>();
@Override
public void set(K key, V value) {
map.put(key, value);
}
@Override
public V get(K key) {
return map.get(key);
}
@Override
public void remove(K key) {
map.remove(key);
}
@Override
public Iterable<Map.Entry<K, V>> entries() {
return map.entrySet();
}
@Override
public Iterable<K> keys() {
return map.keySet();
}
@Override
public Iterable<V> values() {
return map.values();
}
@Override
public void clear() {
map.clear();
}
}
}
| 5,898 |
0 | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun/sdk | Create_ds/flink-statefun/statefun-sdk-embedded/src/main/java/org/apache/flink/statefun/sdk/annotations/ForRuntime.java | /*
* 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.sdk.annotations;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
/**
* Methods or constructors annotated with this annotation, are used for the runtime to extend the
* API with specialized implementation
*/
@Documented
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.TYPE})
public @interface ForRuntime {}
| 5,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.